Ruby 4.1.0dev (2026-10-06 revision 6b1add1e701dcde4be05d63f3f423ef37c3893a4)
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
3699bool
3700rb_gc_impl_live_object_p(void *objspace_ptr, const void *ptr)
3701{
3702 rb_objspace_t *objspace = objspace_ptr;
3703
3704 /* Whether ptr refers to a live object. is_pointer_to_heap is the
3705 * address-only check; T_NONE, T_MOVED, and T_ZOMBIE slots are valid heap
3706 * addresses but not live objects. */
3707 if (!is_pointer_to_heap(objspace, ptr)) return false;
3708
3709 VALUE obj = (VALUE)ptr;
3710 bool live = false;
3711 asan_unpoisoning_object(obj) {
3712 switch (BUILTIN_TYPE(obj)) {
3713 case T_NONE:
3714 case T_MOVED:
3715 case T_ZOMBIE:
3716 break;
3717 default:
3718 live = true;
3719 break;
3720 }
3721 }
3722 return live;
3723}
3724
3725/* Flags preserved from the original object when it becomes a zombie, and so also the
3726 * only ones that may legitimately be set on one. */
3727#define ZOMBIE_OBJ_KEPT_FLAGS (FL_FINALIZE)
3728
3729void
3730rb_gc_impl_make_zombie(void *objspace_ptr, VALUE obj, void (*dfree)(void *), void *data)
3731{
3732 rb_objspace_t *objspace = objspace_ptr;
3733
3734 struct RZombie *zombie = RZOMBIE(obj);
3735 zombie->flags = T_ZOMBIE | (zombie->flags & ZOMBIE_OBJ_KEPT_FLAGS);
3736 zombie->dfree = dfree;
3737 zombie->data = data;
3738 VALUE prev, next = heap_pages_deferred_final;
3739 do {
3740 zombie->next = prev = next;
3741 next = RUBY_ATOMIC_VALUE_CAS(heap_pages_deferred_final, prev, obj);
3742 } while (next != prev);
3743
3744 struct heap_page *page = GET_HEAP_PAGE(obj);
3745 page->final_slots++;
3746 page->heap->final_slots_count++;
3747}
3748
3749static void
3750tdata_unsafe_free_chunk_reset(struct tdata_unsafe_free_chunk *chunk)
3751{
3752 chunk->next = NULL;
3753 chunk->count = 0;
3754 chunk->embed_xfree_bits = 0;
3755}
3756
3757static struct tdata_unsafe_free_chunk *
3758tdata_unsafe_free_chunk_alloc(void)
3759{
3760 /* Pops race each other (several Ractors can be sweeping), but pushes happen only
3761 * inside the drain, which holds a VM barrier -- and a barrier cannot complete while
3762 * a Ractor is inside gc_sweep_page. No push ever overlaps a pop, so the head only
3763 * moves forward and this CAS pop needs no ABA tagging. A sweep performed by a
3764 * thread other than the objspace's owner would break that. */
3765 struct tdata_unsafe_free_chunk *head =
3766 rbimpl_atomic_ptr_load((void **)&global_objspace->tdata_unsafe_free_cache,
3767 RBIMPL_ATOMIC_ACQUIRE);
3768 while (head) {
3769 struct tdata_unsafe_free_chunk *prev =
3770 rbimpl_atomic_ptr_cas((void **)&global_objspace->tdata_unsafe_free_cache,
3771 head, head->next,
3772 RBIMPL_ATOMIC_ACQ_REL, RBIMPL_ATOMIC_ACQUIRE);
3773 if (prev == head) {
3774 rbimpl_atomic_size_dec(&global_objspace->tdata_unsafe_free_cache_len,
3775 RBIMPL_ATOMIC_RELAXED);
3776 tdata_unsafe_free_chunk_reset(head);
3777 return head;
3778 }
3779 head = prev;
3780 }
3781
3782 /* Not xmalloc: this runs mid-sweep, and the chunks are GC bookkeeping that should not
3783 * feed back into malloc_increase (mark stack chunks do the same). */
3784 struct tdata_unsafe_free_chunk *chunk = malloc(sizeof(struct tdata_unsafe_free_chunk));
3785 if (!chunk) rb_memerror();
3786 tdata_unsafe_free_chunk_reset(chunk);
3787 return chunk;
3788}
3789
3790/* Hand this objspace's partial chunk to the global stack. The entries were counted as
3791 * they were appended, so the pending count does not change here. */
3792static void
3793gc_tdata_unsafe_free_publish(rb_objspace_t *objspace)
3794{
3795 struct tdata_unsafe_free_chunk *chunk = objspace->tdata_unsafe_free_chunk;
3796 if (chunk == NULL) return;
3797 GC_ASSERT(chunk->count > 0);
3798 objspace->tdata_unsafe_free_chunk = NULL;
3799
3800 struct tdata_unsafe_free_chunk *prev, *head =
3801 rbimpl_atomic_ptr_load((void **)&global_objspace->tdata_unsafe_free_published,
3802 RBIMPL_ATOMIC_RELAXED);
3803 do {
3804 chunk->next = prev = head;
3805 head = rbimpl_atomic_ptr_cas((void **)&global_objspace->tdata_unsafe_free_published,
3806 prev, chunk,
3807 RBIMPL_ATOMIC_ACQ_REL, RBIMPL_ATOMIC_ACQUIRE);
3808 } while (head != prev);
3809}
3810
3811/* Copy out what obj's deferred free needs, running no dfree. Returns true when the
3812 * caller may reclaim the slot and false when obj became a zombie, matching rb_gc_obj_free. */
3813static bool
3814gc_defer_thread_unsafe_free(rb_objspace_t *objspace, VALUE obj, bool *trigger)
3815{
3816 GC_ASSERT(!((uintptr_t)RTYPEDDATA(obj)->type & TYPED_DATA_EMBEDDED));
3817 const rb_data_type_t *type = RTYPEDDATA_TYPE(obj);
3818 void *data = RTYPEDDATA(obj)->data;
3819 GC_ASSERT(data != NULL);
3820
3821 rb_gc_obj_free_vm_weak_references(obj);
3822
3823 size_t count = rbimpl_atomic_size_fetch_add(&global_objspace->tdata_deferred_free_count, 1,
3824 RBIMPL_ATOMIC_RELAXED) + 1;
3825 if (!*trigger && count >= TDATA_DEFERRED_FREE_THRESHOLD) {
3826 *trigger = true;
3827 }
3828
3829 struct tdata_unsafe_free_chunk *chunk = objspace->tdata_unsafe_free_chunk;
3830 if (chunk == NULL) {
3831 chunk = objspace->tdata_unsafe_free_chunk = tdata_unsafe_free_chunk_alloc();
3832 }
3833 if (type->flags & RUBY_TYPED_EMBEDDABLE) {
3834 chunk->embed_xfree_bits |= (uint32_t)1 << chunk->count;
3835 }
3836 struct tdata_unsafe_free_entry *entry = &chunk->entries[chunk->count++];
3837 entry->dfree = type->function.dfree;
3838 entry->data = data;
3839 if (chunk->count == TDATA_UNSAFE_FREE_CHUNK_CAPA) {
3840 gc_tdata_unsafe_free_publish(objspace);
3841 }
3842
3843 if (FL_TEST_RAW(obj, FL_FINALIZE)) {
3844 /* The dfree is on the side list now, so this zombie carries none: it goes on the
3845 * regular deferred list, where the owner runs its Ruby finalizer promptly and
3846 * reclaims the slot, instead of waiting for the barrier. */
3847 rb_gc_impl_make_zombie(objspace, obj, 0, 0);
3848 return false;
3849 }
3850 return true;
3851}
3852
3853typedef int each_obj_callback(void *, void *, size_t, void *);
3854typedef int each_page_callback(struct heap_page *, void *);
3855
3858 bool reenable_incremental;
3859
3860 /* Visit only the pages that hold shareable objects, so a foreign Ractor's objspace
3861 * can be walked for its shareable objects alone, without touching the rest of its
3862 * isolated heap. */
3863 bool shareable_only;
3864
3865 /* Set when walking a foreign objspace without settling its stopped lazy sweep
3866 * (settling would run the owner's obj_free and dfree on this thread). Objects the
3867 * sweep is about to free are skipped: on an unswept page, unmarked means dead. */
3868 bool skip_unswept_dead;
3869
3870 each_obj_callback *each_obj_callback;
3871 each_page_callback *each_page_callback;
3872 void *data;
3873
3874 struct heap_page **pages[HEAP_COUNT];
3875 size_t pages_counts[HEAP_COUNT];
3876};
3877
3878static VALUE
3879objspace_each_objects_ensure(VALUE arg)
3880{
3881 struct each_obj_data *data = (struct each_obj_data *)arg;
3882 rb_objspace_t *objspace = data->objspace;
3883
3884 /* Reenable incremental GC */
3885 if (data->reenable_incremental) {
3886 objspace->flags.dont_incremental = FALSE;
3887 }
3888
3889 for (int i = 0; i < HEAP_COUNT; i++) {
3890 struct heap_page **pages = data->pages[i];
3891 free(pages);
3892 }
3893
3894 return Qnil;
3895}
3896
3897static VALUE
3898objspace_each_objects_try(VALUE arg)
3899{
3900 struct each_obj_data *data = (struct each_obj_data *)arg;
3901 rb_objspace_t *objspace = data->objspace;
3902
3903 /* Copy pages from all heaps to their respective buffers. */
3904 for (int i = 0; i < HEAP_COUNT; i++) {
3905 rb_heap_t *heap = &heaps[i];
3906 size_t size = heap->total_pages * sizeof(struct heap_page *);
3907
3908 struct heap_page **pages = malloc(size);
3909 if (!pages) rb_memerror();
3910
3911 /* Set up pages buffer by iterating over all pages in the current eden
3912 * heap. This will be a snapshot of the state of the heap before we
3913 * call the callback over each page that exists in this buffer. Thus it
3914 * is safe for the callback to allocate objects without possibly entering
3915 * an infinite loop. */
3916 struct heap_page *page = 0;
3917 size_t pages_count = 0;
3918 ccan_list_for_each(&heap->pages, page, page_node) {
3919 pages[pages_count] = page;
3920 pages_count++;
3921 }
3922 data->pages[i] = pages;
3923 data->pages_counts[i] = pages_count;
3924 GC_ASSERT(pages_count == heap->total_pages);
3925 }
3926
3927 for (int i = 0; i < HEAP_COUNT; i++) {
3928 rb_heap_t *heap = &heaps[i];
3929 size_t pages_count = data->pages_counts[i];
3930 struct heap_page **pages = data->pages[i];
3931
3932 struct heap_page *page = ccan_list_top(&heap->pages, struct heap_page, page_node);
3933 for (size_t i = 0; i < pages_count; i++) {
3934 /* If we have reached the end of the linked list then there are no
3935 * more pages, so break. */
3936 if (page == NULL) break;
3937
3938 /* If this page does not match the one in the buffer, then move to
3939 * the next page in the buffer. */
3940 if (pages[i] != page) continue;
3941
3942 uintptr_t pstart = (uintptr_t)page->start;
3943 uintptr_t pend = pstart + (page->total_slots * heap->slot_size);
3944
3945 if (data->shareable_only) {
3946 /* Hand shareable objects to the callback one slot at a time, not the
3947 * whole page: walking a foreign Ractor's objspace must never expose its
3948 * unshareable objects, which the caller cannot inspect safely. */
3949 if (page->flags.has_shareable_objects) {
3950 /* This walk runs over a foreign objspace under the barrier and
3951 * must not settle the owner's stopped lazy sweep: settling would run
3952 * the owner's obj_free and dfree on this thread with this Ractor's
3953 * identity (wrong per-Ractor tables, a foreign T_DATA dfree). So no
3954 * gc_rest, and objects the sweep is about to free are skipped: on an
3955 * unswept page unmarked means dead and its shareable bit merely has
3956 * not been bulk-cleared yet. Passing one to the callback would
3957 * resurrect it, handing out a reference the owner's sweep frees as
3958 * soon as the barrier lifts. */
3959 const bool page_unswept = is_lazy_sweeping(objspace) && page->flags.before_sweep;
3960 int planes = CEILDIV(page->total_slots, BITS_BITLENGTH);
3961 uintptr_t base = pstart;
3962 bool stop = false;
3963 for (int j = 0; j < planes && !stop; j++) {
3964 bits_t bits = page->shareable_bits[j];
3965 uintptr_t slot = base;
3966 while (bits) {
3967 if ((bits & 1) && data->each_obj_callback &&
3968 !(page_unswept && !RVALUE_MARKED(objspace, (VALUE)slot)) &&
3969 (*data->each_obj_callback)((void *)slot, (void *)(slot + heap->slot_size),
3970 heap->slot_size, data->data)) {
3971 stop = true;
3972 break;
3973 }
3974 slot += heap->slot_size;
3975 bits >>= 1;
3976 }
3977 base += BITS_BITLENGTH * heap->slot_size;
3978 }
3979 if (stop) break;
3980 }
3981 }
3982 else if (data->skip_unswept_dead &&
3983 is_lazy_sweeping(objspace) && page->flags.before_sweep) {
3984 /* A foreign page pending sweep: hand out the live objects one slot at a
3985 * time and skip the unmarked (dead) ones the owner's sweep frees as soon
3986 * as the barrier lifts. */
3987 bool stop = false;
3988 for (uintptr_t slot = pstart; slot < pend; slot += heap->slot_size) {
3989 if (!RVALUE_MARKED(objspace, (VALUE)slot)) continue;
3990 if (data->each_obj_callback &&
3991 (*data->each_obj_callback)((void *)slot, (void *)(slot + heap->slot_size),
3992 heap->slot_size, data->data)) {
3993 stop = true;
3994 break;
3995 }
3996 }
3997 if (stop) break;
3998 }
3999 else {
4000 if (data->each_obj_callback &&
4001 (*data->each_obj_callback)((void *)pstart, (void *)pend, heap->slot_size, data->data)) {
4002 break;
4003 }
4004 if (data->each_page_callback &&
4005 (*data->each_page_callback)(page, data->data)) {
4006 break;
4007 }
4008 }
4009
4010 page = ccan_list_next(&heap->pages, page, page_node);
4011 }
4012 }
4013
4014 return Qnil;
4015}
4016
4017static void
4018objspace_each_exec(bool protected, struct each_obj_data *each_obj_data)
4019{
4020 /* Disable incremental GC */
4022 bool reenable_incremental = FALSE;
4023 if (protected) {
4024 reenable_incremental = !objspace->flags.dont_incremental;
4025
4026 gc_rest(objspace);
4027 objspace->flags.dont_incremental = TRUE;
4028 }
4029
4030 each_obj_data->reenable_incremental = reenable_incremental;
4031 memset(&each_obj_data->pages, 0, sizeof(each_obj_data->pages));
4032 memset(&each_obj_data->pages_counts, 0, sizeof(each_obj_data->pages_counts));
4033 rb_ensure(objspace_each_objects_try, (VALUE)each_obj_data,
4034 objspace_each_objects_ensure, (VALUE)each_obj_data);
4035}
4036
4037static void
4038objspace_each_objects(rb_objspace_t *objspace, each_obj_callback *callback, void *data, bool protected)
4039{
4040 struct each_obj_data each_obj_data = {
4041 .objspace = objspace,
4042 .each_obj_callback = callback,
4043 .each_page_callback = NULL,
4044 .data = data,
4045 };
4046 objspace_each_exec(protected, &each_obj_data);
4047}
4048
4049void
4050rb_gc_impl_each_objects(void *objspace_ptr, each_obj_callback *callback, void *data)
4051{
4052 objspace_each_objects(objspace_ptr, callback, data, TRUE);
4053}
4054
4055/* Like rb_gc_impl_each_objects but visiting only pages that hold shareable objects, to
4056 * reach a foreign Ractor's shareable objects without walking the rest of its heap. */
4057void
4058rb_gc_impl_each_objects_shareable(void *objspace_ptr, each_obj_callback *callback, void *data)
4059{
4060 struct each_obj_data each_obj_data = {
4061 .objspace = objspace_ptr,
4062 .shareable_only = true,
4063 .each_obj_callback = callback,
4064 .each_page_callback = NULL,
4065 .data = data,
4066 };
4067 /* Not the protected variant: this objspace belongs to another Ractor (the caller
4068 * holds the barrier). The protected path calls gc_rest, which would run the owner's
4069 * stopped lazy sweep (its obj_free and dfree) on the walking thread with the
4070 * walker's Ractor identity (wrong per-Ractor tables, a foreign T_DATA dfree). The
4071 * owner is stopped and its page list is stable, and the walk itself skips dead,
4072 * unswept objects (the shareable_only branch of objspace_each_objects_try). The
4073 * walker's own incremental GC state is untouched, since this is not its objspace. */
4074 objspace_each_exec(FALSE, &each_obj_data);
4075}
4076
4077/* Walk every object of a foreign Ractor's objspace, unshareable ones included. Only for
4078 * callers that hold the barrier and whose callback is pure C (a heap dump, memory
4079 * accounting). As in the shareable walk above, the owner's stopped lazy sweep is not
4080 * settled and dead, unswept objects are skipped by the walk (skip_unswept_dead). */
4081void
4082rb_gc_impl_each_objects_foreign(void *objspace_ptr, each_obj_callback *callback, void *data)
4083{
4084 struct each_obj_data each_obj_data = {
4085 .objspace = objspace_ptr,
4086 .skip_unswept_dead = true,
4087 .each_obj_callback = callback,
4088 .each_page_callback = NULL,
4089 .data = data,
4090 };
4091 objspace_each_exec(FALSE, &each_obj_data);
4092}
4093
4094#if GC_CAN_COMPILE_COMPACTION
4095static void
4096objspace_each_pages(rb_objspace_t *objspace, each_page_callback *callback, void *data, bool protected)
4097{
4098 struct each_obj_data each_obj_data = {
4099 .objspace = objspace,
4100 .each_obj_callback = NULL,
4101 .each_page_callback = callback,
4102 .data = data,
4103 };
4104 objspace_each_exec(protected, &each_obj_data);
4105}
4106#endif
4107
4108VALUE
4109rb_gc_impl_define_finalizer(void *objspace_ptr, VALUE obj, VALUE block)
4110{
4111 rb_objspace_t *objspace = objspace_ptr;
4112 VALUE table;
4113 st_data_t data;
4114
4115 GC_ASSERT(!OBJ_FROZEN(obj));
4116
4117 /* Registering, storing and running finalizers all belong to the object's own
4118 * objspace, so refuse to define one on another Ractor's object (even a shareable
4119 * one): it would land in a table the owner's sweep never consults. */
4120 if (GET_HEAP_OBJSPACE(obj) != objspace) {
4121 rb_raise(rb_eRactorIsolationError,
4122 "can not define a finalizer for an object of another Ractor");
4123 }
4124
4125 RBASIC(obj)->flags |= FL_FINALIZE;
4126
4127 unsigned int lev = RB_GC_VM_LOCK();
4128
4129 if (st_lookup(finalizer_table, obj, &data)) {
4130 table = (VALUE)data;
4131 VALUE dup_table = rb_ary_dup(table);
4132
4133 RB_GC_VM_UNLOCK(lev);
4134 /* avoid duplicate block, table is usually small */
4135 {
4136 long len = RARRAY_LEN(table);
4137 long i;
4138
4139 for (i = 0; i < len; i++) {
4140 VALUE recv = RARRAY_AREF(dup_table, i);
4141 if (rb_equal(recv, block)) { // can't be called with VM lock held
4142 return recv;
4143 }
4144 }
4145 }
4146 lev = RB_GC_VM_LOCK();
4147 RB_GC_GUARD(dup_table);
4148
4149 rb_ary_push(table, block);
4150 }
4151 else {
4152 table = rb_ary_new3(2, rb_obj_id(obj), block);
4153 rb_obj_hide(table);
4154 st_add_direct(finalizer_table, obj, table);
4155 }
4156
4157 RB_GC_VM_UNLOCK(lev);
4158
4159 return block;
4160}
4161
4162void
4163rb_gc_impl_undefine_finalizer(void *objspace_ptr, VALUE obj)
4164{
4165 rb_objspace_t *objspace = objspace_ptr;
4166
4167 GC_ASSERT(!OBJ_FROZEN(obj));
4168
4169 /* Symmetric with define. */
4170 if (GET_HEAP_OBJSPACE(obj) != objspace) {
4171 rb_raise(rb_eRactorIsolationError,
4172 "can not undefine a finalizer of an object of another Ractor");
4173 }
4174
4175 st_data_t data = obj;
4176
4177 int lev = RB_GC_VM_LOCK();
4178 st_delete(finalizer_table, &data, 0);
4179 RB_GC_VM_UNLOCK(lev);
4180
4181 FL_UNSET(obj, FL_FINALIZE);
4182}
4183
4184void
4185rb_gc_impl_copy_finalizer(void *objspace_ptr, VALUE dest, VALUE obj)
4186{
4187 /* Finalizers do not cross objspaces: a copy of another Ractor's object starts with
4188 * none (guards the public rb_gc_copy_finalizer C API; no in-tree caller crosses).
4189 * A same-objspace copy behaves as before. Table accessed under the VM lock. */
4190 rb_objspace_t *objspace = objspace_ptr;
4191 VALUE table;
4192 st_data_t data;
4193
4194 if (!FL_TEST(obj, FL_FINALIZE)) return;
4195 if (GET_HEAP_OBJSPACE(obj) != objspace) return;
4196
4197 int lev = RB_GC_VM_LOCK();
4198 if (RB_LIKELY(st_lookup(finalizer_table, obj, &data))) {
4199 table = rb_ary_dup((VALUE)data);
4200 RARRAY_ASET(table, 0, rb_obj_id(dest));
4201 st_insert(finalizer_table, dest, table);
4202 FL_SET(dest, FL_FINALIZE);
4203 }
4204 else {
4205 rb_bug("rb_gc_copy_finalizer: FL_FINALIZE set but not found in finalizer_table: %s", rb_obj_info(obj));
4206 }
4207 RB_GC_VM_UNLOCK(lev);
4208}
4209
4210static VALUE
4211get_final(long i, void *data)
4212{
4213 VALUE table = (VALUE)data;
4214
4215 return RARRAY_AREF(table, i + 1);
4216}
4217
4218static void
4219run_final(rb_objspace_t *objspace, VALUE zombie)
4220{
4221 if (RZOMBIE(zombie)->dfree) {
4222 RZOMBIE(zombie)->dfree(RZOMBIE(zombie)->data);
4223 }
4224
4225 st_data_t key = (st_data_t)zombie;
4226 if (FL_TEST_RAW(zombie, FL_FINALIZE)) {
4227 FL_UNSET(zombie, FL_FINALIZE);
4228 st_data_t table;
4229 if (st_delete(finalizer_table, &key, &table)) {
4230 rb_gc_run_obj_finalizer(RARRAY_AREF(table, 0), RARRAY_LEN(table) - 1, get_final, (void *)table);
4231 }
4232 else {
4233 rb_bug("FL_FINALIZE flag is set, but finalizers are not found");
4234 }
4235 }
4236 else {
4237 GC_ASSERT(!st_lookup(finalizer_table, key, NULL));
4238 }
4239}
4240
4241static void
4242finalize_list(rb_objspace_t *objspace, VALUE zombie)
4243{
4244 while (zombie) {
4245 VALUE next_zombie;
4246 struct heap_page *page;
4247 rb_asan_unpoison_object(zombie, false);
4248 next_zombie = RZOMBIE(zombie)->next;
4249 page = GET_HEAP_PAGE(zombie);
4250
4251 run_final(objspace, zombie);
4252 {
4253 GC_ASSERT(BUILTIN_TYPE(zombie) == T_ZOMBIE);
4254 GC_ASSERT(page->heap->final_slots_count > 0);
4255 GC_ASSERT(page->final_slots > 0);
4256
4257 page->heap->final_slots_count--;
4258 page->final_slots--;
4259 page->free_slots++;
4260 RVALUE_AGE_SET_BITMAP(zombie, 0);
4261 heap_page_add_free_region(objspace, page, zombie);
4262 page->heap->total_freed_objects++;
4263 }
4264
4265 zombie = next_zombie;
4266 }
4267}
4268
4269static void
4270finalize_zombies(rb_objspace_t *objspace)
4271{
4272 VALUE zombie;
4273 while ((zombie = RUBY_ATOMIC_VALUE_EXCHANGE(heap_pages_deferred_final, 0)) != 0) {
4274 finalize_list(objspace, zombie);
4275 }
4276}
4277
4278static void
4279finalize_deferred(rb_objspace_t *objspace)
4280{
4281 rb_gc_set_pending_interrupt();
4282 finalize_zombies(objspace);
4283 rb_gc_unset_pending_interrupt();
4284}
4285
4286static void
4287gc_finalize_deferred(void *dmy)
4288{
4289 /* One postponed job is shared by every objspace: the preregistration table only
4290 * holds about 32 entries and Ractors are created continuously. A deferred finalizer
4291 * belongs to the objspace of the thread that ran the job, i.e. the current one. */
4292 rb_objspace_t *objspace = rb_gc_get_objspace();
4293 if (RUBY_ATOMIC_EXCHANGE(finalizing, 1)) return;
4294
4295 finalize_deferred(objspace);
4296 RUBY_ATOMIC_SET(finalizing, 0);
4297}
4298
4299static void
4300gc_finalize_deferred_register(rb_objspace_t *objspace)
4301{
4302 /* Enqueue gc_finalize_deferred on this objspace's owning Ractor. A global GC can
4303 * defer a foreign objspace's finalizers, and those must run on their owner rather
4304 * than on the driver. */
4305 rb_gc_trigger_finalize_deferred(objspace, objspace->finalize_deferred_pjob);
4306}
4307
4308static int pop_mark_stack(mark_stack_t *stack, VALUE *data);
4309
4310/* Throw away an unfinished incremental mark and leave the objspace in gc_mode_none. The
4311 * mark bits the partial mark set stay behind, so the caller must clear them before the
4312 * heap is collected again. */
4313static void
4314gc_abort_incremental_marking(rb_objspace_t *objspace)
4315{
4316 GC_ASSERT(is_incremental_marking(objspace));
4317
4318 VALUE obj;
4319 while (pop_mark_stack(&objspace->mark_stack, &obj));
4320
4321 /* gc_grey records the weak references it greys for gc_marks_finish to resolve; this
4322 * cycle never reaches it, and the entries would outlive their objects. */
4323 rb_darray_clear(objspace->weak_references);
4324
4325 objspace->flags.during_incremental_marking = FALSE;
4326 gc_mode_set(objspace, gc_mode_none);
4327}
4328
4329static void
4330gc_abort(void *objspace_ptr)
4331{
4332 rb_objspace_t *objspace = objspace_ptr;
4333
4334 if (is_incremental_marking(objspace)) {
4335 gc_abort_incremental_marking(objspace);
4336 }
4337
4338 if (is_lazy_sweeping(objspace)) {
4339 objspace->sweeping_heap_count = 0;
4340 for (int i = 0; i < HEAP_COUNT; i++) {
4341 rb_heap_t *heap = &heaps[i];
4342
4343 heap->sweeping_page = NULL;
4344 struct heap_page *page = NULL;
4345
4346 ccan_list_for_each(&heap->pages, page, page_node) {
4347 page->flags.before_sweep = false;
4348 }
4349 }
4350 }
4351
4352 for (int i = 0; i < HEAP_COUNT; i++) {
4353 rb_heap_t *heap = &heaps[i];
4354 gc_bitmaps_clear(objspace, heap, false);
4355 }
4356
4357 gc_mode_set(objspace, gc_mode_none);
4358}
4359
4360#if VERIFY_FREE_SIZE
4361# ifdef RB_THREAD_LOCAL_SPECIFIER
4362# define GC_FREEING_OBJ_TLS RB_THREAD_LOCAL_SPECIFIER
4363# else
4364# define GC_FREEING_OBJ_TLS
4365# endif
4366
4367static GC_FREEING_OBJ_TLS VALUE gc_freeing_obj;
4368
4369/* Remember what we are tearing down so that a bad xfree() underneath can name
4370 * the object and not just the buffer. Saved and restored because a dfree
4371 * callback can free another object. */
4372static bool
4373gc_obj_free(void *objspace, VALUE obj)
4374{
4375 VALUE prev = gc_freeing_obj;
4376 gc_freeing_obj = obj;
4377
4378 bool freed = rb_gc_obj_free(objspace, obj);
4379
4380 gc_freeing_obj = prev;
4381 return freed;
4382}
4383
4384static const char *
4385gc_freeing_obj_info(void)
4386{
4387 /* Not thread-local: only reachable from a rb_bug() path, where a second
4388 * thread racing us is already unrecoverable. */
4389 static char buf[128];
4390
4391 if (!gc_freeing_obj) return NULL;
4392
4393 snprintf(buf, sizeof(buf), "%p %s", (void *)gc_freeing_obj, rb_obj_info(gc_freeing_obj));
4394 return buf;
4395}
4396#else
4397# define gc_obj_free(objspace, obj) rb_gc_obj_free((objspace), (obj))
4398# define gc_freeing_obj_info() NULL
4399#endif
4400
4401void
4402rb_gc_impl_shutdown_free_objects(void *objspace_ptr)
4403{
4404 rb_objspace_t *objspace = objspace_ptr;
4405
4406 for (size_t i = 0; i < rb_darray_size(objspace->heap_pages.sorted); i++) {
4407 struct heap_page *page = rb_darray_get(objspace->heap_pages.sorted, i);
4408 short stride = page->slot_size;
4409
4410 uintptr_t p = (uintptr_t)page->start;
4411 uintptr_t pend = p + page->total_slots * stride;
4412 for (; p < pend; p += stride) {
4413 VALUE vp = (VALUE)p;
4414 asan_unpoisoning_object(vp) {
4415 if (RB_BUILTIN_TYPE(vp) != T_NONE) {
4416 rb_gc_obj_free_vm_weak_references(vp);
4417 if (gc_obj_free(objspace, vp)) {
4418 RBASIC(vp)->flags = 0;
4419 }
4420 }
4421 }
4422 }
4423 }
4424}
4425
4426static int
4427rb_gc_impl_shutdown_call_finalizer_i(st_data_t key, st_data_t val, st_data_t _data)
4428{
4429 VALUE obj = (VALUE)key;
4430 VALUE table = (VALUE)val;
4431
4432 GC_ASSERT(RB_FL_TEST(obj, FL_FINALIZE));
4433 GC_ASSERT(RB_BUILTIN_TYPE(val) == T_ARRAY);
4434
4435 rb_gc_run_obj_finalizer(RARRAY_AREF(table, 0), RARRAY_LEN(table) - 1, get_final, (void *)table);
4436
4437 FL_UNSET(obj, FL_FINALIZE);
4438
4439 return ST_DELETE;
4440}
4441
4442void
4443rb_gc_impl_shutdown_call_finalizer(void *objspace_ptr)
4444{
4445 rb_objspace_t *objspace = objspace_ptr;
4446
4447#if RGENGC_CHECK_MODE >= 2
4448 gc_verify_internal_consistency(objspace);
4449#endif
4450
4451 /* prohibit incremental GC */
4452 objspace->flags.dont_incremental = 1;
4453
4454 if (RUBY_ATOMIC_EXCHANGE(finalizing, 1)) {
4455 /* Abort incremental marking and lazy sweeping to speed up shutdown. */
4456 gc_abort(objspace);
4457 dont_gc_on();
4458 return;
4459 }
4460
4461 while (finalizer_table->num_entries) {
4462 st_foreach(finalizer_table, rb_gc_impl_shutdown_call_finalizer_i, 0);
4463 }
4464
4465 /* run finalizers */
4466 finalize_deferred(objspace);
4467 GC_ASSERT(heap_pages_deferred_final == 0);
4468
4469 /* Deferred non-thread-safe frees: their objects are long gone, so the object walk
4470 * below will not reach them. Reap them here. */
4471 gc_tdata_unsafe_drain_objspaces(&objspace, 1);
4472
4473 /* Abort incremental marking and lazy sweeping to speed up shutdown. */
4474 gc_abort(objspace);
4475
4476 /* prohibit GC because force T_DATA finalizers can break an object graph consistency */
4477 dont_gc_on();
4478
4479 /* running data/file finalizers are part of garbage collection */
4480 unsigned int lock_lev;
4481 gc_enter(objspace, gc_enter_event_finalizer, &lock_lev);
4482
4483 /* run data/file object's finalizers */
4484 for (size_t i = 0; i < rb_darray_size(objspace->heap_pages.sorted); i++) {
4485 struct heap_page *page = rb_darray_get(objspace->heap_pages.sorted, i);
4486 short stride = page->slot_size;
4487
4488 uintptr_t p = (uintptr_t)page->start;
4489 uintptr_t pend = p + page->total_slots * stride;
4490 for (; p < pend; p += stride) {
4491 VALUE vp = (VALUE)p;
4492 asan_unpoisoning_object(vp) {
4493 if (rb_gc_shutdown_call_finalizer_p(vp)) {
4494 rb_gc_obj_free_vm_weak_references(vp);
4495 if (gc_obj_free(objspace, vp)) {
4496 RBASIC(vp)->flags = 0;
4497 }
4498 }
4499 }
4500 }
4501 }
4502
4503 gc_exit(objspace, gc_enter_event_finalizer, &lock_lev);
4504
4505 finalize_zombies(objspace);
4506
4507 st_free_table(finalizer_table);
4508 finalizer_table = 0;
4509 RUBY_ATOMIC_SET(finalizing, 0);
4510}
4511
4512void
4513rb_gc_impl_each_object(void *objspace_ptr, void (*func)(VALUE obj, void *data), void *data)
4514{
4515 rb_objspace_t *objspace = objspace_ptr;
4516
4517 for (size_t i = 0; i < rb_darray_size(objspace->heap_pages.sorted); i++) {
4518 struct heap_page *page = rb_darray_get(objspace->heap_pages.sorted, i);
4519 short stride = page->slot_size;
4520
4521 uintptr_t p = (uintptr_t)page->start;
4522 uintptr_t pend = p + page->total_slots * stride;
4523 for (; p < pend; p += stride) {
4524 VALUE obj = (VALUE)p;
4525
4526 asan_unpoisoning_object(obj) {
4527 func(obj, data);
4528 }
4529 }
4530 }
4531}
4532
4533/*
4534 ------------------------ Garbage Collection ------------------------
4535*/
4536
4537/* Sweeping */
4538
4539static size_t
4540objspace_available_slots(rb_objspace_t *objspace)
4541{
4542 size_t total_slots = 0;
4543 for (int i = 0; i < HEAP_COUNT; i++) {
4544 rb_heap_t *heap = &heaps[i];
4545 total_slots += heap->total_slots;
4546 }
4547 return total_slots;
4548}
4549
4550static size_t
4551objspace_live_slots(rb_objspace_t *objspace)
4552{
4553 return total_allocated_objects(objspace) - total_freed_objects(objspace) - total_final_slots_count(objspace);
4554}
4555
4556static size_t
4557objspace_free_slots(rb_objspace_t *objspace)
4558{
4559 return objspace_available_slots(objspace) - objspace_live_slots(objspace) - total_final_slots_count(objspace);
4560}
4561
4562static void
4563gc_setup_mark_bits(struct heap_page *page)
4564{
4565 /* copy oldgen bitmap to mark bitmap */
4566 memcpy(&page->mark_bits[0], &page->uncollectible_bits[0], HEAP_PAGE_BITMAP_SIZE);
4567}
4568
4569static int gc_is_moveable_obj(rb_objspace_t *objspace, VALUE obj);
4570static VALUE gc_move(rb_objspace_t *objspace, VALUE scan, VALUE free, struct heap_page *src_page, struct heap_page *dest_page);
4571
4572#if defined(_WIN32)
4573enum {HEAP_PAGE_LOCK = PAGE_NOACCESS, HEAP_PAGE_UNLOCK = PAGE_READWRITE};
4574
4575static BOOL
4576protect_page_body(struct heap_page_body *body, DWORD protect)
4577{
4578 DWORD old_protect;
4579 return VirtualProtect(body, HEAP_PAGE_SIZE, protect, &old_protect) != 0;
4580}
4581#elif defined(__wasi__)
4582// wasi-libc's mprotect emulation does not support PROT_NONE
4583enum {HEAP_PAGE_LOCK, HEAP_PAGE_UNLOCK};
4584#define protect_page_body(body, protect) 1
4585#else
4586enum {HEAP_PAGE_LOCK = PROT_NONE, HEAP_PAGE_UNLOCK = PROT_READ | PROT_WRITE};
4587#define protect_page_body(body, protect) !mprotect((body), HEAP_PAGE_SIZE, (protect))
4588#endif
4589
4590static void
4591lock_page_body(rb_objspace_t *objspace, struct heap_page_body *body)
4592{
4593 if (!protect_page_body(body, HEAP_PAGE_LOCK)) {
4594 rb_bug("Couldn't protect page %p, errno: %s", (void *)body, strerror(errno));
4595 }
4596 else {
4597 gc_report(5, objspace, "Protecting page in move %p\n", (void *)body);
4598 }
4599}
4600
4601static void
4602unlock_page_body(rb_objspace_t *objspace, struct heap_page_body *body)
4603{
4604 if (!protect_page_body(body, HEAP_PAGE_UNLOCK)) {
4605 rb_bug("Couldn't unprotect page %p, errno: %s", (void *)body, strerror(errno));
4606 }
4607 else {
4608 gc_report(5, objspace, "Unprotecting page in move %p\n", (void *)body);
4609 }
4610}
4611
4612static uintptr_t
4613heap_page_alloc_slot_from_region(struct heap_page *free_page)
4614{
4615 asan_unlock_freelist(free_page);
4616 struct free_region *region = free_page->free_region;
4617 asan_lock_freelist(free_page);
4618
4619 if (region == NULL) {
4620 return 0;
4621 }
4622
4623 rb_asan_unpoison_object((VALUE)region, false);
4624 GC_ASSERT(RB_TYPE_P((VALUE)region, T_NONE));
4625 uintptr_t dest = (uintptr_t)region;
4626 uintptr_t region_end = region->end;
4627 struct free_region *next = region->next;
4628
4629 uintptr_t new_start = dest + free_page->slot_size;
4630
4631 asan_unlock_freelist(free_page);
4632 if (new_start < region_end) {
4633 VALUE next_start = (VALUE)new_start;
4634 rb_asan_unpoison_object(next_start, false);
4635 struct free_region *new_region = (struct free_region *)new_start;
4636 new_region->flags = 0;
4637 new_region->end = region_end;
4638 new_region->next = next;
4639 rb_asan_poison_object(next_start);
4640 free_page->free_region = new_region;
4641 }
4642 else {
4643 free_page->free_region = next;
4644 }
4645 asan_lock_freelist(free_page);
4646
4647 return dest;
4648}
4649
4650static bool
4651try_move(rb_objspace_t *objspace, rb_heap_t *heap, struct heap_page *free_page, VALUE src)
4652{
4653 GC_ASSERT(gc_is_moveable_obj(objspace, src));
4654
4655 struct heap_page *src_page = GET_HEAP_PAGE(src);
4656 if (!free_page) {
4657 return false;
4658 }
4659
4660 /* We should return true if either src is successfully moved, or src is
4661 * unmoveable. A false return will cause the sweeping cursor to be
4662 * incremented to the next page, and src will attempt to move again */
4663 GC_ASSERT(RVALUE_MARKED(objspace, src));
4664
4665 uintptr_t dest_slot = heap_page_alloc_slot_from_region(free_page);
4666 if (dest_slot == 0) {
4667 return false;
4668 }
4669 VALUE dest = (VALUE)dest_slot;
4670
4671 GC_ASSERT(RB_BUILTIN_TYPE(dest) == T_NONE);
4672
4673 if (src_page->slot_size > free_page->slot_size) {
4674 objspace->rcompactor.moved_down_count_table[BUILTIN_TYPE(src)]++;
4675 }
4676 else if (free_page->slot_size > src_page->slot_size) {
4677 objspace->rcompactor.moved_up_count_table[BUILTIN_TYPE(src)]++;
4678 }
4679 objspace->rcompactor.moved_count_table[BUILTIN_TYPE(src)]++;
4680 objspace->rcompactor.total_moved++;
4681
4682 gc_move(objspace, src, dest, src_page, free_page);
4683 gc_pin(objspace, src);
4684 free_page->free_slots--;
4685
4686 return true;
4687}
4688
4689static void
4690gc_unprotect_pages(rb_objspace_t *objspace, rb_heap_t *heap)
4691{
4692 struct heap_page *cursor = heap->compact_cursor;
4693
4694 while (cursor) {
4695 unlock_page_body(objspace, cursor->body);
4696 cursor = ccan_list_next(&heap->pages, cursor, page_node);
4697 }
4698}
4699
4700static void gc_update_references(rb_objspace_t *objspace);
4701static void gc_update_references_heap(rb_objspace_t *objspace);
4702static void gc_update_references_global(rb_objspace_t *objspace);
4703#if GC_CAN_COMPILE_COMPACTION
4704static void invalidate_moved_page(rb_objspace_t *objspace, struct heap_page *page);
4705#endif
4706
4707#if defined(__MINGW32__) || defined(_WIN32)
4708# define GC_COMPACTION_SUPPORTED 1
4709#else
4710/* If not MinGW, Windows, or does not have mmap, we cannot use mprotect for
4711 * the read barrier, so we must disable compaction. */
4712# define GC_COMPACTION_SUPPORTED (GC_CAN_COMPILE_COMPACTION && HEAP_PAGE_ALLOC_USE_MMAP)
4713#endif
4714
4715#if GC_CAN_COMPILE_COMPACTION
4716static void
4717read_barrier_handler(uintptr_t address)
4718{
4719 rb_objspace_t *objspace = (rb_objspace_t *)rb_gc_get_objspace();
4720
4721 struct heap_page_body *page_body = GET_PAGE_BODY(address);
4722
4723 /* If the page_body is NULL, then mprotect cannot handle it and will crash
4724 * with "Cannot allocate memory". */
4725 if (page_body == NULL) {
4726 rb_bug("read_barrier_handler: segmentation fault at %p", (void *)address);
4727 }
4728
4729 int lev = RB_GC_VM_LOCK();
4730 {
4731 unlock_page_body(objspace, page_body);
4732
4733 objspace->profile.read_barrier_faults++;
4734
4735 invalidate_moved_page(objspace, GET_HEAP_PAGE(address));
4736 }
4737 RB_GC_VM_UNLOCK(lev);
4738}
4739#endif
4740
4741#if !GC_CAN_COMPILE_COMPACTION
4742static void
4743uninstall_handlers(void)
4744{
4745 /* no-op */
4746}
4747
4748static void
4749install_handlers(void)
4750{
4751 /* no-op */
4752}
4753#elif defined(_WIN32)
4754static LPTOP_LEVEL_EXCEPTION_FILTER old_handler;
4755typedef void (*signal_handler)(int);
4756static signal_handler old_sigsegv_handler;
4757
4758static LONG WINAPI
4759read_barrier_signal(EXCEPTION_POINTERS *info)
4760{
4761 /* EXCEPTION_ACCESS_VIOLATION is what's raised by access to protected pages */
4762 if (info->ExceptionRecord->ExceptionCode == EXCEPTION_ACCESS_VIOLATION) {
4763 /* > The second array element specifies the virtual address of the inaccessible data.
4764 * https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-exception_record
4765 *
4766 * Use this address to invalidate the page */
4767 read_barrier_handler((uintptr_t)info->ExceptionRecord->ExceptionInformation[1]);
4768 return EXCEPTION_CONTINUE_EXECUTION;
4769 }
4770 else {
4771 return EXCEPTION_CONTINUE_SEARCH;
4772 }
4773}
4774
4775static void
4776uninstall_handlers(void)
4777{
4778 signal(SIGSEGV, old_sigsegv_handler);
4779 SetUnhandledExceptionFilter(old_handler);
4780}
4781
4782static void
4783install_handlers(void)
4784{
4785 /* Remove SEGV handler so that the Unhandled Exception Filter handles it */
4786 old_sigsegv_handler = signal(SIGSEGV, NULL);
4787 /* Unhandled Exception Filter has access to the violation address similar
4788 * to si_addr from sigaction */
4789 old_handler = SetUnhandledExceptionFilter(read_barrier_signal);
4790}
4791#else
4792static struct sigaction old_sigbus_handler;
4793static struct sigaction old_sigsegv_handler;
4794
4795#ifdef HAVE_MACH_TASK_EXCEPTION_PORTS
4796static exception_mask_t old_exception_masks[32];
4797static mach_port_t old_exception_ports[32];
4798static exception_behavior_t old_exception_behaviors[32];
4799static thread_state_flavor_t old_exception_flavors[32];
4800static mach_msg_type_number_t old_exception_count;
4801
4802static void
4803disable_mach_bad_access_exc(void)
4804{
4805 old_exception_count = sizeof(old_exception_masks) / sizeof(old_exception_masks[0]);
4806 task_swap_exception_ports(
4807 mach_task_self(), EXC_MASK_BAD_ACCESS,
4808 MACH_PORT_NULL, EXCEPTION_DEFAULT, 0,
4809 old_exception_masks, &old_exception_count,
4810 old_exception_ports, old_exception_behaviors, old_exception_flavors
4811 );
4812}
4813
4814static void
4815restore_mach_bad_access_exc(void)
4816{
4817 for (mach_msg_type_number_t i = 0; i < old_exception_count; i++) {
4818 task_set_exception_ports(
4819 mach_task_self(),
4820 old_exception_masks[i], old_exception_ports[i],
4821 old_exception_behaviors[i], old_exception_flavors[i]
4822 );
4823 }
4824}
4825#endif
4826
4827#if defined(HAVE_PTHREAD_SIGMASK)
4828# define gc_sigmask pthread_sigmask
4829#else
4830# define gc_sigmask sigprocmask
4831#endif
4832
4833static void
4834read_barrier_signal(int sig, siginfo_t *info, void *data)
4835{
4836 // setup SEGV/BUS handlers for errors
4837 struct sigaction prev_sigbus, prev_sigsegv;
4838 sigaction(SIGBUS, &old_sigbus_handler, &prev_sigbus);
4839 sigaction(SIGSEGV, &old_sigsegv_handler, &prev_sigsegv);
4840
4841 // enable SIGBUS/SEGV
4842 sigset_t set, prev_set;
4843 sigemptyset(&set);
4844 sigaddset(&set, SIGBUS);
4845 sigaddset(&set, SIGSEGV);
4846 gc_sigmask(SIG_UNBLOCK, &set, &prev_set);
4847#ifdef HAVE_MACH_TASK_EXCEPTION_PORTS
4848 disable_mach_bad_access_exc();
4849#endif
4850 // run handler
4851 read_barrier_handler((uintptr_t)info->si_addr);
4852
4853 // reset SEGV/BUS handlers
4854#ifdef HAVE_MACH_TASK_EXCEPTION_PORTS
4855 restore_mach_bad_access_exc();
4856#endif
4857 sigaction(SIGBUS, &prev_sigbus, NULL);
4858 sigaction(SIGSEGV, &prev_sigsegv, NULL);
4859 gc_sigmask(SIG_SETMASK, &prev_set, NULL);
4860}
4861
4862static void
4863uninstall_handlers(void)
4864{
4865#ifdef HAVE_MACH_TASK_EXCEPTION_PORTS
4866 restore_mach_bad_access_exc();
4867#endif
4868 sigaction(SIGBUS, &old_sigbus_handler, NULL);
4869 sigaction(SIGSEGV, &old_sigsegv_handler, NULL);
4870}
4871
4872static void
4873install_handlers(void)
4874{
4875 struct sigaction action;
4876 memset(&action, 0, sizeof(struct sigaction));
4877 sigemptyset(&action.sa_mask);
4878 action.sa_sigaction = read_barrier_signal;
4879 action.sa_flags = SA_SIGINFO | SA_ONSTACK;
4880
4881 sigaction(SIGBUS, &action, &old_sigbus_handler);
4882 sigaction(SIGSEGV, &action, &old_sigsegv_handler);
4883#ifdef HAVE_MACH_TASK_EXCEPTION_PORTS
4884 disable_mach_bad_access_exc();
4885#endif
4886}
4887#endif
4888
4889static void
4890gc_compact_finish(rb_objspace_t *objspace)
4891{
4892 for (int i = 0; i < HEAP_COUNT; i++) {
4893 rb_heap_t *heap = &heaps[i];
4894 gc_unprotect_pages(objspace, heap);
4895 }
4896
4897 if (!global_objspace->global_gc.compacting) uninstall_handlers();
4898
4899 if (global_objspace->global_gc.compacting) {
4900 /* In a compacting global GC this updates only this objspace's heap references;
4901 * gc_start_global sets during_reference_updating on every objspace (the
4902 * move-or-mark decision reads it via rb_gc_get_objspace()) and runs the
4903 * non-idempotent VM-global side (gc_update_references_global) once at the end. */
4904 gc_update_references_heap(objspace);
4905 }
4906 else {
4907 gc_update_references(objspace);
4908 }
4909 objspace->profile.compact_count++;
4910
4911 for (int i = 0; i < HEAP_COUNT; i++) {
4912 rb_heap_t *heap = &heaps[i];
4913 heap->compact_cursor = NULL;
4914 heap->free_pages = NULL;
4915 heap->compact_cursor_index = 0;
4916 }
4917
4918 if (gc_prof_enabled(objspace)) {
4919 gc_profile_record *record = gc_prof_record(objspace);
4920 record->moved_objects = objspace->rcompactor.total_moved - record->moved_objects;
4921 }
4922 if (!global_objspace->global_gc.compacting) objspace->flags.during_compacting = FALSE;
4923}
4924
4926 struct heap_page *page;
4927 int final_slots;
4928 int freed_slots;
4929 int empty_slots;
4930 /* Hoisted out of the per-slot pinned-free assert: too expensive for the sweep loop
4931 * as an external call. */
4932 const bool check_pinned_free;
4933 /* This is a parallel local sweep (multi-Ractor, not a global GC), so a non-thread-safe
4934 * T_DATA dfree must be deferred to the global GC or the postponed job rather than run here. */
4935 const bool defer_thread_unsafe_local_sweep;
4936 bool trigger_thread_unsafe_sweep_postponed_job;
4937
4938 struct free_region *free_region;
4939};
4940
4941/* NOTE: We must free the root fiber during postmortem collection, otherwise another Ractor
4942 * can collect the fiber through a major GC while we're still tearing it down. Once fibers are
4943 * THREAD_SAFE_FREE, we no longer need the root fiber condition as it will be guaranteed to be
4944 * collected during this time. */
4945static bool
4946gc_obj_defer_local_free_p(rb_objspace_t *objspace, VALUE obj)
4947{
4948 if (BUILTIN_TYPE(obj) != T_DATA) return false;
4949
4950 const rb_data_type_t *type = RTYPEDDATA_TYPE(obj);
4951 if (!rb_gc_data_type_deferred_free_p(type)) return false;
4952
4953 if (RTYPEDDATA_GET_DATA(obj) == NULL) return false;
4954
4955 if (type->flags & RUBY_TYPED_FREE_IMMEDIATELY) {
4956 if (objspace->flags.during_postmortem) {
4957 if (rb_fiber_current() == obj) {
4958 return false;
4959 }
4960 }
4961 return true;
4962 }
4963 else {
4964 return false;
4965 }
4966}
4967
4968static void gc_tdata_deferred_free_job(void *unused);
4969static void gc_tdata_deferred_free_pjob_ensure(void);
4970static unsigned int gc_during_gc_get(const rb_objspace_t *objspace);
4971static void gc_during_gc_set(rb_objspace_t *objspace, unsigned int v);
4972static void gc_global_snapshot_objspaces(void);
4973
4974static void
4975gc_tdata_deferred_free_pjob_ensure(void)
4976{
4977 if (global_objspace->tdata_deferred_free_pjob == POSTPONED_JOB_HANDLE_INVALID) {
4978 global_objspace->tdata_deferred_free_pjob =
4979 rb_postponed_job_preregister(0, gc_tdata_deferred_free_job, NULL);
4980 if (global_objspace->tdata_deferred_free_pjob == POSTPONED_JOB_HANDLE_INVALID) {
4981 rb_bug("Could not preregister postponed job for deferred T_DATA free");
4982 }
4983 }
4984}
4985
4986/* A terminating Ractor's postmortem collection runs on an EC whose stack is already
4987 * torn down: it never checks interrupts again, so a job triggered there is lost and no
4988 * later sweep can rediscover the entries. Hand those to the main Ractor. */
4989static void
4990gc_tdata_deferred_free_trigger(rb_objspace_t *objspace)
4991{
4992 if (objspace->flags.during_postmortem) {
4993 rb_gc_trigger_postponed_job_on_main(global_objspace->tdata_deferred_free_pjob);
4994 }
4995 else {
4996 rb_postponed_job_trigger(global_objspace->tdata_deferred_free_pjob);
4997 }
4998}
4999
5000static void
5001gc_tdata_unsafe_free_entry(const struct tdata_unsafe_free_entry *entry, bool embed_xfree)
5002{
5003 entry->dfree(entry->data);
5004 if (embed_xfree) {
5005 xfree(entry->data);
5006 }
5007}
5008
5009static void
5010tdata_unsafe_free_chunk_recycle(struct tdata_unsafe_free_chunk *chunk)
5011{
5012 if (global_objspace->tdata_unsafe_free_cache_len >= TDATA_UNSAFE_FREE_CACHE_MAX) {
5013 free(chunk);
5014 return;
5015 }
5016 tdata_unsafe_free_chunk_reset(chunk);
5017 chunk->next = global_objspace->tdata_unsafe_free_cache;
5018 rbimpl_atomic_ptr_store((volatile void **)&global_objspace->tdata_unsafe_free_cache, chunk,
5019 RBIMPL_ATOMIC_RELEASE);
5020 global_objspace->tdata_unsafe_free_cache_len++;
5021}
5022
5023static void
5024gc_tdata_unsafe_drain_chunk(struct tdata_unsafe_free_chunk *chunk)
5025{
5026 for (unsigned int i = 0; i < chunk->count; i++) {
5027 gc_tdata_unsafe_free_entry(&chunk->entries[i],
5028 (chunk->embed_xfree_bits >> i) & 1);
5029 }
5030 tdata_unsafe_free_chunk_recycle(chunk);
5031}
5032
5033/* Run every pending deferred free: the published chunks (which belong to no objspace)
5034 * plus the given objspaces' partial chunks. The caller must have stopped the world --
5035 * VM barrier held, or a single Ractor left in the process -- and must pass every live
5036 * objspace, since the pending count is zeroed here. (Shutdown is the one exception:
5037 * nothing reads the count afterwards.) */
5038static void
5039gc_tdata_unsafe_drain_objspaces(rb_objspace_t **objspaces, size_t n)
5040{
5041 struct tdata_unsafe_free_chunk *chunk =
5042 rbimpl_atomic_ptr_exchange((void **)&global_objspace->tdata_unsafe_free_published, NULL,
5043 RBIMPL_ATOMIC_ACQ_REL);
5044 while (chunk) {
5045 struct tdata_unsafe_free_chunk *next = chunk->next;
5046 gc_tdata_unsafe_drain_chunk(chunk);
5047 chunk = next;
5048 }
5049
5050 for (size_t i = 0; i < n; i++) {
5051 rb_objspace_t *os = objspaces[i];
5052 struct tdata_unsafe_free_chunk *partial = os->tdata_unsafe_free_chunk;
5053 if (partial) {
5054 os->tdata_unsafe_free_chunk = NULL;
5055 gc_tdata_unsafe_drain_chunk(partial);
5056 }
5057 }
5058
5059 rbimpl_atomic_size_exchange(&global_objspace->tdata_deferred_free_count, 0,
5060 RBIMPL_ATOMIC_RELAXED);
5061}
5062
5063/* Stop the world and run the dfree function for all deferred T_DATAs. */
5064static void
5065gc_tdata_unsafe_drain(void)
5066{
5067 unsigned int lev = RB_GC_VM_LOCK();
5068
5069 if (tdata_deferred_free_count_load() == 0) {
5070 RB_GC_VM_UNLOCK(lev);
5071 return;
5072 }
5073
5074 rb_gc_vm_barrier();
5075
5076 gc_global_snapshot_objspaces();
5077
5078 /* Set during_gc=TRUE and init vm_context for the CURRENT objspace only.
5079 * The no-alloc guard checks only the allocating (=current) objspace's during_gc,
5080 * and rb_gc_get_ec() reads only the current objspace's vm_context.ec. */
5081 rb_objspace_t *objspace = rb_gc_get_objspace();
5082 unsigned int saved_during_gc = gc_during_gc_get(objspace);
5083 dont_gc_on();
5084 rb_gc_initialize_vm_context(&objspace->vm_context);
5085 gc_during_gc_set(objspace, TRUE);
5086
5087 gc_tdata_unsafe_drain_objspaces(global_objspace->global_gc.objspaces,
5088 global_objspace->global_gc.n_objspaces);
5089
5090 gc_during_gc_set(objspace, saved_during_gc);
5091 dont_gc_off();
5092
5093 RB_GC_VM_UNLOCK(lev);
5094}
5095
5096static void
5097gc_tdata_deferred_free_job(void *unused)
5098{
5099 (void)unused;
5100
5101 size_t count = tdata_deferred_free_count_load();
5102 if (count == 0) return;
5103 if (count < TDATA_DEFERRED_FREE_THRESHOLD && !rb_gc_single_objspace_p()) return;
5104
5105 gc_tdata_unsafe_drain();
5106}
5107
5108static inline void
5109gc_sweep_register_free_slot(rb_objspace_t *objspace, struct heap_page *page, struct gc_sweep_context *ctx, uintptr_t p, short slot_size)
5110{
5111 rb_asan_unpoison_object(p, false);
5112 ((struct RBasic *)p)->flags = 0;
5113
5114 /* Keep a freed slot from carrying its old shareable and shref bits into the next
5115 * object born there; the actual clear happens per bitmap word at the end of
5116 * gc_sweep_page rather than per slot. */
5117
5118 struct free_region *existing_region = ctx->free_region;
5119 if (existing_region) rb_asan_unpoison_object((VALUE)existing_region, false);
5120
5121 if (RB_LIKELY(existing_region && p == existing_region->end)) {
5122 existing_region->end = p + slot_size;
5123 }
5124 else {
5125 struct free_region *free_region = (struct free_region *)p;
5126 free_region->end = p + slot_size;
5127 free_region->next = existing_region;
5128
5129 ctx->free_region = free_region;
5130 }
5131
5132 if (existing_region) rb_asan_poison_object((VALUE)existing_region);
5133 rb_asan_poison_object(p);
5134}
5135
5136static inline void
5137gc_sweep_plane(rb_objspace_t *objspace, rb_heap_t *heap, uintptr_t p, bits_t bitset, struct gc_sweep_context *ctx)
5138{
5139 struct heap_page *sweep_page = ctx->page;
5140 short slot_size = sweep_page->slot_size;
5141
5142 do {
5143 VALUE vp = (VALUE)p;
5144 GC_ASSERT(vp % sizeof(VALUE) == 0);
5145
5146 rb_asan_unpoison_object(vp, false);
5147 if (bitset & 1) {
5148 switch (BUILTIN_TYPE(vp)) {
5149 case T_MOVED:
5150 if (objspace->flags.during_compacting) {
5151 /* The sweep cursor shouldn't have made it to any
5152 * T_MOVED slots while the compact flag is enabled.
5153 * The sweep cursor and compact cursor move in
5154 * opposite directions, and when they meet references will
5155 * get updated and "during_compacting" should get disabled */
5156 rb_bug("T_MOVED shouldn't be seen until compaction is finished");
5157 }
5158 gc_report(3, objspace, "page_sweep: %s is freed\n", rb_obj_info(vp));
5159 ctx->empty_slots++;
5160 gc_sweep_register_free_slot(objspace, sweep_page, ctx, p, slot_size);
5161 break;
5162 case T_ZOMBIE:
5163 /* already counted */
5164 break;
5165 case T_NONE:
5166 ctx->empty_slots++; /* already freed */
5167 gc_sweep_register_free_slot(objspace, sweep_page, ctx, p, slot_size);
5168 break;
5169
5170 default:
5171#if RGENGC_CHECK_MODE
5172 /* A local GC must never free a pinned slot; a global GC may (its exact
5173 * mark collects dead shareable objects). Reading the bits here is
5174 * CHECK-only and still valid: the bulk clear runs after the free loop. */
5175 if (ctx->check_pinned_free &&
5176 (MARKED_IN_BITMAP(GET_HEAP_SHAREABLE_BITS(vp), vp) ||
5177 MARKED_IN_BITMAP(GET_HEAP_SHREF_BITS(vp), vp))) {
5178 rb_bug("page_sweep: freeing pinned slot %s (shareable=%d shref=%d single_now=%d)",
5179 rb_obj_info(vp),
5180 (int)!!MARKED_IN_BITMAP(GET_HEAP_SHAREABLE_BITS(vp), vp),
5181 (int)!!MARKED_IN_BITMAP(GET_HEAP_SHREF_BITS(vp), vp),
5182 (int)rb_gc_single_objspace_p());
5183 }
5184#endif
5185#if RGENGC_CHECK_MODE
5186 if (!is_full_marking(objspace)) {
5187 if (RVALUE_OLD_P(objspace, vp)) rb_bug("page_sweep: %p - old while minor GC.", (void *)p);
5188 if (RVALUE_REMEMBERED(objspace, vp)) rb_bug("page_sweep: %p - remembered.", (void *)p);
5189 }
5190#endif
5191
5192#if RGENGC_CHECK_MODE
5193#define CHECK(x) if (x(objspace, vp) != FALSE) rb_bug("obj_free: " #x "(%s) != FALSE", rb_obj_info(vp))
5194 CHECK(RVALUE_WB_UNPROTECTED);
5195 CHECK(RVALUE_MARKED);
5196 CHECK(RVALUE_MARKING);
5197 CHECK(RVALUE_UNCOLLECTIBLE);
5198#undef CHECK
5199#endif
5200
5201 if (!rb_gc_obj_needs_cleanup_p(vp)) {
5202 (void)VALGRIND_MAKE_MEM_UNDEFINED((void*)p, slot_size);
5203 gc_sweep_register_free_slot(objspace, sweep_page, ctx, p, slot_size);
5204 gc_report(3, objspace, "page_sweep: %s (fast path) is freed\n", rb_obj_info(vp));
5205 ctx->freed_slots++;
5206 }
5207 else {
5208 gc_report(2, objspace, "page_sweep: free %p\n", (void *)p);
5209
5210 if (RB_UNLIKELY(ctx->defer_thread_unsafe_local_sweep && gc_obj_defer_local_free_p(objspace, vp))) {
5211 /* Defer the dfree instead of running it here: it needs the world
5212 * stopped, which a parallel local sweep cannot give it. The slot is reusable
5213 * right away unless we had to create a zombie. */
5214 if (gc_defer_thread_unsafe_free(objspace, vp,
5215 &ctx->trigger_thread_unsafe_sweep_postponed_job)) {
5216 (void)VALGRIND_MAKE_MEM_UNDEFINED((void*)p, slot_size);
5217 gc_sweep_register_free_slot(objspace, sweep_page, ctx, p, slot_size);
5218 ctx->freed_slots++;
5219 }
5220 else {
5221 ctx->final_slots++;
5222 }
5223 break;
5224 }
5225 rb_gc_obj_free_vm_weak_references(vp);
5226 if (gc_obj_free(objspace, vp)) {
5227 (void)VALGRIND_MAKE_MEM_UNDEFINED((void*)p, slot_size);
5228 gc_sweep_register_free_slot(objspace, sweep_page, ctx, p, slot_size);
5229 gc_report(3, objspace, "page_sweep: %s is freed\n", rb_obj_info(vp));
5230 ctx->freed_slots++;
5231 }
5232 else {
5233 ctx->final_slots++;
5234 }
5235 }
5236 break;
5237 }
5238 }
5239 p += slot_size;
5240 bitset >>= 1;
5241 } while (bitset);
5242}
5243
5244static inline void
5245gc_sweep_page(rb_objspace_t *objspace, rb_heap_t *heap, struct gc_sweep_context *ctx)
5246{
5247 struct heap_page *sweep_page = ctx->page;
5248 GC_ASSERT(sweep_page->heap == heap);
5249
5250 uintptr_t p;
5251 bits_t *bits, bitset;
5252
5253 gc_report(2, objspace, "page_sweep: start.\n");
5254
5255#if RGENGC_CHECK_MODE
5256 if (!objspace->flags.immediate_sweep) {
5257 GC_ASSERT(sweep_page->flags.before_sweep == TRUE);
5258 }
5259#endif
5260 sweep_page->flags.before_sweep = FALSE;
5261 sweep_page->free_slots = 0;
5262
5263 asan_unlock_freelist(sweep_page);
5264 sweep_page->free_region = NULL;
5265 asan_lock_freelist(sweep_page);
5266 ctx->free_region = NULL;
5267
5268 p = (uintptr_t)sweep_page->start;
5269 bits = sweep_page->mark_bits;
5270 short slot_size = sweep_page->slot_size;
5271 int total_slots = sweep_page->total_slots;
5272 int bitmap_plane_count = CEILDIV(total_slots, BITS_BITLENGTH);
5273
5274 int out_of_range_bits = total_slots % BITS_BITLENGTH;
5275 if (out_of_range_bits != 0) {
5276 bits[bitmap_plane_count - 1] |= ~(((bits_t)1 << out_of_range_bits) - 1);
5277 }
5278
5279 // Clear wb_unprotected and age bits for all unmarked slots
5280 {
5281 bits_t *wb_unprotected_bits = sweep_page->wb_unprotected_bits;
5282 bits_t *age_bits = sweep_page->age_bits;
5283 for (int i = 0; i < bitmap_plane_count; i++) {
5284 bits_t unmarked = ~bits[i];
5285 wb_unprotected_bits[i] &= ~unmarked;
5286 age_bits[i * 2] &= ~unmarked;
5287 age_bits[i * 2 + 1] &= ~unmarked;
5288 }
5289 }
5290
5291 for (int i = 0; i < bitmap_plane_count; i++) {
5292 bitset = ~bits[i];
5293 if (bitset) {
5294 gc_sweep_plane(objspace, heap, p, bitset, ctx);
5295 }
5296 p += BITS_BITLENGTH * slot_size;
5297 }
5298
5299 /* Bulk-clear the freed slots' shareable and shref bits before the freelist is
5300 * published, so a reused slot is clean. Freed slots are exactly the unmarked ones,
5301 * so `bits &= mark_bits` keeps live shareable objects (which must stay pinned) and
5302 * drops the rest. Pages with neither bit are skipped. */
5303 if (sweep_page->flags.has_shareable_objects || sweep_page->flags.has_shref_objects) {
5304 bits_t *shareable_bits = sweep_page->shareable_bits;
5305 bits_t *shref_bits = sweep_page->shref_bits;
5306 bits_t sh = 0, sr = 0;
5307 for (int i = 0; i < bitmap_plane_count; i++) {
5308 shareable_bits[i] &= bits[i];
5309 shref_bits[i] &= bits[i];
5310 sh |= shareable_bits[i];
5311 sr |= shref_bits[i];
5312 }
5313 if (!sh) sweep_page->flags.has_shareable_objects = FALSE;
5314 if (!sr) sweep_page->flags.has_shref_objects = FALSE;
5315 }
5316
5317 asan_unlock_freelist(sweep_page);
5318 sweep_page->free_region = ctx->free_region;
5319 asan_lock_freelist(sweep_page);
5320
5321 if (!heap->compact_cursor) {
5322 gc_setup_mark_bits(sweep_page);
5323 }
5324
5325#if GC_PROFILE_MORE_DETAIL
5326 if (gc_prof_enabled(objspace)) {
5327 gc_profile_record *record = gc_prof_record(objspace);
5328 record->removing_objects += ctx->final_slots + ctx->freed_slots;
5329 record->empty_objects += ctx->empty_slots;
5330 }
5331#endif
5332 if (0) fprintf(stderr, "gc_sweep_page(%"PRIdSIZE"): total_slots: %d, freed_slots: %d, empty_slots: %d, final_slots: %d\n",
5333 rb_gc_count(),
5334 sweep_page->total_slots,
5335 ctx->freed_slots, ctx->empty_slots, ctx->final_slots);
5336
5337 sweep_page->free_slots += ctx->freed_slots + ctx->empty_slots;
5338 sweep_page->heap->total_freed_objects += ctx->freed_slots;
5339
5340 if (heap_pages_deferred_final && !finalizing) {
5341 gc_finalize_deferred_register(objspace);
5342 }
5343
5344#if RGENGC_CHECK_MODE
5345 int region_slots = 0;
5346 asan_unlock_freelist(sweep_page);
5347 struct free_region *region = sweep_page->free_region;
5348 while (region) {
5349 rb_asan_unpoison_object((VALUE)region, false);
5350 GC_ASSERT(RB_TYPE_P((VALUE)region, T_NONE));
5351 uintptr_t region_start = (uintptr_t)region;
5352 uintptr_t region_end = region->end;
5353 struct free_region *next = region->next;
5354 rb_asan_poison_object((VALUE)region);
5355
5356 GC_ASSERT(region_end > region_start);
5357 GC_ASSERT((region_end - region_start) % slot_size == 0);
5358 region_slots += (int)((region_end - region_start) / slot_size);
5359
5360 region = next;
5361 }
5362 asan_lock_freelist(sweep_page);
5363 if (region_slots != sweep_page->free_slots) {
5364 rb_bug("inconsistent free region slots: expected %d but was %d", sweep_page->free_slots, region_slots);
5365 }
5366#endif
5367
5368 gc_report(2, objspace, "page_sweep: end.\n");
5369}
5370
5371static const char *
5372gc_mode_name(enum gc_mode mode)
5373{
5374 switch (mode) {
5375 case gc_mode_none: return "none";
5376 case gc_mode_marking: return "marking";
5377 case gc_mode_sweeping: return "sweeping";
5378 case gc_mode_compacting: return "compacting";
5379 default: rb_bug("gc_mode_name: unknown mode: %d", (int)mode);
5380 }
5381}
5382
5383static void
5384gc_mode_transition(rb_objspace_t *objspace, enum gc_mode mode)
5385{
5386#if RGENGC_CHECK_MODE
5387 enum gc_mode prev_mode = gc_mode(objspace);
5388 switch (prev_mode) {
5389 case gc_mode_none:
5390 /* A global GC marks every objspace as one heap (mark_roots on the driver), so an
5391 * individual objspace's mode stays `none` during that mark; the sweep inside the
5392 * barrier then makes the legitimate none -> sweeping transition. */
5393 GC_ASSERT(mode == gc_mode_marking ||
5394 (objspace->flags.during_global_gc && mode == gc_mode_sweeping));
5395 break;
5396 case gc_mode_marking: GC_ASSERT(mode == gc_mode_sweeping); break;
5397 case gc_mode_sweeping: GC_ASSERT(mode == gc_mode_none || mode == gc_mode_compacting); break;
5398 case gc_mode_compacting: GC_ASSERT(mode == gc_mode_none); break;
5399 }
5400#endif
5401 if (0) fprintf(stderr, "gc_mode_transition: %s->%s\n", gc_mode_name(gc_mode(objspace)), gc_mode_name(mode));
5402 gc_mode_set(objspace, mode);
5403}
5404
5405static void
5406heap_page_flush_alloc_regions(struct heap_page *page, rb_heap_t *heap)
5407{
5408 struct free_region *chain = heap->newobj.alloc_next_region;
5409
5410 if (heap->newobj.alloc_cursor < heap->newobj.alloc_cursor_end) {
5411 VALUE start = (VALUE)heap->newobj.alloc_cursor;
5412 rb_asan_unpoison_object(start, false);
5413 struct free_region *remnant = (struct free_region *)start;
5414 remnant->flags = 0;
5415 remnant->end = heap->newobj.alloc_cursor_end;
5416 remnant->next = chain;
5417 rb_asan_poison_object(start);
5418 chain = remnant;
5419 }
5420
5421 if (chain) {
5422 asan_unlock_freelist(page);
5423 if (page->free_region) {
5424 struct free_region *p = page->free_region;
5425 rb_asan_unpoison_object((VALUE)p, false);
5426 while (p->next) {
5427 struct free_region *prev = p;
5428 p = p->next;
5429 rb_asan_poison_object((VALUE)prev);
5430 rb_asan_unpoison_object((VALUE)p, false);
5431 }
5432 p->next = chain;
5433 rb_asan_poison_object((VALUE)p);
5434 }
5435 else {
5436 page->free_region = chain;
5437 }
5438 asan_lock_freelist(page);
5439 }
5440}
5441
5442static void
5443gc_sweep_start_heap(rb_objspace_t *objspace, rb_heap_t *heap)
5444{
5445 heap->sweeping_page = ccan_list_top(&heap->pages, struct heap_page, page_node);
5446 if (heap->sweeping_page) {
5447 objspace->sweeping_heap_count++;
5448 }
5449 heap->free_pages = NULL;
5450 heap->pooled_pages = NULL;
5451 if (!objspace->flags.immediate_sweep) {
5452 struct heap_page *page = NULL;
5453
5454 ccan_list_for_each(&heap->pages, page, page_node) {
5455 page->flags.before_sweep = TRUE;
5456 }
5457 }
5458}
5459
5460#if GC_CAN_COMPILE_COMPACTION
5461static void gc_sort_heap_by_compare_func(rb_objspace_t *objspace, gc_compact_compare_func compare_func);
5462static int compare_pinned_slots(const void *left, const void *right, void *d);
5463#endif
5464
5465/* Return the current allocation page and freelist to their pages, so the sweeper sees a
5466 * consistent heap. */
5467static void
5468heap_alloc_state_clear(rb_objspace_t *objspace)
5469{
5470 objspace->incremental_mark_step_allocated_slots = 0;
5471
5472 for (size_t heap_idx = 0; heap_idx < HEAP_COUNT; heap_idx++) {
5473 rb_heap_t *heap = &heaps[heap_idx];
5474
5475 struct heap_page *page = heap->newobj.alloc_using_page;
5476 RUBY_DEBUG_LOG("heap alloc_using_page:%p cursor:%p", (void *)page, (void *)heap->newobj.alloc_cursor);
5477
5478 if (page) {
5479 heap_page_flush_alloc_regions(page, heap);
5480 }
5481
5482 heap->newobj.alloc_using_page = NULL;
5483 heap->newobj.alloc_cursor = 0;
5484 heap->newobj.alloc_cursor_end = 0;
5485 heap->newobj.alloc_next_region = NULL;
5486 }
5487}
5488
5489static void
5490gc_sweep_freeobj_hooks_page(rb_objspace_t *objspace, struct heap_page *page)
5491{
5492 bits_t *bits = page->mark_bits;
5493 uintptr_t p = (uintptr_t)page->start;
5494 short slot_size = page->slot_size;
5495 int total_slots = page->total_slots;
5496 int bitmap_plane_count = CEILDIV(total_slots, BITS_BITLENGTH);
5497
5498 int out_of_range_bits = total_slots % BITS_BITLENGTH;
5499 bits_t last_plane_mask = (out_of_range_bits != 0)
5500 ? ~(((bits_t)1 << out_of_range_bits) - 1)
5501 : 0;
5502
5503 for (int j = 0; j < bitmap_plane_count; j++) {
5504 bits_t bitset = ~bits[j];
5505 if (j == bitmap_plane_count - 1) {
5506 bitset &= ~last_plane_mask;
5507 }
5508
5509 uintptr_t pp = p;
5510 while (bitset) {
5511 if (bitset & 1) {
5512 VALUE vp = (VALUE)pp;
5513 asan_unpoisoning_object(vp) {
5514 switch (BUILTIN_TYPE(vp)) {
5515 case T_NONE:
5516 case T_ZOMBIE:
5517 case T_MOVED:
5518 break;
5519 default:
5520 rb_gc_event_hook(vp, RUBY_INTERNAL_EVENT_FREEOBJ);
5521 break;
5522 }
5523 }
5524 }
5525 pp += slot_size;
5526 bitset >>= 1;
5527 }
5528 p += BITS_BITLENGTH * slot_size;
5529 }
5530}
5531
5532static void
5533gc_sweep_freeobj_hooks(rb_objspace_t *objspace)
5534{
5535 for (int i = 0; i < HEAP_COUNT; i++) {
5536 rb_heap_t *heap = &heaps[i];
5537 struct heap_page *page = NULL;
5538
5539 ccan_list_for_each(&heap->pages, page, page_node) {
5540 gc_sweep_freeobj_hooks_page(objspace, page);
5541 }
5542 }
5543}
5544
5545static void
5546gc_sweep_start(rb_objspace_t *objspace)
5547{
5548 gc_mode_transition(objspace, gc_mode_sweeping);
5549 objspace->rincgc.pooled_slots = 0;
5550
5551 if (RB_UNLIKELY(objspace->hook_events & RUBY_INTERNAL_EVENT_FREEOBJ)) {
5552 /* FREEOBJ is never enabled outside the main objspace
5553 * (rb_objspace_set_event_hook), so this hook, which runs user callbacks,
5554 * cannot fire during a non-main Ractor's lock-free local sweep. */
5555 GC_ASSERT(objspace == global_objspace->main_objspace);
5556 gc_sweep_freeobj_hooks(objspace);
5557 }
5558
5559#if GC_CAN_COMPILE_COMPACTION
5560 if (objspace->flags.during_compacting) {
5561 gc_sort_heap_by_compare_func(
5562 objspace,
5563 objspace->rcompactor.compare_func ? objspace->rcompactor.compare_func : compare_pinned_slots
5564 );
5565 }
5566#endif
5567
5568 for (int i = 0; i < HEAP_COUNT; i++) {
5569 rb_heap_t *heap = &heaps[i];
5570 gc_sweep_start_heap(objspace, heap);
5571
5572 /* We should call gc_sweep_finish_heap for size pools with no pages. */
5573 if (heap->sweeping_page == NULL) {
5574 GC_ASSERT(heap->total_pages == 0);
5575 GC_ASSERT(heap->total_slots == 0);
5576 gc_sweep_finish_heap(objspace, heap);
5577 }
5578 }
5579
5580 heap_alloc_state_clear(objspace);
5581}
5582
5583static void
5584gc_sweep_finish_heap(rb_objspace_t *objspace, rb_heap_t *heap)
5585{
5586 size_t total_slots = heap->total_slots;
5587 size_t swept_slots = heap->freed_slots + heap->empty_slots;
5588
5589 size_t init_slots = objspace_heap_init_bytes(objspace) / heap->slot_size;
5590 size_t min_free_slots = (size_t)(MAX(total_slots, init_slots) * gc_params.heap_free_slots_min_ratio);
5591
5592 if (swept_slots < min_free_slots &&
5593 /* The heap is a growth heap if it freed more slots than had empty slots. */
5594 ((heap->empty_slots == 0 && total_slots > 0) || heap->freed_slots > heap->empty_slots)) {
5595 /* If we don't have enough slots and we have pages on the tomb heap, move
5596 * pages from the tomb heap to the eden heap. This may prevent page
5597 * creation thrashing (frequently allocating and deallocting pages) and
5598 * GC thrashing (running GC more frequently than required). */
5599 struct heap_page *resurrected_page;
5600 while (swept_slots < min_free_slots &&
5601 (resurrected_page = heap_page_resurrect(objspace))) {
5602 heap_add_page(objspace, heap, resurrected_page);
5603 heap_add_freepage(heap, resurrected_page);
5604
5605 swept_slots += resurrected_page->free_slots;
5606 }
5607
5608 if (swept_slots < min_free_slots) {
5609 /* Grow this heap if we are in a major GC or if we haven't run at least
5610 * RVALUE_OLD_AGE minor GC since the last major GC. */
5611 if (is_full_marking(objspace) ||
5612 objspace->profile.count - objspace->rgengc.last_major_gc < RVALUE_OLD_AGE) {
5613 if (objspace->heap_pages.allocatable_bytes < min_free_slots * heap->slot_size) {
5614 heap_allocatable_bytes_expand(objspace, heap, swept_slots, heap->total_slots, heap->slot_size);
5615 }
5616 }
5617 else if (swept_slots < min_free_slots * 7 / 8 &&
5618 objspace->heap_pages.allocatable_bytes < (min_free_slots * 7 / 8 - swept_slots) * heap->slot_size) {
5619 gc_needs_major_flags |= GPR_FLAG_MAJOR_BY_NOFREE;
5620 heap->force_major_gc_count++;
5621 }
5622 }
5623 }
5624}
5625
5626static void
5627gc_sweep_finish(rb_objspace_t *objspace)
5628{
5629 gc_report(1, objspace, "gc_sweep_finish\n");
5630
5631 gc_prof_set_heap_info(objspace);
5632 heap_pages_free_unused_pages(objspace);
5633 if (rb_gc_single_objspace_p() && is_full_marking(objspace)) {
5634 /* gc_marks_finish retains ~2/3 of empty pages in objspace->empty_pages for reuse,
5635 * only the excess reaches the pool. */
5636 page_pool_reclaim(global_objspace);
5637 }
5638
5639 for (int i = 0; i < HEAP_COUNT; i++) {
5640 rb_heap_t *heap = &heaps[i];
5641
5642 heap->freed_slots = 0;
5643 heap->empty_slots = 0;
5644
5645 if (!will_be_incremental_marking(objspace)) {
5646 struct heap_page *end_page = heap->free_pages;
5647 if (end_page) {
5648 while (end_page->free_next) end_page = end_page->free_next;
5649 end_page->free_next = heap->pooled_pages;
5650 }
5651 else {
5652 heap->free_pages = heap->pooled_pages;
5653 }
5654 heap->pooled_pages = NULL;
5655 objspace->rincgc.pooled_slots = 0;
5656 }
5657 }
5658
5659 /* Not before: while sweeping is in progress its frees must keep reducing
5660 * malloc_increase (objspace_malloc_increase_body sweeps and retries on it). */
5661 gc_malloc_counters_snapshot_free_at_last_gc(objspace, &objspace->malloc_counters.counters);
5662#if RGENGC_ESTIMATE_OLDMALLOC
5663 gc_malloc_counters_snapshot_free_at_last_gc(objspace, &objspace->malloc_counters.oldcounters);
5664#endif
5665
5666 /* Leftovers from an earlier multi-Ractor phase: no later sweep can rediscover them
5667 * (their slots are gone), and with one Ractor left the drain's barrier has nothing
5668 * to wait for. */
5669 if (tdata_deferred_free_count_load() > 0 && rb_gc_single_objspace_p()) {
5670 gc_tdata_deferred_free_trigger(objspace);
5671 }
5672
5674 gc_mode_transition(objspace, gc_mode_none);
5675}
5676
5677static int
5678gc_sweep_step(rb_objspace_t *objspace, rb_heap_t *heap)
5679{
5680 struct heap_page *sweep_page = heap->sweeping_page;
5681 int swept_slots = 0;
5682 int pooled_slots = 0;
5683 int sweep_budget = GC_INCREMENTAL_SWEEP_BYTES / heap->slot_size;
5684 int pool_budget = GC_INCREMENTAL_SWEEP_POOL_BYTES / heap->slot_size;
5685
5686 if (sweep_page == NULL) return FALSE;
5687
5688#if GC_ENABLE_LAZY_SWEEP
5689 gc_prof_sweep_timer_start(objspace);
5690#endif
5691
5692 /* Per-slot pinned-free assert (gc_sweep_context): check only when this cycle's mark
5693 * ran the pinned walk. The current world state would misfire: a single-world
5694 * cycle leaves dead shareable objects unmarked and its sweep can straddle the switch
5695 * to multi-objspace. A global GC's exact mark does not pin, so it is excluded. */
5696 const bool check_pinned_free = objspace->last_cycle_pinned;
5697
5698 const bool defer_thread_unsafe_local_sweep =
5699 !rb_gc_single_objspace_p() && !objspace->flags.during_global_gc;
5700 bool trigger_thread_unsafe_sweep_postponed_job = false;
5701
5702 do {
5703 RUBY_DEBUG_LOG("sweep_page:%p", (void *)sweep_page);
5704
5705 struct gc_sweep_context ctx = {
5706 .page = sweep_page,
5707 .final_slots = 0,
5708 .freed_slots = 0,
5709 .empty_slots = 0,
5710 .check_pinned_free = check_pinned_free,
5711 .defer_thread_unsafe_local_sweep = defer_thread_unsafe_local_sweep,
5712 .trigger_thread_unsafe_sweep_postponed_job = trigger_thread_unsafe_sweep_postponed_job,
5713 };
5714 gc_sweep_page(objspace, heap, &ctx);
5715 int free_slots = ctx.freed_slots + ctx.empty_slots;
5716 trigger_thread_unsafe_sweep_postponed_job = ctx.trigger_thread_unsafe_sweep_postponed_job;
5717
5718 RUBY_DTRACE_GC_HOOK(SWEEP_PAGE, ctx.page->slot_size, ctx.final_slots, ctx.freed_slots, ctx.empty_slots);
5719
5720 heap->sweeping_page = ccan_list_next(&heap->pages, sweep_page, page_node);
5721
5722 if (free_slots == sweep_page->total_slots && heap->total_pages > 1) {
5723 /* There are no living objects, so move this page to the global empty pages.
5724 * The last one stays: nothing grows a heap that has no pages at all. */
5725 heap_unlink_page(objspace, heap, sweep_page);
5726
5727 sweep_page->start = 0;
5728 sweep_page->total_slots = 0;
5729 sweep_page->slot_size = 0;
5730 sweep_page->heap = NULL;
5731 sweep_page->free_slots = 0;
5732
5733 asan_unlock_freelist(sweep_page);
5734 sweep_page->free_region = NULL;
5735 asan_lock_freelist(sweep_page);
5736
5737 asan_poison_memory_region(sweep_page->body, HEAP_PAGE_SIZE);
5738
5739 objspace->empty_pages_count++;
5740 sweep_page->free_next = objspace->empty_pages;
5741 objspace->empty_pages = sweep_page;
5742 }
5743 else if (free_slots > 0) {
5744 heap->freed_slots += ctx.freed_slots;
5745 heap->empty_slots += ctx.empty_slots;
5746
5747 if (pooled_slots < pool_budget) {
5748 heap_add_poolpage(objspace, heap, sweep_page);
5749 pooled_slots += free_slots;
5750 }
5751 else {
5752 heap_add_freepage(heap, sweep_page);
5753 swept_slots += free_slots;
5754 if (swept_slots > sweep_budget) {
5755 break;
5756 }
5757 }
5758 }
5759 else {
5760 sweep_page->free_next = NULL;
5761 }
5762 } while ((sweep_page = heap->sweeping_page));
5763
5764 if (trigger_thread_unsafe_sweep_postponed_job) {
5765 gc_report(2, objspace, "thread-unsafe sweep postponed job triggered\n");
5766 gc_tdata_deferred_free_trigger(objspace);
5767 }
5768
5769 if (!heap->sweeping_page) {
5770 objspace->sweeping_heap_count--;
5771 GC_ASSERT(objspace->sweeping_heap_count >= 0);
5772 gc_sweep_finish_heap(objspace, heap);
5773
5774 if (!has_sweeping_pages(objspace)) {
5775 gc_sweep_finish(objspace);
5776 }
5777 }
5778
5779#if GC_ENABLE_LAZY_SWEEP
5780 gc_prof_sweep_timer_stop(objspace);
5781#endif
5782
5783 return heap->free_pages != NULL;
5784}
5785
5786static void
5787gc_sweep_rest(rb_objspace_t *objspace)
5788{
5789 for (int i = 0; i < HEAP_COUNT; i++) {
5790 rb_heap_t *heap = &heaps[i];
5791
5792 while (heap->sweeping_page) {
5793 gc_sweep_step(objspace, heap);
5794 }
5795 }
5796
5797 /* An objspace with no live pages never runs gc_sweep_step and so never reaches
5798 * gc_sweep_finish, leaving mode at sweeping or compacting until the next cycle's
5799 * gc_sweep_start asserts. If every heap is swept out, settle it to none here. */
5800 if (gc_mode(objspace) != gc_mode_none && !has_sweeping_pages(objspace)) {
5801 gc_sweep_finish(objspace);
5802 }
5803}
5804
5805static void
5806gc_sweep_continue(rb_objspace_t *objspace, rb_heap_t *sweep_heap)
5807{
5808 GC_ASSERT(dont_gc_val() == FALSE || objspace->profile.latest_gc_info & GPR_FLAG_METHOD);
5809 if (!GC_ENABLE_LAZY_SWEEP) return;
5810
5811 gc_sweeping_enter(objspace);
5812
5813 for (int i = 0; i < HEAP_COUNT; i++) {
5814 rb_heap_t *heap = &heaps[i];
5815 if (gc_sweep_step(objspace, heap)) {
5816 GC_ASSERT(heap->free_pages != NULL);
5817 }
5818 else if (heap == sweep_heap) {
5819 if (objspace->empty_pages_count > 0 || objspace->heap_pages.allocatable_bytes > 0) {
5820 /* [Bug #21548]
5821 *
5822 * If this heap is the heap we want to sweep, but we weren't able
5823 * to free any slots, but we also either have empty pages or could
5824 * allocate new pages, then we want to preemptively claim a page
5825 * because it's possible that sweeping another heap will call
5826 * gc_sweep_finish_heap, which may use up all of the
5827 * empty/allocatable pages. If other heaps are not finished sweeping
5828 * then we do not finish this GC and we will end up triggering a new
5829 * GC cycle during this GC phase. */
5830 heap_page_allocate_and_initialize(objspace, heap);
5831
5832 GC_ASSERT(heap->free_pages != NULL);
5833 }
5834 else {
5835 /* Not allowed to create a new page so finish sweeping. */
5836 gc_sweep_rest(objspace);
5837 GC_ASSERT(gc_mode(objspace) == gc_mode_none);
5838 break;
5839 }
5840 }
5841 }
5842
5843 gc_sweeping_exit(objspace);
5844}
5845
5846static void
5847gc_sweep_step_for_malloc(rb_objspace_t *objspace)
5848{
5849 GC_ASSERT(is_lazy_sweeping(objspace));
5850
5851 unsigned int lock_lev;
5852 gc_enter(objspace, gc_enter_event_continue, &lock_lev);
5853
5854 gc_sweeping_enter(objspace);
5855
5856 for (int i = 0; i < HEAP_COUNT; i++) {
5857 rb_heap_t *heap = &heaps[i];
5858 gc_sweep_step(objspace, heap);
5859 }
5860
5861 gc_sweeping_exit(objspace);
5862
5863 gc_exit(objspace, gc_enter_event_continue, &lock_lev);
5864}
5865
5866static bool gc_global_pointer_to_heap_p(const void *ptr);
5867
5868VALUE
5869rb_gc_impl_location(void *objspace_ptr, VALUE value)
5870{
5871 rb_objspace_t *objspace = objspace_ptr;
5872 VALUE destination;
5873
5874 /* A local (single-objspace) compaction never moves another objspace's objects, so
5875 * leave foreign references alone. A compacting global GC moves objects everywhere
5876 * under the barrier, so there every objspace's heap is searched for forwarding. */
5877 if (RB_UNLIKELY(objspace->flags.during_global_gc)
5878 ? !gc_global_pointer_to_heap_p((void *)value)
5879 : !is_pointer_to_heap(objspace_ptr, (void *)value)) {
5880 return value;
5881 }
5882
5883 asan_unpoisoning_object(value) {
5884 if (BUILTIN_TYPE(value) == T_MOVED) {
5885 destination = (VALUE)RMOVED(value)->destination;
5886 GC_ASSERT(BUILTIN_TYPE(destination) != T_NONE);
5887 }
5888 else {
5889 destination = value;
5890 }
5891 }
5892
5893 return destination;
5894}
5895
5896#if GC_CAN_COMPILE_COMPACTION
5897static void
5898invalidate_moved_plane(rb_objspace_t *objspace, struct heap_page *page, uintptr_t p, bits_t bitset)
5899{
5900 if (bitset) {
5901 do {
5902 if (bitset & 1) {
5903 VALUE forwarding_object = (VALUE)p;
5904 VALUE object;
5905
5906 if (BUILTIN_TYPE(forwarding_object) == T_MOVED) {
5907 GC_ASSERT(RVALUE_PINNED(objspace, forwarding_object));
5908 GC_ASSERT(!RVALUE_MARKED(objspace, forwarding_object));
5909
5910 CLEAR_IN_BITMAP(GET_HEAP_PINNED_BITS(forwarding_object), forwarding_object);
5911
5912 object = rb_gc_impl_location(objspace, forwarding_object);
5913 gc_move(objspace, object, forwarding_object, GET_HEAP_PAGE(object), page);
5914 /* forwarding_object is now our actual object, and "object"
5915 * is the free slot for the original page */
5916
5917 struct heap_page *orig_page = GET_HEAP_PAGE(object);
5918 orig_page->free_slots++;
5919 RVALUE_AGE_SET_BITMAP(object, 0);
5920 heap_page_add_free_region(objspace, orig_page, object);
5921
5922 GC_ASSERT(RVALUE_MARKED(objspace, forwarding_object));
5923 GC_ASSERT(BUILTIN_TYPE(forwarding_object) != T_MOVED);
5924 GC_ASSERT(BUILTIN_TYPE(forwarding_object) != T_NONE);
5925 }
5926 }
5927 p += page->slot_size;
5928 bitset >>= 1;
5929 } while (bitset);
5930 }
5931}
5932
5933static void
5934invalidate_moved_page(rb_objspace_t *objspace, struct heap_page *page)
5935{
5936 int i;
5937 bits_t *mark_bits, *pin_bits;
5938 bits_t bitset;
5939 short slot_size = page->slot_size;
5940 int total_slots = page->total_slots;
5941 int bitmap_plane_count = CEILDIV(total_slots, BITS_BITLENGTH);
5942
5943 mark_bits = page->mark_bits;
5944 pin_bits = page->pinned_bits;
5945
5946 uintptr_t p = page->start;
5947
5948 for (i=0; i < bitmap_plane_count; i++) {
5949 /* Moved objects are pinned but never marked. We reuse the pin bits
5950 * to indicate there is a moved object in this slot. */
5951 bitset = pin_bits[i] & ~mark_bits[i];
5952 invalidate_moved_plane(objspace, page, p, bitset);
5953 p += BITS_BITLENGTH * slot_size;
5954 }
5955}
5956#endif
5957
5958static void
5959gc_compact_start(rb_objspace_t *objspace)
5960{
5961 struct heap_page *page = NULL;
5962 gc_mode_transition(objspace, gc_mode_compacting);
5963
5964 for (int i = 0; i < HEAP_COUNT; i++) {
5965 rb_heap_t *heap = &heaps[i];
5966 ccan_list_for_each(&heap->pages, page, page_node) {
5967 page->flags.before_sweep = TRUE;
5968 }
5969
5970 heap->compact_cursor = ccan_list_tail(&heap->pages, struct heap_page, page_node);
5971 heap->compact_cursor_index = 0;
5972 }
5973
5974 if (gc_prof_enabled(objspace)) {
5975 gc_profile_record *record = gc_prof_record(objspace);
5976 record->moved_objects = objspace->rcompactor.total_moved;
5977 }
5978
5979 memset(objspace->rcompactor.considered_count_table, 0, T_MASK * sizeof(size_t));
5980 memset(objspace->rcompactor.moved_count_table, 0, T_MASK * sizeof(size_t));
5981 memset(objspace->rcompactor.moved_up_count_table, 0, T_MASK * sizeof(size_t));
5982 memset(objspace->rcompactor.moved_down_count_table, 0, T_MASK * sizeof(size_t));
5983
5984 /* Set up read barrier for pages containing MOVED objects */
5985 /* A compacting global GC installs the read barrier once for every objspace. */
5986 if (!global_objspace->global_gc.compacting) install_handlers();
5987}
5988
5989static void gc_sweep_compact(rb_objspace_t *objspace);
5990
5991static void
5992gc_sweep(rb_objspace_t *objspace)
5993{
5994 gc_sweeping_enter(objspace);
5995
5996 const unsigned int immediate_sweep = objspace->flags.immediate_sweep;
5997
5998 gc_report(1, objspace, "gc_sweep: immediate: %d\n", immediate_sweep);
5999
6000 gc_sweep_start(objspace);
6001 if (objspace->flags.during_compacting) {
6002 rb_hrtime_t compact_start_time = gc_prof_enabled(objspace) ? rb_hrtime_now() : 0;
6003 gc_sweep_compact(objspace);
6004 if (gc_prof_enabled(objspace)) {
6005 rb_hrtime_t compact_wall_time = elapsed_hrtime_from(compact_start_time);
6006 gc_profile_record *record = gc_prof_record(objspace);
6007 record->gc_compact_wall_time = rb_hrtime_add(record->gc_compact_wall_time,
6008 compact_wall_time);
6009 objspace->profile.gc_sweep_excluded_wall_time = rb_hrtime_add(
6010 objspace->profile.gc_sweep_excluded_wall_time,
6011 compact_wall_time);
6012 }
6013 }
6014
6015 if (immediate_sweep) {
6016#if !GC_ENABLE_LAZY_SWEEP
6017 gc_prof_sweep_timer_start(objspace);
6018#endif
6019 gc_sweep_rest(objspace);
6020#if !GC_ENABLE_LAZY_SWEEP
6021 gc_prof_sweep_timer_stop(objspace);
6022#endif
6023 }
6024 else {
6025
6026 /* Sweep every size pool. */
6027 for (int i = 0; i < HEAP_COUNT; i++) {
6028 rb_heap_t *heap = &heaps[i];
6029 gc_sweep_step(objspace, heap);
6030 }
6031 }
6032
6033 gc_sweeping_exit(objspace);
6034}
6035
6036/* Marking - Marking stack */
6037
6038static stack_chunk_t *
6039stack_chunk_alloc(void)
6040{
6041 stack_chunk_t *res;
6042
6043 res = malloc(sizeof(stack_chunk_t));
6044 if (!res)
6045 rb_memerror();
6046
6047 return res;
6048}
6049
6050static inline int
6051is_mark_stack_empty(mark_stack_t *stack)
6052{
6053 return stack->chunk == NULL;
6054}
6055
6056static size_t
6057mark_stack_size(mark_stack_t *stack)
6058{
6059 size_t size = stack->index;
6060 stack_chunk_t *chunk = stack->chunk ? stack->chunk->next : NULL;
6061
6062 while (chunk) {
6063 size += stack->limit;
6064 chunk = chunk->next;
6065 }
6066 return size;
6067}
6068
6069static void
6070add_stack_chunk_cache(mark_stack_t *stack, stack_chunk_t *chunk)
6071{
6072 chunk->next = stack->cache;
6073 stack->cache = chunk;
6074 stack->cache_size++;
6075}
6076
6077static void
6078shrink_stack_chunk_cache(mark_stack_t *stack)
6079{
6080 stack_chunk_t *chunk;
6081
6082 if (stack->unused_cache_size > (stack->cache_size/2)) {
6083 chunk = stack->cache;
6084 stack->cache = stack->cache->next;
6085 stack->cache_size--;
6086 free(chunk);
6087 }
6088 stack->unused_cache_size = stack->cache_size;
6089}
6090
6091static void
6092push_mark_stack_chunk(mark_stack_t *stack)
6093{
6094 stack_chunk_t *next;
6095
6096 GC_ASSERT(stack->index == stack->limit);
6097
6098 if (stack->cache_size > 0) {
6099 next = stack->cache;
6100 stack->cache = stack->cache->next;
6101 stack->cache_size--;
6102 if (stack->unused_cache_size > stack->cache_size)
6103 stack->unused_cache_size = stack->cache_size;
6104 }
6105 else {
6106 next = stack_chunk_alloc();
6107 }
6108 next->next = stack->chunk;
6109 stack->chunk = next;
6110 stack->index = 0;
6111}
6112
6113static void
6114pop_mark_stack_chunk(mark_stack_t *stack)
6115{
6116 stack_chunk_t *prev;
6117
6118 prev = stack->chunk->next;
6119 GC_ASSERT(stack->index == 0);
6120 add_stack_chunk_cache(stack, stack->chunk);
6121 stack->chunk = prev;
6122 stack->index = stack->limit;
6123}
6124
6125static void
6126mark_stack_chunk_list_free(stack_chunk_t *chunk)
6127{
6128 stack_chunk_t *next = NULL;
6129
6130 while (chunk != NULL) {
6131 next = chunk->next;
6132 free(chunk);
6133 chunk = next;
6134 }
6135}
6136
6137static void
6138free_stack_chunks(mark_stack_t *stack)
6139{
6140 mark_stack_chunk_list_free(stack->chunk);
6141}
6142
6143static void
6144mark_stack_free_cache(mark_stack_t *stack)
6145{
6146 mark_stack_chunk_list_free(stack->cache);
6147 stack->cache_size = 0;
6148 stack->unused_cache_size = 0;
6149}
6150
6151static void
6152push_mark_stack(mark_stack_t *stack, VALUE obj)
6153{
6154 switch (BUILTIN_TYPE(obj)) {
6155 case T_OBJECT:
6156 case T_CLASS:
6157 case T_MODULE:
6158 case T_FLOAT:
6159 case T_STRING:
6160 case T_REGEXP:
6161 case T_ARRAY:
6162 case T_HASH:
6163 case T_STRUCT:
6164 case T_BIGNUM:
6165 case T_FILE:
6166 case T_DATA:
6167 case T_MATCH:
6168 case T_COMPLEX:
6169 case T_RATIONAL:
6170 case T_TRUE:
6171 case T_FALSE:
6172 case T_SYMBOL:
6173 case T_IMEMO:
6174 case T_ICLASS:
6175 if (stack->index == stack->limit) {
6176 push_mark_stack_chunk(stack);
6177 }
6178 stack->chunk->data[stack->index++] = obj;
6179 return;
6180
6181 case T_NONE:
6182 case T_NIL:
6183 case T_FIXNUM:
6184 case T_MOVED:
6185 case T_ZOMBIE:
6186 case T_UNDEF:
6187 case T_MASK:
6188 rb_bug("push_mark_stack() called for broken object");
6189 break;
6190
6191 case T_NODE:
6192 rb_bug("push_mark_stack: unexpected T_NODE object");
6193 break;
6194 }
6195
6196 rb_bug("rb_gc_mark(): unknown data type 0x%x(%p) %s",
6197 BUILTIN_TYPE(obj), (void *)obj,
6198 is_pointer_to_heap((rb_objspace_t *)rb_gc_get_objspace(), (void *)obj) ? "corrupted object" : "non object");
6199}
6200
6201static int
6202pop_mark_stack(mark_stack_t *stack, VALUE *data)
6203{
6204 if (is_mark_stack_empty(stack)) {
6205 return FALSE;
6206 }
6207 if (stack->index == 1) {
6208 *data = stack->chunk->data[--stack->index];
6209 pop_mark_stack_chunk(stack);
6210 }
6211 else {
6212 *data = stack->chunk->data[--stack->index];
6213 }
6214 return TRUE;
6215}
6216
6217static void
6218init_mark_stack(mark_stack_t *stack)
6219{
6220 int i;
6221
6222 MEMZERO(stack, mark_stack_t, 1);
6223 stack->index = stack->limit = STACK_CHUNK_SIZE;
6224
6225 for (i=0; i < 4; i++) {
6226 add_stack_chunk_cache(stack, stack_chunk_alloc());
6227 }
6228 stack->unused_cache_size = stack->cache_size;
6229}
6230
6231/* Marking */
6232
6233ALWAYS_INLINE(static int gc_mark_set(rb_objspace_t *objspace, VALUE obj));
6234ALWAYS_INLINE(static void gc_mark_check_t_none(rb_objspace_t *objspace, VALUE obj));
6235ALWAYS_INLINE(static void rgengc_check_relation(rb_objspace_t *objspace, VALUE obj));
6236ALWAYS_INLINE(static void gc_aging(rb_objspace_t *objspace, VALUE obj));
6237ALWAYS_INLINE(static void gc_grey(rb_objspace_t *objspace, VALUE obj));
6238static void
6239rgengc_check_relation(rb_objspace_t *objspace, VALUE obj)
6240{
6241 if (objspace->rgengc.parent_object_old_p) {
6242 if (!RVALUE_OLD_P(objspace, obj)) {
6243 rgengc_remember(objspace, objspace->rgengc.parent_object);
6244 /* It is in the rememberset now, so its remaining children have nothing left
6245 * to ask for: stop testing them. */
6246 objspace->rgengc.parent_object_old_p = false;
6247 }
6248 }
6249}
6250
6251static inline int
6252gc_mark_set(rb_objspace_t *objspace, VALUE obj)
6253{
6254 if (RVALUE_MARKED(objspace, obj)) return 0;
6255 MARK_IN_BITMAP(GET_HEAP_MARK_BITS(obj), obj);
6256 return 1;
6257}
6258
6259static void
6260gc_aging(rb_objspace_t *objspace, VALUE obj)
6261{
6262 /* Disable aging if Major GC's are disabled. This will prevent longish lived
6263 * objects filling up the heap at the expense of marking many more objects.
6264 *
6265 * We should always pre-warm our process when disabling majors, by running
6266 * GC manually several times so that most objects likely to become oldgen
6267 * are already oldgen.
6268 */
6269 if(!gc_config_full_mark_val)
6270 return;
6271
6272 struct heap_page *page = GET_HEAP_PAGE(obj);
6273
6274 GC_ASSERT(RVALUE_MARKING(objspace, obj) == FALSE);
6275 check_rvalue_consistency(objspace, obj);
6276
6277 if (!RVALUE_PAGE_WB_UNPROTECTED(page, obj)) {
6278 if (!RVALUE_OLD_P(objspace, obj)) {
6279 int t = BUILTIN_TYPE(obj);
6280 if (t == T_CLASS || t == T_MODULE || t == T_ICLASS) {
6281 gc_report(3, objspace, "gc_aging: YOUNG class: %s\n", rb_obj_info(obj));
6282 RVALUE_AGE_SET(obj, RVALUE_OLD_AGE);
6283 RVALUE_OLD_UNCOLLECTIBLE_SET(objspace, obj);
6284 }
6285 else {
6286 gc_report(3, objspace, "gc_aging: YOUNG: %s\n", rb_obj_info(obj));
6287 RVALUE_AGE_INC(objspace, obj);
6288 }
6289 }
6290 else if (is_full_marking(objspace)) {
6291 GC_ASSERT(RVALUE_PAGE_UNCOLLECTIBLE(page, obj) == FALSE);
6292 RVALUE_PAGE_OLD_UNCOLLECTIBLE_SET(objspace, page, obj);
6293 }
6294 }
6295 check_rvalue_consistency(objspace, obj);
6296
6297 objspace->marked_slots++;
6298}
6299
6300static void
6301gc_grey(rb_objspace_t *objspace, VALUE obj)
6302{
6303#if RGENGC_CHECK_MODE
6304 if (RVALUE_MARKED(objspace, obj) == FALSE) rb_bug("gc_grey: %s is not marked.", rb_obj_info(obj));
6305 if (RVALUE_MARKING(objspace, obj) == TRUE) rb_bug("gc_grey: %s is marking/remembered.", rb_obj_info(obj));
6306#endif
6307
6308 if (is_incremental_marking(objspace)) {
6309 MARK_IN_BITMAP(GET_HEAP_MARKING_BITS(obj), obj);
6310 }
6311
6313 rb_darray_append_without_gc(&objspace->weak_references, obj);
6314 }
6315
6316 push_mark_stack(&objspace->mark_stack, obj);
6317}
6318
6319static inline void
6320gc_mark_check_t_none(rb_objspace_t *objspace, VALUE obj)
6321{
6322 if (RB_UNLIKELY(BUILTIN_TYPE(obj) == T_NONE)) {
6323 enum {info_size = 256};
6324 char obj_info_buf[info_size];
6325 rb_raw_obj_info(obj_info_buf, info_size, obj);
6326
6327 char parent_obj_info_buf[info_size];
6328 rb_raw_obj_info(parent_obj_info_buf, info_size, objspace->rgengc.parent_object);
6329
6330 rb_bug("try to mark T_NONE object (obj: %s, parent: %s)", obj_info_buf, parent_obj_info_buf);
6331 }
6332}
6333
6334static void
6335gc_mark(rb_objspace_t *objspace, VALUE obj)
6336{
6337 GC_ASSERT(during_gc);
6338 GC_ASSERT(!objspace->flags.during_reference_updating);
6339
6340 /* Never step into another objspace: a foreign object is a live leaf whose liveness
6341 * belongs to its owner, so touching its bitmaps here would be unsound. A global GC
6342 * lifts this: everyone is stopped and the bits live on the object's own page. */
6343 if (gc_skip_foreign_object_p(objspace, obj)) {
6344 return;
6345 }
6346
6347 if (RB_UNLIKELY(objspace->flags.during_global_gc)) {
6348 /* Recompute the shref of every shareable -> unshareable edge, within and across
6349 * objspaces: the clear pass dropped all shref bits and the write barrier
6350 * maintains them from here on. */
6351 VALUE parent = objspace->rgengc.parent_object;
6352 if (!UNDEF_P(parent) && parent != Qfalse &&
6355 struct heap_page *page = GET_HEAP_PAGE(obj);
6356 _MARK_IN_BITMAP(page->shref_bits, page, obj);
6357 page->flags.has_shref_objects = TRUE;
6358 }
6359 }
6360
6361 rgengc_check_relation(objspace, obj);
6362 if (!gc_mark_set(objspace, obj)) return; /* already marked */
6363
6364 if (0) { // for debug GC marking miss
6365 RUBY_DEBUG_LOG("%p (%s) parent:%p (%s)",
6366 (void *)obj, obj_type_name(obj),
6367 (void *)objspace->rgengc.parent_object, obj_type_name(objspace->rgengc.parent_object));
6368 }
6369
6370 gc_mark_check_t_none(objspace, obj);
6371
6372 gc_aging(objspace, obj);
6373 gc_grey(objspace, obj);
6374}
6375
6376static inline void
6377gc_pin(rb_objspace_t *objspace, VALUE obj)
6378{
6379 GC_ASSERT(!SPECIAL_CONST_P(obj));
6380
6381 if (RB_UNLIKELY(objspace->flags.during_compacting)) {
6382 /* Never write a foreign page's pinned bit (a global GC may: everyone is stopped). */
6383 if (gc_skip_foreign_object_p(objspace, obj)) return;
6384
6385 if (RB_LIKELY(during_gc)) {
6386 if (!RVALUE_PINNED(objspace, obj)) {
6387 GC_ASSERT(GET_HEAP_PAGE(obj)->pinned_slots <= GET_HEAP_PAGE(obj)->total_slots);
6388 GET_HEAP_PAGE(obj)->pinned_slots++;
6389 MARK_IN_BITMAP(GET_HEAP_PINNED_BITS(obj), obj);
6390 }
6391 }
6392 }
6393}
6394
6395static inline void
6396gc_mark_and_pin(rb_objspace_t *objspace, VALUE obj)
6397{
6398 gc_pin(objspace, obj);
6399 gc_mark(objspace, obj);
6400}
6401
6402void
6403rb_gc_impl_mark_and_move(void *objspace_ptr, VALUE *ptr)
6404{
6405 rb_objspace_t *objspace = objspace_ptr;
6406
6407 if (RB_UNLIKELY(objspace->flags.during_reference_updating)) {
6408 GC_ASSERT(objspace->flags.during_compacting);
6409 GC_ASSERT(during_gc);
6410
6411 VALUE destination = rb_gc_impl_location(objspace, *ptr);
6412 if (destination != *ptr) {
6413 *ptr = destination;
6414 }
6415 }
6416 else {
6417 gc_mark(objspace, *ptr);
6418 }
6419}
6420
6421void
6422rb_gc_impl_mark(void *objspace_ptr, VALUE obj)
6423{
6424 rb_objspace_t *objspace = objspace_ptr;
6425
6426 gc_mark(objspace, obj);
6427}
6428
6429void
6430rb_gc_impl_mark_and_pin(void *objspace_ptr, VALUE obj)
6431{
6432 rb_objspace_t *objspace = objspace_ptr;
6433
6434 gc_mark_and_pin(objspace, obj);
6435}
6436
6437/* A word scanned conservatively by a global GC can point into any objspace, so ownership
6438 * is decided against the driver's snapshot of every objspace (the bits then land on the
6439 * owner's page through gc_mark and gc_pin). */
6440static bool
6441gc_global_pointer_to_heap_p(const void *ptr)
6442{
6443 const rb_global_objspace_t *g = global_objspace;
6444 uintptr_t p = (uintptr_t)ptr;
6445
6446 if (p < g->page_index.lomem || p > g->page_index.himem) return false;
6447 if (p % sizeof(VALUE) != 0) return false;
6448
6449 struct heap_page **res = bsearch(ptr, g->page_index.pages, g->page_index.n_pages,
6450 sizeof(struct heap_page *), ptr_in_page_body_p);
6451 if (res == NULL) return false;
6452
6453 struct heap_page *page = *res;
6454 if (heap_page_in_global_empty_pages_pool(page->objspace, page)) return false;
6455 if (p < page->start) return false;
6456 if (p >= page->start + (page->total_slots * page->slot_size)) return false;
6457 if ((p - page->start) % page->slot_size != 0) return false;
6458 return true;
6459}
6460
6461void
6462rb_gc_impl_mark_maybe(void *objspace_ptr, VALUE obj)
6463{
6464 rb_objspace_t *objspace = objspace_ptr;
6465
6466 (void)VALGRIND_MAKE_MEM_DEFINED(&obj, sizeof(obj));
6467
6468 if (RB_UNLIKELY(objspace->flags.during_global_gc)
6469 ? gc_global_pointer_to_heap_p((void *)obj)
6470 : is_pointer_to_heap(objspace, (void *)obj)) {
6471 asan_unpoisoning_object(obj) {
6472 /* Garbage can live on the stack, so do not mark or pin */
6473 switch (BUILTIN_TYPE(obj)) {
6474 case T_ZOMBIE:
6475 case T_NONE:
6476 break;
6477 default:
6478 gc_mark_and_pin(objspace, obj);
6479 break;
6480 }
6481 }
6482 }
6483}
6484
6485static int
6486pin_value(st_data_t key, st_data_t value, st_data_t data)
6487{
6488 rb_gc_impl_mark_and_pin((void *)data, (VALUE)value);
6489
6490 return ST_CONTINUE;
6491}
6492
6493static inline void
6494gc_mark_set_parent_raw(rb_objspace_t *objspace, VALUE obj, bool old_p)
6495{
6496 asan_unpoison_memory_region(&objspace->rgengc.parent_object, sizeof(objspace->rgengc.parent_object), false);
6497 asan_unpoison_memory_region(&objspace->rgengc.parent_object_old_p, sizeof(objspace->rgengc.parent_object_old_p), false);
6498 objspace->rgengc.parent_object = obj;
6499 objspace->rgengc.parent_object_old_p = old_p;
6500}
6501
6502static inline void
6503gc_mark_set_parent(rb_objspace_t *objspace, VALUE obj)
6504{
6505 gc_mark_set_parent_raw(objspace, obj, RVALUE_OLD_P(objspace, obj));
6506}
6507
6508static inline void
6509gc_mark_set_parent_invalid(rb_objspace_t *objspace)
6510{
6511 asan_poison_memory_region(&objspace->rgengc.parent_object, sizeof(objspace->rgengc.parent_object));
6512 asan_poison_memory_region(&objspace->rgengc.parent_object_old_p, sizeof(objspace->rgengc.parent_object_old_p));
6513}
6514
6515static void pinned_roots_mark(rb_objspace_t *objspace, rb_heap_t *heap);
6516
6517static void
6518mark_roots(rb_objspace_t *objspace, const char **categoryp)
6519{
6520 VALUE objspace_guard = (VALUE)objspace;
6521#define MARK_CHECKPOINT(category) do { \
6522 if (categoryp) *categoryp = category; \
6523} while (0)
6524
6525 /* Pinning shareable objects and shrefs runs at the end of marking (gc_marks_finish),
6526 * not here: after the full walk it only has to touch what ordinary marking missed,
6527 * which is both cheap and a useful retention metric. */
6528
6529 MARK_CHECKPOINT("objspace");
6530 gc_mark_set_parent_raw(objspace, Qundef, false);
6531
6532 if (objspace->flags.during_global_gc) {
6533 /* Pin the finalizer tables of every objspace, zombies included.
6534 * (finalizer_table is a macro over the local "objspace".) */
6535 rb_objspace_t *const driver = objspace;
6536 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
6537 rb_objspace_t *objspace = global_objspace->global_gc.objspaces[i];
6538 if (finalizer_table != NULL) {
6539 st_foreach(finalizer_table, pin_value, (st_data_t)driver);
6540 }
6541 }
6542 }
6543 else if (finalizer_table != NULL) {
6544 st_foreach(finalizer_table, pin_value, (st_data_t)objspace);
6545 }
6546
6547 if (stress_to_class) rb_gc_mark(stress_to_class);
6548
6549 rb_gc_save_machine_context();
6550 rb_gc_mark_roots(objspace, categoryp);
6551 /* Keep this frame, including its saved registers, until root marking has
6552 * scanned the machine stack. */
6553 RB_GC_GUARD(objspace_guard);
6554 gc_mark_set_parent_invalid(objspace);
6555}
6556
6557static void
6558gc_mark_children(rb_objspace_t *objspace, VALUE obj)
6559{
6560 gc_mark_set_parent(objspace, obj);
6561 rb_gc_mark_children(objspace, obj);
6562 gc_mark_set_parent_invalid(objspace);
6563}
6564
6569static inline int
6570gc_mark_stacked_objects(rb_objspace_t *objspace, int incremental, size_t count)
6571{
6572 mark_stack_t *mstack = &objspace->mark_stack;
6573 VALUE obj;
6574 size_t marked_slots_at_the_beginning = objspace->marked_slots;
6575 size_t popped_count = 0;
6576
6577 while (pop_mark_stack(mstack, &obj)) {
6578 if (obj == Qundef) continue; /* skip */
6579
6580 if (RGENGC_CHECK_MODE && !RVALUE_MARKED(objspace, obj)) {
6581 rb_bug("gc_mark_stacked_objects: %s is not marked.", rb_obj_info(obj));
6582 }
6583 gc_mark_children(objspace, obj);
6584
6585 popped_count++;
6586
6587 if (incremental) {
6588 if (RGENGC_CHECK_MODE && !RVALUE_MARKING(objspace, obj)) {
6589 rb_bug("gc_mark_stacked_objects: incremental, but marking bit is 0");
6590 }
6591 CLEAR_IN_BITMAP(GET_HEAP_MARKING_BITS(obj), obj);
6592
6593 if (popped_count + (objspace->marked_slots - marked_slots_at_the_beginning) > count) {
6594 break;
6595 }
6596 }
6597 else {
6598 /* just ignore marking bits */
6599 }
6600 }
6601
6602 RUBY_DTRACE_GC_HOOK(MARK_STACKED_OBJECTS, popped_count);
6603
6604 if (RGENGC_CHECK_MODE >= 3) gc_verify_internal_consistency(objspace);
6605
6606 if (is_mark_stack_empty(mstack)) {
6607 shrink_stack_chunk_cache(mstack);
6608 return TRUE;
6609 }
6610 else {
6611 return FALSE;
6612 }
6613}
6614
6615static int
6616gc_mark_stacked_objects_incremental(rb_objspace_t *objspace, size_t count)
6617{
6618 return gc_mark_stacked_objects(objspace, TRUE, count);
6619}
6620
6621static int
6622gc_mark_stacked_objects_all(rb_objspace_t *objspace)
6623{
6624 return gc_mark_stacked_objects(objspace, FALSE, 0);
6625}
6626
6627#if RGENGC_CHECK_MODE >= 4
6628
6629#define MAKE_ROOTSIG(obj) (((VALUE)(obj) << 1) | 0x01)
6630#define IS_ROOTSIG(obj) ((VALUE)(obj) & 0x01)
6631#define GET_ROOTSIG(obj) ((const char *)((VALUE)(obj) >> 1))
6632
6633struct reflist {
6634 VALUE *list;
6635 int pos;
6636 int size;
6637};
6638
6639static struct reflist *
6640reflist_create(VALUE obj)
6641{
6642 struct reflist *refs = xmalloc(sizeof(struct reflist));
6643 refs->size = 1;
6644 refs->list = ALLOC_N(VALUE, refs->size);
6645 refs->list[0] = obj;
6646 refs->pos = 1;
6647 return refs;
6648}
6649
6650static void
6651reflist_destruct(struct reflist *refs)
6652{
6653 xfree(refs->list);
6654 xfree(refs);
6655}
6656
6657static void
6658reflist_add(struct reflist *refs, VALUE obj)
6659{
6660 if (refs->pos == refs->size) {
6661 refs->size *= 2;
6662 SIZED_REALLOC_N(refs->list, VALUE, refs->size, refs->size/2);
6663 }
6664
6665 refs->list[refs->pos++] = obj;
6666}
6667
6668static void
6669reflist_dump(struct reflist *refs)
6670{
6671 int i;
6672 for (i=0; i<refs->pos; i++) {
6673 VALUE obj = refs->list[i];
6674 if (IS_ROOTSIG(obj)) { /* root */
6675 fprintf(stderr, "<root@%s>", GET_ROOTSIG(obj));
6676 }
6677 else {
6678 fprintf(stderr, "<%s>", rb_obj_info(obj));
6679 }
6680 if (i+1 < refs->pos) fprintf(stderr, ", ");
6681 }
6682}
6683
6684static int
6685reflist_referred_from_machine_context(struct reflist *refs)
6686{
6687 int i;
6688 for (i=0; i<refs->pos; i++) {
6689 VALUE obj = refs->list[i];
6690 if (IS_ROOTSIG(obj) && strcmp(GET_ROOTSIG(obj), "machine_context") == 0) return 1;
6691 }
6692 return 0;
6693}
6694
6695struct allrefs {
6697 /* a -> obj1
6698 * b -> obj1
6699 * c -> obj1
6700 * c -> obj2
6701 * d -> obj3
6702 * #=> {obj1 => [a, b, c], obj2 => [c, d]}
6703 */
6704 struct st_table *references;
6705 const char *category;
6706 VALUE root_obj;
6708};
6709
6710static int
6711allrefs_add(struct allrefs *data, VALUE obj)
6712{
6713 struct reflist *refs;
6714 st_data_t r;
6715
6716 if (st_lookup(data->references, obj, &r)) {
6717 refs = (struct reflist *)r;
6718 reflist_add(refs, data->root_obj);
6719 return 0;
6720 }
6721 else {
6722 refs = reflist_create(data->root_obj);
6723 st_insert(data->references, obj, (st_data_t)refs);
6724 return 1;
6725 }
6726}
6727
6728static void
6729allrefs_i(VALUE obj, void *ptr)
6730{
6731 struct allrefs *data = (struct allrefs *)ptr;
6732
6733 if (allrefs_add(data, obj)) {
6734 push_mark_stack(&data->mark_stack, obj);
6735 }
6736}
6737
6738static void
6739allrefs_roots_i(VALUE obj, void *ptr)
6740{
6741 struct allrefs *data = (struct allrefs *)ptr;
6742 if (strlen(data->category) == 0) rb_bug("!!!");
6743 data->root_obj = MAKE_ROOTSIG(data->category);
6744
6745 if (allrefs_add(data, obj)) {
6746 push_mark_stack(&data->mark_stack, obj);
6747 }
6748}
6749#define PUSH_MARK_FUNC_DATA(v) do { \
6750 struct gc_mark_func_data_struct *prev_mark_func_data = GET_VM()->gc.mark_func_data; \
6751 GET_VM()->gc.mark_func_data = (v);
6752
6753#define POP_MARK_FUNC_DATA() GET_VM()->gc.mark_func_data = prev_mark_func_data;} while (0)
6754
6755static st_table *
6756objspace_allrefs(rb_objspace_t *objspace)
6757{
6758 struct allrefs data;
6759 struct gc_mark_func_data_struct mfd;
6760 VALUE obj;
6761 int prev_dont_gc = dont_gc_val();
6762 dont_gc_on();
6763
6764 data.objspace = objspace;
6765 data.references = st_init_numtable();
6766 init_mark_stack(&data.mark_stack);
6767
6768 mfd.mark_func = allrefs_roots_i;
6769 mfd.data = &data;
6770
6771 /* traverse root objects */
6772 PUSH_MARK_FUNC_DATA(&mfd);
6773 GET_VM()->gc.mark_func_data = &mfd;
6774 mark_roots(objspace, &data.category);
6775 POP_MARK_FUNC_DATA();
6776
6777 /* traverse rest objects reachable from root objects */
6778 while (pop_mark_stack(&data.mark_stack, &obj)) {
6779 rb_objspace_reachable_objects_from(data.root_obj = obj, allrefs_i, &data);
6780 }
6781 free_stack_chunks(&data.mark_stack);
6782
6783 dont_gc_set(prev_dont_gc);
6784 return data.references;
6785}
6786
6787static int
6788objspace_allrefs_destruct_i(st_data_t key, st_data_t value, st_data_t ptr)
6789{
6790 struct reflist *refs = (struct reflist *)value;
6791 reflist_destruct(refs);
6792 return ST_CONTINUE;
6793}
6794
6795static void
6796objspace_allrefs_destruct(struct st_table *refs)
6797{
6798 st_foreach(refs, objspace_allrefs_destruct_i, 0);
6799 st_free_table(refs);
6800}
6801
6802#if RGENGC_CHECK_MODE >= 5
6803static int
6804allrefs_dump_i(st_data_t k, st_data_t v, st_data_t ptr)
6805{
6806 VALUE obj = (VALUE)k;
6807 struct reflist *refs = (struct reflist *)v;
6808 fprintf(stderr, "[allrefs_dump_i] %s <- ", rb_obj_info(obj));
6809 reflist_dump(refs);
6810 fprintf(stderr, "\n");
6811 return ST_CONTINUE;
6812}
6813
6814static void
6815allrefs_dump(rb_objspace_t *objspace)
6816{
6817 VALUE size = objspace->rgengc.allrefs_table->num_entries;
6818 fprintf(stderr, "[all refs] (size: %"PRIuVALUE")\n", size);
6819 st_foreach(objspace->rgengc.allrefs_table, allrefs_dump_i, 0);
6820}
6821#endif
6822
6823static int
6824gc_check_after_marks_i(st_data_t k, st_data_t v, st_data_t ptr)
6825{
6826 VALUE obj = k;
6827 struct reflist *refs = (struct reflist *)v;
6829
6830 /* object should be marked or oldgen */
6831 if (!RVALUE_MARKED(objspace, obj)) {
6832 fprintf(stderr, "gc_check_after_marks_i: %s is not marked and not oldgen.\n", rb_obj_info(obj));
6833 fprintf(stderr, "gc_check_after_marks_i: %p is referred from ", (void *)obj);
6834 reflist_dump(refs);
6835
6836 if (reflist_referred_from_machine_context(refs)) {
6837 fprintf(stderr, " (marked from machine stack).\n");
6838 /* marked from machine context can be false positive */
6839 }
6840 else {
6841 objspace->rgengc.error_count++;
6842 fprintf(stderr, "\n");
6843 }
6844 }
6845 return ST_CONTINUE;
6846}
6847
6848static void
6849gc_marks_check(rb_objspace_t *objspace, st_foreach_callback_func *checker_func, const char *checker_name)
6850{
6851 MALLOC_COUNTERS_LOCK(objspace);
6852 struct gc_malloc_bytes saved_malloc = {
6853 .malloc = gc_counter_load_relaxed(&objspace->malloc_counters.counters.malloc),
6854 .free = gc_counter_load_relaxed(&objspace->malloc_counters.counters.free),
6855 .malloc_at_last_gc = gc_counter_load_relaxed(&objspace->malloc_counters.counters.malloc_at_last_gc),
6856 .free_at_last_gc = gc_counter_load_relaxed(&objspace->malloc_counters.counters.free_at_last_gc),
6857 };
6858#if RGENGC_ESTIMATE_OLDMALLOC
6859 struct gc_malloc_bytes saved_oldmalloc = {
6860 .malloc = gc_counter_load_relaxed(&objspace->malloc_counters.oldcounters.malloc),
6861 .free = gc_counter_load_relaxed(&objspace->malloc_counters.oldcounters.free),
6862 .malloc_at_last_gc = gc_counter_load_relaxed(&objspace->malloc_counters.oldcounters.malloc_at_last_gc),
6863 .free_at_last_gc = gc_counter_load_relaxed(&objspace->malloc_counters.oldcounters.free_at_last_gc),
6864 };
6865#endif
6866 MALLOC_COUNTERS_UNLOCK(objspace);
6867 VALUE already_disabled = rb_objspace_gc_disable(objspace);
6868
6869 objspace->rgengc.allrefs_table = objspace_allrefs(objspace);
6870
6871 if (checker_func) {
6872 st_foreach(objspace->rgengc.allrefs_table, checker_func, (st_data_t)objspace);
6873 }
6874
6875 if (objspace->rgengc.error_count > 0) {
6876#if RGENGC_CHECK_MODE >= 5
6877 allrefs_dump(objspace);
6878#endif
6879 if (checker_name) rb_bug("%s: GC has problem.", checker_name);
6880 }
6881
6882 objspace_allrefs_destruct(objspace->rgengc.allrefs_table);
6883 objspace->rgengc.allrefs_table = 0;
6884
6885 if (already_disabled == Qfalse) rb_objspace_gc_enable(objspace);
6886 MALLOC_COUNTERS_LOCK(objspace);
6887 gc_counter_store_release(&objspace->malloc_counters.counters.malloc, saved_malloc.malloc);
6888 gc_counter_store_release(&objspace->malloc_counters.counters.free, saved_malloc.free);
6889 gc_counter_store_release(&objspace->malloc_counters.counters.malloc_at_last_gc, saved_malloc.malloc_at_last_gc);
6890 gc_counter_store_release(&objspace->malloc_counters.counters.free_at_last_gc, saved_malloc.free_at_last_gc);
6891#if RGENGC_ESTIMATE_OLDMALLOC
6892 gc_counter_store_release(&objspace->malloc_counters.oldcounters.malloc, saved_oldmalloc.malloc);
6893 gc_counter_store_release(&objspace->malloc_counters.oldcounters.free, saved_oldmalloc.free);
6894 gc_counter_store_release(&objspace->malloc_counters.oldcounters.malloc_at_last_gc, saved_oldmalloc.malloc_at_last_gc);
6895 gc_counter_store_release(&objspace->malloc_counters.oldcounters.free_at_last_gc, saved_oldmalloc.free_at_last_gc);
6896#endif
6897 MALLOC_COUNTERS_UNLOCK(objspace);
6898}
6899#endif /* RGENGC_CHECK_MODE >= 4 */
6900
6903 /* True only while the world is stopped: a GC.verify holding the VM lock and barrier,
6904 * or a global GC. Cross-objspace checks (walking every objspace's pages) are sound
6905 * only then. */
6906 bool world_stopped;
6907 int err_count;
6908 size_t live_object_count;
6909 size_t zombie_object_count;
6910
6911 VALUE parent;
6912 bool parent_shareable;
6913 size_t old_object_count;
6914 size_t remembered_shady_count;
6915};
6916
6917
6918static void
6919check_generation_i(const VALUE child, void *ptr)
6920{
6922 const VALUE parent = data->parent;
6923
6924 if (RGENGC_CHECK_MODE) GC_ASSERT(RVALUE_OLD_P(data->objspace, parent));
6925
6926 /* A cross-objspace edge is kept alive by the shareable/shref mechanism and is not
6927 * tracked in this objspace's remembered set. */
6928 if (GET_HEAP_OBJSPACE(child) != data->objspace) return;
6929
6930 /* Once the process goes multi-Ractor, the shareable world is managed by pinning and
6931 * shrefs rather than by the remembered set: the pinned walk at the end of a mark
6932 * re-marks every shareable object (and its shref'd children) each local cycle, and a
6933 * global GC rebuilds the generation state. So the generational old->young invariant
6934 * does not hold when either endpoint is shareable: an old constcache, cc_table or
6935 * interned string pointing at a core class that is young after a global GC is the
6936 * typical false positive. That state outlives the return to a single Ractor until
6937 * the next major (an old shareable singleton class pointing at a young
6938 * attached_object, say), so the test uses rb_gc_ever_multi_ractor_p(), which stays
6939 * true forever once multiple Ractors existed. A program that never goes multi keeps
6940 * the strict check, and ASAN catches what is left. */
6941 if (rb_gc_ever_multi_ractor_p() &&
6942 (MARKED_IN_BITMAP(GET_HEAP_SHAREABLE_BITS(parent), parent) ||
6943 MARKED_IN_BITMAP(GET_HEAP_SHAREABLE_BITS(child), child))) {
6944 return;
6945 }
6946
6947 if (!RVALUE_OLD_P(data->objspace, child)) {
6948 /* A young shareable child is pinned and kept alive by the local GC (only a
6949 * global GC collects it), so it survives even when the old parent does not
6950 * remember it. It is outside the generational remembered set, so exclude it
6951 * from the old->young check. */
6952 if (!RVALUE_REMEMBERED(data->objspace, parent) &&
6953 !RVALUE_REMEMBERED(data->objspace, child) &&
6954 !RVALUE_UNCOLLECTIBLE(data->objspace, child) &&
6956 fprintf(stderr, "verify_internal_consistency_reachable_i: WB miss (O->Y) %s -> %s\n", rb_obj_info(parent), rb_obj_info(child));
6957 data->err_count++;
6958 }
6959 }
6960}
6961
6962static void
6963check_color_i(const VALUE child, void *ptr)
6964{
6966 const VALUE parent = data->parent;
6967
6968 /* This cycle never marks a foreign child (gc_skip_foreign_object_p) and the write
6969 * barrier is a no-op across objspaces, so its colour says nothing here. */
6970 if (GET_HEAP_OBJSPACE(child) != data->objspace) return;
6971
6972 if (!RVALUE_WB_UNPROTECTED(data->objspace, parent) && RVALUE_WHITE_P(data->objspace, child)) {
6973 fprintf(stderr, "verify_internal_consistency_reachable_i: WB miss (B->W) - %s -> %s\n",
6974 rb_obj_info(parent), rb_obj_info(child));
6975 data->err_count++;
6976 }
6977}
6978
6979static void
6980check_children_i(const VALUE child, void *ptr)
6981{
6983
6984 /* Fast path: a child in this objspace (99.99% of all edges). */
6985 if (RB_LIKELY(is_pointer_to_heap(data->objspace, (void *)child))) {
6986 if (check_rvalue_consistency_force(data->objspace, child, FALSE) != 0) {
6987 fprintf(stderr, "check_children_i: %s has error (referenced from %s)\n",
6988 rb_obj_info(child), rb_obj_info(data->parent));
6989 data->err_count++;
6990 }
6991 return;
6992 }
6993
6994 /* The remaining cross-objspace check (verify_pointer_in_any_heap_p) walks every
6995 * objspace's pages, sound only with the world stopped: mid-local-GC other Ractors
6996 * change page structures concurrently. The next world-stopped verify re-checks. */
6997 if (!data->world_stopped) return;
6998
6999 /* A non-heap child reaches this callback only when a stale field was followed by a
7000 * plain rb_gc_mark (the dmark of a live but unreachable wrapper, say). Report it and
7001 * keep going rather than aborting. */
7002 if (!verify_pointer_in_any_heap_p((void *)child)) {
7003 /* The graph is in flux mid-merge, so a transient non-heap edge is expected; it
7004 * is re-checked after the merge. */
7005 if (global_objspace->during_absorb) return;
7006 fprintf(stderr, "VERIFY-NOTE: non-heap child %p (from %s)\n",
7007 (void *)child, rb_obj_info(data->parent));
7008 return;
7009 }
7010
7011 if (GET_HEAP_OBJSPACE(child) != data->objspace) {
7012 /* A legal cross-objspace edge either starts at a shareable object or is recorded
7013 * in the child's shref bit (an in-flight send or move payload kept alive across
7014 * its owner's local GC; root_scope_check_i honours the same record). An
7015 * unshareable parent holding an unrecorded foreign unshareable child would be
7016 * invisible to both local GCs. The exception is a box's top_self, which every
7017 * thread's th->top_self points at and which is VM-permanent. Skipped during a
7018 * global GC: it clears every shref bit, so the shref exemption would not fire,
7019 * and its unified exact stop-the-world mark makes the invariant itself moot. */
7020 if (!data->parent_shareable &&
7021 child != rb_gc_vm_top_self() &&
7022 !MARKED_IN_BITMAP(GET_HEAP_SHAREABLE_BITS(child), child) &&
7023 !MARKED_IN_BITMAP(GET_HEAP_SHREF_BITS(child), child) &&
7024 !rb_gc_impl_during_global_gc_p(data->objspace) &&
7025 !global_objspace->during_absorb) {
7026 fprintf(stderr, "check_children_i: containment violation: "
7027 "unshareable %s (objspace %p) -> foreign unshareable %s (objspace %p)\n",
7028 rb_obj_info(data->parent), (void *)data->objspace,
7029 rb_obj_info(child), (void *)GET_HEAP_OBJSPACE(child));
7030 data->err_count++;
7031 }
7032
7033 /* The remaining per-objspace sanity rules belong to the owner. */
7034 return;
7035 }
7036}
7037
7038/* Whether a heap slot currently holds a live object. Returns false for empty
7039 * (T_NONE), moved (T_MOVED), and zombie (T_ZOMBIE) slots, and for garbage
7040 * objects about to be swept. */
7041static bool
7042gc_slot_live_object_p(rb_objspace_t *objspace, VALUE obj)
7043{
7044 switch (BUILTIN_TYPE(obj)) {
7045 case T_NONE:
7046 case T_MOVED:
7047 case T_ZOMBIE:
7048 return false;
7049 default:
7050 return !rb_gc_impl_garbage_object_p(objspace, obj);
7051 }
7052}
7053
7054/* Verifier only: does ptr point at a live slot in any objspace? The caller holds the VM
7055 * lock and the barrier, so page_index is stable. */
7056static bool
7057verify_pointer_in_any_heap_p(const void *ptr)
7058{
7059 return gc_global_pointer_to_heap_p(ptr);
7060}
7061
7062/* An exact root of the calling Ractor may only point at a shareable object, its own
7063 * objspace, or an in-flight payload with a recorded shref. Exempt: the conservative
7064 * machine scan (stale slots) and the VM-global containers that are cross-rooted by
7065 * design (every objspace scans them; the marker skips foreign entries). */
7066static void
7067root_scope_check_i(const char *category, VALUE obj, void *ptr)
7068{
7069 struct verify_internal_consistency_struct *data = ptr;
7070
7071 if (RB_SPECIAL_CONST_P(obj)) return;
7072 /* This check walks every objspace (verify_pointer_in_any_heap_p), so it is sound
7073 * only with the world stopped; a mid-local-GC verify races with other Ractors'
7074 * lock-free allocation. */
7075 if (!data->world_stopped) return;
7076 /* Mid-merge the VM-global root tables still point at the unmerged source (transient
7077 * non-heap or foreign roots); re-checked after the merge. */
7078 if (global_objspace->during_absorb) return;
7079 if (strcmp(category, "machine_context") == 0 ||
7080 strcmp(category, "vm_registered_objects") == 0 ||
7081 strcmp(category, "end_proc") == 0 ||
7082 strcmp(category, "trap_list") == 0) {
7083 return;
7084 }
7085
7086 if (!verify_pointer_in_any_heap_p((void *)obj)) {
7087 fprintf(stderr, "root_scope_check_i: root category \"%s\" names a non-heap pointer %p\n",
7088 category, (void *)obj);
7089 data->err_count++;
7090 return;
7091 }
7092
7093 if (GET_HEAP_OBJSPACE(obj) == data->objspace) return;
7094 if (MARKED_IN_BITMAP(GET_HEAP_SHAREABLE_BITS(obj), obj)) return;
7095 if (MARKED_IN_BITMAP(GET_HEAP_SHREF_BITS(obj), obj)) return;
7096 if (obj == rb_gc_vm_top_self()) return; /* VM-permanent (see check_children_i) */
7097
7098 fprintf(stderr, "root_scope_check_i: root category \"%s\" names a foreign "
7099 "unshareable without a shref record: %s (owner %p, self %p)\n",
7100 category, rb_obj_info(obj),
7101 (void *)GET_HEAP_OBJSPACE(obj), (void *)data->objspace);
7102 data->err_count++;
7103}
7104
7105static int
7106verify_internal_consistency_i(void *page_start, void *page_end, size_t stride,
7108{
7109 VALUE obj;
7110 rb_objspace_t *objspace = data->objspace;
7111
7112 for (obj = (VALUE)page_start; obj != (VALUE)page_end; obj += stride) {
7113 asan_unpoisoning_object(obj) {
7114 bool sh_bit = MARKED_IN_BITMAP(GET_HEAP_SHAREABLE_BITS(obj), obj) != 0;
7115 bool sr_bit = MARKED_IN_BITMAP(GET_HEAP_SHREF_BITS(obj), obj) != 0;
7116
7117 if (gc_slot_live_object_p(objspace, obj)) {
7118 /* count objects */
7119 data->live_object_count++;
7120 data->parent = obj;
7121 data->parent_shareable = sh_bit;
7122
7123 /* Bitmap invariants: a page's shareable bit matches FL_SHAREABLE
7124 * exactly, and a shref record only ever points at an unshareable
7125 * object. */
7126 if (sh_bit != !!RB_FL_TEST_RAW(obj, RUBY_FL_SHAREABLE)) {
7127 fprintf(stderr, "verify_internal_consistency_i: shareable bit %d "
7128 "disagrees with FL_SHAREABLE on %s\n", (int)sh_bit, rb_obj_info(obj));
7129 data->err_count++;
7130 }
7131 if (sr_bit && sh_bit) {
7132 fprintf(stderr, "verify_internal_consistency_i: shref bit on a shareable: %s\n",
7133 rb_obj_info(obj));
7134 data->err_count++;
7135 }
7136
7137 /* Normally, we don't expect T_MOVED objects to be in the heap.
7138 * But they can stay alive on the stack, */
7139 if (!gc_object_moved_p(objspace, obj)) {
7140 /* moved slots don't have children */
7141 rb_objspace_reachable_objects_from(obj, check_children_i, (void *)data);
7142 }
7143
7144 /* check health of children */
7145 if (RVALUE_OLD_P(objspace, obj)) data->old_object_count++;
7146 if (RVALUE_WB_UNPROTECTED(objspace, obj) && RVALUE_UNCOLLECTIBLE(objspace, obj)) data->remembered_shady_count++;
7147
7148 if (!is_marking(objspace) && RVALUE_OLD_P(objspace, obj)) {
7149 /* reachable objects from an oldgen object should be old or (young with remember) */
7150 data->parent = obj;
7151 rb_objspace_reachable_objects_from(obj, check_generation_i, (void *)data);
7152 }
7153
7154 if (!is_marking(objspace) && rb_gc_obj_shareable_p(obj)) {
7155 rb_gc_verify_shareable(obj);
7156 }
7157
7158 if (is_incremental_marking(objspace)) {
7159 if (RVALUE_BLACK_P(objspace, obj)) {
7160 /* reachable objects from black objects should be black or grey objects */
7161 data->parent = obj;
7162 rb_objspace_reachable_objects_from(obj, check_color_i, (void *)data);
7163 }
7164 }
7165 }
7166 else {
7167 /* A freed slot must not carry its old pin bit into the next object born
7168 * there (a dead object not swept yet legitimately keeps it until the
7169 * sweep arrives). */
7170 if (BUILTIN_TYPE(obj) == T_NONE && (sh_bit || sr_bit)) {
7171 fprintf(stderr, "verify_internal_consistency_i: T_NONE slot carries "
7172 "shareable=%d shref=%d bits\n", (int)sh_bit, (int)sr_bit);
7173 data->err_count++;
7174 }
7175
7176 if (BUILTIN_TYPE(obj) == T_ZOMBIE) {
7177 data->zombie_object_count++;
7178
7179 if ((RBASIC(obj)->flags & ~ZOMBIE_OBJ_KEPT_FLAGS) != T_ZOMBIE) {
7180 fprintf(stderr, "verify_internal_consistency_i: T_ZOMBIE has extra flags set: %s\n",
7181 rb_obj_info(obj));
7182 data->err_count++;
7183 }
7184
7185 if (!!FL_TEST(obj, FL_FINALIZE) != !!st_is_member(finalizer_table, obj)) {
7186 fprintf(stderr, "verify_internal_consistency_i: FL_FINALIZE %s but %s finalizer_table: %s\n",
7187 FL_TEST(obj, FL_FINALIZE) ? "set" : "not set", st_is_member(finalizer_table, obj) ? "in" : "not in",
7188 rb_obj_info(obj));
7189 data->err_count++;
7190 }
7191 }
7192 }
7193 }
7194 }
7195
7196 return 0;
7197}
7198
7199static int
7200gc_verify_heap_page(rb_objspace_t *objspace, struct heap_page *page, VALUE obj)
7201{
7202 unsigned int has_remembered_shady = FALSE;
7203 unsigned int has_remembered_old = FALSE;
7204 int remembered_old_objects = 0;
7205 int free_objects = 0;
7206 int zombie_objects = 0;
7207
7208 short slot_size = page->slot_size;
7209 uintptr_t start = (uintptr_t)page->start;
7210 uintptr_t end = start + page->total_slots * slot_size;
7211
7212 for (uintptr_t ptr = start; ptr < end; ptr += slot_size) {
7213 VALUE val = (VALUE)ptr;
7214 asan_unpoisoning_object(val) {
7215 enum ruby_value_type type = BUILTIN_TYPE(val);
7216
7217 if (type == T_NONE) free_objects++;
7218 if (type == T_ZOMBIE) zombie_objects++;
7219 if (RVALUE_PAGE_UNCOLLECTIBLE(page, val) && RVALUE_PAGE_WB_UNPROTECTED(page, val)) {
7220 has_remembered_shady = TRUE;
7221 }
7222 if (RVALUE_PAGE_MARKING(page, val)) {
7223 has_remembered_old = TRUE;
7224 remembered_old_objects++;
7225 }
7226 }
7227 }
7228
7229 if (!is_incremental_marking(objspace) &&
7230 page->flags.has_remembered_objects == FALSE && has_remembered_old == TRUE) {
7231
7232 for (uintptr_t ptr = start; ptr < end; ptr += slot_size) {
7233 VALUE val = (VALUE)ptr;
7234 if (RVALUE_PAGE_MARKING(page, val)) {
7235 fprintf(stderr, "marking -> %s\n", rb_obj_info(val));
7236 }
7237 }
7238 rb_bug("page %p's has_remembered_objects should be false, but there are remembered old objects (%d). %s",
7239 (void *)page, remembered_old_objects, obj ? rb_obj_info(obj) : "");
7240 }
7241
7242 if (page->flags.has_uncollectible_wb_unprotected_objects == FALSE && has_remembered_shady == TRUE) {
7243 rb_bug("page %p's has_remembered_shady should be false, but there are remembered shady objects. %s",
7244 (void *)page, obj ? rb_obj_info(obj) : "");
7245 }
7246
7247 if (0) {
7248 /* free_slots may not equal to free_objects */
7249 if (page->free_slots != free_objects) {
7250 rb_bug("page %p's free_slots should be %d, but %d", (void *)page, page->free_slots, free_objects);
7251 }
7252 }
7253 if (page->final_slots != zombie_objects) {
7254 rb_bug("page %p's final_slots should be %d, but %d", (void *)page, page->final_slots, zombie_objects);
7255 }
7256
7257 return remembered_old_objects;
7258}
7259
7260static int
7261gc_verify_heap_pages_(rb_objspace_t *objspace, struct ccan_list_head *head)
7262{
7263 int remembered_old_objects = 0;
7264 struct heap_page *page = 0;
7265
7266 ccan_list_for_each(head, page, page_node) {
7267 asan_unlock_freelist(page);
7268 struct free_region *region = page->free_region;
7269 while (region) {
7270 VALUE vp = (VALUE)region;
7271 rb_asan_unpoison_object(vp, false);
7272 if (BUILTIN_TYPE(vp) != T_NONE) {
7273 fprintf(stderr, "free region head expected to be T_NONE but was: %s\n", rb_obj_info(vp));
7274 }
7275 struct free_region *next = region->next;
7276 rb_asan_poison_object(vp);
7277 region = next;
7278 }
7279 asan_lock_freelist(page);
7280
7281 if (page->flags.has_remembered_objects == FALSE) {
7282 remembered_old_objects += gc_verify_heap_page(objspace, page, Qfalse);
7283 }
7284 }
7285
7286 return remembered_old_objects;
7287}
7288
7289static int
7290gc_verify_heap_pages(rb_objspace_t *objspace)
7291{
7292 int remembered_old_objects = 0;
7293 for (int i = 0; i < HEAP_COUNT; i++) {
7294 remembered_old_objects += gc_verify_heap_pages_(objspace, &((&heaps[i])->pages));
7295 }
7296 return remembered_old_objects;
7297}
7298
7299static void
7300verify_registered_addr(VALUE *slot, VALUE initial_value, void *owner_objspace, void *d)
7301{
7302 struct verify_internal_consistency_struct *data = d;
7303 VALUE v = *slot;
7304
7305 /* Conservative registration permits uninitialized data and pre-registration
7306 * values; only a store made after registration is a violation. */
7307 if (v == initial_value) return;
7308 if (SPECIAL_CONST_P(v)) return;
7309 if (!verify_pointer_in_any_heap_p((void *)v)) return;
7310
7311 bool live = false;
7312 asan_unpoisoning_object(v) {
7313 live = BUILTIN_TYPE(v) != T_NONE && BUILTIN_TYPE(v) != T_ZOMBIE;
7314 }
7315 if (!live) return;
7316
7317 rb_objspace_t *value_objspace = GET_HEAP_OBJSPACE(v);
7318 if (value_objspace == (rb_objspace_t *)owner_objspace) return;
7319 /* Join and orphan handling move a registration to the inheritor before the
7320 * source objspace merge; a global GC scans every registry while the zombie
7321 * exists, so this is a safe transient exemption. */
7322 if (rb_gc_vm_zombie_objspace_p(value_objspace)) return;
7323 if (value_objspace->flags.during_postmortem) return;
7324 if (MARKED_IN_BITMAP(GET_HEAP_SHAREABLE_BITS(v), v)) return;
7325 if (MARKED_IN_BITMAP(GET_HEAP_SHREF_BITS(v), v)) return;
7326 /* When multiple Ractors register one address, ownership by any registrant is
7327 * enough to root the value. */
7328 if (rb_gc_registered_addr_owned_by_registrant_p(slot, value_objspace)) return;
7329
7330 fprintf(stderr, "registered address %p changed since registration to an unshareable object owned by another Ractor: %s\n",
7331 (void *)slot, rb_obj_info(v));
7332 data->err_count++;
7333}
7334
7335static void
7336gc_verify_internal_consistency_(rb_objspace_t *objspace, bool world_stopped)
7337{
7338 struct verify_internal_consistency_struct data = {0};
7339
7340 data.objspace = objspace;
7341 data.world_stopped = world_stopped;
7342 gc_report(5, objspace, "gc_verify_internal_consistency: start\n");
7343
7344 /* check relations */
7345 for (size_t i = 0; i < rb_darray_size(objspace->heap_pages.sorted); i++) {
7346 struct heap_page *page = rb_darray_get(objspace->heap_pages.sorted, i);
7347 short slot_size = page->slot_size;
7348
7349 uintptr_t start = (uintptr_t)page->start;
7350 uintptr_t end = start + page->total_slots * slot_size;
7351
7352 verify_internal_consistency_i((void *)start, (void *)end, slot_size, &data);
7353 }
7354
7355 /* Check the calling Ractor's root scoping (only when verifying the current
7356 * objspace). Skipped during a global GC, which deliberately spans every Ractor's
7357 * roots and legitimately reaches foreign objects: containment does not apply. */
7358 if (!rb_gc_single_objspace_p() && objspace == rb_gc_get_objspace() &&
7359 !rb_gc_impl_during_global_gc_p(objspace)) {
7360 rb_objspace_reachable_objects_from_root(root_scope_check_i, &data);
7361 }
7362
7363 if (data.world_stopped && !global_objspace->during_absorb) {
7364 rb_gc_each_registered_addr(verify_registered_addr, &data);
7365 }
7366
7367 if (data.err_count != 0) {
7368#if RGENGC_CHECK_MODE >= 5
7369 objspace->rgengc.error_count = data.err_count;
7370 gc_marks_check(objspace, NULL, NULL);
7371 allrefs_dump(objspace);
7372#endif
7373 rb_bug("gc_verify_internal_consistency: found internal inconsistency.");
7374 }
7375
7376 /* check heap_page status */
7377 gc_verify_heap_pages(objspace);
7378
7379 /* check counters */
7380
7381 if (!is_lazy_sweeping(objspace) &&
7382 !finalizing &&
7383 !rb_gc_multi_ractor_p()) {
7384 if (objspace_live_slots(objspace) != data.live_object_count) {
7385 fprintf(stderr, "heap_pages_final_slots: %"PRIdSIZE", total_freed_objects: %"PRIdSIZE"\n",
7386 total_final_slots_count(objspace), total_freed_objects(objspace));
7387 rb_bug("inconsistent live slot number: expect %"PRIuSIZE", but %"PRIuSIZE".",
7388 objspace_live_slots(objspace), data.live_object_count);
7389 }
7390 }
7391
7392 if (!is_marking(objspace)) {
7393 if (objspace->rgengc.old_objects != data.old_object_count) {
7394 rb_bug("inconsistent old slot number: expect %"PRIuSIZE", but %"PRIuSIZE".",
7395 objspace->rgengc.old_objects, data.old_object_count);
7396 }
7397 if (objspace->rgengc.uncollectible_wb_unprotected_objects != data.remembered_shady_count) {
7398 rb_bug("inconsistent number of wb unprotected objects: expect %"PRIuSIZE", but %"PRIuSIZE".",
7399 objspace->rgengc.uncollectible_wb_unprotected_objects, data.remembered_shady_count);
7400 }
7401 }
7402
7403 if (!finalizing) {
7404 size_t list_count = 0;
7405
7406 {
7407 VALUE z = heap_pages_deferred_final;
7408 while (z) {
7409 list_count++;
7410 z = RZOMBIE(z)->next;
7411 }
7412 }
7413
7414 if (total_final_slots_count(objspace) != data.zombie_object_count ||
7415 total_final_slots_count(objspace) != list_count) {
7416
7417 rb_bug("inconsistent finalizing object count:\n"
7418 " expect %"PRIuSIZE"\n"
7419 " but %"PRIuSIZE" zombies\n"
7420 " heap_pages_deferred_final list has %"PRIuSIZE" items.",
7421 total_final_slots_count(objspace),
7422 data.zombie_object_count,
7423 list_count);
7424 }
7425 }
7426
7427 gc_report(5, objspace, "gc_verify_internal_consistency: OK\n");
7428}
7429
7430/* The `during_gc` macro expands a bare identifier to `objspace->flags.during_gc`, so a
7431 * foreign objspace's flag cannot be written directly; these helpers reach it through the
7432 * `objspace` argument. */
7433static inline unsigned int
7434gc_during_gc_get(const rb_objspace_t *objspace)
7435{
7436 return during_gc;
7437}
7438
7439static inline void
7440gc_during_gc_set(rb_objspace_t *objspace, unsigned int v)
7441{
7442 during_gc = v;
7443}
7444
7445/* Run the check with during_gc cleared in both the verified objspace and the current
7446 * Ractor's: rb_objspace_reachable_objects_from() decides on rb_gc_get_objspace(), and
7447 * under a global GC the driver verifies foreign objspaces, so the driver's during_gc
7448 * needs clearing too (a no-op when cur == objspace). */
7449static void
7450gc_verify_internal_consistency_body(rb_objspace_t *objspace, bool world_stopped)
7451{
7452 const unsigned int prev_during_gc = during_gc;
7453 during_gc = FALSE; // stop gc here
7454
7455 rb_objspace_t *const cur = rb_gc_get_objspace();
7456 const unsigned int prev_cur_during_gc = (cur != objspace) ? gc_during_gc_get(cur) : 0;
7457 if (cur != objspace) gc_during_gc_set(cur, FALSE);
7458 {
7459 gc_verify_internal_consistency_(objspace, world_stopped);
7460 }
7461 if (cur != objspace) gc_during_gc_set(cur, prev_cur_during_gc);
7462 during_gc = prev_during_gc;
7463}
7464
7465static void
7466gc_verify_internal_consistency(void *objspace_ptr)
7467{
7468 rb_objspace_t *objspace = objspace_ptr;
7469
7470 /* Called mid-GC, take neither the VM lock nor the barrier: waiting would join a
7471 * pending global barrier mid-collection (a GC must never take the VM lock) and let
7472 * the global GC sweep the heap this mark is walking. The barrier is unnecessary
7473 * anyway; the objspace is single-writer, this verify runs on its owner thread, and
7474 * the global driver that sets during_gc everywhere already holds both. */
7475 if (during_gc) {
7476 /* The world is stopped only when the global GC's driver runs this while holding
7477 * the barrier; a non-main Ractor's local GC does not stop other Ractors. */
7478 gc_verify_internal_consistency_body(objspace, rb_gc_impl_during_global_gc_p(objspace));
7479 return;
7480 }
7481
7482 unsigned int lev = RB_GC_VM_LOCK();
7483 {
7484 rb_gc_vm_barrier(); // stop other ractors
7485 gc_verify_internal_consistency_body(objspace, true); // holding the barrier, so walking every objspace is sound
7486 }
7487 RB_GC_VM_UNLOCK(lev);
7488}
7489
7490static void
7491heap_move_pooled_pages_to_free_pages(rb_heap_t *heap)
7492{
7493 if (heap->pooled_pages) {
7494 if (heap->free_pages) {
7495 struct heap_page *free_pages_tail = heap->free_pages;
7496 while (free_pages_tail->free_next) {
7497 free_pages_tail = free_pages_tail->free_next;
7498 }
7499 free_pages_tail->free_next = heap->pooled_pages;
7500 }
7501 else {
7502 heap->free_pages = heap->pooled_pages;
7503 }
7504
7505 heap->pooled_pages = NULL;
7506 }
7507}
7508
7509static int
7510gc_remember_unprotected(rb_objspace_t *objspace, VALUE obj)
7511{
7512 struct heap_page *page = GET_HEAP_PAGE(obj);
7513 bits_t *uncollectible_bits = &page->uncollectible_bits[0];
7514
7515 if (!MARKED_IN_BITMAP(uncollectible_bits, obj)) {
7516 page->flags.has_uncollectible_wb_unprotected_objects = TRUE;
7517 MARK_IN_BITMAP(uncollectible_bits, obj);
7518 /* Like RVALUE_PAGE_OLD_UNCOLLECTIBLE_SET, count it in the object's own objspace. */
7519 page->objspace->rgengc.uncollectible_wb_unprotected_objects++;
7520
7521#if RGENGC_PROFILE > 0
7522 objspace->profile.total_remembered_shady_object_count++;
7523#if RGENGC_PROFILE >= 2
7524 objspace->profile.remembered_shady_object_count_types[BUILTIN_TYPE(obj)]++;
7525#endif
7526#endif
7527 return TRUE;
7528 }
7529 else {
7530 return FALSE;
7531 }
7532}
7533
7534static inline void
7535gc_marks_wb_unprotected_objects_plane(rb_objspace_t *objspace, uintptr_t p, bits_t bits, short slot_size)
7536{
7537 if (bits) {
7538 do {
7539 if (bits & 1) {
7540 gc_report(2, objspace, "gc_marks_wb_unprotected_objects: marked shady: %s\n", rb_obj_info((VALUE)p));
7541 GC_ASSERT(RVALUE_WB_UNPROTECTED(objspace, (VALUE)p));
7542 GC_ASSERT(RVALUE_MARKED(objspace, (VALUE)p));
7543 gc_mark_children(objspace, (VALUE)p);
7544 }
7545 p += slot_size;
7546 bits >>= 1;
7547 } while (bits);
7548 }
7549}
7550
7551static void
7552gc_marks_wb_unprotected_objects(rb_objspace_t *objspace, rb_heap_t *heap)
7553{
7554 struct heap_page *page = 0;
7555
7556 ccan_list_for_each(&heap->pages, page, page_node) {
7557 bits_t *mark_bits = page->mark_bits;
7558 bits_t *wbun_bits = page->wb_unprotected_bits;
7559 uintptr_t p = page->start;
7560 short slot_size = page->slot_size;
7561 int total_slots = page->total_slots;
7562 int bitmap_plane_count = CEILDIV(total_slots, BITS_BITLENGTH);
7563 size_t j;
7564
7565 for (j=0; j<(size_t)bitmap_plane_count; j++) {
7566 bits_t bits = mark_bits[j] & wbun_bits[j];
7567 gc_marks_wb_unprotected_objects_plane(objspace, p, bits, slot_size);
7568 p += BITS_BITLENGTH * slot_size;
7569 }
7570 }
7571
7572 gc_mark_stacked_objects_all(objspace);
7573}
7574
7575void
7576rb_gc_impl_declare_weak_references(void *objspace_ptr, VALUE obj)
7577{
7579}
7580
7581bool
7582rb_gc_impl_handle_weak_references_alive_p(void *objspace_ptr, VALUE obj)
7583{
7584 rb_objspace_t *objspace = objspace_ptr;
7585
7586 /* A local GC cannot decide a foreign object's liveness, so treat it as live; its
7587 * owner or the global GC decides (a global GC's unified mark is exact). */
7588 if (gc_skip_foreign_object_p(objspace, obj)) return true;
7589
7590 bool marked = RVALUE_MARKED(objspace, obj);
7591
7592 if (marked) {
7593 rgengc_check_relation(objspace, obj);
7594 }
7595
7596 return marked;
7597}
7598
7599static void
7600gc_update_weak_references(rb_objspace_t *objspace)
7601{
7602 VALUE *obj_ptr;
7603 rb_darray_foreach(objspace->weak_references, i, obj_ptr) {
7604 gc_mark_set_parent(objspace, *obj_ptr);
7605 rb_gc_handle_weak_references(*obj_ptr);
7606 gc_mark_set_parent_invalid(objspace);
7607 }
7608
7609 size_t capa = rb_darray_capa(objspace->weak_references);
7610 size_t size = rb_darray_size(objspace->weak_references);
7611
7612 objspace->profile.weak_references_count = size;
7613
7614 rb_darray_clear(objspace->weak_references);
7615
7616 /* If the darray has capacity for more than four times the amount used, we
7617 * shrink it down to half of that capacity. */
7618 if (capa > size * 4) {
7619 rb_darray_resize_capa_without_gc(&objspace->weak_references, size * 2);
7620 }
7621}
7622
7623static void
7624gc_marks_finish(rb_objspace_t *objspace)
7625{
7626 /* finish incremental GC */
7627 if (is_incremental_marking(objspace)) {
7628 if (RGENGC_CHECK_MODE && is_mark_stack_empty(&objspace->mark_stack) == 0) {
7629 rb_bug("gc_marks_finish: mark stack is not empty (%"PRIdSIZE").",
7630 mark_stack_size(&objspace->mark_stack));
7631 }
7632
7633 mark_roots(objspace, NULL);
7634 while (gc_mark_stacked_objects_incremental(objspace, INT_MAX) == false);
7635
7636#if RGENGC_CHECK_MODE >= 2
7637 if (gc_verify_heap_pages(objspace) != 0) {
7638 rb_bug("gc_marks_finish (incremental): there are remembered old objects.");
7639 }
7640#endif
7641
7642 objspace->flags.during_incremental_marking = FALSE;
7643 /* check children of all marked wb-unprotected objects */
7644 for (int i = 0; i < HEAP_COUNT; i++) {
7645 gc_marks_wb_unprotected_objects(objspace, &heaps[i]);
7646 }
7647 }
7648
7649 /* Pin the shareable objects and shrefs ordinary marking missed: a local GC must free
7650 * neither (another objspace may hold them). Running after the full walk makes the
7651 * pin count a retention metric: an upper bound on the garbage only a global GC can
7652 * reclaim. A global GC's exact mark does not pin. (The allrefs comparison of
7653 * RGENGC_CHECK_MODE >= 4 does not model these pins; it reports false positives.)
7654 *
7655 * Running it here rather than with the other roots is also what lets an incremental
7656 * mark run while other objspaces exist. The write barrier bails out on a
7657 * cross-objspace edge, so a store made between two mark steps leaves nothing behind
7658 * but a shareable or shref bit; scanning those bitmaps after the last step picks up
7659 * every bit set during the cycle, which a scan at gc_marks_start would miss. */
7660 objspace->last_cycle_pinned = 0;
7661 if (!rb_gc_single_objspace_p() && !objspace->flags.during_global_gc) {
7662 objspace->last_cycle_pinned = 1;
7663 gc_mark_set_parent_raw(objspace, Qundef, false);
7664 for (int i = 0; i < HEAP_COUNT; i++) {
7665 pinned_roots_mark(objspace, &heaps[i]);
7666 }
7667 /* And everything they keep alive. */
7668 gc_mark_stacked_objects_all(objspace);
7669 }
7670
7671 gc_update_weak_references(objspace);
7672
7673#if RGENGC_CHECK_MODE >= 4
7674 during_gc = FALSE;
7675 gc_marks_check(objspace, gc_check_after_marks_i, "after_marks");
7676 during_gc = TRUE;
7677#endif
7678
7679 {
7680 /* Only this objspace's own Ractor allocates from it. The main objspace
7681 * keeps the VM-wide count it has used since before per-Ractor GC. */
7682 const unsigned long ractor_cnt = objspace == global_objspace->main_objspace
7683 ? rb_gc_vm_ractor_count() : 1;
7684 const unsigned long r_mul = ractor_cnt > 8 ? 8 : ractor_cnt; // upto 8
7685
7686 size_t total_slots = objspace_available_slots(objspace);
7687 size_t sweep_slots = total_slots - objspace->marked_slots; /* will be swept slots */
7688 size_t max_free_slots = (size_t)(total_slots * gc_params.heap_free_slots_max_ratio);
7689 size_t min_free_slots = (size_t)(total_slots * gc_params.heap_free_slots_min_ratio);
7690 if (min_free_slots < gc_params.heap_free_slots * r_mul) {
7691 min_free_slots = gc_params.heap_free_slots * r_mul;
7692 }
7693
7694 int full_marking = is_full_marking(objspace);
7695
7696 GC_ASSERT(objspace_available_slots(objspace) >= objspace->marked_slots);
7697
7698 /* Setup freeable slots. */
7699 size_t total_init_slots = 0;
7700 for (int i = 0; i < HEAP_COUNT; i++) {
7701 total_init_slots += (objspace_heap_init_bytes(objspace) / heaps[i].slot_size) * r_mul;
7702 }
7703
7704 if (max_free_slots < total_init_slots) {
7705 max_free_slots = total_init_slots;
7706 }
7707
7708 /* Approximate freeable pages using the average slots-per-pages across all heaps */
7709 if (sweep_slots > max_free_slots) {
7710 size_t excess_slots = sweep_slots - max_free_slots;
7711 size_t total_heap_pages = heap_eden_total_pages(objspace);
7712 heap_pages_freeable_pages = total_heap_pages > 0
7713 ? excess_slots * total_heap_pages / total_slots
7714 : 0;
7715 }
7716 else {
7717 heap_pages_freeable_pages = 0;
7718 }
7719
7720 if (objspace->heap_pages.allocatable_bytes == 0 && sweep_slots < min_free_slots) {
7721 if (!full_marking && sweep_slots < min_free_slots * 7 / 8) {
7722 if (objspace->profile.count - objspace->rgengc.last_major_gc < RVALUE_OLD_AGE) {
7723 full_marking = TRUE;
7724 }
7725 else {
7726 gc_report(1, objspace, "gc_marks_finish: next is full GC!!)\n");
7727 gc_needs_major_flags |= GPR_FLAG_MAJOR_BY_NOFREE;
7728 }
7729 }
7730
7731 if (full_marking) {
7732 heap_allocatable_bytes_expand(objspace, NULL, sweep_slots, total_slots, heaps[0].slot_size);
7733 }
7734 }
7735
7736 if (full_marking) {
7737 /* See the comment about RUBY_GC_HEAP_OLDOBJECT_LIMIT_FACTOR */
7738 const double r = gc_params.oldobject_limit_factor;
7739 objspace->rgengc.uncollectible_wb_unprotected_objects_limit = MAX(
7740 (size_t)(objspace->rgengc.uncollectible_wb_unprotected_objects * r),
7741 (size_t)(objspace->rgengc.old_objects * gc_params.uncollectible_wb_unprotected_objects_limit_ratio)
7742 );
7743 objspace->rgengc.old_objects_limit = (size_t)(objspace->rgengc.old_objects * r);
7744 }
7745
7746 if (objspace->rgengc.uncollectible_wb_unprotected_objects > objspace->rgengc.uncollectible_wb_unprotected_objects_limit) {
7747 gc_needs_major_flags |= GPR_FLAG_MAJOR_BY_SHADY;
7748 }
7749 if (objspace->rgengc.old_objects > objspace->rgengc.old_objects_limit) {
7750 gc_needs_major_flags |= GPR_FLAG_MAJOR_BY_OLDGEN;
7751 }
7752
7753 gc_report(1, objspace, "gc_marks_finish (marks %"PRIdSIZE" objects, "
7754 "old %"PRIdSIZE" objects, total %"PRIdSIZE" slots, "
7755 "sweep %"PRIdSIZE" slots, allocatable %"PRIdSIZE" bytes, next GC: %s)\n",
7756 objspace->marked_slots, objspace->rgengc.old_objects, objspace_available_slots(objspace), sweep_slots, objspace->heap_pages.allocatable_bytes,
7757 gc_needs_major_flags ? "major" : "minor");
7758 }
7759
7760 // TODO: refactor so we don't need to call this
7761 rb_ractor_finish_marking(is_full_marking(objspace));
7762
7764}
7765
7766static bool
7767gc_compact_heap_cursors_met_p(rb_heap_t *heap)
7768{
7769 return heap->sweeping_page == heap->compact_cursor;
7770}
7771
7772
7773static rb_heap_t *
7774gc_compact_destination_pool(rb_objspace_t *objspace, rb_heap_t *src_pool, VALUE obj)
7775{
7776 size_t obj_size = rb_gc_obj_optimal_size(obj);
7777 if (obj_size == 0) {
7778 return src_pool;
7779 }
7780
7781 GC_ASSERT(rb_gc_impl_size_allocatable_p(obj_size));
7782
7783 size_t idx = heap_idx_for_size(obj_size);
7784
7785 return &heaps[idx];
7786}
7787
7788static bool
7789gc_compact_move(rb_objspace_t *objspace, rb_heap_t *heap, VALUE src)
7790{
7791 GC_ASSERT(BUILTIN_TYPE(src) != T_MOVED);
7792 GC_ASSERT(gc_is_moveable_obj(objspace, src));
7793
7794 rb_heap_t *dest_pool = gc_compact_destination_pool(objspace, heap, src);
7795 if (gc_compact_heap_cursors_met_p(dest_pool)) {
7796 return dest_pool != heap;
7797 }
7798
7799 while (!try_move(objspace, dest_pool, dest_pool->free_pages, src)) {
7800 struct gc_sweep_context ctx = {
7801 .page = dest_pool->sweeping_page,
7802 .final_slots = 0,
7803 .freed_slots = 0,
7804 .empty_slots = 0,
7805 };
7806
7807 /* The page of src could be partially compacted, so it may contain
7808 * T_MOVED. Sweeping a page may read objects on this page, so we
7809 * need to lock the page. */
7810 lock_page_body(objspace, GET_PAGE_BODY(src));
7811 gc_sweep_page(objspace, dest_pool, &ctx);
7812 unlock_page_body(objspace, GET_PAGE_BODY(src));
7813
7814 if (dest_pool->sweeping_page->free_slots > 0) {
7815 heap_add_freepage(dest_pool, dest_pool->sweeping_page);
7816 }
7817
7818 dest_pool->sweeping_page = ccan_list_next(&dest_pool->pages, dest_pool->sweeping_page, page_node);
7819 if (gc_compact_heap_cursors_met_p(dest_pool)) {
7820 return dest_pool != heap;
7821 }
7822 }
7823
7824 return true;
7825}
7826
7827static bool
7828gc_compact_plane(rb_objspace_t *objspace, rb_heap_t *heap, uintptr_t p, bits_t bitset, struct heap_page *page)
7829{
7830 short slot_size = page->slot_size;
7831
7832 do {
7833 VALUE vp = (VALUE)p;
7834 GC_ASSERT(vp % sizeof(VALUE) == 0);
7835
7836 if (bitset & 1) {
7837 objspace->rcompactor.considered_count_table[BUILTIN_TYPE(vp)]++;
7838
7839 if (gc_is_moveable_obj(objspace, vp)) {
7840 if (!gc_compact_move(objspace, heap, vp)) {
7841 //the cursors met. bubble up
7842 return false;
7843 }
7844 }
7845 }
7846 p += slot_size;
7847 bitset >>= 1;
7848 } while (bitset);
7849
7850 return true;
7851}
7852
7853// Iterate up all the objects in page, moving them to where they want to go
7854static bool
7855gc_compact_page(rb_objspace_t *objspace, rb_heap_t *heap, struct heap_page *page)
7856{
7857 GC_ASSERT(page == heap->compact_cursor);
7858
7859 bits_t *mark_bits, *pin_bits;
7860 bits_t bitset;
7861 uintptr_t p = page->start;
7862 short slot_size = page->slot_size;
7863 int total_slots = page->total_slots;
7864 int bitmap_plane_count = CEILDIV(total_slots, BITS_BITLENGTH);
7865
7866 mark_bits = page->mark_bits;
7867 pin_bits = page->pinned_bits;
7868
7869 for (int j = 0; j < bitmap_plane_count; j++) {
7870 // objects that can be moved are marked and not pinned
7871 bitset = (mark_bits[j] & ~pin_bits[j]);
7872 if (bitset) {
7873 if (!gc_compact_plane(objspace, heap, (uintptr_t)p, bitset, page))
7874 return false;
7875 }
7876 p += BITS_BITLENGTH * slot_size;
7877 }
7878
7879 return true;
7880}
7881
7882static bool
7883gc_compact_all_compacted_p(rb_objspace_t *objspace)
7884{
7885 for (int i = 0; i < HEAP_COUNT; i++) {
7886 rb_heap_t *heap = &heaps[i];
7887
7888 if (heap->total_pages > 0 &&
7889 !gc_compact_heap_cursors_met_p(heap)) {
7890 return false;
7891 }
7892 }
7893
7894 return true;
7895}
7896
7897/* Compaction's move phase: relocate this objspace's movable objects and leave T_MOVED
7898 * forwarding behind without updating references yet. A global GC calls this for every
7899 * objspace before updating any of them (two phases), so a cross-objspace reference to a
7900 * moved object is rewritten exactly once, after all forwarding exists. */
7901static void
7902gc_compact_relocate(rb_objspace_t *objspace)
7903{
7904 gc_compact_start(objspace);
7905
7906 while (!gc_compact_all_compacted_p(objspace)) {
7907 for (int i = 0; i < HEAP_COUNT; i++) {
7908 rb_heap_t *heap = &heaps[i];
7909
7910 if (gc_compact_heap_cursors_met_p(heap)) {
7911 continue;
7912 }
7913
7914 struct heap_page *start_page = heap->compact_cursor;
7915
7916 if (!gc_compact_page(objspace, heap, start_page)) {
7917 lock_page_body(objspace, start_page->body);
7918
7919 continue;
7920 }
7921
7922 // If we get here, we've finished moving all objects on the compact_cursor page
7923 // So we can lock it and move the cursor on to the next one.
7924 lock_page_body(objspace, start_page->body);
7925 heap->compact_cursor = ccan_list_prev(&heap->pages, heap->compact_cursor, page_node);
7926 }
7927 }
7928}
7929
7930static void
7931gc_sweep_compact(rb_objspace_t *objspace)
7932{
7933 gc_compact_relocate(objspace);
7934 /* A compacting global GC defers the finish (reference update) to the second phase,
7935 * after every objspace has been relocated. */
7936 if (!global_objspace->global_gc.compacting) {
7937 gc_compact_finish(objspace);
7938 }
7939}
7940
7941static void
7942gc_marks_rest(rb_objspace_t *objspace)
7943{
7944 gc_report(1, objspace, "gc_marks_rest\n");
7945
7946 for (int i = 0; i < HEAP_COUNT; i++) {
7947 (&heaps[i])->pooled_pages = NULL;
7948 }
7949
7950 if (is_incremental_marking(objspace)) {
7951 while (gc_mark_stacked_objects_incremental(objspace, INT_MAX) == FALSE);
7952 }
7953 else {
7954 gc_mark_stacked_objects_all(objspace);
7955 }
7956
7957 gc_marks_finish(objspace);
7958}
7959
7960static bool
7961gc_marks_step(rb_objspace_t *objspace, size_t slots)
7962{
7963 bool marking_finished = false;
7964
7965 GC_ASSERT(is_marking(objspace));
7966 if (gc_mark_stacked_objects_incremental(objspace, slots)) {
7967 gc_marks_finish(objspace);
7968
7969 marking_finished = true;
7970 }
7971
7972 return marking_finished;
7973}
7974
7975static bool
7976gc_marks_continue(rb_objspace_t *objspace, rb_heap_t *heap)
7977{
7978 GC_ASSERT(dont_gc_val() == FALSE || objspace->profile.latest_gc_info & GPR_FLAG_METHOD);
7979 bool marking_finished = true;
7980
7981 gc_marking_enter(objspace);
7982
7983 if (heap->free_pages) {
7984 gc_report(2, objspace, "gc_marks_continue: has pooled pages");
7985
7986 marking_finished = gc_marks_step(objspace, objspace->rincgc.step_slots);
7987 }
7988 else {
7989 gc_report(2, objspace, "gc_marks_continue: no more pooled pages (stack depth: %"PRIdSIZE").\n",
7990 mark_stack_size(&objspace->mark_stack));
7991 heap->force_incremental_marking_finish_count++;
7992 gc_marks_rest(objspace);
7993 }
7994
7995 gc_marking_exit(objspace);
7996
7997 return marking_finished;
7998}
7999
8000/* Mark the following as roots of this objspace.
8001 * - Every shareable object: another objspace may hold the only reference, invisible to a
8002 * local GC. Marking them rather than skipping them in the sweep preserves the
8003 * generational invariants (a pinned object ages and gets promoted like any live one).
8004 * Only a global GC decides that a shareable object is dead.
8005 * - Every shref (an unshareable object referenced from a shareable one): the referring
8006 * shareable object can live in another objspace or in an in-flight message queue. The
8007 * write barrier maintains them.
8008 * Skipped while the VM has a single Ractor: a local GC is then a whole-world GC and
8009 * shareable objects may die normally. */
8010static void
8011pinned_roots_mark(rb_objspace_t *objspace, rb_heap_t *heap)
8012{
8013 struct heap_page *page = NULL;
8014
8015 /* Runs before mark_roots, so rgengc_check_relation sees a valid (absent) parent rather
8016 * than the poison left by the previous GC. */
8017 gc_mark_set_parent_raw(objspace, Qundef, false);
8018
8019 /* A local GC never frees or traverses a shareable object, and keeps its unshareable
8020 * children alive through their shref bits, so:
8021 * - a shareable object only gets its mark bit set (like an old object), which keeps
8022 * the sweep off it, and is not traversed;
8023 * - a shref is marked and traversed, like a remembered old->young target: without
8024 * that, the referring shareable object is never walked and it would look
8025 * unreachable.
8026 * Objects can become shareable between GCs, so this pass scans the bitmaps in every
8027 * mark (gc_marks_finish) instead of maintaining a pin set across the sweep. */
8028 ccan_list_for_each(&heap->pages, page, page_node) {
8029 if (!(page->flags.has_shareable_objects | page->flags.has_shref_objects)) continue;
8030
8031 uintptr_t p = page->start;
8032 short slot_size = page->slot_size;
8033 int total_slots = page->total_slots;
8034 int bitmap_plane_count = CEILDIV(total_slots, BITS_BITLENGTH);
8035
8036 for (int j = 0; j < bitmap_plane_count; j++) {
8037 bits_t sr_bits = page->shref_bits[j];
8038 /* Only the pins ordinary marking left unmarked need work here: an already
8039 * marked object (reached by traversal, or pre-marked because it is old) is a
8040 * no-op in gc_mark_set, so skip visiting it. */
8041 bits_t bitset = (page->shareable_bits[j] | sr_bits) & ~page->mark_bits[j];
8042 uintptr_t pp = p;
8043 while (bitset) {
8044 if (bitset & 1) {
8045 VALUE obj = (VALUE)pp;
8046 asan_unpoisoning_object(obj) {
8047 switch (BUILTIN_TYPE(obj)) {
8048 case T_NONE:
8049 case T_ZOMBIE:
8050 case T_MOVED:
8051 /* A dead slot (a zombie awaiting its finalizer) is not a root. */
8052 break;
8053 default:
8054 gc_report(2, objspace, "pinned_roots_mark: mark %s\n", rb_obj_info(obj));
8055 if (sr_bits & 1) {
8056 gc_mark(objspace, obj); /* shref: root + traverse */
8057 }
8058 else if (gc_mark_set(objspace, obj)) {
8059 gc_aging(objspace, obj); /* shareable: mark, no traverse */
8060 /* Pin as well when compaction runs alongside: if a shareable
8061 * object moved, the C-struct slots of other Ractors (a
8062 * port in sync, say) are not updated and go stale. */
8063 gc_pin(objspace, obj);
8064 }
8065 break;
8066 }
8067 }
8068 }
8069 pp += slot_size;
8070 bitset >>= 1;
8071 sr_bits >>= 1;
8072 }
8073 p += BITS_BITLENGTH * slot_size;
8074 }
8075 }
8076}
8077
8078static void
8079gc_marks_start(rb_objspace_t *objspace, int full_mark)
8080{
8081 /* start marking */
8082 gc_report(1, objspace, "gc_marks_start: (%s)\n", full_mark ? "full" : "minor");
8083 gc_mode_transition(objspace, gc_mode_marking);
8084
8085 if (full_mark) {
8086 size_t incremental_marking_steps = (objspace->rincgc.pooled_slots / INCREMENTAL_MARK_STEP_ALLOCATIONS) + 1;
8087 objspace->rincgc.step_slots = (objspace->marked_slots * 2) / incremental_marking_steps;
8088
8089 if (0) fprintf(stderr, "objspace->marked_slots: %"PRIdSIZE", "
8090 "objspace->rincgc.pooled_page_num: %"PRIdSIZE", "
8091 "objspace->rincgc.step_slots: %"PRIdSIZE", \n",
8092 objspace->marked_slots, objspace->rincgc.pooled_slots, objspace->rincgc.step_slots);
8093 objspace->flags.during_minor_gc = FALSE;
8094 if (ruby_enable_autocompact && rb_gc_single_objspace_p()) {
8095 objspace->flags.during_compacting |= TRUE;
8096 }
8097 objspace->profile.major_gc_count++;
8098 objspace->rgengc.uncollectible_wb_unprotected_objects = 0;
8099 objspace->rgengc.old_objects = 0;
8100 objspace->rgengc.last_major_gc = objspace->profile.count;
8101 objspace->marked_slots = 0;
8102
8103 for (int i = 0; i < HEAP_COUNT; i++) {
8104 rb_heap_t *heap = &heaps[i];
8105 gc_bitmaps_clear(objspace, heap, false);
8106 heap_move_pooled_pages_to_free_pages(heap);
8107
8108 if (objspace->flags.during_compacting) {
8109 struct heap_page *page = NULL;
8110
8111 ccan_list_for_each(&heap->pages, page, page_node) {
8112 page->pinned_slots = 0;
8113 }
8114 }
8115 }
8116 }
8117 else {
8118 objspace->flags.during_minor_gc = TRUE;
8119 objspace->marked_slots =
8120 objspace->rgengc.old_objects + objspace->rgengc.uncollectible_wb_unprotected_objects; /* uncollectible objects are marked already */
8121 objspace->profile.minor_gc_count++;
8122
8123 for (int i = 0; i < HEAP_COUNT; i++) {
8124 rgengc_rememberset_mark(objspace, &heaps[i]);
8125 }
8126 }
8127
8128 mark_roots(objspace, NULL);
8129
8130 gc_report(1, objspace, "gc_marks_start: (%s) end, stack in %"PRIdSIZE"\n",
8131 full_mark ? "full" : "minor", mark_stack_size(&objspace->mark_stack));
8132}
8133
8134static bool
8135gc_marks(rb_objspace_t *objspace, int full_mark)
8136{
8137 gc_marking_enter(objspace);
8138
8139 bool marking_finished = false;
8140
8141 /* setup marking */
8142
8143 gc_marks_start(objspace, full_mark);
8144 if (!is_incremental_marking(objspace)) {
8145 gc_marks_rest(objspace);
8146 marking_finished = true;
8147 }
8148
8149#if RGENGC_PROFILE > 0
8150 if (gc_prof_record(objspace)) {
8151 gc_profile_record *record = gc_prof_record(objspace);
8152 record->old_objects = objspace->rgengc.old_objects;
8153 }
8154#endif
8155
8156 gc_marking_exit(objspace);
8157
8158 return marking_finished;
8159}
8160
8161/* RGENGC */
8162
8163static void
8164gc_report_body(int level, rb_objspace_t *objspace, const char *fmt, ...)
8165{
8166 if (level <= RGENGC_DEBUG) {
8167 char buf[1024];
8168 FILE *out = stderr;
8169 va_list args;
8170 const char *status = " ";
8171
8172 if (during_gc) {
8173 status = is_full_marking(objspace) ? "+" : "-";
8174 }
8175 else {
8176 if (is_lazy_sweeping(objspace)) {
8177 status = "S";
8178 }
8179 if (is_incremental_marking(objspace)) {
8180 status = "M";
8181 }
8182 }
8183
8184 va_start(args, fmt);
8185 vsnprintf(buf, 1024, fmt, args);
8186 va_end(args);
8187
8188 fprintf(out, "%s|", status);
8189 fputs(buf, out);
8190 }
8191}
8192
8193/* bit operations */
8194
8195static void
8196rgengc_remembersetbits_set(rb_objspace_t *objspace, VALUE obj)
8197{
8198 struct heap_page *page = GET_HEAP_PAGE(obj);
8199 bits_t *bits = &page->remembered_bits[0];
8200
8201 /* remembered_bits writers are always serialized: the write barrier only remembers a
8202 * local a (under its Ractor's GVL) and a global GC writes from the driver alone.
8203 * Set the bit before the page flag so a page pending re-scan stays in
8204 * rememberset_mark. */
8205 _MARK_IN_BITMAP(bits, page, obj);
8206 page->flags.has_remembered_objects = TRUE;
8207}
8208
8209/* wb, etc */
8210
8211/* return FALSE if already remembered */
8212static void
8213rgengc_remember(rb_objspace_t *objspace, VALUE obj)
8214{
8215 gc_report(6, objspace, "rgengc_remember: %s %s\n", rb_obj_info(obj),
8216 RVALUE_REMEMBERED(objspace, obj) ? "was already remembered" : "is remembered now");
8217
8218 check_rvalue_consistency(objspace, obj);
8219
8220 if (RGENGC_CHECK_MODE) {
8221 if (RVALUE_WB_UNPROTECTED(objspace, obj)) rb_bug("rgengc_remember: %s is not wb protected.", rb_obj_info(obj));
8222 }
8223
8224#if RGENGC_PROFILE > 0
8225 if (!RVALUE_REMEMBERED(objspace, obj)) {
8226 if (RVALUE_WB_UNPROTECTED(objspace, obj) == 0) {
8227 objspace->profile.total_remembered_normal_object_count++;
8228#if RGENGC_PROFILE >= 2
8229 objspace->profile.remembered_normal_object_count_types[BUILTIN_TYPE(obj)]++;
8230#endif
8231 }
8232 }
8233#endif /* RGENGC_PROFILE > 0 */
8234
8235 rgengc_remembersetbits_set(objspace, obj);
8236}
8237
8238#ifndef PROFILE_REMEMBERSET_MARK
8239#define PROFILE_REMEMBERSET_MARK 0
8240#endif
8241
8242static inline void
8243rgengc_rememberset_mark_plane(rb_objspace_t *objspace, uintptr_t p, bits_t bitset, short slot_size)
8244{
8245 if (bitset) {
8246 do {
8247 if (bitset & 1) {
8248 VALUE obj = (VALUE)p;
8249 gc_report(2, objspace, "rgengc_rememberset_mark: mark %s\n", rb_obj_info(obj));
8250 GC_ASSERT(RVALUE_UNCOLLECTIBLE(objspace, obj));
8251 GC_ASSERT(RVALUE_OLD_P(objspace, obj) || RVALUE_WB_UNPROTECTED(objspace, obj));
8252
8253 gc_mark_children(objspace, obj);
8254
8256 rb_darray_append_without_gc(&objspace->weak_references, obj);
8257 }
8258 }
8259 p += slot_size;
8260 bitset >>= 1;
8261 } while (bitset);
8262 }
8263}
8264
8265static void
8266rgengc_rememberset_mark(rb_objspace_t *objspace, rb_heap_t *heap)
8267{
8268 size_t j;
8269 struct heap_page *page = 0;
8270#if PROFILE_REMEMBERSET_MARK
8271 int has_old = 0, has_shady = 0, has_both = 0, skip = 0;
8272#endif
8273 gc_report(1, objspace, "rgengc_rememberset_mark: start\n");
8274
8275 ccan_list_for_each(&heap->pages, page, page_node) {
8276 if (page->flags.has_remembered_objects | page->flags.has_uncollectible_wb_unprotected_objects) {
8277 uintptr_t p = page->start;
8278 short slot_size = page->slot_size;
8279 int total_slots = page->total_slots;
8280 int bitmap_plane_count = CEILDIV(total_slots, BITS_BITLENGTH);
8281 bits_t bitset, bits[HEAP_PAGE_BITMAP_LIMIT];
8282 bits_t *remembered_bits = page->remembered_bits;
8283 bits_t *uncollectible_bits = page->uncollectible_bits;
8284 bits_t *wb_unprotected_bits = page->wb_unprotected_bits;
8285#if PROFILE_REMEMBERSET_MARK
8286 if (page->flags.has_remembered_objects && page->flags.has_uncollectible_wb_unprotected_objects) has_both++;
8287 else if (page->flags.has_remembered_objects) has_old++;
8288 else if (page->flags.has_uncollectible_wb_unprotected_objects) has_shady++;
8289#endif
8290 /* Clear has_remembered_objects before draining the bits. A concurrent
8291 * lock-free write barrier (another Ractor remembering a shareable object on
8292 * this page) sets the bit first and the flag second, so clearing the flag first
8293 * keeps the page scheduled for re-scan even if that set interleaves. The
8294 * per-word drain is an atomic read-and-clear, so an interleaved set is not lost
8295 * (it lands in the zeroed word). */
8296 page->flags.has_remembered_objects = FALSE;
8297 for (j=0; j < (size_t)bitmap_plane_count; j++) {
8298 bits[j] = RUBY_ATOMIC_SIZE_EXCHANGE(*(volatile size_t *)&remembered_bits[j], 0)
8299 | (uncollectible_bits[j] & wb_unprotected_bits[j]);
8300 }
8301
8302 for (j=0; j < (size_t)bitmap_plane_count; j++) {
8303 bitset = bits[j];
8304 rgengc_rememberset_mark_plane(objspace, p, bitset, slot_size);
8305 p += BITS_BITLENGTH * slot_size;
8306 }
8307 }
8308#if PROFILE_REMEMBERSET_MARK
8309 else {
8310 skip++;
8311 }
8312#endif
8313 }
8314
8315#if PROFILE_REMEMBERSET_MARK
8316 fprintf(stderr, "%d\t%d\t%d\t%d\n", has_both, has_old, has_shady, skip);
8317#endif
8318 gc_report(1, objspace, "rgengc_rememberset_mark: finished\n");
8319}
8320
8321static void
8322gc_bitmaps_clear(rb_objspace_t *objspace, rb_heap_t *heap, bool clear_shref)
8323{
8324 struct heap_page *page = 0;
8325
8326 ccan_list_for_each(&heap->pages, page, page_node) {
8327 memset(&page->mark_bits[0], 0, HEAP_PAGE_BITMAP_SIZE);
8328 memset(&page->uncollectible_bits[0], 0, HEAP_PAGE_BITMAP_SIZE);
8329 memset(&page->marking_bits[0], 0, HEAP_PAGE_BITMAP_SIZE);
8330 /* A plain memset can lose a concurrent remember, but only a shareable object can
8331 * be remembered from another Ractor's thread, and pinned_roots_mark re-marks
8332 * those every local cycle, and this clear precedes a major that re-scans all. */
8333 memset(&page->remembered_bits[0], 0, HEAP_PAGE_BITMAP_SIZE);
8334 memset(&page->pinned_bits[0], 0, HEAP_PAGE_BITMAP_SIZE);
8335 page->flags.has_uncollectible_wb_unprotected_objects = FALSE;
8336 page->flags.has_remembered_objects = FALSE;
8337 /* A shref is a local GC's root, so only a stop-the-world global GC may clear them:
8338 * its unified mark re-derives them from every shareable -> unshareable edge. */
8339 if (clear_shref) {
8340 memset(&page->shref_bits[0], 0, HEAP_PAGE_BITMAP_SIZE);
8341 page->flags.has_shref_objects = FALSE;
8342 }
8343 }
8344}
8345
8346/* RGENGC: APIs */
8347
8348NOINLINE(static void gc_writebarrier_generational(VALUE a, VALUE b, rb_objspace_t *objspace));
8349
8350/* Precondition: `a` and `b` live in `objspace`. */
8351static void
8352gc_writebarrier_generational(VALUE a, VALUE b, rb_objspace_t *objspace)
8353{
8354 if (RGENGC_CHECK_MODE) {
8355 if (!RVALUE_OLD_P(objspace, a)) rb_bug("gc_writebarrier_generational: %s is not an old object.", rb_obj_info(a));
8356 if ( RVALUE_OLD_P(objspace, b)) rb_bug("gc_writebarrier_generational: %s is an old object.", rb_obj_info(b));
8357 if (is_incremental_marking(objspace)) rb_bug("gc_writebarrier_generational: called while incremental marking: %s -> %s", rb_obj_info(a), rb_obj_info(b));
8358 }
8359
8360 /* Mark and remember a (the default behaviour).
8361 * No lock: setting a remembered bit is atomic (rgengc_remembersetbits_set), and that is
8362 * the only place a concurrent local GC or another Ractor's write barrier can race. */
8363 if (!RVALUE_REMEMBERED(objspace, a)) {
8364 rgengc_remember(objspace, a);
8365
8366 gc_report(1, objspace, "gc_writebarrier_generational: %s (remembered) -> %s\n", rb_obj_info(a), rb_obj_info(b));
8367 }
8368
8369 check_rvalue_consistency(objspace, a);
8370 check_rvalue_consistency(objspace, b);
8371}
8372
8373static void
8374gc_mark_from(rb_objspace_t *objspace, VALUE obj, VALUE parent)
8375{
8376 gc_mark_set_parent(objspace, parent);
8377 rgengc_check_relation(objspace, obj);
8378 if (gc_mark_set(objspace, obj) != FALSE) {
8379 gc_aging(objspace, obj);
8380 gc_grey(objspace, obj);
8381 }
8382 gc_mark_set_parent_invalid(objspace);
8383}
8384
8385NOINLINE(static void gc_writebarrier_incremental(VALUE a, VALUE b, rb_objspace_t *objspace));
8386
8387/* Precondition: `a` and `b` live in `objspace`. */
8388static void
8389gc_writebarrier_incremental(VALUE a, VALUE b, rb_objspace_t *objspace)
8390{
8391 gc_report(2, objspace, "gc_writebarrier_incremental: [LG] %p -> %s\n", (void *)a, rb_obj_info(b));
8392
8393 if (RVALUE_BLACK_P(objspace, a)) {
8394 if (RVALUE_WHITE_P(objspace, b)) {
8395 if (!RVALUE_WB_UNPROTECTED(objspace, a)) {
8396 gc_report(2, objspace, "gc_writebarrier_incremental: [IN] %p -> %s\n", (void *)a, rb_obj_info(b));
8397 gc_mark_from(objspace, b, a);
8398 }
8399 }
8400 else if (RVALUE_OLD_P(objspace, a) && !RVALUE_OLD_P(objspace, b)) {
8401 rgengc_remember(objspace, a);
8402 }
8403
8404 if (RB_UNLIKELY(objspace->flags.during_compacting)) {
8405 MARK_IN_BITMAP(GET_HEAP_PINNED_BITS(b), b);
8406 }
8407 }
8408}
8409
8410void
8411rb_gc_impl_writebarrier(void *objspace_ptr, VALUE a, VALUE b)
8412{
8413 rb_objspace_t *objspace = objspace_ptr;
8414
8415#if RGENGC_CHECK_MODE
8416 if (SPECIAL_CONST_P(a)) rb_bug("rb_gc_writebarrier: a is special const: %"PRIxVALUE, a);
8417 if (SPECIAL_CONST_P(b)) rb_bug("rb_gc_writebarrier: b is special const: %"PRIxVALUE, b);
8418#else
8421#endif
8422
8423 GC_ASSERT(!during_gc);
8424 GC_ASSERT(RB_BUILTIN_TYPE(a) != T_NONE);
8425 GC_ASSERT(RB_BUILTIN_TYPE(a) != T_MOVED);
8426 GC_ASSERT(RB_BUILTIN_TYPE(a) != T_ZOMBIE);
8427
8428 /* A shareable object now references an unshareable one: record b as a shref so its
8429 * owner's local GC roots it (the parent may live in another objspace, untraversed
8430 * there). Only b's owner stores this, on its own page: a plain store suffices. */
8431 if (RB_UNLIKELY(RB_FL_TEST_RAW(a, RUBY_FL_SHAREABLE)) &&
8433 struct heap_page *bpage = GET_HEAP_PAGE(b);
8434 if (!_MARKED_IN_BITMAP(bpage->shref_bits, bpage, b)) {
8435 _MARK_IN_BITMAP(bpage->shref_bits, bpage, b);
8436 bpage->flags.has_shref_objects = TRUE;
8437 }
8438 }
8439
8440 if (!is_incremental_marking(objspace)) {
8441 /* The generational barrier covers old->young edges within one objspace only.
8442 * NOTE: we shouldn't even check the age of `a` or `b` if they are in another
8443 * objspace, so check locality first. The test is rb_gc_ever_multi_ractor_p, not
8444 * rb_gc_multi_ractor_p: a foreign objspace exists before the process is
8445 * multi-Ractor (rb_gc_objspace_alloc runs while the creator is still the only
8446 * Ractor) and outlives the return to one (a fork parks the others in
8447 * zombie_objspaces). */
8448 if ((rb_gc_ever_multi_ractor_p() &&
8449 (GET_HEAP_OBJSPACE(a) != objspace || GET_HEAP_OBJSPACE(b) != objspace)) ||
8450 !RVALUE_OLD_P(objspace, a) || RVALUE_OLD_P(objspace, b)) {
8451 // do nothing
8452 }
8453 else {
8454 gc_writebarrier_generational(a, b, objspace);
8455 }
8456 }
8457 else {
8458 // Shareable objects from different object spaces are kept alive by shareable bits
8459 if (rb_gc_ever_multi_ractor_p() &&
8460 (GET_HEAP_OBJSPACE(a) != objspace || GET_HEAP_OBJSPACE(b) != objspace)) {
8461 // do nothing
8462 }
8463 else {
8464 gc_writebarrier_incremental(a, b, objspace);
8465 }
8466 }
8467}
8468
8469void
8470rb_gc_impl_obj_became_shareable(void *objspace_ptr, VALUE obj)
8471{
8472 /* An object becomes shareable on its owner thread, so this page update is
8473 * single-writer. */
8474 struct heap_page *page = GET_HEAP_PAGE(obj);
8475
8476 if (_MARKED_IN_BITMAP(page->shareable_bits, page, obj)) return;
8477 gc_page_add_shareable(page, obj);
8478
8479 /* The shref bits recorded while the object was unshareable are now covered by the
8480 * shareable pin, and a shref only points at an unshareable object. The owner thread is
8481 * the only writer, so a plain clear is enough. */
8482 if (_MARKED_IN_BITMAP(page->shref_bits, page, obj)) {
8483 _CLEAR_IN_BITMAP(page->shref_bits, page, obj);
8484 // NOTE: page->has_shref_objects could become stale here (value is true even though logically false)
8485 }
8486}
8487
8488void
8489rb_gc_impl_writebarrier_unprotect(void *objspace_ptr, VALUE obj)
8490{
8491 rb_objspace_t *objspace = objspace_ptr;
8492
8493 /* A shareable object is never WB-unprotected. Keeping shrefs correct relies on every
8494 * store into s->u going through the write barrier, which keeps wb_unprotected_bits
8495 * single-writer (only the owner thread can unprotect its own unshareable objects). */
8496 GC_ASSERT(!RB_FL_TEST_RAW(obj, RUBY_FL_SHAREABLE));
8497
8498 if (RVALUE_WB_UNPROTECTED(objspace, obj)) {
8499 return;
8500 }
8501 else {
8502 gc_report(2, objspace, "rb_gc_writebarrier_unprotect: %s %s\n", rb_obj_info(obj),
8503 RVALUE_REMEMBERED(objspace, obj) ? " (already remembered)" : "");
8504
8505 /* No lock: per the assert obj is our own unshareable, so these bits
8506 * (wb_unprotected, uncollectible, age) are single-writer on an owned page, and
8507 * RVALUE_DEMOTE's remembered-bit clear is atomic against word-sharing writers. */
8508 if (RVALUE_OLD_P(objspace, obj)) {
8509 gc_report(1, objspace, "rb_gc_writebarrier_unprotect: %s\n", rb_obj_info(obj));
8510 RVALUE_DEMOTE(objspace, obj);
8511 gc_mark_set(objspace, obj);
8512 gc_remember_unprotected(objspace, obj);
8513
8514#if RGENGC_PROFILE
8515 objspace->profile.total_shade_operation_count++;
8516#if RGENGC_PROFILE >= 2
8517 objspace->profile.shade_operation_count_types[BUILTIN_TYPE(obj)]++;
8518#endif /* RGENGC_PROFILE >= 2 */
8519#endif /* RGENGC_PROFILE */
8520 }
8521 else {
8522 RVALUE_AGE_RESET(obj);
8523 }
8524
8525 RB_DEBUG_COUNTER_INC(obj_wb_unprotect);
8526 MARK_IN_BITMAP(GET_HEAP_WB_UNPROTECTED_BITS(obj), obj);
8527 }
8528}
8529
8530void
8531rb_gc_impl_copy_attributes(void *objspace_ptr, VALUE dest, VALUE obj)
8532{
8533 rb_objspace_t *objspace = objspace_ptr;
8534
8535 if (RVALUE_WB_UNPROTECTED(objspace, obj)) {
8536 rb_gc_impl_writebarrier_unprotect(objspace, dest);
8537 }
8538 rb_gc_impl_copy_finalizer(objspace, dest, obj);
8539}
8540
8541const char *
8542rb_gc_impl_active_gc_name(void)
8543{
8544 return "default";
8545}
8546
8547/* NOTE: `obj` doesn't necessarily live in `objspace_ptr`, as `objspace_ptr` is just that
8548 * of the current Ractor. */
8549void
8550rb_gc_impl_writebarrier_remember(void *objspace_ptr, VALUE obj)
8551{
8552
8553 rb_objspace_t *objspace = objspace_ptr;
8554
8555 // Shareable objects from other object spaces don't need to be put on the remembered set
8556 // and are only collected during global GC, so not while incremental marking.
8557 if (RB_LIKELY(!rb_gc_ever_multi_ractor_p() || GET_HEAP_OBJSPACE(obj) == objspace)) {
8558 gc_report(1, objspace, "rb_gc_writebarrier_remember: %s\n", rb_obj_info(obj));
8559 if (is_incremental_marking(objspace)) {
8560 if (RVALUE_BLACK_P(objspace, obj)) {
8561 gc_grey(objspace, obj);
8562 }
8563 }
8564 else if (RVALUE_OLD_P(objspace, obj)) {
8565 rgengc_remember(objspace, obj);
8566 }
8567 }
8568}
8569
8571 // Must be ID only
8572 ID ID_wb_protected, ID_age, ID_old, ID_uncollectible, ID_marking,
8573 ID_marked, ID_pinned, ID_remembered, ID_object_id, ID_shareable;
8574};
8575
8576#define RB_GC_OBJECT_METADATA_ENTRY_COUNT (sizeof(struct rb_gc_object_metadata_names) / sizeof(ID))
8577static struct rb_gc_object_metadata_entry object_metadata_entries[RB_GC_OBJECT_METADATA_ENTRY_COUNT + 1];
8578
8580rb_gc_impl_object_metadata(void *objspace_ptr, VALUE obj)
8581{
8582 rb_objspace_t *objspace = objspace_ptr;
8583 size_t n = 0;
8584 static struct rb_gc_object_metadata_names names;
8585
8586 if (!names.ID_marked) {
8587#define I(s) names.ID_##s = rb_intern(#s)
8588 I(wb_protected);
8589 I(age);
8590 I(old);
8591 I(uncollectible);
8592 I(marking);
8593 I(marked);
8594 I(pinned);
8595 I(remembered);
8596 I(object_id);
8597 I(shareable);
8598#undef I
8599 }
8600
8601#define SET_ENTRY(na, v) do { \
8602 GC_ASSERT(n <= RB_GC_OBJECT_METADATA_ENTRY_COUNT); \
8603 object_metadata_entries[n].name = names.ID_##na; \
8604 object_metadata_entries[n].val = v; \
8605 n++; \
8606} while (0)
8607
8608 if (!RVALUE_WB_UNPROTECTED(objspace, obj)) SET_ENTRY(wb_protected, Qtrue);
8609 SET_ENTRY(age, INT2FIX(RVALUE_AGE_GET(obj)));
8610 if (RVALUE_OLD_P(objspace, obj)) SET_ENTRY(old, Qtrue);
8611 if (RVALUE_UNCOLLECTIBLE(objspace, obj)) SET_ENTRY(uncollectible, Qtrue);
8612 if (RVALUE_MARKING(objspace, obj)) SET_ENTRY(marking, Qtrue);
8613 if (RVALUE_MARKED(objspace, obj)) SET_ENTRY(marked, Qtrue);
8614 if (RVALUE_PINNED(objspace, obj)) SET_ENTRY(pinned, Qtrue);
8615 if (RVALUE_REMEMBERED(objspace, obj)) SET_ENTRY(remembered, Qtrue);
8616 if (rb_obj_id_p(obj)) SET_ENTRY(object_id, rb_obj_id(obj));
8617 if (FL_TEST(obj, FL_SHAREABLE)) SET_ENTRY(shareable, Qtrue);
8618
8619 object_metadata_entries[n].name = 0;
8620 object_metadata_entries[n].val = 0;
8621#undef SET_ENTRY
8622
8623 return object_metadata_entries;
8624}
8625
8626void *
8627rb_gc_impl_ractor_cache_alloc(void *objspace_ptr, void *ractor)
8628{
8629 /* No cache needed: allocation happens in a per-Ractor objspace. */
8630 return NULL;
8631}
8632
8633void
8634rb_gc_impl_ractor_cache_free(void *objspace_ptr, void *cache)
8635{
8636 GC_ASSERT(cache == NULL);
8637}
8638
8639/* The terminating Ractor's final local GC, on its own thread: roots are minimal, so the
8640 * mark is tiny, and it reclaims what the joining side would otherwise inherit. Never
8641 * promotes to a global GC (that would STW on every Ractor death); empty pages go
8642 * straight back to the page pool. */
8643/* Finalize the zombies whose cleanup is pure C (a dfree, no Ruby-level finalizer);
8644 * the caller has no Ruby execution context any more, so zombies with a Ruby
8645 * finalizer stay deferred and travel to the inheritor as before. Returns whether
8646 * anything was finalized (those pages then need one more sweep to detach). */
8647static bool
8648finalize_deferred_dfree_only(rb_objspace_t *objspace)
8649{
8650 VALUE dfree_only = 0;
8651 VALUE zombie = RUBY_ATOMIC_VALUE_EXCHANGE(heap_pages_deferred_final, 0);
8652 while (zombie) {
8653 rb_asan_unpoison_object(zombie, false);
8654 VALUE next = RZOMBIE(zombie)->next;
8655 if (FL_TEST_RAW(zombie, FL_FINALIZE)) {
8656 /* re-defer, with the same push as rb_gc_impl_make_zombie */
8657 VALUE prev2, next2 = heap_pages_deferred_final;
8658 do {
8659 RZOMBIE(zombie)->next = prev2 = next2;
8660 next2 = RUBY_ATOMIC_VALUE_CAS(heap_pages_deferred_final, prev2, zombie);
8661 } while (next2 != prev2);
8662 rb_asan_poison_object(zombie);
8663 }
8664 else {
8665 RZOMBIE(zombie)->next = dfree_only;
8666 dfree_only = zombie;
8667 }
8668 zombie = next;
8669 }
8670 if (dfree_only) finalize_list(objspace, dfree_only);
8671 bool did = dfree_only != 0;
8672
8673 gc_tdata_unsafe_free_publish(objspace);
8674 return did;
8675}
8676
8677void
8678rb_gc_impl_objspace_retire_gc(void *objspace_ptr)
8679{
8680 rb_objspace_t *objspace = objspace_ptr;
8681
8682 /* The dying thread's stack is already torn down here, so the root scan must skip
8683 * its machine context (rb_gc_mark_roots). */
8684 objspace->flags.during_postmortem = 1;
8685
8686 gc_rest(objspace);
8687 gc_start(objspace, GPR_FLAG_FULL_MARK | GPR_FLAG_IMMEDIATE_MARK | GPR_FLAG_IMMEDIATE_SWEEP);
8688
8689 /* The sweep above turned this heap's dead IO and the like into deferred zombies
8690 * (the per-Ractor stdio holds a page per Ractor otherwise); finalize the C-only
8691 * ones here and re-sweep the nearly-empty heap so their pages detach as empty. */
8692 if (finalize_deferred_dfree_only(objspace)) {
8693 gc_start(objspace, GPR_FLAG_FULL_MARK | GPR_FLAG_IMMEDIATE_MARK | GPR_FLAG_IMMEDIATE_SWEEP);
8694 }
8695
8696 heap_pages_freeable_pages = objspace->empty_pages_count;
8697 heap_pages_free_unused_pages(objspace);
8698
8699 objspace->flags.during_postmortem = 0;
8700}
8701
8702bool
8703rb_gc_impl_during_postmortem_p(void *objspace_ptr)
8704{
8705 rb_objspace_t *objspace = objspace_ptr;
8706 return objspace->flags.during_postmortem != 0;
8707}
8708
8709static void
8710heap_ready_to_gc(rb_objspace_t *objspace, rb_heap_t *heap)
8711{
8712 if (!heap->free_pages) {
8713 if (!heap_page_allocate_and_initialize(objspace, heap)) {
8714 objspace->heap_pages.allocatable_bytes = HEAP_PAGE_SIZE;
8715 heap_page_allocate_and_initialize(objspace, heap);
8716 }
8717 }
8718}
8719
8720static int
8721ready_to_gc(rb_objspace_t *objspace)
8722{
8723 if ((!objspace->flags.during_postmortem && rb_gc_gc_disabled_global_p()) || dont_gc_val() || during_gc) {
8724 for (int i = 0; i < HEAP_COUNT; i++) {
8725 rb_heap_t *heap = &heaps[i];
8726 heap_ready_to_gc(objspace, heap);
8727 }
8728 return FALSE;
8729 }
8730 else {
8731 return TRUE;
8732 }
8733}
8734
8735static void
8736gc_reset_malloc_info(rb_objspace_t *objspace, bool full_mark)
8737{
8738 gc_prof_set_malloc_info(objspace);
8739 {
8740 int64_t inc = gc_malloc_counters_increase(objspace, &objspace->malloc_counters.counters);
8741 gc_malloc_counters_snapshot(objspace, &objspace->malloc_counters.counters);
8742 size_t old_limit = malloc_limit;
8743
8744 /* A net-negative `inc` (more freed than malloc'd since last GC) is
8745 * treated the same as "allocated less than malloc_limit".
8746 * This matches what we were doing pre-monotonic counters, but is it right? */
8747 if (inc > 0 && (size_t)inc > malloc_limit) {
8748 malloc_limit = (size_t)((size_t)inc * gc_params.malloc_limit_growth_factor);
8749 if (malloc_limit > gc_params.malloc_limit_max) {
8750 malloc_limit = gc_params.malloc_limit_max;
8751 }
8752 }
8753 else {
8754 malloc_limit = (size_t)(malloc_limit * 0.98); /* magic number */
8755 if (malloc_limit < gc_params.malloc_limit_min) {
8756 malloc_limit = gc_params.malloc_limit_min;
8757 }
8758 }
8759
8760 if (0) {
8761 if (old_limit != malloc_limit) {
8762 fprintf(stderr, "[%"PRIuSIZE"] malloc_limit: %"PRIuSIZE" -> %"PRIuSIZE"\n",
8763 rb_gc_count(), old_limit, malloc_limit);
8764 }
8765 else {
8766 fprintf(stderr, "[%"PRIuSIZE"] malloc_limit: not changed (%"PRIuSIZE")\n",
8767 rb_gc_count(), malloc_limit);
8768 }
8769 }
8770 }
8771
8772 /* reset oldmalloc info */
8773#if RGENGC_ESTIMATE_OLDMALLOC
8774 if (!full_mark) {
8775 /* No full snapshot on minor GC: oldmalloc_increase accumulates across
8776 * minors and resets at major GC. (gc_sweep_finish still advances the
8777 * free baseline after every sweep.) */
8778 int64_t oldmalloc_increase = gc_malloc_counters_increase(objspace, &objspace->malloc_counters.oldcounters);
8779 if (oldmalloc_increase > 0 &&
8780 (uint64_t)oldmalloc_increase > objspace->rgengc.oldmalloc_increase_limit) {
8781 gc_needs_major_flags |= GPR_FLAG_MAJOR_BY_OLDMALLOC;
8782 objspace->rgengc.oldmalloc_increase_limit =
8783 (size_t)(objspace->rgengc.oldmalloc_increase_limit * gc_params.oldmalloc_limit_growth_factor);
8784
8785 if (objspace->rgengc.oldmalloc_increase_limit > gc_params.oldmalloc_limit_max) {
8786 objspace->rgengc.oldmalloc_increase_limit = gc_params.oldmalloc_limit_max;
8787 }
8788 }
8789
8790 if (0) fprintf(stderr, "%"PRIdSIZE"\t%d\t%"PRId64"\t%"PRIuSIZE"\t%"PRIdSIZE"\n",
8791 rb_gc_count(),
8792 gc_needs_major_flags,
8793 oldmalloc_increase,
8794 objspace->rgengc.oldmalloc_increase_limit,
8795 gc_params.oldmalloc_limit_max);
8796 }
8797 else {
8798 gc_malloc_counters_snapshot(objspace, &objspace->malloc_counters.oldcounters);
8799
8800 if ((objspace->profile.latest_gc_info & GPR_FLAG_MAJOR_BY_OLDMALLOC) == 0) {
8801 objspace->rgengc.oldmalloc_increase_limit =
8802 (size_t)(objspace->rgengc.oldmalloc_increase_limit / ((gc_params.oldmalloc_limit_growth_factor - 1)/10 + 1));
8803 if (objspace->rgengc.oldmalloc_increase_limit < gc_params.oldmalloc_limit_min) {
8804 objspace->rgengc.oldmalloc_increase_limit = gc_params.oldmalloc_limit_min;
8805 }
8806 }
8807 }
8808#endif
8809}
8810
8811/* What a collection records about itself before it runs. A global collection reports the
8812 * driver's objspace, so it comes through here too. */
8813static void
8814gc_start_record(rb_objspace_t *objspace, unsigned int reason, bool full_mark)
8815{
8816 objspace->profile.latest_gc_info = reason;
8817#if GC_PROFILE_MORE_DETAIL
8818 objspace->profile.total_allocated_objects_at_gc_start = total_allocated_objects(objspace);
8819 objspace->profile.heap_used_at_gc_start = rb_darray_size(objspace->heap_pages.sorted);
8820#endif
8821 objspace->profile.weak_references_count = 0;
8822 gc_prof_setup_new_record(objspace, reason);
8823 gc_reset_malloc_info(objspace, full_mark);
8824}
8825
8826static bool gc_start_global(rb_objspace_t *driver, unsigned int reason, bool compact, bool allow_skip);
8827
8828/* Decide whether this collection has to be global. A local GC can reclaim neither
8829 * shareable objects nor zombie objspaces, so once those grow past their limits only a
8830 * global GC makes progress. All inputs belong to this objspace. */
8831static bool
8832gc_need_global_p(rb_objspace_t *objspace)
8833{
8834 if (rb_gc_single_objspace_p()) return false;
8835 /* A Ractor's death must not stop the world, so the retire GC stays local. */
8836 if (objspace->flags.during_postmortem) return false;
8837 if (objspace->shareable_objects > objspace->shareable_objects_limit) return true;
8838 /* A zombie's garbage only a global cycle reclaims, but what survived the last one
8839 * is live data, so retrigger only once TRIGGER more pages accumulate on top of it.
8840 * Otherwise one live-heavy unjoined zombie turns every GC stop-the-world forever. */
8841 {
8842 size_t zp = rb_gc_vm_zombie_total_pages();
8843 size_t base = global_objspace->zombie_pages_survivors < zp ? global_objspace->zombie_pages_survivors : zp;
8844 if (zp - base >= ZOMBIE_PAGES_TRIGGER) return true;
8845 }
8846 return false;
8847}
8848
8849static int
8850garbage_collect(rb_objspace_t *objspace, unsigned int reason)
8851{
8852 int ret;
8853
8854#if GC_PROFILE_MORE_DETAIL
8855 objspace->profile.prepare_time = getrusage_time();
8856#endif
8857
8858 gc_rest(objspace);
8859
8860#if GC_PROFILE_MORE_DETAIL
8861 objspace->profile.prepare_time = getrusage_time() - objspace->profile.prepare_time;
8862#endif
8863
8864 ret = gc_start(objspace, reason);
8865
8866 return ret;
8867}
8868
8869static int
8870gc_start(rb_objspace_t *objspace, unsigned int reason)
8871{
8872 unsigned int do_full_mark = !!(reason & GPR_FLAG_FULL_MARK);
8873
8874 if (!rb_darray_size(objspace->heap_pages.sorted)) return TRUE; /* heap is not ready */
8875 if (!(reason & GPR_FLAG_METHOD) && !ready_to_gc(objspace)) return TRUE; /* GC is not allowed */
8876
8877 /* An explicit GC.start(global: true) never gets here: rb_gc_impl_start has already decided from
8878 * the `global` keyword, and GPR_FLAG_METHOD keeps `global: false` from being promoted back. */
8879 if (!(reason & GPR_FLAG_METHOD) && gc_need_global_p(objspace)) {
8880 /* A global GC is always a major, so autocompact applies. */
8881 if (gc_start_global(objspace, reason, ruby_enable_autocompact, true)) {
8882 return TRUE;
8883 }
8884 /* Fall through to a local GC */
8885 }
8886
8887 rb_gc_initialize_vm_context(&objspace->vm_context);
8888
8889 GC_ASSERT(gc_mode(objspace) == gc_mode_none, "gc_mode is %s\n", gc_mode_name(gc_mode(objspace)));
8890 GC_ASSERT(!is_lazy_sweeping(objspace));
8891 GC_ASSERT(!is_incremental_marking(objspace));
8892
8893 /* reason may be clobbered, later, so keep set immediate_sweep here */
8894 objspace->flags.immediate_sweep = !!(reason & GPR_FLAG_IMMEDIATE_SWEEP);
8895
8896 if (ruby_gc_stressful) {
8897 int flag = FIXNUM_P(ruby_gc_stress_mode) ? FIX2INT(ruby_gc_stress_mode) : 0;
8898
8899 if ((flag & (1 << gc_stress_no_major)) == 0) {
8900 do_full_mark = TRUE;
8901 }
8902
8903 objspace->flags.immediate_sweep = !(flag & (1<<gc_stress_no_immediate_sweep));
8904 }
8905
8906 if (gc_needs_major_flags) {
8907 reason |= gc_needs_major_flags;
8908 do_full_mark = TRUE;
8909 }
8910
8911 /* if major gc has been disabled, never do a full mark */
8912 if (!gc_config_full_mark_val) {
8913 do_full_mark = FALSE;
8914 }
8915 gc_needs_major_flags = GPR_FLAG_NONE;
8916
8917 if (do_full_mark && (reason & GPR_FLAG_MAJOR_MASK) == 0) {
8918 reason |= GPR_FLAG_MAJOR_BY_FORCE; /* GC by CAPI, METHOD, and so on. */
8919 }
8920
8921 if (objspace->flags.dont_incremental ||
8922 reason & GPR_FLAG_IMMEDIATE_MARK ||
8923 ruby_gc_stressful) {
8924 objspace->flags.during_incremental_marking = FALSE;
8925 }
8926 else {
8927 objspace->flags.during_incremental_marking = do_full_mark;
8928 }
8929
8930 /* Compaction on the local GC path (autocompact) runs only with a single objspace:
8931 * without the stop-the-world barrier, moving objects would break cross-objspace
8932 * references. With multiple objspaces GC.compact and autocompact go through the
8933 * compacting global GC instead (rb_gc_impl_start, or the promotion above). */
8934 if (do_full_mark && ruby_enable_autocompact && rb_gc_single_objspace_p()) {
8935 objspace->flags.during_compacting = TRUE;
8936#if RGENGC_CHECK_MODE
8937 objspace->rcompactor.compare_func = ruby_autocompact_compare_func;
8938#endif
8939 }
8940 else {
8941 objspace->flags.during_compacting = !!(reason & GPR_FLAG_COMPACT);
8942 if (objspace->flags.during_compacting && !rb_gc_single_objspace_p()) {
8943 // compaction is currently global GC only with more than 1 running Ractor
8944 objspace->flags.during_compacting = FALSE;
8945 }
8946 }
8947
8948 if (!GC_ENABLE_LAZY_SWEEP || objspace->flags.dont_incremental) {
8949 objspace->flags.immediate_sweep = TRUE;
8950 }
8951
8952 if (objspace->flags.immediate_sweep) reason |= GPR_FLAG_IMMEDIATE_SWEEP;
8953
8954 /* Enter after during_compacting is decided */
8955 unsigned int lock_lev;
8956 gc_enter(objspace, gc_enter_event_start, &lock_lev);
8957
8958 gc_report(1, objspace, "gc_start(reason: %x) => %u, %d, %d\n",
8959 reason,
8960 do_full_mark, !is_incremental_marking(objspace), objspace->flags.immediate_sweep);
8961
8962 RB_DEBUG_COUNTER_INC(gc_count);
8963
8964 if (reason & GPR_FLAG_MAJOR_MASK) {
8965 (void)RB_DEBUG_COUNTER_INC_IF(gc_major_nofree, reason & GPR_FLAG_MAJOR_BY_NOFREE);
8966 (void)RB_DEBUG_COUNTER_INC_IF(gc_major_oldgen, reason & GPR_FLAG_MAJOR_BY_OLDGEN);
8967 (void)RB_DEBUG_COUNTER_INC_IF(gc_major_shady, reason & GPR_FLAG_MAJOR_BY_SHADY);
8968 (void)RB_DEBUG_COUNTER_INC_IF(gc_major_force, reason & GPR_FLAG_MAJOR_BY_FORCE);
8969#if RGENGC_ESTIMATE_OLDMALLOC
8970 (void)RB_DEBUG_COUNTER_INC_IF(gc_major_oldmalloc, reason & GPR_FLAG_MAJOR_BY_OLDMALLOC);
8971#endif
8972 }
8973 else {
8974 (void)RB_DEBUG_COUNTER_INC_IF(gc_minor_newobj, reason & GPR_FLAG_NEWOBJ);
8975 (void)RB_DEBUG_COUNTER_INC_IF(gc_minor_malloc, reason & GPR_FLAG_MALLOC);
8976 (void)RB_DEBUG_COUNTER_INC_IF(gc_minor_method, reason & GPR_FLAG_METHOD);
8977 (void)RB_DEBUG_COUNTER_INC_IF(gc_minor_capi, reason & GPR_FLAG_CAPI);
8978 (void)RB_DEBUG_COUNTER_INC_IF(gc_minor_stress, reason & GPR_FLAG_STRESS);
8979 }
8980
8981 objspace->profile.count++;
8982 gc_start_record(objspace, reason, do_full_mark);
8983
8984 gc_event_hook(objspace, RUBY_INTERNAL_EVENT_GC_START);
8985
8986 GC_ASSERT(during_gc);
8987
8988 gc_prof_timer_start(objspace);
8989 {
8990 if (gc_marks(objspace, do_full_mark)) {
8991 gc_sweep(objspace);
8992 }
8993 }
8994 gc_prof_timer_stop(objspace);
8995
8996 gc_exit(objspace, gc_enter_event_start, &lock_lev);
8997
8998 /* Verify after the GC, at a real safepoint with during_gc cleared: mid-GC it would
8999 * call rb_objspace_reachable_objects_from, whose barrier VM lock would join another
9000 * Ractor's global GC barrier and let it collect on this half-collected heap. */
9001#if RGENGC_CHECK_MODE >= 2
9002 gc_verify_internal_consistency(objspace);
9003#endif
9004 return TRUE;
9005}
9006
9007static void
9008gc_rest(rb_objspace_t *objspace)
9009{
9010 if (is_incremental_marking(objspace) || is_lazy_sweeping(objspace)) {
9011 unsigned int lock_lev;
9012 gc_enter(objspace, gc_enter_event_rest, &lock_lev);
9013
9014 if (is_incremental_marking(objspace)) {
9015 gc_marking_enter(objspace);
9016 gc_marks_rest(objspace);
9017 gc_marking_exit(objspace);
9018
9019 gc_sweep(objspace);
9020 }
9021
9022 if (is_lazy_sweeping(objspace)) {
9023 gc_sweeping_enter(objspace);
9024 gc_sweep_rest(objspace);
9025 gc_sweeping_exit(objspace);
9026 }
9027
9028 gc_exit(objspace, gc_enter_event_rest, &lock_lev);
9029
9030 if (RGENGC_CHECK_MODE >= 2) gc_verify_internal_consistency(objspace); /* after GC, see gc_start */
9031 }
9032}
9033
9036 unsigned int reason;
9037};
9038
9039static void
9040gc_current_status_fill(rb_objspace_t *objspace, char *buff)
9041{
9042 int i = 0;
9043 if (is_marking(objspace)) {
9044 buff[i++] = 'M';
9045 if (is_full_marking(objspace)) buff[i++] = 'F';
9046 if (is_incremental_marking(objspace)) buff[i++] = 'I';
9047 }
9048 else if (is_sweeping(objspace)) {
9049 buff[i++] = 'S';
9050 if (is_lazy_sweeping(objspace)) buff[i++] = 'L';
9051 }
9052 else {
9053 buff[i++] = 'N';
9054 }
9055 buff[i] = '\0';
9056}
9057
9058static const char *
9059gc_current_status(rb_objspace_t *objspace)
9060{
9061 static char buff[0x10];
9062 gc_current_status_fill(objspace, buff);
9063 return buff;
9064}
9065
9066#if PRINT_ENTER_EXIT_TICK
9067
9068static tick_t last_exit_tick;
9069static tick_t enter_tick;
9070static int enter_count = 0;
9071static char last_gc_status[0x10];
9072
9073static inline void
9074gc_record(rb_objspace_t *objspace, int direction, const char *event)
9075{
9076 if (direction == 0) { /* enter */
9077 enter_count++;
9078 enter_tick = tick();
9079 gc_current_status_fill(objspace, last_gc_status);
9080 }
9081 else { /* exit */
9082 tick_t exit_tick = tick();
9083 char current_gc_status[0x10];
9084 gc_current_status_fill(objspace, current_gc_status);
9085#if 1
9086 /* [last mutator time] [gc time] [event] */
9087 fprintf(stderr, "%"PRItick"\t%"PRItick"\t%s\t[%s->%s|%c]\n",
9088 enter_tick - last_exit_tick,
9089 exit_tick - enter_tick,
9090 event,
9091 last_gc_status, current_gc_status,
9092 (objspace->profile.latest_gc_info & GPR_FLAG_MAJOR_MASK) ? '+' : '-');
9093 last_exit_tick = exit_tick;
9094#else
9095 /* [enter_tick] [gc time] [event] */
9096 fprintf(stderr, "%"PRItick"\t%"PRItick"\t%s\t[%s->%s|%c]\n",
9097 enter_tick,
9098 exit_tick - enter_tick,
9099 event,
9100 last_gc_status, current_gc_status,
9101 (objspace->profile.latest_gc_info & GPR_FLAG_MAJOR_MASK) ? '+' : '-');
9102#endif
9103 }
9104}
9105#else /* PRINT_ENTER_EXIT_TICK */
9106static inline void
9107gc_record(rb_objspace_t *objspace, int direction, const char *event)
9108{
9109 /* null */
9110}
9111#endif /* PRINT_ENTER_EXIT_TICK */
9112
9113static const char *
9114gc_enter_event_cstr(enum gc_enter_event event)
9115{
9116 switch (event) {
9117 case gc_enter_event_start: return "start";
9118 case gc_enter_event_continue: return "continue";
9119 case gc_enter_event_rest: return "rest";
9120 case gc_enter_event_finalizer: return "finalizer";
9121 case gc_enter_event_global: return "global";
9122 case gc_enter_event_global_auto: return "global_auto";
9123 }
9124 return NULL;
9125}
9126
9127static void
9128gc_enter_count(enum gc_enter_event event)
9129{
9130 switch (event) {
9131 case gc_enter_event_start: RB_DEBUG_COUNTER_INC(gc_enter_start); break;
9132 case gc_enter_event_continue: RB_DEBUG_COUNTER_INC(gc_enter_continue); break;
9133 case gc_enter_event_rest: RB_DEBUG_COUNTER_INC(gc_enter_rest); break;
9134 case gc_enter_event_finalizer: RB_DEBUG_COUNTER_INC(gc_enter_finalizer); break;
9135 case gc_enter_event_global: RB_DEBUG_COUNTER_INC(gc_enter_start); break;
9136 case gc_enter_event_global_auto: RB_DEBUG_COUNTER_INC(gc_enter_start); break;
9137 }
9138}
9139
9140static bool current_process_time(struct timespec *ts);
9141
9142/* A gc phase must be timed on the collecting thread's own cpu. A local gc runs
9143 * while the other ractors keep going, and process cpu time counts their work as
9144 * gc: with eight busy ractors the same ten collections were reported as 131ms
9145 * instead of 3ms, more than the wall clock they ran in. The kernel also answers
9146 * this one without walking every thread in the process. */
9147static bool
9148current_thread_time(struct timespec *ts)
9149{
9150#if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_THREAD_CPUTIME_ID)
9151 {
9152 static int try_clock_gettime = 1;
9153 if (try_clock_gettime) {
9154 if (clock_gettime(CLOCK_THREAD_CPUTIME_ID, ts) == 0) {
9155 return true;
9156 }
9157 else {
9158 try_clock_gettime = 0;
9159 }
9160 }
9161 }
9162#endif
9163 return current_process_time(ts);
9164}
9165
9166static void
9167gc_clock_start(struct timespec *ts)
9168{
9169 if (!current_thread_time(ts)) {
9170 ts->tv_sec = 0;
9171 ts->tv_nsec = 0;
9172 }
9173}
9174
9175static unsigned long long
9176gc_clock_end(struct timespec *ts)
9177{
9178 struct timespec end_time;
9179
9180 if ((ts->tv_sec > 0 || ts->tv_nsec > 0) &&
9181 current_thread_time(&end_time) &&
9182 end_time.tv_sec >= ts->tv_sec) {
9183 return (unsigned long long)(end_time.tv_sec - ts->tv_sec) * (1000 * 1000 * 1000) +
9184 (end_time.tv_nsec - ts->tv_nsec);
9185 }
9186
9187 return 0;
9188}
9189
9190static void
9191gc_process_stat_after_fork_i(void *objspace_ptr, void *data)
9192{
9193 rb_objspace_t *objspace = objspace_ptr;
9194 rb_native_mutex_initialize(&objspace->process_stat.lock);
9195}
9196
9197static inline bool
9198gc_local_gc_holds_vm_lock(void)
9199{
9200 return rb_gc_single_objspace_p();
9201}
9202
9203static inline bool
9204gc_enter(rb_objspace_t *objspace, enum gc_enter_event event, unsigned int *lock_lev)
9205{
9206 /*
9207 * NOTE: The GC must never take the barrier VM lock from inside itself: the waiter could
9208 * join a pending barrier mid-collection and expose its half-collected heap to the global
9209 * GC. A no-barrier lock is safe. Other shared structures the GC paths touch use their own
9210 * native mutexes or the page-pool lock. */
9211 *lock_lev = 0;
9212
9213 RUBY_DTRACE_GC_HOOK(ENTER, event);
9214
9215 if (objspace->profile.run) {
9216 switch (event) {
9217 case gc_enter_event_start:
9218 case gc_enter_event_continue:
9219 case gc_enter_event_rest:
9220 case gc_enter_event_global:
9221 case gc_enter_event_global_auto:
9222 /* A global GC is the longest pause the process takes, so it is the last thing
9223 * the profiler may leave unmeasured. The switch below stops the world for it,
9224 * which is exactly the interval gc_stop_time is meant to name, so start the
9225 * clock here like a local collection does. */
9226 objspace->profile.gc_pause_start_time = rb_hrtime_now();
9227 break;
9228 case gc_enter_event_finalizer:
9229 break;
9230 }
9231 }
9232 switch (event) {
9233 case gc_enter_event_global:
9234 *lock_lev = RB_GC_VM_LOCK();
9235 // stop other ractors
9236 rb_gc_vm_barrier();
9237 break;
9238 case gc_enter_event_global_auto:
9239 *lock_lev = RB_GC_VM_LOCK();
9240 if (!gc_need_global_p(objspace)) {
9241 RB_GC_VM_UNLOCK(*lock_lev);
9242 *lock_lev = 0;
9243 objspace->profile.gc_pause_start_time = 0;
9244 return false;
9245 }
9246 rb_gc_vm_barrier();
9247 break;
9248 case gc_enter_event_finalizer:
9249 /* Shutdown finalizers read VM-global tables (fstring, symbol) and free T_DATA that
9250 * is not thread-safe, so take the no-barrier VM lock. */
9251 *lock_lev = RB_GC_VM_LOCK_NO_BARRIER();
9252 break;
9253 default:
9254 objspace->flags.gc_lock_barrier = FALSE;
9255 if (objspace->flags.during_compacting) {
9256 /* Compaction relocates objects and rewrites every Ractor's JIT and global
9257 * references, so it stops the world with a barrier VM lock. rb_gc_vm_barrier is
9258 * a reentrant no-op with a single Ractor, so an inner barrier request during the
9259 * move folds into this one and gc_exit ends it. */
9260 *lock_lev = RB_GC_VM_LOCK();
9261 rb_gc_vm_barrier();
9262 objspace->flags.gc_lock_barrier = TRUE;
9263 }
9264 else if (gc_local_gc_holds_vm_lock()) {
9265 *lock_lev = RB_GC_VM_LOCK_NO_BARRIER();
9266 }
9267 break;
9268 }
9269
9270 if (objspace->profile.gc_pause_start_time) {
9271 objspace->profile.gc_stw_start_time = rb_hrtime_now();
9272 objspace->profile.gc_stop_time = rb_hrtime_sub(
9273 objspace->profile.gc_stw_start_time,
9274 objspace->profile.gc_pause_start_time);
9275 }
9276
9277 gc_enter_count(event);
9278 if (RB_UNLIKELY(during_gc != 0)) rb_bug("during_gc != 0");
9279 if (RGENGC_CHECK_MODE >= 3) gc_verify_internal_consistency(objspace);
9280
9281 during_gc = TRUE;
9282 RUBY_DEBUG_LOG("%s (%s)",gc_enter_event_cstr(event), gc_current_status(objspace));
9283 gc_report(1, objspace, "gc_enter: %s [%s]\n", gc_enter_event_cstr(event), gc_current_status(objspace));
9284 gc_record(objspace, 0, gc_enter_event_cstr(event));
9285
9286 gc_event_hook(objspace, RUBY_INTERNAL_EVENT_GC_ENTER);
9287 return true;
9288}
9289
9290static inline void
9291gc_exit(rb_objspace_t *objspace, enum gc_enter_event event, unsigned int *lock_lev)
9292{
9293 GC_ASSERT(during_gc != 0);
9294
9295 RUBY_DTRACE_GC_HOOK(EXIT, event);
9296
9297 gc_event_hook(objspace, RUBY_INTERNAL_EVENT_GC_EXIT);
9298
9299 if (objspace->profile.gc_pause_start_time) {
9300 if (gc_prof_enabled(objspace)) {
9301 rb_hrtime_t now = rb_hrtime_now();
9302 gc_profile_record *record = gc_prof_record(objspace);
9303 record->gc_pause_time = rb_hrtime_add(record->gc_pause_time,
9304 rb_hrtime_sub(now, objspace->profile.gc_pause_start_time));
9305 record->gc_stop_time = rb_hrtime_add(record->gc_stop_time,
9306 objspace->profile.gc_stop_time);
9307 record->gc_stw_time = rb_hrtime_add(record->gc_stw_time,
9308 rb_hrtime_sub(now, objspace->profile.gc_stw_start_time));
9309 }
9310 objspace->profile.gc_pause_start_time = 0;
9311 objspace->profile.gc_stw_start_time = 0;
9312 objspace->profile.gc_stop_time = 0;
9313 }
9314
9315 gc_record(objspace, 1, gc_enter_event_cstr(event));
9316 RUBY_DEBUG_LOG("%s (%s)", gc_enter_event_cstr(event), gc_current_status(objspace));
9317 gc_report(1, objspace, "gc_exit: %s [%s]\n", gc_enter_event_cstr(event), gc_current_status(objspace));
9318 during_gc = FALSE;
9319 gc_process_stat_publish(objspace);
9320
9321 switch (event) {
9322 case gc_enter_event_global:
9323 case gc_enter_event_global_auto:
9324 RB_GC_VM_UNLOCK(*lock_lev);
9325 break;
9326 case gc_enter_event_finalizer:
9327 RB_GC_VM_UNLOCK_NO_BARRIER(*lock_lev);
9328 break;
9329 default:
9330 if (*lock_lev != 0) {
9331 if (objspace->flags.gc_lock_barrier) {
9332 objspace->flags.gc_lock_barrier = FALSE;
9333 RB_GC_VM_UNLOCK(*lock_lev);
9334 }
9335 else {
9336 RB_GC_VM_UNLOCK_NO_BARRIER(*lock_lev);
9337 }
9338 }
9339 break;
9340 }
9341}
9342
9343#ifndef MEASURE_GC
9344#define MEASURE_GC (objspace->flags.measure_gc)
9345#endif
9346
9347static void
9348gc_marking_enter(rb_objspace_t *objspace)
9349{
9350 GC_ASSERT(during_gc != 0);
9351
9352 gc_prof_mark_timer_start(objspace);
9353
9354 if (gc_prof_enabled(objspace)) {
9355 objspace->profile.gc_mark_phase_wall_start_time = rb_hrtime_now();
9356 }
9357
9358 if (MEASURE_GC) {
9359 gc_clock_start(&objspace->profile.marking_start_time);
9360 }
9361
9362 rb_gc_initialize_vm_context(&objspace->vm_context);
9363}
9364
9365static void
9366gc_marking_exit(rb_objspace_t *objspace)
9367{
9368 GC_ASSERT(during_gc != 0);
9369
9370 if (MEASURE_GC) {
9371 objspace->profile.marking_time_ns += gc_clock_end(&objspace->profile.marking_start_time);
9372 }
9373
9374 if (gc_prof_enabled(objspace)) {
9375 gc_profile_record *record = gc_prof_record(objspace);
9376 record->gc_mark_wall_time = rb_hrtime_add(record->gc_mark_wall_time,
9377 elapsed_hrtime_from(objspace->profile.gc_mark_phase_wall_start_time));
9378 }
9379
9380 gc_prof_mark_timer_stop(objspace);
9381}
9382
9383static void
9384gc_sweeping_cpu_enter(rb_objspace_t *objspace)
9385{
9386 if (MEASURE_GC) {
9387 gc_clock_start(&objspace->profile.sweeping_start_time);
9388 }
9389}
9390
9391static void
9392gc_sweeping_cpu_exit(rb_objspace_t *objspace)
9393{
9394 if (MEASURE_GC) {
9395 objspace->profile.sweeping_time_ns += gc_clock_end(&objspace->profile.sweeping_start_time);
9396 }
9397}
9398
9399static void
9400gc_sweeping_enter(rb_objspace_t *objspace)
9401{
9402 GC_ASSERT(during_gc != 0);
9403
9404 if (gc_prof_enabled(objspace)) {
9405 objspace->profile.gc_sweep_phase_wall_start_time = rb_hrtime_now();
9406 objspace->profile.gc_sweep_excluded_wall_time = 0;
9407 }
9408
9409 gc_sweeping_cpu_enter(objspace);
9410
9411 rb_gc_initialize_vm_context(&objspace->vm_context);
9412}
9413
9414static void
9415gc_sweeping_exit(rb_objspace_t *objspace)
9416{
9417 GC_ASSERT(during_gc != 0);
9418
9419 gc_sweeping_cpu_exit(objspace);
9420
9421 if (gc_prof_enabled(objspace)) {
9422 rb_hrtime_t sweep_wall_time = elapsed_hrtime_from(objspace->profile.gc_sweep_phase_wall_start_time);
9423 gc_profile_record *record = gc_prof_record(objspace);
9424 sweep_wall_time = rb_hrtime_sub(sweep_wall_time,
9425 objspace->profile.gc_sweep_excluded_wall_time);
9426 record->gc_sweep_wall_time = rb_hrtime_add(record->gc_sweep_wall_time,
9427 sweep_wall_time);
9428 objspace->profile.gc_sweep_excluded_wall_time = 0;
9429 }
9430}
9431
9432static void *
9433gc_with_gvl(void *ptr)
9434{
9435 struct objspace_and_reason *oar = (struct objspace_and_reason *)ptr;
9436 return (void *)(VALUE)garbage_collect(oar->objspace, oar->reason);
9437}
9438
9439int ruby_thread_has_gvl_p(void);
9440
9441static int
9442garbage_collect_with_gvl(rb_objspace_t *objspace, unsigned int reason)
9443{
9444 if (rb_gc_gc_disabled_global_p() || dont_gc_val()) {
9445 return TRUE;
9446 }
9447 else if (!ruby_native_thread_p()) {
9448 return TRUE;
9449 }
9450 else if (!ruby_thread_has_gvl_p()) {
9451 void *ret;
9452 struct objspace_and_reason oar;
9453 oar.objspace = objspace;
9454 oar.reason = reason;
9455 ret = rb_thread_call_with_gvl(gc_with_gvl, (void *)&oar);
9456
9457 return !!ret;
9458 }
9459 else {
9460 return garbage_collect(objspace, reason);
9461 }
9462}
9463
9464static int
9465gc_set_candidate_object_i(void *vstart, void *vend, size_t stride, void *data)
9466{
9468
9469 VALUE v = (VALUE)vstart;
9470 for (; v != (VALUE)vend; v += stride) {
9471 asan_unpoisoning_object(v) {
9472 switch (BUILTIN_TYPE(v)) {
9473 case T_NONE:
9474 case T_ZOMBIE:
9475 break;
9476 default:
9477 rb_gc_prepare_heap_process_object(v);
9478 if (!RVALUE_OLD_P(objspace, v) && !RVALUE_WB_UNPROTECTED(objspace, v)) {
9479 RVALUE_AGE_SET_CANDIDATE(objspace, v);
9480 }
9481 }
9482 }
9483 }
9484
9485 return 0;
9486}
9487
9488bool
9489rb_gc_impl_multi_objspace_p(void)
9490{
9491 return true;
9492}
9493
9494bool
9495rb_gc_impl_during_global_gc_p(void *objspace_ptr)
9496{
9497 rb_objspace_t *objspace = objspace_ptr;
9498 return objspace->flags.during_global_gc != 0;
9499}
9500
9501bool
9502rb_gc_impl_obj_foreign_p(void *objspace_ptr, VALUE obj)
9503{
9504 return gc_foreign_object_p(objspace_ptr, obj);
9505}
9506
9507
9508/* Whether obj is recorded as an unshareable object referenced from a shareable one. For
9509 * the verifier: a shareable -> unshareable edge is only accepted if the write barrier
9510 * recorded it here. */
9511bool
9512rb_gc_impl_shref_marked_p(void *objspace_ptr, VALUE obj)
9513{
9514 return MARKED_IN_BITMAP(GET_HEAP_SHREF_BITS(obj), obj) != 0;
9515}
9516
9517/* The objspace's current page count (used for the zombie_objspaces page accounting). */
9518size_t
9519rb_gc_impl_heap_page_count(void *objspace_ptr)
9520{
9521 rb_objspace_t *objspace = objspace_ptr;
9522 return rb_darray_size(objspace->heap_pages.sorted);
9523}
9524
9525static void
9526gc_global_objspaces_i(void *os, void *data)
9527{
9528 if (global_objspace->global_gc.n_objspaces == global_objspace->global_gc.objspaces_capa) {
9529 size_t new_capa = global_objspace->global_gc.objspaces_capa ? global_objspace->global_gc.objspaces_capa * 2 : 16;
9530 struct rb_objspace **new_list = realloc(global_objspace->global_gc.objspaces, new_capa * sizeof(*new_list));
9531 if (new_list == NULL) rb_bug("gc_global_objspaces_i: realloc failed");
9532 global_objspace->global_gc.objspaces = new_list;
9533 global_objspace->global_gc.objspaces_capa = new_capa;
9534 }
9535 global_objspace->global_gc.objspaces[global_objspace->global_gc.n_objspaces++] = os;
9536}
9537
9538/* Re-snapshot every objspace this cycle covers, zombies included. The objspaces/capa
9539 * buffer is reused from the previous cycle. */
9540static void
9541gc_global_snapshot_objspaces(void)
9542{
9543 global_objspace->global_gc.n_objspaces = 0;
9544 rb_gc_vm_each_objspace(gc_global_objspaces_i, NULL);
9545
9546#if RGENGC_CHECK_MODE
9547 /* Check that the incrementally maintained page_index agrees with the per-objspace
9548 * sorted arrays. */
9549 size_t total = 0;
9550 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
9551 total += rb_darray_size(global_objspace->global_gc.objspaces[i]->heap_pages.sorted);
9552 }
9553 GC_ASSERT(total == global_objspace->page_index.n_pages);
9554#endif
9555}
9556
9557/* Global GC: stop every Ractor and clear/mark/sweep all objspaces as one heap. It is the
9558 * only collector that can free shareable objects and decide cross-objspace reachability
9559 * precisely. */
9560/* The global GC's generic_fields weak pass, after the unified mark fixpoint, before the
9561 * sweep. Per-object rb_mark_generic_ivar is a no-op during a global GC (the driver has
9562 * GET_RACTOR() != owner); the whole table is swept here instead. Weak-KEY: mark the val
9563 * (fields_obj, a strong child) only for a live key, drain dead keys' entries. Marking a
9564 * val can make another key live, so repeat to a fixpoint. */
9567 bool progress;
9568};
9569
9570static int
9571genfields_mark_i(VALUE key, VALUE val, void *arg)
9572{
9573 struct genfields_mark_arg *a = (struct genfields_mark_arg *)arg;
9574 if (RB_SPECIAL_CONST_P(val) || !RVALUE_MARKED_BITMAP(key)) {
9575 return ST_CONTINUE;
9576 }
9577 /* Record the old(key)->young(val) edge with the host (key) as parent, even when val
9578 * is already marked: a conservative machine-stack scan can mark a fresh fields_obj
9579 * parentless before this pass, and branching on the mark bit would leave the key
9580 * unremembered, so the next minor GC misses the young val ("WB miss (O->Y)").
9581 * gc_mark runs rgengc_check_relation before its already-marked return: call always. */
9582 bool newly = !RVALUE_MARKED_BITMAP(val);
9583 gc_mark_set_parent(a->objspace, key);
9584 gc_mark(a->objspace, val);
9585 if (newly) a->progress = true;
9586 return ST_CONTINUE;
9587}
9588
9589static bool
9590genfields_dead_p(VALUE key)
9591{
9592 return RVALUE_MARKED_BITMAP(key) == 0;
9593}
9594
9595static void
9596gc_global_mark_generic_fields(rb_objspace_t *driver)
9597{
9598 struct genfields_mark_arg arg = { driver, false };
9599 do {
9600 arg.progress = false;
9601 /* Each entry's mark sets parent=key (genfields_mark_i) so the generational WB is
9602 * recorded correctly. gc_mark_stacked_objects_all sets its own per-object parent,
9603 * so restore the invalid parent (the poison contract) before calling it. */
9604 rb_gc_vm_generic_fields_mark_foreach(genfields_mark_i, &arg);
9605 gc_mark_set_parent_invalid(driver);
9606 if (arg.progress) {
9607 gc_mark_stacked_objects_all(driver);
9608 }
9609 } while (arg.progress);
9610
9611 rb_gc_vm_generic_fields_drain_dead(genfields_dead_p);
9612}
9613
9614/* Two Ractors choosing a global GC at once are serialized by the VM lock in gc_enter. If two
9615 * globals start concurrently, only one global will run and the other will run a local GC after
9616 * the barrier ends. */
9617static bool
9618gc_start_global(rb_objspace_t *driver, unsigned int reason, bool compact, bool allow_skip)
9619{
9620 unsigned int lock_lev;
9621 enum gc_enter_event event = allow_skip ? gc_enter_event_global_auto : gc_enter_event_global;
9622 if (!gc_enter(driver, event, &lock_lev)) {
9623 return false;
9624 }
9625
9626 reason |= GPR_FLAG_GLOBAL;
9627
9628 /* A global GC is a collection of the driver's objspace too, and its profile.count
9629 * below says so, so report it like a local one. The driver is the objspace whose
9630 * count moves, which is the one a hook reading GC.stat would compare against. For
9631 * the same reason it records a profile entry and reports what triggered it. */
9632 gc_start_record(driver, reason, true);
9633 gc_event_hook(driver, RUBY_INTERNAL_EVENT_GC_START);
9634 gc_prof_timer_start(driver);
9635
9636 gc_global_snapshot_objspaces();
9637
9638 /* Mark every objspace as in a global GC before step 3 settles the lazy sweeps: the
9639 * settle frees other objspaces' garbage on the driver thread, and
9640 * rb_free_generic_ivar must see "global GC in progress" to defer generic_fields
9641 * removal to the weak-pass drain. */
9642 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
9643 global_objspace->global_gc.objspaces[i]->flags.during_global_gc = TRUE;
9644 }
9645
9646 /* A global GC collects every objspace, so each needs the malloc-counter reset the
9647 * driver got in gc_start_record; without it, gc_sweep_finish advancing free_at_last_gc
9648 * (step 9) would leave their malloc_increase overstated by everything swept here. */
9649 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
9650 rb_objspace_t *const os = global_objspace->global_gc.objspaces[i];
9651 if (os != driver) {
9652 os->profile.latest_gc_info = reason;
9653 gc_reset_malloc_info(os, true);
9654 }
9655 }
9656
9657 /* step 3: settle every lazy sweep so the mark bits' meaning is fixed before the clear
9658 * below. (during_gc is a macro over the local "objspace".) rb_gc_get_ec() resolves
9659 * through objspace->vm_context during a GC, so initialize it for all: the driver
9660 * thread runs every objspace's phases. */
9661 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
9662 rb_objspace_t *objspace = global_objspace->global_gc.objspaces[i];
9663 /* The barrier can stop a Ractor between the steps of its own incremental mark, and
9664 * nothing else finishes another objspace's mark. Drop the partial mark rather
9665 * than clear its flags in step 5 under a live gray stack: the owner would resume
9666 * with a mark stack into a heap this GC has since re-marked and swept. Nothing is
9667 * lost, the unified mark below redoes the work. */
9668 if (is_incremental_marking(objspace)) {
9669 gc_abort_incremental_marking(objspace);
9670 }
9671 GC_ASSERT(!is_incremental_marking(objspace));
9672 GC_ASSERT(is_mark_stack_empty(&objspace->mark_stack));
9673 rb_gc_initialize_vm_context(&objspace->vm_context);
9674 if (objspace != driver) during_gc = TRUE;
9675 gc_sweep_rest(objspace);
9676 }
9677
9678 /* step 5: clear every objspace's mark bits, remembered sets, generation counters and
9679 * shrefs (missing even one leaves a stale mark bit and a UAF). (heaps is a macro over
9680 * the local "objspace".) */
9681 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
9682 rb_objspace_t *objspace = global_objspace->global_gc.objspaces[i];
9683 objspace->flags.during_minor_gc = FALSE;
9684 objspace->flags.during_incremental_marking = FALSE;
9685 /* The unified mark is precise and does not pin, so the per-objspace sweep below must
9686 * not re-check against a stale local cycle. */
9687 objspace->last_cycle_pinned = 0;
9688 objspace->rgengc.uncollectible_wb_unprotected_objects = 0;
9689 objspace->rgengc.old_objects = 0;
9690 objspace->rgengc.last_major_gc = objspace->profile.count;
9691 objspace->rgengc.need_major_gc = GPR_FLAG_NONE;
9692 objspace->marked_slots = 0;
9693 for (int h = 0; h < HEAP_COUNT; h++) {
9694 rb_heap_t *heap = &heaps[h];
9695 gc_bitmaps_clear(objspace, heap, true);
9696 heap_move_pooled_pages_to_free_pages(heap);
9697 }
9698 }
9699 driver->profile.global_gc_count++;
9700 global_objspace->global_gc.count++;
9701
9702 /* Enable compaction in every objspace before the mark: the unified conservative root
9703 * scan then pins machine-stack referents (gc_pin only pins while during_compacting)
9704 * and step 9's sweep relocates the rest. global_gc.compacting defers the
9705 * reference-update phase to phase 2 below (two phases, safe across objspaces). */
9706 global_objspace->global_gc.compacting = compact;
9707 if (compact) {
9708 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
9709 rb_objspace_t *objspace = global_objspace->global_gc.objspaces[i];
9710 objspace->flags.during_compacting = TRUE;
9711#if RGENGC_CHECK_MODE
9712 if (ruby_enable_autocompact) {
9713 objspace->rcompactor.compare_func = ruby_autocompact_compare_func;
9714 }
9715#endif
9716 /* A global GC skips gc_marks_start, which is what resets pinned_slots for a
9717 * compacting local GC, so reset it here. step 5 cleared pinned_bits; the
9718 * conservative mark re-pins machine-stack referents. */
9719 for (int h = 0; h < HEAP_COUNT; h++) {
9720 struct heap_page *page = NULL;
9721 ccan_list_for_each(&heaps[h].pages, page, page_node) {
9722 page->pinned_slots = 0;
9723 }
9724 }
9725 }
9726 }
9727
9728 /* steps 6-7: every Ractor's roots (gc.c walks them all), then one unified precise
9729 * mark. A global GC does not go through gc_marks, so the marking
9730 * phase is opened here instead; it closes after rb_ractor_finish_marking below, which is
9731 * where gc_marks_finish ends for a local collection. */
9732 gc_marking_enter(driver);
9733
9734 mark_roots(driver, NULL);
9735 gc_mark_stacked_objects_all(driver);
9736
9737 /* Run the generic_fields weak pass after the mark fixpoint: mark the vals (fields_obj)
9738 * of live keys and drain the entries of dead ones. The per-object rb_mark_generic_ivar
9739 * is a no-op during a global GC, so this is the only path that marks generic_fields. */
9740 gc_global_mark_generic_fields(driver);
9741
9742 gc_event_hook(driver, RUBY_INTERNAL_EVENT_GC_END_MARK);
9743
9744 /* step 8 */
9745 gc_update_weak_references(driver);
9746
9747 /* This cycle's root pass over every Ractor has swept the deleted ractor-local keys out of
9748 * each storage. Free the key structs while still inside the barrier (a local GC never
9749 * can; see rb_ractor_finish_marking). */
9750 rb_ractor_finish_marking(true);
9751
9752 gc_marking_exit(driver);
9753
9754 /* step 9: sweep every objspace inside the barrier, not lazily. Dead shareable objects
9755 * are reclaimed here and emptied pages go back to the pool. */
9756 if (!compact) {
9757 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
9758 rb_objspace_t *os = global_objspace->global_gc.objspaces[i];
9759 unsigned int prev_immediate = os->flags.immediate_sweep;
9760 os->flags.immediate_sweep = TRUE;
9761 gc_sweep(os);
9762 os->flags.immediate_sweep = prev_immediate;
9763 }
9764 }
9765 else {
9766 /* The move -> update-references -> free flow runs as three passes across ALL
9767 * objspaces, not per objspace: (a) updating references must see every objspace's
9768 * forwarding (a reference can point at a moved foreign object), and (b) freeing
9769 * source pages must wait until everyone is updated (or another objspace's update
9770 * reads a freed T_MOVED). The read barrier is installed once for all passes. */
9771 install_handlers();
9772
9773 /* Only the driver records a profile entry for a global GC (gc_start_record), so time
9774 * only the driver's compaction work. The move/update/free below runs inside the
9775 * driver's sweep phase (gc_sweeping_enter/exit); attribute it to GC_COMPACT_WALL_TIME
9776 * and exclude it from the driver's sweep wall time so the two do not double-count,
9777 * mirroring the compacting branch of the local gc_sweep(). */
9778 const bool driver_prof = gc_prof_enabled(driver);
9779 rb_hrtime_t driver_compact_wall_time = 0;
9780
9781 /* pass 1 (move): relocate every objspace and leave T_MOVED forwarding behind. */
9782 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
9783 rb_objspace_t *os = global_objspace->global_gc.objspaces[i];
9784 gc_sweeping_enter(os);
9785 gc_sweep_start(os); /* mode -> sweeping, order the heap for compaction */
9786 rb_hrtime_t t0 = (os == driver && driver_prof) ? rb_hrtime_now() : 0;
9787 gc_compact_relocate(os); /* mode -> compacting, move */
9788 if (os == driver && driver_prof) {
9789 driver_compact_wall_time = rb_hrtime_add(driver_compact_wall_time, elapsed_hrtime_from(t0));
9790 }
9791 gc_sweeping_cpu_exit(os);
9792 }
9793
9794 /* pass 2 (update): all forwarding now exists, so update every objspace's
9795 * references (cross-objspace ones resolve too); gc_compact_finish also unprotects
9796 * pages and clears during_compacting. The move-or-mark decision reads
9797 * rb_gc_get_objspace()'s during_reference_updating: set it on every objspace. */
9798 gc_sweeping_cpu_enter(driver);
9799 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
9800 global_objspace->global_gc.objspaces[i]->flags.during_reference_updating = TRUE;
9801 }
9802
9803 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
9804 rb_objspace_t *objspace = global_objspace->global_gc.objspaces[i];
9805 for (int h = 0; h < HEAP_COUNT; h++) {
9806 gc_unprotect_pages(objspace, &heaps[h]);
9807 }
9808 }
9809 rb_gc_before_updating_jit_code();
9810 gc_sweeping_cpu_exit(driver);
9811 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
9812 rb_objspace_t *os = global_objspace->global_gc.objspaces[i];
9813 gc_sweeping_cpu_enter(os);
9814 rb_hrtime_t t0 = (os == driver && driver_prof) ? rb_hrtime_now() : 0;
9815 gc_compact_finish(os);
9816 if (os == driver && driver_prof) {
9817 driver_compact_wall_time = rb_hrtime_add(driver_compact_wall_time, elapsed_hrtime_from(t0));
9818 }
9819 gc_sweeping_cpu_exit(os);
9820 }
9821 /* The VM-global / weak-table side of the reference update runs once (each objspace's
9822 * heap side already ran in gc_compact_finish above). */
9823 {
9824 gc_sweeping_cpu_enter(driver);
9825 rb_hrtime_t t0 = driver_prof ? rb_hrtime_now() : 0;
9826 gc_update_references_global(driver);
9827 if (driver_prof) {
9828 driver_compact_wall_time = rb_hrtime_add(driver_compact_wall_time, elapsed_hrtime_from(t0));
9829 }
9830 gc_sweeping_cpu_exit(driver);
9831 }
9832 gc_sweeping_cpu_enter(driver);
9833 rb_gc_after_updating_jit_code();
9834 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
9835 global_objspace->global_gc.objspaces[i]->flags.during_reference_updating = FALSE;
9836 global_objspace->global_gc.objspaces[i]->flags.during_compacting = FALSE;
9837 }
9838 global_objspace->global_gc.compacting = false;
9839 uninstall_handlers();
9840 gc_sweeping_cpu_exit(driver);
9841
9842 /* Record the driver's compaction time and exclude it from the driver's sweep phase.
9843 * gc_sweeping_exit(driver) in pass 3 subtracts gc_sweep_excluded_wall_time from the
9844 * sweep wall time, so this must be set before it runs. The excluded value is a sum
9845 * of sub-intervals of the driver's sweep phase, so the subtraction cannot underflow. */
9846 if (driver_prof) {
9847 gc_profile_record *const record = gc_prof_record(driver);
9848 record->gc_compact_wall_time = rb_hrtime_add(record->gc_compact_wall_time,
9849 driver_compact_wall_time);
9850 driver->profile.gc_sweep_excluded_wall_time = rb_hrtime_add(
9851 driver->profile.gc_sweep_excluded_wall_time, driver_compact_wall_time);
9852 }
9853
9854 /* pass 3 (free): page-sweep every objspace, freeing dead objects and the source pages
9855 * that are now empty. during_compacting is already cleared, so the sweep treats
9856 * T_MOVED as usual. */
9857 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
9858 rb_objspace_t *os = global_objspace->global_gc.objspaces[i];
9859 gc_sweeping_cpu_enter(os);
9860 gc_sweep_rest(os);
9861 gc_sweeping_exit(os);
9862 }
9863 }
9864 global_objspace->global_gc.compacting = false;
9865
9866 /* A global GC never calls gc_marks_finish, which budgets heap growth
9867 * (allocatable_bytes). An objspace still full after the global sweep (materializing
9868 * a large received copy, say) has no free pages, no empty pages, budget 0, and its next
9869 * allocation would hit newobj_refill's "cannot create a new page after a major GC".
9870 * Give every objspace stuck like that the growth budget gc_marks_finish would. */
9871 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
9872 rb_objspace_t *objspace = global_objspace->global_gc.objspaces[i];
9873 if (objspace->heap_pages.allocatable_bytes != 0 || objspace->empty_pages_count != 0) {
9874 continue;
9875 }
9876 bool stuck = false;
9877 for (int h = 0; h < HEAP_COUNT; h++) {
9878 if (heaps[h].free_pages == NULL) { stuck = true; break; }
9879 }
9880 if (stuck) {
9881 heap_allocatable_bytes_expand(objspace, NULL, 0,
9882 objspace_available_slots(objspace), heaps[0].slot_size);
9883 }
9884 }
9885
9886 /* Recount the surviving shareable objects (the sweep already folded the dead ones out of
9887 * shareable_bits) and reset each trigger limit. */
9888 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
9889 rb_objspace_t *objspace = global_objspace->global_gc.objspaces[i];
9890 size_t survivors = 0;
9891 for (int h = 0; h < HEAP_COUNT; h++) {
9892 struct heap_page *page = NULL;
9893 ccan_list_for_each(&heaps[h].pages, page, page_node) {
9894 if (!page->flags.has_shareable_objects) continue;
9895 for (int j = 0; j < HEAP_PAGE_BITMAP_LIMIT; j++) {
9896 survivors += rb_popcount_intptr(page->shareable_bits[j]);
9897 }
9898 }
9899 }
9900 objspace->shareable_objects = survivors;
9901 size_t new_limit = (size_t)(survivors * SHAREABLE_OBJECTS_LIMIT_FACTOR);
9902 if (new_limit < SHAREABLE_OBJECTS_LIMIT_MIN) new_limit = SHAREABLE_OBJECTS_LIMIT_MIN;
9903 objspace->shareable_objects_limit = new_limit;
9904 }
9905
9906 /* Deferred non-thread-safe frees: the world is already stopped here, so reap them
9907 * without a second barrier. Uses the driver's snapshot rather than taking its own,
9908 * which step 10 below still walks. */
9909 gc_tdata_unsafe_drain_objspaces(global_objspace->global_gc.objspaces,
9910 global_objspace->global_gc.n_objspaces);
9911 driver->profile.count++;
9912
9913 /* step 10 */
9914 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
9915 rb_objspace_t *objspace = global_objspace->global_gc.objspaces[i];
9916 objspace->flags.during_global_gc = FALSE;
9917 if (objspace != driver) {
9918 during_gc = FALSE;
9919 gc_process_stat_publish(objspace);
9920 }
9921 }
9922
9923 /* The unified mark re-established the reachability of absorbed shareable objects, so a
9924 * single objspace's local mark is trustworthy again (pinning can be skipped until the
9925 * next absorb). */
9926 rb_gc_reset_absorbed_since_global_gc();
9927
9928 /* Re-measure the zombie_objspaces table now that the garbage is gone; entries are stable
9929 * inside the barrier. Without this, the page trigger above keeps firing on the stale
9930 * numbers left when a joinable (slotted) zombie retires without any pass merging it. */
9931 rb_gc_vm_refresh_zombie_pages();
9932 global_objspace->zombie_pages_survivors = rb_gc_vm_zombie_total_pages();
9933
9934 /* If the sweep above collected an unjoined Ractor object, ractor_free disowned its
9935 * zombie_objspaces entry and posted the merge to main as a postponed job; the objspace
9936 * stays enumerable until main absorbs it at its next safepoint. */
9937
9938 gc_prof_timer_stop(driver);
9939 gc_exit(driver, event, &lock_lev);
9940 return true;
9941}
9942
9943static int
9944absorb_finalizer_i(st_data_t key, st_data_t val, st_data_t data)
9945{
9947 st_insert(finalizer_table, key, val);
9948 return ST_CONTINUE;
9949}
9950
9951static void
9952gc_make_mid_mark_objspace_absorbable(rb_objspace_t *src)
9953{
9954 rb_objspace_t *objspace = src;
9955 for (int h = 0; h < HEAP_COUNT; h++) {
9956 struct heap_page *page = NULL;
9957 ccan_list_for_each(&heaps[h].pages, page, page_node) {
9958 short stride = page->slot_size;
9959 uintptr_t p = (uintptr_t)page->start;
9960 uintptr_t pend = p + page->total_slots * stride;
9961
9962 for (; p < pend; p += stride) {
9963 VALUE vp = (VALUE)p;
9964 asan_unpoisoning_object(vp) {
9965 switch (RB_BUILTIN_TYPE(vp)) {
9966 case T_NONE:
9967 case T_ZOMBIE:
9968 break;
9969 default:
9970 RVALUE_AGE_RESET(vp);
9971 break;
9972 }
9973 }
9974 }
9975 }
9976 gc_bitmaps_clear(objspace, &heaps[h], false);
9977 }
9978 objspace->rgengc.old_objects = 0;
9979 objspace->rgengc.uncollectible_wb_unprotected_objects = 0;
9980 objspace->marked_slots = 0;
9981}
9982
9983/* Merge a dead Ractor's objspace into dst under the VM lock. src has no owner thread and
9984 * dst is the calling thread's own objspace (join/value) or main with everyone stopped
9985 * (global GC), so single-writer holds throughout. Pages move whole (their bits describe
9986 * objects, not the objspace), and dst's next collection is forced full to rebuild the
9987 * generational state. */
9988static void
9989objspace_absorb(rb_objspace_t *dst, rb_objspace_t *src)
9990{
9991 GC_ASSERT(dst != src);
9992
9993 /* Suppress the cross-objspace verifier checks while the graph is in flux (see
9994 * global_objspace->during_absorb). */
9995 const bool prev_absorb = global_objspace->during_absorb;
9996 global_objspace->during_absorb = true;
9997
9998 /* Settle dst first: adding pages under a walking lazy-sweep cursor, or into a
9999 * half-marked incremental heap, would sweep the merged pages with src's stale mark
10000 * bits and free live objects. */
10001 gc_rest(dst);
10002
10003 /* Settle src: no incremental marking, lazy sweep or in-progress allocation page. */
10004 {
10005 rb_objspace_t *objspace = src;
10006 /* A zombie parked by fork (rb_ractor_terminate_atfork retires the objspace
10007 * without the retire GC) can be mid-incremental-mark, and that mark cannot be
10008 * finished. Its owner's threads did not survive the fork, so mark_roots would
10009 * scan the absorbing Ractor's roots instead of src's. Drop the cycle. */
10010 if (is_incremental_marking(objspace)) {
10011 gc_abort_incremental_marking(objspace);
10012 gc_make_mid_mark_objspace_absorbable(objspace);
10013 }
10014 gc_rest(src); // if mid-sweep
10015 heap_alloc_state_clear(objspace);
10016 /* gc_sweep_finish leaves swept pages "pooled" for a coming incremental mark; src
10017 * never runs one (it is about to be merged), so return them to its free list now,
10018 * restoring the pooled_pages == NULL the page merge below assumes (mirrors
10019 * gc_start_global step 3). */
10020 for (int h = 0; h < HEAP_COUNT; h++) {
10021 heap_move_pooled_pages_to_free_pages(&heaps[h]);
10022 }
10023 }
10024
10025 /* From here the merge must not run dst's GC: the finalizer st_insert below can cross
10026 * the malloc-accounting threshold, and a GC then would sweep src's detached finalizer
10027 * procs, reachable only from this C frame, into dangling VALUEs. Page/darray moves
10028 * allocate nothing (_without_gc), so disabling costs nothing and makes the splice
10029 * atomic. (The two settles above deliberately collect: they stay outside.) */
10030 const bool dst_gc_was_enabled = rb_gc_impl_gc_enabled_p(dst);
10031 if (dst_gc_was_enabled) rb_gc_impl_gc_disable(dst, false);
10032
10033 /* Hand over the pages size pool by size pool. ("heaps" is a macro over the local
10034 * objspace, so the arrays are taken through scoped locals.) */
10035 rb_heap_t *dst_heaps;
10036 rb_heap_t *src_heaps;
10037 {
10038 rb_objspace_t *objspace = dst;
10039 dst_heaps = heaps;
10040 }
10041 {
10042 rb_objspace_t *objspace = src;
10043 src_heaps = heaps;
10044 }
10045 for (int h = 0; h < HEAP_COUNT; h++) {
10046 rb_heap_t *dheap = &dst_heaps[h];
10047 rb_heap_t *sheap = &src_heaps[h];
10048 struct heap_page *page = NULL;
10049
10050 GC_ASSERT(sheap->sweeping_page == NULL);
10051 GC_ASSERT(sheap->pooled_pages == NULL);
10052
10053 ccan_list_for_each(&sheap->pages, page, page_node) {
10054 page->objspace = dst;
10055 page->heap = dheap;
10056 }
10057 ccan_list_append_list(&dheap->pages, &sheap->pages);
10058
10059 /* Append the free-page chain to the tail. */
10060 if (sheap->free_pages) {
10061 struct heap_page **tail = &dheap->free_pages;
10062 while (*tail) tail = &(*tail)->free_next;
10063 *tail = sheap->free_pages;
10064 sheap->free_pages = NULL;
10065 }
10066
10067 dheap->total_pages += sheap->total_pages;
10068 dheap->total_slots += sheap->total_slots;
10069 dheap->total_allocated_pages += sheap->total_allocated_pages;
10070 dheap->total_allocated_objects += sheap->total_allocated_objects;
10071 dheap->total_freed_objects += sheap->total_freed_objects;
10072 dheap->final_slots_count += sheap->final_slots_count;
10073 }
10074
10075 /* The objspace-wide page bookkeeping. */
10076 {
10077 rb_objspace_t *objspace = dst; /* for the heap_pages_* macros */
10078 struct heap_page *page = NULL;
10079 size_t srcn = rb_darray_size(src->heap_pages.sorted);
10080 for (size_t i = 0; i < srcn; i++) {
10081 page = rb_darray_get(src->heap_pages.sorted, i);
10082 /* Residents of the empty pool (no live objects) are returned to page_pool rather
10083 * than inherited; dst's allocation demand is cheaply met from the shared pool's
10084 * free list. */
10085 if (heap_page_in_global_empty_pages_pool(src, page)) {
10086 heap_page_free(src, page);
10087 continue;
10088 }
10089 uintptr_t body = (uintptr_t)page->body;
10090 uintptr_t start = body + sizeof(struct heap_page_header);
10091 uintptr_t end = body + HEAP_PAGE_SIZE;
10092
10093 /* Keep the array ordered by page BODY address: heap_page_for_ptr bsearches
10094 * body ranges, and a detached empty page has start == 0, so ordering by
10095 * page->start would miss live pages (a global GC would then fail to mark a
10096 * registered root and sweep it). */
10097 size_t lo = 0;
10098 size_t hi = rb_darray_size(objspace->heap_pages.sorted);
10099 while (lo < hi) {
10100 size_t mid = (lo + hi) / 2;
10101 struct heap_page *mid_page = rb_darray_get(objspace->heap_pages.sorted, mid);
10102 if ((uintptr_t)mid_page->body < body) lo = mid + 1;
10103 else hi = mid;
10104 }
10105 rb_darray_insert_without_gc(&objspace->heap_pages.sorted, hi, page);
10106
10107 if (heap_pages_lomem == 0 || heap_pages_lomem > start) heap_pages_lomem = start;
10108 if (heap_pages_himem < end) heap_pages_himem = end;
10109 }
10110 objspace->heap_pages.allocated_pages += src->heap_pages.allocated_pages;
10111 objspace->heap_pages.freed_pages += src->heap_pages.freed_pages;
10112 rb_darray_free_without_gc(src->heap_pages.sorted);
10113 src->heap_pages.sorted = NULL;
10114 /* The empty_pages chain's structs were freed in the loop above. */
10115 src->empty_pages = NULL;
10116 src->empty_pages_count = 0;
10117 }
10118
10119 /* Finalizers: move the table's entries, and the dead Ractor's deferred zombies are run
10120 * by dst's thread from now on. */
10121 {
10122 st_table *src_finalizers;
10123 {
10124 rb_objspace_t *objspace = src;
10125 src_finalizers = finalizer_table;
10126 finalizer_table = NULL;
10127 }
10128 if (src_finalizers) {
10129 rb_objspace_t *objspace = dst;
10130 if (finalizer_table == NULL) {
10131 finalizer_table = src_finalizers;
10132 }
10133 else {
10134 st_foreach(src_finalizers, absorb_finalizer_i, (st_data_t)dst);
10135 st_free_table(src_finalizers);
10136 }
10137 }
10138 }
10139 {
10140 VALUE src_deferred = RUBY_ATOMIC_VALUE_EXCHANGE(src->heap_pages.deferred_final, 0);
10141 if (src_deferred) {
10142 VALUE tail_obj = src_deferred;
10143 rb_asan_unpoison_object(tail_obj, false);
10144 while (RZOMBIE(tail_obj)->next) {
10145 VALUE next_obj = RZOMBIE(tail_obj)->next;
10146 rb_asan_poison_object(tail_obj);
10147 tail_obj = next_obj;
10148 rb_asan_unpoison_object(tail_obj, false);
10149 }
10150 VALUE prev;
10151 do {
10152 prev = dst->heap_pages.deferred_final;
10153 RZOMBIE(tail_obj)->next = prev;
10154 } while (RUBY_ATOMIC_VALUE_CAS(dst->heap_pages.deferred_final, prev, src_deferred) != prev);
10155 rb_asan_poison_object(tail_obj);
10156 /* No owner was left to run these zombies (register's owner walk misses a dead
10157 * Ractor). dst runs this merge, so schedule dst's job here; otherwise they wait
10158 * until dst's next GC. */
10159 rb_postponed_job_trigger(dst->finalize_deferred_pjob);
10160 }
10161 }
10162 if (src->tdata_unsafe_free_chunk) {
10163 gc_tdata_unsafe_free_publish(src);
10164 }
10165 if (tdata_deferred_free_count_load() >= TDATA_DEFERRED_FREE_THRESHOLD) {
10166 gc_tdata_deferred_free_trigger(dst);
10167 }
10168
10169 /* Counters inherited by dst. */
10170 dst->rgengc.old_objects += src->rgengc.old_objects;
10171 dst->rgengc.uncollectible_wb_unprotected_objects += src->rgengc.uncollectible_wb_unprotected_objects;
10172 dst->shareable_objects += src->shareable_objects;
10173
10174 /* Merged pages carry src's mark/age state, so dst rebuilds its view at the next
10175 * collection. Note that this can be worked around by calling `GC.config(rgengc_allow_full_mark: false)`,
10176 * so the absorbed heap should be in a state where a minor GC would also work correctly.
10177 */
10178 dst->rgengc.need_major_gc |= GPR_FLAG_MAJOR_BY_FORCE;
10179
10180 /* src's outstanding malloc pressure moves with the xmalloc'd buffers. Later frees are
10181 * charged to dst, so without this transfer dst underestimates its own heap and delays
10182 * GCs. dst is live, so take its counter lock where gc_counter_add is not atomic. */
10183 {
10184 int64_t inc = gc_malloc_counters_increase(src, &src->malloc_counters.counters);
10185#if RGENGC_ESTIMATE_OLDMALLOC
10186 int64_t oldinc = gc_malloc_counters_increase(src, &src->malloc_counters.oldcounters);
10187#endif
10188 MALLOC_COUNTERS_LOCK(dst);
10189 if (inc > 0) gc_counter_add(&dst->malloc_counters.counters.malloc, (size_t)inc);
10190#if RGENGC_ESTIMATE_OLDMALLOC
10191 if (oldinc > 0) gc_counter_add(&dst->malloc_counters.oldcounters.malloc, (size_t)oldinc);
10192#endif
10193 MALLOC_COUNTERS_UNLOCK(dst);
10194 }
10195
10196 {
10197 struct gc_process_stat_snapshot final_snap;
10198 gc_process_stat_capture(src, &final_snap);
10199 gc_process_stat_add(&global_objspace->process_stat_archive, &final_snap);
10200 }
10201 rb_native_mutex_destroy(&src->process_stat.lock);
10202
10203 /* Free the shell (as rb_gc_impl_objspace_free does). */
10204 free(src->profile.records);
10205 free_stack_chunks(&src->mark_stack);
10206 mark_stack_free_cache(&src->mark_stack);
10207 GC_ASSERT(rb_darray_size(src->weak_references) == 0);
10208 rb_darray_free_without_gc(src->weak_references);
10209#ifdef MALLOC_COUNTERS_NEED_LOCK
10210 rb_native_mutex_destroy(&src->malloc_counters.lock);
10211#endif
10212 free(src);
10213
10214 if (dst_gc_was_enabled) rb_gc_impl_gc_enable(dst);
10215
10216 /* Return the empty pages inheritance piled up in dst (mostly from the dead Ractor's
10217 * teardown material) to the pool with no budget. An empty page is by definition safe to
10218 * release, and re-acquiring one from the pool is cheap. */
10219 {
10220 rb_objspace_t *objspace = dst;
10221 heap_pages_freeable_pages = objspace->empty_pages_count;
10222 heap_pages_free_unused_pages(objspace);
10223 }
10224
10225 global_objspace->during_absorb = prev_absorb;
10226}
10227
10228void
10229rb_gc_impl_objspace_absorb(void *dst_ptr, void *src_ptr)
10230{
10231 objspace_absorb(dst_ptr, src_ptr);
10232}
10233
10234void
10235rb_gc_impl_start(void *objspace_ptr, bool full_mark, bool immediate_mark, bool immediate_sweep, bool compact, bool global)
10236{
10237 rb_objspace_t *objspace = objspace_ptr;
10238 unsigned int reason = (GPR_FLAG_FULL_MARK |
10239 GPR_FLAG_IMMEDIATE_MARK |
10240 GPR_FLAG_IMMEDIATE_SWEEP |
10241 GPR_FLAG_METHOD);
10242
10243 int full_marking_p = gc_config_full_mark_val;
10244 gc_config_full_mark_set(TRUE);
10245
10246 /* For now, compact implies full mark / sweep, so ignore other flags */
10247 if (compact) {
10248 GC_ASSERT(GC_COMPACTION_SUPPORTED);
10249
10250 reason |= GPR_FLAG_COMPACT;
10251 if (!rb_gc_single_objspace_p()) {
10252 global = true;
10253 }
10254 }
10255 else {
10256 if (!full_mark) reason &= ~GPR_FLAG_FULL_MARK;
10257 if (!immediate_mark) reason &= ~GPR_FLAG_IMMEDIATE_MARK;
10258 if (!immediate_sweep) reason &= ~GPR_FLAG_IMMEDIATE_SWEEP;
10259 }
10260
10261 if ((reason & (GPR_FLAG_FULL_MARK | GPR_FLAG_IMMEDIATE_MARK | GPR_FLAG_IMMEDIATE_SWEEP)) !=
10262 (GPR_FLAG_FULL_MARK | GPR_FLAG_IMMEDIATE_MARK | GPR_FLAG_IMMEDIATE_SWEEP)) {
10263 global = false;
10264 }
10265
10266 if (global && !rb_gc_single_objspace_p()) {
10267 /* A mid-cycle driver is settled by gc_start_global itself: it aborts the partial
10268 * mark and finishes the lazy sweep, so the dead slots are T_NONE before the
10269 * unified conservative root scan. */
10270 gc_start_global(objspace, reason, compact || ruby_enable_autocompact, false);
10271 }
10272 else {
10273 garbage_collect(objspace, reason);
10274 }
10275
10276 gc_finalize_deferred(objspace);
10277 /* An explicit GC.start is expected to reclaim immediately, so run the deferred non-thread-safe
10278 * frees synchronously instead of leaving them to gc_sweep_finish's postponed job. */
10279 if (tdata_deferred_free_count_load() > 0 && rb_gc_single_objspace_p()) {
10280 gc_tdata_unsafe_drain();
10281 }
10282 gc_config_full_mark_set(full_marking_p);
10283}
10284
10285void
10286rb_gc_impl_prepare_heap(void *objspace_ptr)
10287{
10288 rb_objspace_t *objspace = objspace_ptr;
10289
10290 rb_gc_impl_each_objects(objspace, gc_set_candidate_object_i, objspace_ptr);
10291
10292 double orig_max_free_slots = gc_params.heap_free_slots_max_ratio;
10293 /* Ensure that all empty pages are moved onto empty_pages. */
10294 gc_params.heap_free_slots_max_ratio = 0.0;
10295 rb_gc_impl_start(objspace, true, true, true, true, true);
10296 gc_params.heap_free_slots_max_ratio = orig_max_free_slots;
10297
10298 objspace->heap_pages.allocatable_bytes = 0;
10299 heap_pages_freeable_pages = objspace->empty_pages_count;
10300 heap_pages_free_unused_pages(objspace_ptr);
10301 GC_ASSERT(heap_pages_freeable_pages == 0);
10302 GC_ASSERT(objspace->empty_pages_count == 0);
10303
10304 // Process.warmup is meant to be called at the end of the boot sequence, which is commonly allocation
10305 // heavy and result in GC limits raising significantly, but it's not indicative of the limits needed
10306 // for runtime.
10307 // Recompute the allocatable_bytes limit based on `gc_params.heap_init_bytes`.
10308 GC_ASSERT(objspace->heap_pages.allocatable_bytes == 0);
10309 for (int i = 0; i < HEAP_COUNT; i++) {
10310 rb_heap_t *heap = &heaps[i];
10311 heap_allocatable_bytes_expand(objspace, heap, heap->empty_slots, heap->total_slots, heap->slot_size);
10312 }
10313
10314#if defined(HAVE_MALLOC_TRIM) && !defined(RUBY_ALTERNATIVE_MALLOC_HEADER)
10315 malloc_trim(0);
10316#endif
10317}
10318
10319static int
10320gc_is_moveable_obj(rb_objspace_t *objspace, VALUE obj)
10321{
10322 GC_ASSERT(!SPECIAL_CONST_P(obj));
10323
10324 switch (BUILTIN_TYPE(obj)) {
10325 case T_NONE:
10326 case T_MOVED:
10327 case T_ZOMBIE:
10328 return FALSE;
10329 case T_SYMBOL:
10330 case T_STRING:
10331 case T_OBJECT:
10332 case T_FLOAT:
10333 case T_IMEMO:
10334 case T_ARRAY:
10335 case T_BIGNUM:
10336 case T_ICLASS:
10337 case T_MODULE:
10338 case T_REGEXP:
10339 case T_DATA:
10340 case T_MATCH:
10341 case T_STRUCT:
10342 case T_HASH:
10343 case T_FILE:
10344 case T_COMPLEX:
10345 case T_RATIONAL:
10346 case T_NODE:
10347 case T_CLASS:
10348 if (FL_TEST_RAW(obj, FL_FINALIZE)) {
10349 /* The finalizer table is a numtable. It looks up objects by address.
10350 * We can't mark the keys in the finalizer table because that would
10351 * prevent the objects from being collected. This check prevents
10352 * objects that are keys in the finalizer table from being moved
10353 * without directly pinning them. */
10354 GC_ASSERT(st_is_member(finalizer_table, obj));
10355
10356 return FALSE;
10357 }
10358 GC_ASSERT(RVALUE_MARKED(objspace, obj));
10359 GC_ASSERT(!RVALUE_PINNED(objspace, obj));
10360
10361 return TRUE;
10362
10363 default:
10364 rb_bug("gc_is_moveable_obj: unreachable (%d)", (int)BUILTIN_TYPE(obj));
10365 break;
10366 }
10367
10368 return FALSE;
10369}
10370
10371void rb_mv_generic_ivar(VALUE src, VALUE dst);
10372
10373static VALUE
10374gc_move(rb_objspace_t *objspace, VALUE src, VALUE dest, struct heap_page *src_page, struct heap_page *dest_page)
10375{
10376 size_t src_slot_size = src_page->slot_size;
10377 size_t slot_size = dest_page->slot_size;
10378
10379 int marked;
10380 int wb_unprotected;
10381 int uncollectible;
10382 int age;
10383
10384 gc_report(4, objspace, "Moving object: %p -> %p\n", (void *)src, (void *)dest);
10385
10386 GC_ASSERT(BUILTIN_TYPE(src) != T_NONE);
10387 GC_ASSERT(!MARKED_IN_BITMAP(GET_HEAP_MARK_BITS(dest), dest));
10388
10389 GC_ASSERT(!RVALUE_MARKING(objspace, src));
10390
10391 /* Save off bits for current object. */
10392 marked = RVALUE_MARKED(objspace, src);
10393 wb_unprotected = RVALUE_WB_UNPROTECTED(objspace, src);
10394 uncollectible = RVALUE_UNCOLLECTIBLE(objspace, src);
10395 bool remembered = RVALUE_REMEMBERED(objspace, src);
10396 /* Pin bits travel with the object. Losing one during single-objspace compaction would
10397 * silently unpin it once the process goes multi-objspace, letting a local GC free a method
10398 * entry or shref target that another Ractor references. */
10399 bool shareable = MARKED_IN_BITMAP(GET_HEAP_SHAREABLE_BITS(src), src) != 0;
10400 bool shref = MARKED_IN_BITMAP(GET_HEAP_SHREF_BITS(src), src) != 0;
10401 age = RVALUE_AGE_GET(src);
10402
10403 /* Clear bits for eventual T_MOVED */
10404 CLEAR_IN_BITMAP(GET_HEAP_MARK_BITS(src), src);
10405 CLEAR_IN_BITMAP(GET_HEAP_WB_UNPROTECTED_BITS(src), src);
10406 CLEAR_IN_BITMAP(GET_HEAP_UNCOLLECTIBLE_BITS(src), src);
10407 CLEAR_IN_BITMAP(GET_HEAP_PAGE(src)->remembered_bits, src);
10408 CLEAR_IN_BITMAP(GET_HEAP_SHAREABLE_BITS(src), src);
10409 CLEAR_IN_BITMAP(GET_HEAP_SHREF_BITS(src), src);
10410
10411 /* Move the object */
10412 memcpy((void *)dest, (void *)src, MIN(src_slot_size, slot_size));
10413
10414 if (src_slot_size != slot_size) {
10415 rb_gc_obj_changed_slot_size(dest, slot_size - RVALUE_OVERHEAD);
10416 }
10417
10418 if (RVALUE_OVERHEAD > 0) {
10419 void *dest_overhead = (void *)(((uintptr_t)dest) + slot_size - RVALUE_OVERHEAD);
10420 void *src_overhead = (void *)(((uintptr_t)src) + src_slot_size - RVALUE_OVERHEAD);
10421
10422 memcpy(dest_overhead, src_overhead, RVALUE_OVERHEAD);
10423 }
10424
10425 memset((void *)src, 0, src_slot_size);
10426 RVALUE_AGE_SET_BITMAP(src, 0);
10427
10428 /* Set bits for object in new location */
10429 if (remembered) {
10430 MARK_IN_BITMAP(GET_HEAP_PAGE(dest)->remembered_bits, dest);
10431 }
10432 else {
10433 CLEAR_IN_BITMAP(GET_HEAP_PAGE(dest)->remembered_bits, dest);
10434 }
10435
10436 if (marked) {
10437 MARK_IN_BITMAP(GET_HEAP_MARK_BITS(dest), dest);
10438 }
10439 else {
10440 CLEAR_IN_BITMAP(GET_HEAP_MARK_BITS(dest), dest);
10441 }
10442
10443 if (wb_unprotected) {
10444 MARK_IN_BITMAP(GET_HEAP_WB_UNPROTECTED_BITS(dest), dest);
10445 }
10446 else {
10447 CLEAR_IN_BITMAP(GET_HEAP_WB_UNPROTECTED_BITS(dest), dest);
10448 }
10449
10450 if (uncollectible) {
10451 MARK_IN_BITMAP(GET_HEAP_UNCOLLECTIBLE_BITS(dest), dest);
10452 }
10453 else {
10454 CLEAR_IN_BITMAP(GET_HEAP_UNCOLLECTIBLE_BITS(dest), dest);
10455 }
10456
10457 if (shareable) {
10458 MARK_IN_BITMAP(GET_HEAP_SHAREABLE_BITS(dest), dest);
10459 GET_HEAP_PAGE(dest)->flags.has_shareable_objects = TRUE;
10460 }
10461 else {
10462 CLEAR_IN_BITMAP(GET_HEAP_SHAREABLE_BITS(dest), dest);
10463 }
10464
10465 if (shref) {
10466 MARK_IN_BITMAP(GET_HEAP_SHREF_BITS(dest), dest);
10467 GET_HEAP_PAGE(dest)->flags.has_shref_objects = TRUE;
10468 }
10469 else {
10470 CLEAR_IN_BITMAP(GET_HEAP_SHREF_BITS(dest), dest);
10471 }
10472
10473 RVALUE_AGE_SET(dest, age);
10474
10475 /* A re-embedded object (rb_gc_obj_changed_slot_size) references its
10476 * former fields_obj's contents directly; the write-barrier history
10477 * lived on the discarded fields_obj, so remember the object. */
10478 if (src_slot_size != slot_size && age >= RVALUE_OLD_AGE && !remembered) {
10479 rgengc_remember(objspace, dest);
10480 }
10481
10482 /* Assign forwarding address */
10483 RMOVED(src)->flags = T_MOVED;
10484 RMOVED(src)->dummy = Qundef;
10485 RMOVED(src)->destination = dest;
10486 GC_ASSERT(BUILTIN_TYPE(dest) != T_NONE);
10487
10488 GET_HEAP_PAGE(src)->heap->total_freed_objects++;
10489 GET_HEAP_PAGE(dest)->heap->total_allocated_objects++;
10490
10491 return src;
10492}
10493
10494#if GC_CAN_COMPILE_COMPACTION
10495static int
10496compare_pinned_slots(const void *left, const void *right, void *dummy)
10497{
10498 struct heap_page *left_page;
10499 struct heap_page *right_page;
10500
10501 left_page = *(struct heap_page * const *)left;
10502 right_page = *(struct heap_page * const *)right;
10503
10504 return left_page->pinned_slots - right_page->pinned_slots;
10505}
10506
10507static int
10508compare_free_slots(const void *left, const void *right, void *dummy)
10509{
10510 struct heap_page *left_page;
10511 struct heap_page *right_page;
10512
10513 left_page = *(struct heap_page * const *)left;
10514 right_page = *(struct heap_page * const *)right;
10515
10516 return left_page->free_slots - right_page->free_slots;
10517}
10518
10519static void
10520gc_sort_heap_by_compare_func(rb_objspace_t *objspace, gc_compact_compare_func compare_func)
10521{
10522 for (int j = 0; j < HEAP_COUNT; j++) {
10523 rb_heap_t *heap = &heaps[j];
10524
10525 size_t total_pages = heap->total_pages;
10526 size_t size = rb_size_mul_or_raise(total_pages, sizeof(struct heap_page *), rb_eRuntimeError);
10527 struct heap_page *page = 0, **page_list = malloc(size);
10528 size_t i = 0;
10529
10530 heap->free_pages = NULL;
10531 ccan_list_for_each(&heap->pages, page, page_node) {
10532 page_list[i++] = page;
10533 GC_ASSERT(page);
10534 }
10535
10536 GC_ASSERT((size_t)i == total_pages);
10537
10538 /* Sort the heap so "filled pages" are first. `heap_add_page` adds to the
10539 * head of the list, so empty pages will end up at the start of the heap */
10540 ruby_qsort(page_list, total_pages, sizeof(struct heap_page *), compare_func, NULL);
10541
10542 /* Reset the eden heap */
10543 ccan_list_head_init(&heap->pages);
10544
10545 for (i = 0; i < total_pages; i++) {
10546 ccan_list_add(&heap->pages, &page_list[i]->page_node);
10547 if (page_list[i]->free_slots != 0) {
10548 heap_add_freepage(heap, page_list[i]);
10549 }
10550 }
10551
10552 free(page_list);
10553 }
10554}
10555#endif
10556
10557void
10558rb_gc_impl_register_pinning_obj(void *objspace_ptr, VALUE obj)
10559{
10560 /* no-op */
10561}
10562
10563bool
10564rb_gc_impl_object_moved_p(void *objspace_ptr, VALUE obj)
10565{
10566 return gc_object_moved_p(objspace_ptr, obj);
10567}
10568
10569static int
10570gc_ref_update(void *vstart, void *vend, size_t stride, rb_objspace_t *objspace, struct heap_page *page)
10571{
10572 VALUE v = (VALUE)vstart;
10573
10574 page->flags.has_uncollectible_wb_unprotected_objects = FALSE;
10575 page->flags.has_remembered_objects = FALSE;
10576
10577 /* For each object on the page */
10578 for (; v != (VALUE)vend; v += stride) {
10579 asan_unpoisoning_object(v) {
10580 switch (BUILTIN_TYPE(v)) {
10581 case T_NONE:
10582 case T_MOVED:
10583 case T_ZOMBIE:
10584 break;
10585 default:
10586 if (RVALUE_WB_UNPROTECTED(objspace, v)) {
10587 page->flags.has_uncollectible_wb_unprotected_objects = TRUE;
10588 }
10589 if (RVALUE_REMEMBERED(objspace, v)) {
10590 page->flags.has_remembered_objects = TRUE;
10591 }
10592 if (page->flags.before_sweep) {
10593 if (RVALUE_MARKED(objspace, v)) {
10594 rb_gc_update_object_references(objspace, v);
10595 }
10596 }
10597 else {
10598 rb_gc_update_object_references(objspace, v);
10599 }
10600 }
10601 }
10602 }
10603
10604 return 0;
10605}
10606
10607static int
10608gc_update_references_weak_table_i(VALUE obj, void *data)
10609{
10610 int ret;
10611 asan_unpoisoning_object(obj) {
10612 ret = BUILTIN_TYPE(obj) == T_MOVED ? ST_REPLACE : ST_CONTINUE;
10613 }
10614 return ret;
10615}
10616
10617static int
10618gc_update_references_weak_table_replace_i(VALUE *obj, void *data)
10619{
10620 rb_gc_update_moved(obj);
10621
10622 return ST_CONTINUE;
10623}
10624
10625/* The per-objspace side of the reference update: walk this objspace's heap objects and rewrite
10626 * moved references (following T_MOVED forwarding across objspaces). A compacting global GC
10627 * runs this for every objspace. */
10628static void
10629gc_update_references_heap(rb_objspace_t *objspace)
10630{
10631 struct heap_page *page = NULL;
10632
10633 for (int i = 0; i < HEAP_COUNT; i++) {
10634 bool should_set_mark_bits = TRUE;
10635 rb_heap_t *heap = &heaps[i];
10636
10637 ccan_list_for_each(&heap->pages, page, page_node) {
10638 uintptr_t start = (uintptr_t)page->start;
10639 uintptr_t end = start + (page->total_slots * heap->slot_size);
10640
10641 gc_ref_update((void *)start, (void *)end, heap->slot_size, objspace, page);
10642 if (page == heap->sweeping_page) {
10643 should_set_mark_bits = FALSE;
10644 }
10645 if (should_set_mark_bits) {
10646 gc_setup_mark_bits(page);
10647 }
10648 }
10649 }
10650}
10651
10652/* The VM-global side of the reference update (finalizer table, every Ractor's VM roots,
10653 * weak tables). Process-wide, so a compacting global GC runs it once after every heap
10654 * side: rb_gc_update_vm_references and the weak tables' mark_and_move are not idempotent. */
10655static void
10656gc_update_references_global(rb_objspace_t *objspace)
10657{
10658 gc_update_table_refs(finalizer_table);
10659
10660 rb_gc_update_vm_references((void *)objspace);
10661
10662 for (int table = 0; table < RB_GC_VM_WEAK_TABLE_COUNT; table++) {
10663 rb_gc_vm_weak_table_foreach(
10664 gc_update_references_weak_table_i,
10665 gc_update_references_weak_table_replace_i,
10666 NULL,
10667 false,
10668 table
10669 );
10670 }
10671}
10672
10673static void
10674gc_update_references(rb_objspace_t *objspace)
10675{
10676 objspace->flags.during_reference_updating = true;
10677
10678 rb_gc_before_updating_jit_code();
10679
10680 gc_update_references_heap(objspace);
10681 gc_update_references_global(objspace);
10682
10683 rb_gc_after_updating_jit_code();
10684
10685 objspace->flags.during_reference_updating = false;
10686}
10687
10688#if GC_CAN_COMPILE_COMPACTION
10689static void
10690root_obj_check_moved_i(const char *category, VALUE obj, void *data)
10691{
10692 rb_objspace_t *objspace = data;
10693
10694 if (gc_object_moved_p(objspace, obj)) {
10695 rb_bug("ROOT %s points to MOVED: %p -> %s", category, (void *)obj, rb_obj_info(rb_gc_impl_location(objspace, obj)));
10696 }
10697}
10698
10699static void
10700reachable_object_check_moved_i(VALUE ref, void *data)
10701{
10702 VALUE parent = (VALUE)data;
10703 if (gc_object_moved_p(rb_gc_get_objspace(), ref)) {
10704 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)));
10705 }
10706}
10707
10708static int
10709heap_check_moved_i(void *vstart, void *vend, size_t stride, void *data)
10710{
10711 rb_objspace_t *objspace = data;
10712
10713 VALUE v = (VALUE)vstart;
10714 for (; v != (VALUE)vend; v += stride) {
10715 if (gc_object_moved_p(objspace, v)) {
10716 /* Moved object still on the heap, something may have a reference. */
10717 }
10718 else {
10719 asan_unpoisoning_object(v) {
10720 switch (BUILTIN_TYPE(v)) {
10721 case T_NONE:
10722 case T_ZOMBIE:
10723 break;
10724 default:
10725 if (!rb_gc_impl_garbage_object_p(objspace, v)) {
10726 rb_objspace_reachable_objects_from(v, reachable_object_check_moved_i, (void *)v);
10727 }
10728 }
10729 }
10730 }
10731 }
10732
10733 return 0;
10734}
10735#endif
10736
10737bool
10738rb_gc_impl_during_gc_p(void *objspace_ptr)
10739{
10740 rb_objspace_t *objspace = objspace_ptr;
10741
10742 return during_gc;
10743}
10744
10745#if RGENGC_PROFILE >= 2
10746
10747static const char*
10748type_name(int type, VALUE obj)
10749{
10750 switch ((enum ruby_value_type)type) {
10751 case RUBY_T_NONE: return "T_NONE";
10752 case RUBY_T_OBJECT: return "T_OBJECT";
10753 case RUBY_T_CLASS: return "T_CLASS";
10754 case RUBY_T_MODULE: return "T_MODULE";
10755 case RUBY_T_FLOAT: return "T_FLOAT";
10756 case RUBY_T_STRING: return "T_STRING";
10757 case RUBY_T_REGEXP: return "T_REGEXP";
10758 case RUBY_T_ARRAY: return "T_ARRAY";
10759 case RUBY_T_HASH: return "T_HASH";
10760 case RUBY_T_STRUCT: return "T_STRUCT";
10761 case RUBY_T_BIGNUM: return "T_BIGNUM";
10762 case RUBY_T_FILE: return "T_FILE";
10763 case RUBY_T_DATA: return "T_DATA";
10764 case RUBY_T_MATCH: return "T_MATCH";
10765 case RUBY_T_COMPLEX: return "T_COMPLEX";
10766 case RUBY_T_RATIONAL: return "T_RATIONAL";
10767 case RUBY_T_NIL: return "T_NIL";
10768 case RUBY_T_TRUE: return "T_TRUE";
10769 case RUBY_T_FALSE: return "T_FALSE";
10770 case RUBY_T_SYMBOL: return "T_SYMBOL";
10771 case RUBY_T_FIXNUM: return "T_FIXNUM";
10772 case RUBY_T_UNDEF: return "T_UNDEF";
10773 case RUBY_T_IMEMO: return "T_IMEMO";
10774 case RUBY_T_NODE: return "T_NODE";
10775 case RUBY_T_ICLASS: return "T_ICLASS";
10776 case RUBY_T_ZOMBIE: return "T_ZOMBIE";
10777 case RUBY_T_MOVED: return "T_MOVED";
10778 default: return "unknown";
10779 }
10780}
10781
10782static void
10783gc_count_add_each_types(VALUE hash, const char *name, const size_t *types)
10784{
10785 VALUE result = rb_hash_new_capa(T_MASK);
10786 int i;
10787 for (i=0; i<T_MASK; i++) {
10788 const char *type = type_name(i, 0);
10789 rb_hash_aset(result, ID2SYM(rb_intern(type)), SIZET2NUM(types[i]));
10790 }
10791 rb_hash_aset(hash, ID2SYM(rb_intern(name)), result);
10792}
10793#endif
10794
10795size_t
10796rb_gc_impl_gc_count(void *objspace_ptr)
10797{
10798 rb_objspace_t *objspace = objspace_ptr;
10799
10800 return objspace->profile.count;
10801}
10802
10803/* Filled by setup_gc_latest_gc_info_symbols() at boot, not on first use. */
10804static VALUE sym_major_by, sym_gc_by, sym_immediate_sweep, sym_have_finalizer, sym_state, sym_need_major_by;
10805static VALUE sym_nofree, sym_oldgen, sym_shady, sym_force, sym_stress;
10806#if RGENGC_ESTIMATE_OLDMALLOC
10807static VALUE sym_oldmalloc;
10808#endif
10809static VALUE sym_newobj, sym_malloc, sym_method, sym_capi;
10810static VALUE sym_none, sym_marking, sym_sweeping;
10811static VALUE sym_weak_references_count;
10812
10813static void
10814setup_gc_latest_gc_info_symbols(void)
10815{
10816#define S(s) sym_##s = ID2SYM(rb_intern_const(#s))
10817 S(major_by);
10818 S(gc_by);
10819 S(immediate_sweep);
10820 S(have_finalizer);
10821 S(state);
10822 S(need_major_by);
10823
10824 S(stress);
10825 S(nofree);
10826 S(oldgen);
10827 S(shady);
10828 S(force);
10829#if RGENGC_ESTIMATE_OLDMALLOC
10830 S(oldmalloc);
10831#endif
10832 S(newobj);
10833 S(malloc);
10834 S(method);
10835 S(capi);
10836
10837 S(none);
10838 S(marking);
10839 S(sweeping);
10840
10841 S(weak_references_count);
10842#undef S
10843}
10844
10845static VALUE
10846gc_info_decode(rb_objspace_t *objspace, const VALUE hash_or_key, const unsigned int orig_flags)
10847{
10848 VALUE hash = Qnil, key = Qnil;
10849 VALUE major_by, need_major_by;
10850 unsigned int flags = orig_flags ? orig_flags : objspace->profile.latest_gc_info;
10851
10852 if (SYMBOL_P(hash_or_key)) {
10853 key = hash_or_key;
10854 }
10855 else if (RB_TYPE_P(hash_or_key, T_HASH)) {
10856 hash = hash_or_key;
10857 }
10858 else {
10859 rb_bug("gc_info_decode: non-hash or symbol given");
10860 }
10861
10862#define SET(name, attr) \
10863 if (key == sym_##name) \
10864 return (attr); \
10865 else if (hash != Qnil) \
10866 rb_hash_aset(hash, sym_##name, (attr));
10867
10868 major_by =
10869 (flags & GPR_FLAG_MAJOR_BY_NOFREE) ? sym_nofree :
10870 (flags & GPR_FLAG_MAJOR_BY_OLDGEN) ? sym_oldgen :
10871 (flags & GPR_FLAG_MAJOR_BY_SHADY) ? sym_shady :
10872 (flags & GPR_FLAG_MAJOR_BY_FORCE) ? sym_force :
10873#if RGENGC_ESTIMATE_OLDMALLOC
10874 (flags & GPR_FLAG_MAJOR_BY_OLDMALLOC) ? sym_oldmalloc :
10875#endif
10876 Qnil;
10877 SET(major_by, major_by);
10878
10879 if (orig_flags == 0) { /* set need_major_by only if flags not set explicitly */
10880 unsigned int need_major_flags = gc_needs_major_flags;
10881 need_major_by =
10882 (need_major_flags & GPR_FLAG_MAJOR_BY_NOFREE) ? sym_nofree :
10883 (need_major_flags & GPR_FLAG_MAJOR_BY_OLDGEN) ? sym_oldgen :
10884 (need_major_flags & GPR_FLAG_MAJOR_BY_SHADY) ? sym_shady :
10885 (need_major_flags & GPR_FLAG_MAJOR_BY_FORCE) ? sym_force :
10886#if RGENGC_ESTIMATE_OLDMALLOC
10887 (need_major_flags & GPR_FLAG_MAJOR_BY_OLDMALLOC) ? sym_oldmalloc :
10888#endif
10889 Qnil;
10890 SET(need_major_by, need_major_by);
10891 }
10892
10893 SET(gc_by,
10894 (flags & GPR_FLAG_NEWOBJ) ? sym_newobj :
10895 (flags & GPR_FLAG_MALLOC) ? sym_malloc :
10896 (flags & GPR_FLAG_METHOD) ? sym_method :
10897 (flags & GPR_FLAG_CAPI) ? sym_capi :
10898 (flags & GPR_FLAG_STRESS) ? sym_stress :
10899 Qnil
10900 );
10901
10902 SET(have_finalizer, (flags & GPR_FLAG_HAVE_FINALIZE) ? Qtrue : Qfalse);
10903 SET(immediate_sweep, (flags & GPR_FLAG_IMMEDIATE_SWEEP) ? Qtrue : Qfalse);
10904
10905 if (orig_flags == 0) {
10906 SET(state, gc_mode(objspace) == gc_mode_none ? sym_none :
10907 gc_mode(objspace) == gc_mode_marking ? sym_marking : sym_sweeping);
10908 }
10909
10910 SET(weak_references_count, LONG2FIX(objspace->profile.weak_references_count));
10911#undef SET
10912
10913 if (!NIL_P(key)) {
10914 // Matched key should return above
10915 return Qundef;
10916 }
10917
10918 return hash;
10919}
10920
10921VALUE
10922rb_gc_impl_latest_gc_info(void *objspace_ptr, VALUE key)
10923{
10924 rb_objspace_t *objspace = objspace_ptr;
10925
10926 return gc_info_decode(objspace, key, 0);
10927}
10928
10929
10930enum gc_stat_sym {
10931 gc_stat_sym_count,
10932 gc_stat_sym_time,
10933 gc_stat_sym_marking_time,
10934 gc_stat_sym_sweeping_time,
10935 gc_stat_sym_heap_allocated_pages,
10936 gc_stat_sym_heap_empty_pages,
10937 gc_stat_sym_heap_allocatable_bytes,
10938 gc_stat_sym_heap_available_slots,
10939 gc_stat_sym_heap_live_slots,
10940 gc_stat_sym_heap_free_slots,
10941 gc_stat_sym_heap_final_slots,
10942 gc_stat_sym_heap_marked_slots,
10943 gc_stat_sym_heap_eden_pages,
10944 gc_stat_sym_total_allocated_pages,
10945 gc_stat_sym_total_freed_pages,
10946 gc_stat_sym_total_allocated_objects,
10947 gc_stat_sym_total_freed_objects,
10948 gc_stat_sym_total_malloc_bytes,
10949 gc_stat_sym_total_free_bytes,
10950 gc_stat_sym_malloc_increase_bytes,
10951 gc_stat_sym_malloc_increase_bytes_limit,
10952 gc_stat_sym_minor_gc_count,
10953 gc_stat_sym_major_gc_count,
10954 gc_stat_sym_global_gc_count,
10955 gc_stat_sym_compact_count,
10956 gc_stat_sym_read_barrier_faults,
10957 gc_stat_sym_total_moved_objects,
10958 gc_stat_sym_remembered_wb_unprotected_objects,
10959 gc_stat_sym_remembered_wb_unprotected_objects_limit,
10960 gc_stat_sym_old_objects,
10961 gc_stat_sym_old_objects_limit,
10962#if RGENGC_ESTIMATE_OLDMALLOC
10963 gc_stat_sym_oldmalloc_increase_bytes,
10964 gc_stat_sym_oldmalloc_increase_bytes_limit,
10965#endif
10966#if RGENGC_PROFILE
10967 gc_stat_sym_total_generated_normal_object_count,
10968 gc_stat_sym_total_generated_shady_object_count,
10969 gc_stat_sym_total_shade_operation_count,
10970 gc_stat_sym_total_promoted_count,
10971 gc_stat_sym_total_remembered_normal_object_count,
10972 gc_stat_sym_total_remembered_shady_object_count,
10973#endif
10974 gc_stat_sym_page_pool_arenas,
10975 gc_stat_sym_page_pool_arenas_freed,
10976 gc_stat_sym_page_pool_total_pages,
10977 gc_stat_sym_page_pool_discarded_pages,
10978 gc_stat_sym_last
10979};
10980
10981static VALUE gc_stat_symbols[gc_stat_sym_last];
10982
10983static void
10984setup_gc_stat_symbols(void)
10985{
10986#define S(s) gc_stat_symbols[gc_stat_sym_##s] = ID2SYM(rb_intern_const(#s))
10987 S(count);
10988 S(time);
10989 S(marking_time),
10990 S(sweeping_time),
10991 S(heap_allocated_pages);
10992 S(heap_empty_pages);
10993 S(heap_allocatable_bytes);
10994 S(heap_available_slots);
10995 S(heap_live_slots);
10996 S(heap_free_slots);
10997 S(heap_final_slots);
10998 S(heap_marked_slots);
10999 S(heap_eden_pages);
11000 S(total_allocated_pages);
11001 S(total_freed_pages);
11002 S(total_allocated_objects);
11003 S(total_freed_objects);
11004 S(total_malloc_bytes);
11005 S(total_free_bytes);
11006 S(malloc_increase_bytes);
11007 S(malloc_increase_bytes_limit);
11008 S(minor_gc_count);
11009 S(major_gc_count);
11010 S(global_gc_count);
11011 S(compact_count);
11012 S(read_barrier_faults);
11013 S(total_moved_objects);
11014 S(remembered_wb_unprotected_objects);
11015 S(remembered_wb_unprotected_objects_limit);
11016 S(old_objects);
11017 S(old_objects_limit);
11018#if RGENGC_ESTIMATE_OLDMALLOC
11019 S(oldmalloc_increase_bytes);
11020 S(oldmalloc_increase_bytes_limit);
11021#endif
11022#if RGENGC_PROFILE
11023 S(total_generated_normal_object_count);
11024 S(total_generated_shady_object_count);
11025 S(total_shade_operation_count);
11026 S(total_promoted_count);
11027 S(total_remembered_normal_object_count);
11028 S(total_remembered_shady_object_count);
11029#endif /* RGENGC_PROFILE */
11030 S(page_pool_arenas);
11031 S(page_pool_arenas_freed);
11032 S(page_pool_total_pages);
11033 S(page_pool_discarded_pages);
11034#undef S
11035}
11036
11037static uint64_t
11038ns_to_ms(uint64_t ns)
11039{
11040 return ns / (1000 * 1000);
11041}
11042
11043static void malloc_increase_local_flush(rb_objspace_t *objspace);
11044
11045static void
11046gc_process_stat_accumulate_i(void *objspace_ptr, void *data)
11047{
11048 rb_objspace_t *objspace = objspace_ptr;
11049 struct gc_process_stat_total *total = (struct gc_process_stat_total *)data;
11050 struct gc_process_stat_snapshot snap;
11051 rb_native_mutex_lock(&objspace->process_stat.lock);
11052 snap = objspace->process_stat.published;
11053 rb_native_mutex_unlock(&objspace->process_stat.lock);
11054 gc_process_stat_add(total, &snap);
11055}
11056
11057static VALUE
11058gc_process_stat(VALUE hash_or_sym)
11059{
11060 VALUE hash = Qnil, key = Qnil;
11061
11062 if (RB_TYPE_P(hash_or_sym, T_HASH)) {
11063 hash = hash_or_sym;
11064 }
11065 else if (SYMBOL_P(hash_or_sym)) {
11066 key = hash_or_sym;
11067 }
11068 else {
11069 rb_bug("non-hash or symbol given");
11070 }
11071
11072 struct gc_process_stat_total total;
11073 uint64_t direct_global_gc_count;
11074 unsigned int lev = RB_GC_VM_LOCK();
11075 total = global_objspace->process_stat_archive;
11076 rb_gc_vm_each_objspace(gc_process_stat_accumulate_i, &total);
11077 direct_global_gc_count = global_objspace->global_gc.count;
11078 RB_GC_VM_UNLOCK(lev);
11079
11080 rb_objspace_t *const current = rb_gc_get_objspace();
11081 if (!gc_during_gc_get(current)) {
11082 GC_ASSERT(total.global_gc_count == direct_global_gc_count);
11083 }
11084
11085 /* Convert to Ruby values after all collector locks are released. */
11086 uint64_t time_ns = total.marking_time_ns + total.sweeping_time_ns;
11087
11088#define SET64(name, attr) \
11089 if (key == gc_stat_symbols[gc_stat_sym_##name]) \
11090 return ULL2NUM(attr); \
11091 else if (hash != Qnil) \
11092 rb_hash_aset(hash, gc_stat_symbols[gc_stat_sym_##name], ULL2NUM(attr));
11093
11094 SET64(count, total.count);
11095 SET64(time, ns_to_ms(time_ns));
11096 SET64(marking_time, ns_to_ms(total.marking_time_ns));
11097 SET64(sweeping_time, ns_to_ms(total.sweeping_time_ns));
11098 SET64(minor_gc_count, total.minor_gc_count);
11099 SET64(major_gc_count, total.major_gc_count);
11100 SET64(global_gc_count, total.global_gc_count);
11101
11102#undef SET64
11103
11104 if (!NIL_P(key)) {
11105 /* Matched key should return above. */
11106 return Qundef;
11107 }
11108
11109 return hash;
11110}
11111
11112VALUE
11113rb_gc_impl_stat(void *objspace_ptr, VALUE hash_or_sym)
11114{
11115 if (objspace_ptr == NULL) {
11116 return gc_process_stat(hash_or_sym);
11117 }
11118
11119 rb_objspace_t *objspace = objspace_ptr;
11120 VALUE hash = Qnil, key = Qnil;
11121
11122 malloc_increase_local_flush(objspace);
11123
11124 if (RB_TYPE_P(hash_or_sym, T_HASH)) {
11125 hash = hash_or_sym;
11126 }
11127 else if (SYMBOL_P(hash_or_sym)) {
11128 key = hash_or_sym;
11129 }
11130 else {
11131 rb_bug("non-hash or symbol given");
11132 }
11133
11134#define SET(name, attr) \
11135 if (key == gc_stat_symbols[gc_stat_sym_##name]) \
11136 return SIZET2NUM(attr); \
11137 else if (hash != Qnil) \
11138 rb_hash_aset(hash, gc_stat_symbols[gc_stat_sym_##name], SIZET2NUM(attr));
11139#define SET64(name, attr) \
11140 if (key == gc_stat_symbols[gc_stat_sym_##name]) \
11141 return ULL2NUM(attr); \
11142 else if (hash != Qnil) \
11143 rb_hash_aset(hash, gc_stat_symbols[gc_stat_sym_##name], ULL2NUM(attr));
11144
11145 SET(count, objspace->profile.count);
11146 SET(time, (size_t)ns_to_ms(objspace->profile.marking_time_ns + objspace->profile.sweeping_time_ns)); // TODO: UINT64T2NUM
11147 SET(marking_time, (size_t)ns_to_ms(objspace->profile.marking_time_ns));
11148 SET(sweeping_time, (size_t)ns_to_ms(objspace->profile.sweeping_time_ns));
11149
11150 {
11151 uint64_t total_malloc = (uint64_t)gc_counter_load_relaxed(&objspace->malloc_counters.counters.malloc);
11152 uint64_t total_free = (uint64_t)gc_counter_load_relaxed(&objspace->malloc_counters.counters.free);
11153 SET64(total_malloc_bytes, total_malloc);
11154 SET64(total_free_bytes, total_free);
11155 }
11156
11157 /* implementation dependent counters (small / fixnum-safe) */
11158 SET(heap_allocated_pages, rb_darray_size(objspace->heap_pages.sorted));
11159 SET(heap_empty_pages, objspace->empty_pages_count)
11160 SET(heap_allocatable_bytes, objspace->heap_pages.allocatable_bytes);
11161 SET(heap_eden_pages, heap_eden_total_pages(objspace));
11162 SET(total_allocated_pages, objspace->heap_pages.allocated_pages);
11163 SET(total_freed_pages, objspace->heap_pages.freed_pages);
11164 SET(malloc_increase_bytes, gc_malloc_counters_increase_unsigned(objspace, &objspace->malloc_counters.counters));
11165 SET(malloc_increase_bytes_limit, malloc_limit);
11166 SET(minor_gc_count, objspace->profile.minor_gc_count);
11167 SET(major_gc_count, objspace->profile.major_gc_count);
11168 SET(global_gc_count, objspace->profile.global_gc_count);
11169 SET(compact_count, objspace->profile.compact_count);
11170 SET(read_barrier_faults, objspace->profile.read_barrier_faults);
11171 SET(total_moved_objects, objspace->rcompactor.total_moved);
11172 SET(remembered_wb_unprotected_objects, objspace->rgengc.uncollectible_wb_unprotected_objects);
11173 SET(remembered_wb_unprotected_objects_limit, objspace->rgengc.uncollectible_wb_unprotected_objects_limit);
11174 SET(old_objects, objspace->rgengc.old_objects);
11175 SET(old_objects_limit, objspace->rgengc.old_objects_limit);
11176#if RGENGC_ESTIMATE_OLDMALLOC
11177 SET(oldmalloc_increase_bytes, gc_malloc_counters_increase_unsigned(objspace, &objspace->malloc_counters.oldcounters));
11178 SET(oldmalloc_increase_bytes_limit, objspace->rgengc.oldmalloc_increase_limit);
11179#endif
11180
11181 SET(total_allocated_objects, total_allocated_objects(objspace));
11182 SET(total_freed_objects, total_freed_objects(objspace));
11183 SET(heap_available_slots, objspace_available_slots(objspace));
11184 SET(heap_live_slots, objspace_live_slots(objspace));
11185 SET(heap_free_slots, objspace_free_slots(objspace));
11186 SET(heap_final_slots, total_final_slots_count(objspace));
11187 SET(heap_marked_slots, objspace->marked_slots);
11188
11189 SET(page_pool_arenas, global_objspace->page_pool.arena_count);
11190 SET(page_pool_arenas_freed, global_objspace->page_pool.arenas_unmapped);
11191 SET(page_pool_total_pages, (size_t)global_objspace->page_pool.arena_count * PAGE_POOL_ARENA_BODIES);
11192 SET(page_pool_discarded_pages, global_objspace->page_pool.advised_count);
11193
11194#if RGENGC_PROFILE
11195 SET(total_generated_normal_object_count, objspace->profile.total_generated_normal_object_count);
11196 SET(total_generated_shady_object_count, objspace->profile.total_generated_shady_object_count);
11197 SET(total_shade_operation_count, objspace->profile.total_shade_operation_count);
11198 SET(total_promoted_count, objspace->profile.total_promoted_count);
11199 SET(total_remembered_normal_object_count, objspace->profile.total_remembered_normal_object_count);
11200 SET(total_remembered_shady_object_count, objspace->profile.total_remembered_shady_object_count);
11201#endif /* RGENGC_PROFILE */
11202#undef SET
11203#undef SET64
11204
11205 if (!NIL_P(key)) {
11206 // Matched key should return above
11207 return Qundef;
11208 }
11209
11210#if defined(RGENGC_PROFILE) && RGENGC_PROFILE >= 2
11211 if (hash != Qnil) {
11212 gc_count_add_each_types(hash, "generated_normal_object_count_types", objspace->profile.generated_normal_object_count_types);
11213 gc_count_add_each_types(hash, "generated_shady_object_count_types", objspace->profile.generated_shady_object_count_types);
11214 gc_count_add_each_types(hash, "shade_operation_count_types", objspace->profile.shade_operation_count_types);
11215 gc_count_add_each_types(hash, "promoted_types", objspace->profile.promoted_types);
11216 gc_count_add_each_types(hash, "remembered_normal_object_count_types", objspace->profile.remembered_normal_object_count_types);
11217 gc_count_add_each_types(hash, "remembered_shady_object_count_types", objspace->profile.remembered_shady_object_count_types);
11218 }
11219#endif
11220
11221 return hash;
11222}
11223
11224enum gc_stat_heap_sym {
11225 gc_stat_heap_sym_slot_size,
11226 gc_stat_heap_sym_heap_live_slots,
11227 gc_stat_heap_sym_heap_free_slots,
11228 gc_stat_heap_sym_heap_final_slots,
11229 gc_stat_heap_sym_heap_eden_pages,
11230 gc_stat_heap_sym_heap_eden_slots,
11231 gc_stat_heap_sym_total_allocated_pages,
11232 gc_stat_heap_sym_force_major_gc_count,
11233 gc_stat_heap_sym_force_incremental_marking_finish_count,
11234 gc_stat_heap_sym_heap_allocatable_slots,
11235 gc_stat_heap_sym_total_allocated_objects,
11236 gc_stat_heap_sym_total_freed_objects,
11237 gc_stat_heap_sym_last
11238};
11239
11240static VALUE gc_stat_heap_symbols[gc_stat_heap_sym_last];
11241
11242static void
11243setup_gc_stat_heap_symbols(void)
11244{
11245#define S(s) gc_stat_heap_symbols[gc_stat_heap_sym_##s] = ID2SYM(rb_intern_const(#s))
11246 S(slot_size);
11247 S(heap_live_slots);
11248 S(heap_free_slots);
11249 S(heap_final_slots);
11250 S(heap_eden_pages);
11251 S(heap_eden_slots);
11252 S(heap_allocatable_slots);
11253 S(total_allocated_pages);
11254 S(force_major_gc_count);
11255 S(force_incremental_marking_finish_count);
11256 S(total_allocated_objects);
11257 S(total_freed_objects);
11258#undef S
11259}
11260
11261static VALUE
11262stat_one_heap(rb_objspace_t *objspace, rb_heap_t *heap, VALUE hash, VALUE key)
11263{
11264#define SET(name, attr) \
11265 if (key == gc_stat_heap_symbols[gc_stat_heap_sym_##name]) \
11266 return SIZET2NUM(attr); \
11267 else if (hash != Qnil) \
11268 rb_hash_aset(hash, gc_stat_heap_symbols[gc_stat_heap_sym_##name], SIZET2NUM(attr));
11269
11270 SET(slot_size, heap->slot_size);
11271 SET(heap_live_slots, heap->total_allocated_objects - heap->total_freed_objects - heap->final_slots_count);
11272 SET(heap_free_slots, heap->total_slots - (heap->total_allocated_objects - heap->total_freed_objects));
11273 SET(heap_final_slots, heap->final_slots_count);
11274 SET(heap_eden_pages, heap->total_pages);
11275 SET(heap_eden_slots, heap->total_slots);
11276 SET(heap_allocatable_slots, objspace->heap_pages.allocatable_bytes / heap->slot_size);
11277 SET(total_allocated_pages, heap->total_allocated_pages);
11278 SET(force_major_gc_count, heap->force_major_gc_count);
11279 SET(force_incremental_marking_finish_count, heap->force_incremental_marking_finish_count);
11280 SET(total_allocated_objects, heap->total_allocated_objects);
11281 SET(total_freed_objects, heap->total_freed_objects);
11282#undef SET
11283
11284 if (!NIL_P(key)) {
11285 // Matched key should return above
11286 return Qundef;
11287 }
11288
11289 return hash;
11290}
11291
11292VALUE
11293rb_gc_impl_stat_heap(void *objspace_ptr, VALUE heap_name, VALUE hash_or_sym)
11294{
11295 rb_objspace_t *objspace = objspace_ptr;
11296
11297 if (NIL_P(heap_name)) {
11298 if (!RB_TYPE_P(hash_or_sym, T_HASH)) {
11299 rb_bug("non-hash given");
11300 }
11301
11302 for (int i = 0; i < HEAP_COUNT; i++) {
11303 VALUE hash = rb_hash_aref(hash_or_sym, INT2FIX(i));
11304 if (NIL_P(hash)) {
11305 hash = rb_hash_new();
11306 rb_hash_aset(hash_or_sym, INT2FIX(i), hash);
11307 }
11308
11309 stat_one_heap(objspace, &heaps[i], hash, Qnil);
11310 }
11311 }
11312 else if (FIXNUM_P(heap_name)) {
11313 int heap_idx = FIX2INT(heap_name);
11314
11315 if (heap_idx < 0 || heap_idx >= HEAP_COUNT) {
11316 rb_raise(rb_eArgError, "size pool index out of range");
11317 }
11318
11319 if (SYMBOL_P(hash_or_sym)) {
11320 return stat_one_heap(objspace, &heaps[heap_idx], Qnil, hash_or_sym);
11321 }
11322 else if (RB_TYPE_P(hash_or_sym, T_HASH)) {
11323 return stat_one_heap(objspace, &heaps[heap_idx], hash_or_sym, Qnil);
11324 }
11325 else {
11326 rb_bug("non-hash or symbol given");
11327 }
11328 }
11329 else {
11330 rb_bug("heap_name must be nil or an Integer");
11331 }
11332
11333 return hash_or_sym;
11334}
11335
11336/* I could include internal.h for this, but doing so undefines some Array macros
11337 * necessary for initialising objects, and I don't want to include all the array
11338 * headers to get them back
11339 * TODO: Investigate why RARRAY_AREF gets undefined in internal.h
11340 */
11341#ifndef RBOOL
11342#define RBOOL(v) (v ? Qtrue : Qfalse)
11343#endif
11344
11345VALUE
11346rb_gc_impl_config_get(void *objspace_ptr)
11347{
11348#define sym(name) ID2SYM(rb_intern_const(name))
11349 rb_objspace_t *objspace = objspace_ptr;
11350 VALUE hash = rb_hash_new();
11351
11352 rb_hash_aset(hash, sym("rgengc_allow_full_mark"), RBOOL(gc_config_full_mark_val));
11353
11354 return hash;
11355}
11356
11357static int
11358gc_config_set_key(VALUE key, VALUE value, VALUE data)
11359{
11361 if (rb_sym2id(key) == rb_intern("rgengc_allow_full_mark")) {
11362 gc_rest(objspace);
11363 gc_config_full_mark_set(RTEST(value));
11364 }
11365 return ST_CONTINUE;
11366}
11367
11368void
11369rb_gc_impl_config_set(void *objspace_ptr, VALUE hash)
11370{
11371 rb_objspace_t *objspace = objspace_ptr;
11372
11373 if (!RB_TYPE_P(hash, T_HASH)) {
11374 rb_raise(rb_eArgError, "expected keyword arguments");
11375 }
11376
11377 rb_hash_foreach(hash, gc_config_set_key, (st_data_t)objspace);
11378}
11379
11380VALUE
11381rb_gc_impl_stress_get(void *objspace_ptr)
11382{
11383 return ruby_gc_stress_mode;
11384}
11385
11386void
11387rb_gc_impl_stress_set(void *objspace_ptr, VALUE flag)
11388{
11389 global_objspace->gc_stressful = RTEST(flag);
11390 global_objspace->gc_stress_mode = flag;
11391}
11392
11393static int
11394get_envparam_size(const char *name, size_t *default_value, size_t lower_bound)
11395{
11396 const char *ptr = getenv(name);
11397 ssize_t val;
11398
11399 if (ptr != NULL && *ptr) {
11400 size_t unit = 0;
11401 char *end;
11402#if SIZEOF_SIZE_T == SIZEOF_LONG_LONG
11403 val = strtoll(ptr, &end, 0);
11404#else
11405 val = strtol(ptr, &end, 0);
11406#endif
11407 switch (*end) {
11408 case 'k': case 'K':
11409 unit = 1024;
11410 ++end;
11411 break;
11412 case 'm': case 'M':
11413 unit = 1024*1024;
11414 ++end;
11415 break;
11416 case 'g': case 'G':
11417 unit = 1024*1024*1024;
11418 ++end;
11419 break;
11420 }
11421 while (*end && isspace((unsigned char)*end)) end++;
11422 if (*end) {
11423 if (RTEST(ruby_verbose)) fprintf(stderr, "invalid string for %s: %s\n", name, ptr);
11424 return 0;
11425 }
11426 if (unit > 0) {
11427 if (val < -(ssize_t)(SIZE_MAX / 2 / unit) || (ssize_t)(SIZE_MAX / 2 / unit) < val) {
11428 if (RTEST(ruby_verbose)) fprintf(stderr, "%s=%s is ignored because it overflows\n", name, ptr);
11429 return 0;
11430 }
11431 val *= unit;
11432 }
11433 if (val > 0 && (size_t)val > lower_bound) {
11434 if (RTEST(ruby_verbose)) {
11435 fprintf(stderr, "%s=%"PRIdSIZE" (default value: %"PRIuSIZE")\n", name, val, *default_value);
11436 }
11437 *default_value = (size_t)val;
11438 return 1;
11439 }
11440 else {
11441 if (RTEST(ruby_verbose)) {
11442 fprintf(stderr, "%s=%"PRIdSIZE" (default value: %"PRIuSIZE") is ignored because it must be greater than %"PRIuSIZE".\n",
11443 name, val, *default_value, lower_bound);
11444 }
11445 return 0;
11446 }
11447 }
11448 return 0;
11449}
11450
11451static int
11452get_envparam_double(const char *name, double *default_value, double lower_bound, double upper_bound, int accept_zero)
11453{
11454 const char *ptr = getenv(name);
11455 double val;
11456
11457 if (ptr != NULL && *ptr) {
11458 char *end;
11459 val = strtod(ptr, &end);
11460 if (!*ptr || *end) {
11461 if (RTEST(ruby_verbose)) fprintf(stderr, "invalid string for %s: %s\n", name, ptr);
11462 return 0;
11463 }
11464
11465 if (accept_zero && val == 0.0) {
11466 goto accept;
11467 }
11468 else if (val <= lower_bound) {
11469 if (RTEST(ruby_verbose)) {
11470 fprintf(stderr, "%s=%f (default value: %f) is ignored because it must be greater than %f.\n",
11471 name, val, *default_value, lower_bound);
11472 }
11473 }
11474 else if (upper_bound != 0.0 && /* ignore upper_bound if it is 0.0 */
11475 val > upper_bound) {
11476 if (RTEST(ruby_verbose)) {
11477 fprintf(stderr, "%s=%f (default value: %f) is ignored because it must be lower than %f.\n",
11478 name, val, *default_value, upper_bound);
11479 }
11480 }
11481 else {
11482 goto accept;
11483 }
11484 }
11485 return 0;
11486
11487 accept:
11488 if (RTEST(ruby_verbose)) fprintf(stderr, "%s=%f (default value: %f)\n", name, val, *default_value);
11489 *default_value = val;
11490 return 1;
11491}
11492
11493/*
11494 * GC tuning environment variables
11495 *
11496 * * RUBY_GC_HEAP_FREE_SLOTS
11497 * - Prepare at least this amount of slots after GC.
11498 * - Allocate slots if there are not enough slots.
11499 * * RUBY_GC_HEAP_GROWTH_FACTOR (new from 2.1)
11500 * - Allocate slots by this factor.
11501 * - (next slots number) = (current slots number) * (this factor)
11502 * * RUBY_GC_HEAP_GROWTH_MAX_BYTES (was RUBY_GC_HEAP_GROWTH_MAX_SLOTS)
11503 * - Allocation rate is limited to this number of bytes.
11504 * * RUBY_GC_HEAP_FREE_SLOTS_MIN_RATIO (new from 2.4)
11505 * - Allocate additional pages when the number of free slots is
11506 * lower than the value (total_slots * (this ratio)).
11507 * * RUBY_GC_HEAP_FREE_SLOTS_GOAL_RATIO (new from 2.4)
11508 * - Allocate slots to satisfy this formula:
11509 * free_slots = total_slots * goal_ratio
11510 * - In other words, prepare (total_slots * goal_ratio) free slots.
11511 * - if this value is 0.0, then use RUBY_GC_HEAP_GROWTH_FACTOR directly.
11512 * * RUBY_GC_HEAP_FREE_SLOTS_MAX_RATIO (new from 2.4)
11513 * - Allow to free pages when the number of free slots is
11514 * greater than the value (total_slots * (this ratio)).
11515 * * RUBY_GC_HEAP_OLDOBJECT_LIMIT_FACTOR (new from 2.1.1)
11516 * - Do full GC when the number of old objects is more than R * N
11517 * where R is this factor and
11518 * N is the number of old objects just after last full GC.
11519 *
11520 * * obsolete
11521 * * RUBY_FREE_MIN -> RUBY_GC_HEAP_FREE_SLOTS (from 2.1)
11522 * * RUBY_HEAP_MIN_SLOTS -> RUBY_GC_HEAP_INIT_SLOTS (from 2.1) -> RUBY_GC_HEAP_INIT_BYTES
11523 *
11524 * * RUBY_GC_MALLOC_LIMIT
11525 * * RUBY_GC_MALLOC_LIMIT_MAX (new from 2.1)
11526 * * RUBY_GC_MALLOC_LIMIT_GROWTH_FACTOR (new from 2.1)
11527 *
11528 * * RUBY_GC_OLDMALLOC_LIMIT (new from 2.1)
11529 * * RUBY_GC_OLDMALLOC_LIMIT_MAX (new from 2.1)
11530 * * RUBY_GC_OLDMALLOC_LIMIT_GROWTH_FACTOR (new from 2.1)
11531 */
11532
11533void
11534rb_gc_impl_set_params(void *objspace_ptr)
11535{
11536 rb_objspace_t *objspace = objspace_ptr;
11537 get_envparam_size("RUBY_GC_HEAP_FREE_SLOTS", &gc_params.heap_free_slots, 0);
11538
11539 get_envparam_size("RUBY_GC_HEAP_INIT_BYTES", &gc_params.heap_init_bytes,
11540 heap_init_bytes_min() - 1);
11541 get_envparam_size("RUBY_GC_RACTOR_HEAP_INIT_BYTES", &gc_params.ractor_heap_init_bytes,
11542 heap_init_bytes_min() - 1);
11543
11544 get_envparam_double("RUBY_GC_HEAP_GROWTH_FACTOR", &gc_params.growth_factor, 1.0, 0.0, FALSE);
11545 get_envparam_size ("RUBY_GC_HEAP_GROWTH_MAX_BYTES", &gc_params.growth_max_bytes, 0);
11546 get_envparam_double("RUBY_GC_HEAP_FREE_SLOTS_MIN_RATIO", &gc_params.heap_free_slots_min_ratio,
11547 0.0, 1.0, FALSE);
11548 get_envparam_double("RUBY_GC_HEAP_FREE_SLOTS_MAX_RATIO", &gc_params.heap_free_slots_max_ratio,
11549 gc_params.heap_free_slots_min_ratio, 1.0, FALSE);
11550 get_envparam_double("RUBY_GC_HEAP_FREE_SLOTS_GOAL_RATIO", &gc_params.heap_free_slots_goal_ratio,
11551 gc_params.heap_free_slots_min_ratio, gc_params.heap_free_slots_max_ratio, TRUE);
11552 get_envparam_double("RUBY_GC_HEAP_OLDOBJECT_LIMIT_FACTOR", &gc_params.oldobject_limit_factor, 0.0, 0.0, TRUE);
11553 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);
11554
11555 if (get_envparam_size("RUBY_GC_MALLOC_LIMIT", &gc_params.malloc_limit_min, 0)) {
11556 malloc_limit = gc_params.malloc_limit_min;
11557 }
11558 get_envparam_size ("RUBY_GC_MALLOC_LIMIT_MAX", &gc_params.malloc_limit_max, 0);
11559 if (!gc_params.malloc_limit_max) { /* ignore max-check if 0 */
11560 gc_params.malloc_limit_max = SIZE_MAX;
11561 }
11562 get_envparam_double("RUBY_GC_MALLOC_LIMIT_GROWTH_FACTOR", &gc_params.malloc_limit_growth_factor, 1.0, 0.0, FALSE);
11563
11564#if RGENGC_ESTIMATE_OLDMALLOC
11565 if (get_envparam_size("RUBY_GC_OLDMALLOC_LIMIT", &gc_params.oldmalloc_limit_min, 0)) {
11566 objspace->rgengc.oldmalloc_increase_limit = gc_params.oldmalloc_limit_min;
11567 }
11568 get_envparam_size ("RUBY_GC_OLDMALLOC_LIMIT_MAX", &gc_params.oldmalloc_limit_max, 0);
11569 get_envparam_double("RUBY_GC_OLDMALLOC_LIMIT_GROWTH_FACTOR", &gc_params.oldmalloc_limit_growth_factor, 1.0, 0.0, FALSE);
11570#endif
11571}
11572
11573static inline size_t
11574objspace_malloc_size(rb_objspace_t *objspace, void *ptr, size_t hint)
11575{
11576#ifdef HAVE_MALLOC_USABLE_SIZE
11577 if (!hint) {
11578 hint = malloc_usable_size(ptr);
11579 }
11580#endif
11581 return hint;
11582}
11583
11584enum memop_type {
11585 MEMOP_TYPE_MALLOC = 0,
11586 MEMOP_TYPE_FREE,
11587 MEMOP_TYPE_REALLOC
11588};
11589
11590static inline void
11591atomic_sub_nounderflow(size_t *var, size_t sub)
11592{
11593 if (sub == 0) return;
11594
11595 while (1) {
11596 size_t val = *var;
11597 if (val < sub) sub = val;
11598 if (RUBY_ATOMIC_SIZE_CAS(*var, val, val-sub) == val) break;
11599 }
11600}
11601
11602#define gc_stress_full_mark_after_malloc_p() \
11603 (FIXNUM_P(ruby_gc_stress_mode) && (FIX2LONG(ruby_gc_stress_mode) & (1<<gc_stress_full_mark_after_malloc)))
11604
11605static void
11606objspace_malloc_gc_stress(rb_objspace_t *objspace)
11607{
11608 if (ruby_gc_stressful && ruby_native_thread_p()) {
11609 unsigned int reason = (GPR_FLAG_IMMEDIATE_MARK | GPR_FLAG_IMMEDIATE_SWEEP |
11610 GPR_FLAG_STRESS | GPR_FLAG_MALLOC);
11611
11612 if (gc_stress_full_mark_after_malloc_p()) {
11613 reason |= GPR_FLAG_FULL_MARK;
11614 }
11615 garbage_collect_with_gvl(objspace, reason);
11616 }
11617}
11618
11619static void
11620malloc_increase_commit(rb_objspace_t *objspace, size_t new_size, size_t old_size)
11621{
11622 if (new_size > old_size) {
11623 size_t delta = new_size - old_size;
11624 MALLOC_COUNTERS_LOCK(objspace);
11625 gc_counter_add(&objspace->malloc_counters.counters.malloc, delta);
11626#if RGENGC_ESTIMATE_OLDMALLOC
11627 gc_counter_add(&objspace->malloc_counters.oldcounters.malloc, delta);
11628#endif
11629 MALLOC_COUNTERS_UNLOCK(objspace);
11630 }
11631 else if (old_size > new_size) {
11632 size_t delta = old_size - new_size;
11633 MALLOC_COUNTERS_LOCK(objspace);
11634 gc_counter_add(&objspace->malloc_counters.counters.free, delta);
11635#if RGENGC_ESTIMATE_OLDMALLOC
11636 gc_counter_add(&objspace->malloc_counters.oldcounters.free, delta);
11637#endif
11638 MALLOC_COUNTERS_UNLOCK(objspace);
11639 }
11640}
11641
11642#if USE_MALLOC_INCREASE_LOCAL
11643static void
11644malloc_increase_local_flush(rb_objspace_t *objspace)
11645{
11646 int delta = malloc_increase_local;
11647 if (delta == 0) return;
11648
11649 malloc_increase_local = 0;
11650 if (delta > 0) {
11651 malloc_increase_commit(objspace, (size_t)delta, 0);
11652 }
11653 else {
11654 malloc_increase_commit(objspace, 0, (size_t)(-delta));
11655 }
11656}
11657#else
11658static void
11659malloc_increase_local_flush(rb_objspace_t *objspace)
11660{
11661}
11662#endif
11663
11664static inline bool
11665objspace_malloc_increase_report(rb_objspace_t *objspace, void *mem, size_t new_size, size_t old_size, enum memop_type type, bool gc_allowed)
11666{
11667 if (0) fprintf(stderr, "increase - ptr: %p, type: %s, new_size: %"PRIdSIZE", old_size: %"PRIdSIZE"\n",
11668 mem,
11669 type == MEMOP_TYPE_MALLOC ? "malloc" :
11670 type == MEMOP_TYPE_FREE ? "free " :
11671 type == MEMOP_TYPE_REALLOC ? "realloc": "error",
11672 new_size, old_size);
11673 return false;
11674}
11675
11676static bool
11677objspace_malloc_increase_body(rb_objspace_t *objspace, void *mem, size_t new_size, size_t old_size, enum memop_type type, bool gc_allowed)
11678{
11679#if USE_MALLOC_INCREASE_LOCAL
11680 if (new_size < GC_MALLOC_INCREASE_LOCAL_THRESHOLD &&
11681 old_size < GC_MALLOC_INCREASE_LOCAL_THRESHOLD) {
11682 malloc_increase_local += (int)new_size - (int)old_size;
11683
11684 if (malloc_increase_local >= GC_MALLOC_INCREASE_LOCAL_THRESHOLD ||
11685 malloc_increase_local <= -GC_MALLOC_INCREASE_LOCAL_THRESHOLD) {
11686 malloc_increase_local_flush(objspace);
11687 }
11688 }
11689 else {
11690 malloc_increase_local_flush(objspace);
11691 malloc_increase_commit(objspace, new_size, old_size);
11692 }
11693#else
11694 malloc_increase_commit(objspace, new_size, old_size);
11695#endif
11696
11697 if (type == MEMOP_TYPE_MALLOC && gc_allowed) {
11698 retry:
11699 if (malloc_increase > malloc_limit && ruby_native_thread_p() && !dont_gc_val() && !rb_gc_gc_disabled_global_p()) {
11700 if (ruby_thread_has_gvl_p() && is_lazy_sweeping(objspace)) {
11701 gc_sweep_step_for_malloc(objspace); /* sweeping frees may reduce malloc_increase */
11702 goto retry;
11703 }
11704 garbage_collect_with_gvl(objspace, GPR_FLAG_MALLOC);
11705 }
11706 }
11707
11708#if MALLOC_ALLOCATED_SIZE
11709 if (new_size >= old_size) {
11710 RUBY_ATOMIC_SIZE_ADD(objspace->malloc_params.allocated_size, new_size - old_size);
11711 }
11712 else {
11713 size_t dec_size = old_size - new_size;
11714
11715#if MALLOC_ALLOCATED_SIZE_CHECK
11716 size_t allocated_size = objspace->malloc_params.allocated_size;
11717 if (allocated_size < dec_size) {
11718 rb_bug("objspace_malloc_increase: underflow malloc_params.allocated_size.");
11719 }
11720#endif
11721 atomic_sub_nounderflow(&objspace->malloc_params.allocated_size, dec_size);
11722 }
11723
11724 switch (type) {
11725 case MEMOP_TYPE_MALLOC:
11726 RUBY_ATOMIC_SIZE_INC(objspace->malloc_params.allocations);
11727 break;
11728 case MEMOP_TYPE_FREE:
11729 {
11730 size_t allocations = objspace->malloc_params.allocations;
11731 if (allocations > 0) {
11732 atomic_sub_nounderflow(&objspace->malloc_params.allocations, 1);
11733 }
11734#if MALLOC_ALLOCATED_SIZE_CHECK
11735 else {
11736 GC_ASSERT(objspace->malloc_params.allocations > 0);
11737 }
11738#endif
11739 }
11740 break;
11741 case MEMOP_TYPE_REALLOC: /* ignore */ break;
11742 }
11743#endif
11744 return true;
11745}
11746
11747#define objspace_malloc_increase(...) \
11748 for (bool malloc_increase_done = objspace_malloc_increase_report(__VA_ARGS__); \
11749 !malloc_increase_done; \
11750 malloc_increase_done = objspace_malloc_increase_body(__VA_ARGS__))
11751
11752struct malloc_obj_info { /* 4 words */
11753 size_t size;
11754};
11755
11756static inline size_t
11757objspace_malloc_prepare(rb_objspace_t *objspace, size_t size)
11758{
11759 if (size == 0) size = 1;
11760
11761#if CALC_EXACT_MALLOC_SIZE
11762 size += sizeof(struct malloc_obj_info);
11763#endif
11764
11765 return size;
11766}
11767
11768static bool
11769malloc_during_gc_p(rb_objspace_t *objspace)
11770{
11771 /* malloc is not allowed during GC when we're not using multiple ractors
11772 * (since ractors can run while another thread is sweeping) and when we
11773 * have the GVL (since if we don't have the GVL, we'll try to acquire the
11774 * GVL which will block and ensure the other thread finishes GC). */
11775 return during_gc && !dont_gc_val() && !rb_gc_multi_ractor_p() && ruby_thread_has_gvl_p();
11776}
11777
11778static inline void *
11779objspace_malloc_fixup(rb_objspace_t *objspace, void *mem, size_t size, bool gc_allowed)
11780{
11781 size = objspace_malloc_size(objspace, mem, size);
11782 objspace_malloc_increase(objspace, mem, size, 0, MEMOP_TYPE_MALLOC, gc_allowed) {}
11783
11784#if CALC_EXACT_MALLOC_SIZE
11785 {
11786 struct malloc_obj_info *info = mem;
11787 info->size = size;
11788 mem = info + 1;
11789 }
11790#endif
11791
11792 return mem;
11793}
11794
11795#if defined(__GNUC__) && RUBY_DEBUG
11796#define RB_BUG_INSTEAD_OF_RB_MEMERROR 1
11797#endif
11798
11799#ifndef RB_BUG_INSTEAD_OF_RB_MEMERROR
11800# define RB_BUG_INSTEAD_OF_RB_MEMERROR 0
11801#endif
11802
11803#define GC_MEMERROR(...) \
11804 ((RB_BUG_INSTEAD_OF_RB_MEMERROR+0) ? rb_bug("" __VA_ARGS__) : (void)0)
11805
11806#define TRY_WITH_GC(siz, expr) do { \
11807 const gc_profile_record_flag gpr = \
11808 GPR_FLAG_FULL_MARK | \
11809 GPR_FLAG_IMMEDIATE_MARK | \
11810 GPR_FLAG_IMMEDIATE_SWEEP | \
11811 GPR_FLAG_MALLOC; \
11812 /* stress GC must also honor gc_allowed (malloc_gc_disabled) */ \
11813 if (gc_allowed) objspace_malloc_gc_stress(objspace); \
11814 \
11815 if (RB_LIKELY((expr))) { \
11816 /* Success on 1st try */ \
11817 } \
11818 else if (gc_allowed && !garbage_collect_with_gvl(objspace, gpr)) { \
11819 /* @shyouhei thinks this doesn't happen */ \
11820 GC_MEMERROR("TRY_WITH_GC: could not GC"); \
11821 } \
11822 else if ((expr)) { \
11823 /* Success on 2nd try */ \
11824 } \
11825 else { \
11826 GC_MEMERROR("TRY_WITH_GC: could not allocate:" \
11827 "%"PRIdSIZE" bytes for %s", \
11828 siz, # expr); \
11829 } \
11830 } while (0)
11831
11832static void
11833check_malloc_not_in_gc(rb_objspace_t *objspace, const char *msg)
11834{
11835 if (RB_UNLIKELY(malloc_during_gc_p(objspace))) {
11836 dont_gc_on();
11837 during_gc = false;
11838 rb_bug("Cannot %s during GC", msg);
11839 }
11840}
11841
11842void
11843rb_gc_impl_free(void *objspace_ptr, void *ptr, size_t old_size)
11844{
11845 rb_objspace_t *objspace = objspace_ptr;
11846
11847 if (!ptr) {
11848 /*
11849 * ISO/IEC 9899 says "If ptr is a null pointer, no action occurs" since
11850 * its first version. We would better follow.
11851 */
11852 return;
11853 }
11854#if CALC_EXACT_MALLOC_SIZE
11855 struct malloc_obj_info *info = (struct malloc_obj_info *)ptr - 1;
11856#if VERIFY_FREE_SIZE
11857 if (!info->size) {
11858 const char *freeing = gc_freeing_obj_info();
11859 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,
11860 freeing ? ", while freeing " : "", freeing ? freeing : "");
11861 }
11862
11863 if (old_size && (old_size + sizeof(struct malloc_obj_info)) != info->size) {
11864 const char *freeing = gc_freeing_obj_info();
11865 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),
11866 freeing ? ", while freeing " : "", freeing ? freeing : "");
11867 }
11868#endif
11869 ptr = info;
11870 old_size = info->size;
11871#endif
11872 old_size = objspace_malloc_size(objspace, ptr, old_size);
11873
11874 objspace_malloc_increase(objspace, ptr, 0, old_size, MEMOP_TYPE_FREE, true) {
11875 free(ptr);
11876 ptr = NULL;
11877 RB_DEBUG_COUNTER_INC(heap_xfree);
11878 }
11879}
11880
11881void *
11882rb_gc_impl_malloc(void *objspace_ptr, size_t size, bool gc_allowed)
11883{
11884 rb_objspace_t *objspace = objspace_ptr;
11885 check_malloc_not_in_gc(objspace, "malloc");
11886
11887 void *mem;
11888
11889 size = objspace_malloc_prepare(objspace, size);
11890 TRY_WITH_GC(size, mem = malloc(size));
11891 RB_DEBUG_COUNTER_INC(heap_xmalloc);
11892 if (!mem) return mem;
11893 return objspace_malloc_fixup(objspace, mem, size, gc_allowed);
11894}
11895
11896void *
11897rb_gc_impl_calloc(void *objspace_ptr, size_t size, bool gc_allowed)
11898{
11899 rb_objspace_t *objspace = objspace_ptr;
11900
11901 if (RB_UNLIKELY(malloc_during_gc_p(objspace))) {
11902 rb_warn("calloc during GC detected, this could cause crashes if it triggers another GC");
11903#if RGENGC_CHECK_MODE || RUBY_DEBUG
11904 rb_bug("Cannot calloc during GC");
11905#endif
11906 }
11907
11908 void *mem;
11909
11910 size = objspace_malloc_prepare(objspace, size);
11911 TRY_WITH_GC(size, mem = calloc1(size));
11912 if (!mem) return mem;
11913 return objspace_malloc_fixup(objspace, mem, size, gc_allowed);
11914}
11915
11916void *
11917rb_gc_impl_realloc(void *objspace_ptr, void *ptr, size_t new_size, size_t old_size, bool gc_allowed)
11918{
11919 rb_objspace_t *objspace = objspace_ptr;
11920
11921 check_malloc_not_in_gc(objspace, "realloc");
11922
11923 void *mem;
11924
11925 if (!ptr) return rb_gc_impl_malloc(objspace, new_size, gc_allowed);
11926
11927 /*
11928 * The behavior of realloc(ptr, 0) is implementation defined.
11929 * Therefore we don't use realloc(ptr, 0) for portability reason.
11930 * see http://www.open-std.org/jtc1/sc22/wg14/www/docs/dr_400.htm
11931 */
11932 if (new_size == 0) {
11933 if ((mem = rb_gc_impl_malloc(objspace, 0, gc_allowed)) != NULL) {
11934 /*
11935 * - OpenBSD's malloc(3) man page says that when 0 is passed, it
11936 * returns a non-NULL pointer to an access-protected memory page.
11937 * The returned pointer cannot be read / written at all, but
11938 * still be a valid argument of free().
11939 *
11940 * https://man.openbsd.org/malloc.3
11941 *
11942 * - Linux's malloc(3) man page says that it _might_ perhaps return
11943 * a non-NULL pointer when its argument is 0. That return value
11944 * is safe (and is expected) to be passed to free().
11945 *
11946 * https://man7.org/linux/man-pages/man3/malloc.3.html
11947 *
11948 * - As I read the implementation jemalloc's malloc() returns fully
11949 * normal 16 bytes memory region when its argument is 0.
11950 *
11951 * - As I read the implementation musl libc's malloc() returns
11952 * fully normal 32 bytes memory region when its argument is 0.
11953 *
11954 * - Other malloc implementations can also return non-NULL.
11955 */
11956 rb_gc_impl_free(objspace, ptr, old_size);
11957 return mem;
11958 }
11959 else {
11960 /*
11961 * It is dangerous to return NULL here, because that could lead to
11962 * RCE. Fallback to 1 byte instead of zero.
11963 *
11964 * https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2019-11932
11965 */
11966 new_size = 1;
11967 }
11968 }
11969
11970#if CALC_EXACT_MALLOC_SIZE
11971 {
11972 struct malloc_obj_info *info = (struct malloc_obj_info *)ptr - 1;
11973 new_size += sizeof(struct malloc_obj_info);
11974 ptr = info;
11975#if VERIFY_FREE_SIZE
11976 if (old_size && (old_size + sizeof(struct malloc_obj_info)) != info->size) {
11977 const char *freeing = gc_freeing_obj_info();
11978 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),
11979 freeing ? ", while freeing " : "", freeing ? freeing : "");
11980 }
11981#endif
11982 old_size = info->size;
11983 }
11984#endif
11985
11986 old_size = objspace_malloc_size(objspace, ptr, old_size);
11987 TRY_WITH_GC(new_size, mem = RB_GNUC_EXTENSION_BLOCK(realloc(ptr, new_size)));
11988 if (!mem) return mem;
11989 new_size = objspace_malloc_size(objspace, mem, new_size);
11990
11991#if CALC_EXACT_MALLOC_SIZE
11992 {
11993 struct malloc_obj_info *info = mem;
11994 info->size = new_size;
11995 mem = info + 1;
11996 }
11997#endif
11998
11999 objspace_malloc_increase(objspace, mem, new_size, old_size, MEMOP_TYPE_REALLOC, gc_allowed);
12000
12001 RB_DEBUG_COUNTER_INC(heap_xrealloc);
12002 return mem;
12003}
12004
12005void
12006rb_gc_impl_adjust_memory_usage(void *objspace_ptr, ssize_t diff)
12007{
12008 rb_objspace_t *objspace = objspace_ptr;
12009
12010 if (diff > 0) {
12011 objspace_malloc_increase(objspace, 0, diff, 0, MEMOP_TYPE_REALLOC, true);
12012 }
12013 else if (diff < 0) {
12014 objspace_malloc_increase(objspace, 0, 0, -diff, MEMOP_TYPE_REALLOC, true);
12015 }
12016}
12017
12018// TODO: move GC profiler stuff back into gc.c
12019/*
12020 ------------------------------ GC profiler ------------------------------
12021*/
12022
12023#define GC_PROFILE_RECORD_DEFAULT_SIZE 100
12024#define GC_PROFILE_RECORD_DEFAULT_MAX_RECORDS 4096
12025#define GC_PROFILE_RECORD_UNBOUNDED 0
12026
12027static bool
12028current_process_time(struct timespec *ts)
12029{
12030#if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_PROCESS_CPUTIME_ID)
12031 {
12032 static int try_clock_gettime = 1;
12033 if (try_clock_gettime) {
12034 if (clock_gettime(CLOCK_PROCESS_CPUTIME_ID, ts) == 0) {
12035 return true;
12036 }
12037 else {
12038 try_clock_gettime = 0;
12039 }
12040 }
12041 }
12042#endif
12043
12044#ifdef RUSAGE_SELF
12045 {
12046 struct rusage usage;
12047 struct timeval time;
12048 if (getrusage(RUSAGE_SELF, &usage) == 0) {
12049 time = usage.ru_utime;
12050 ts->tv_sec = time.tv_sec;
12051 ts->tv_nsec = (int32_t)time.tv_usec * 1000;
12052 return true;
12053 }
12054 }
12055#endif
12056
12057#ifdef _WIN32
12058 {
12059 FILETIME creation_time, exit_time, kernel_time, user_time;
12060 ULARGE_INTEGER ui;
12061
12062 if (GetProcessTimes(GetCurrentProcess(),
12063 &creation_time, &exit_time, &kernel_time, &user_time) != 0) {
12064 memcpy(&ui, &user_time, sizeof(FILETIME));
12065#define PER100NSEC (uint64_t)(1000 * 1000 * 10)
12066 ts->tv_nsec = (long)(ui.QuadPart % PER100NSEC);
12067 ts->tv_sec = (time_t)(ui.QuadPart / PER100NSEC);
12068 return true;
12069 }
12070 }
12071#endif
12072
12073 return false;
12074}
12075
12076static double
12077getrusage_time(void)
12078{
12079 struct timespec ts;
12080 if (current_process_time(&ts)) {
12081 return ts.tv_sec + ts.tv_nsec * 1e-9;
12082 }
12083 else {
12084 return 0.0;
12085 }
12086}
12087
12088static inline double
12089hrtime_to_sec(rb_hrtime_t time)
12090{
12091 return (double)time / (double)RB_HRTIME_PER_SEC;
12092}
12093
12094static inline rb_hrtime_t
12095elapsed_hrtime_from(rb_hrtime_t start)
12096{
12097 return rb_hrtime_sub(rb_hrtime_now(), start);
12098}
12099
12100
12101static inline size_t
12102gc_profile_record_count(rb_objspace_t *objspace)
12103{
12104 return objspace->profile.record_count;
12105}
12106
12107static inline size_t
12108gc_profile_record_index(rb_objspace_t *objspace, size_t logical_index)
12109{
12110 if (objspace->profile.max_records != GC_PROFILE_RECORD_UNBOUNDED &&
12111 objspace->profile.record_count == objspace->profile.size) {
12112 return (objspace->profile.next_index + logical_index) % objspace->profile.size;
12113 }
12114 else {
12115 return logical_index;
12116 }
12117}
12118
12119static void
12120gc_profile_records_free(rb_objspace_t *objspace)
12121{
12122 void *p = objspace->profile.records;
12123 objspace->profile.records = NULL;
12124 objspace->profile.size = 0;
12125 objspace->profile.next_index = 0;
12126 objspace->profile.record_count = 0;
12127 objspace->profile.current_record = 0;
12128 free(p);
12129}
12130
12131static inline void
12132gc_prof_setup_new_record(rb_objspace_t *objspace, unsigned int reason)
12133{
12134 if (objspace->profile.run) {
12135 size_t index;
12136 gc_profile_record *record;
12137
12138 if (objspace->profile.max_records == GC_PROFILE_RECORD_UNBOUNDED) {
12139 index = objspace->profile.record_count++;
12140 objspace->profile.next_index = objspace->profile.record_count;
12141
12142 if (!objspace->profile.records) {
12143 objspace->profile.size = GC_PROFILE_RECORD_DEFAULT_SIZE;
12144 objspace->profile.records = malloc(xmalloc2_size(sizeof(gc_profile_record), objspace->profile.size));
12145 }
12146 if (index >= objspace->profile.size) {
12147 void *ptr;
12148 objspace->profile.size += 1000;
12149 ptr = realloc(objspace->profile.records, xmalloc2_size(sizeof(gc_profile_record), objspace->profile.size));
12150 if (!ptr) rb_memerror();
12151 objspace->profile.records = ptr;
12152 }
12153 }
12154 else {
12155 if (!objspace->profile.records) {
12156 objspace->profile.size = objspace->profile.max_records;
12157 objspace->profile.records = malloc(xmalloc2_size(sizeof(gc_profile_record), objspace->profile.size));
12158 }
12159 index = objspace->profile.next_index;
12160 objspace->profile.next_index = (objspace->profile.next_index + 1) % objspace->profile.size;
12161 if (objspace->profile.record_count < objspace->profile.size) {
12162 objspace->profile.record_count++;
12163 }
12164 }
12165
12166 if (!objspace->profile.records) {
12167 rb_bug("gc_profile malloc or realloc miss");
12168 }
12169 record = objspace->profile.current_record = &objspace->profile.records[index];
12170 MEMZERO(record, gc_profile_record, 1);
12171
12172 /* setup before-GC parameter */
12173 record->flags = reason | (ruby_gc_stressful ? GPR_FLAG_STRESS : 0);
12174 record->sequence = objspace->profile.record_sequence++;
12175 record->gc_invoke_wall_time = rb_hrtime_sub(rb_hrtime_now(),
12176 objspace->profile.invoke_wall_time);
12177#if MALLOC_ALLOCATED_SIZE
12178 record->allocated_size = malloc_allocated_size;
12179#endif
12180#if GC_PROFILE_MORE_DETAIL && GC_PROFILE_DETAIL_MEMORY
12181#ifdef RUSAGE_SELF
12182 {
12183 struct rusage usage;
12184 if (getrusage(RUSAGE_SELF, &usage) == 0) {
12185 record->maxrss = usage.ru_maxrss;
12186 record->minflt = usage.ru_minflt;
12187 record->majflt = usage.ru_majflt;
12188 }
12189 }
12190#endif
12191#endif
12192 }
12193}
12194
12195static inline void
12196gc_prof_timer_start(rb_objspace_t *objspace)
12197{
12198 if (gc_prof_enabled(objspace)) {
12199 gc_profile_record *record = gc_prof_record(objspace);
12200#if GC_PROFILE_MORE_DETAIL
12201 record->prepare_time = objspace->profile.prepare_time;
12202#endif
12203 record->gc_time = 0;
12204 record->gc_invoke_time = getrusage_time();
12205 objspace->profile.gc_wall_start_time = rb_hrtime_now();
12206 }
12207}
12208
12209static double
12210elapsed_time_from(double time)
12211{
12212 double now = getrusage_time();
12213 if (now > time) {
12214 return now - time;
12215 }
12216 else {
12217 return 0;
12218 }
12219}
12220
12221static inline void
12222gc_prof_timer_stop(rb_objspace_t *objspace)
12223{
12224 if (gc_prof_enabled(objspace)) {
12225 gc_profile_record *record = gc_prof_record(objspace);
12226 record->gc_time = elapsed_time_from(record->gc_invoke_time);
12227 record->gc_invoke_time -= objspace->profile.invoke_time;
12228 record->gc_wall_time = elapsed_hrtime_from(objspace->profile.gc_wall_start_time);
12229 }
12230}
12231
12232static inline void
12233gc_prof_mark_timer_start(rb_objspace_t *objspace)
12234{
12235 RUBY_DTRACE_GC_HOOK(MARK_BEGIN);
12236#if GC_PROFILE_MORE_DETAIL
12237 if (gc_prof_enabled(objspace)) {
12238 gc_prof_record(objspace)->gc_mark_time = getrusage_time();
12239 }
12240#endif
12241}
12242
12243static inline void
12244gc_prof_mark_timer_stop(rb_objspace_t *objspace)
12245{
12246 RUBY_DTRACE_GC_HOOK(MARK_END);
12247#if GC_PROFILE_MORE_DETAIL
12248 if (gc_prof_enabled(objspace)) {
12249 gc_profile_record *record = gc_prof_record(objspace);
12250 record->gc_mark_time = elapsed_time_from(record->gc_mark_time);
12251 }
12252#endif
12253}
12254
12255static inline void
12256gc_prof_sweep_timer_start(rb_objspace_t *objspace)
12257{
12258 RUBY_DTRACE_GC_HOOK(SWEEP_BEGIN);
12259 if (gc_prof_enabled(objspace)) {
12260 gc_profile_record *record = gc_prof_record(objspace);
12261
12262 if (record->gc_time > 0 || GC_PROFILE_MORE_DETAIL) {
12263 objspace->profile.gc_sweep_start_time = getrusage_time();
12264 objspace->profile.gc_sweep_wall_start_time = rb_hrtime_now();
12265 }
12266 }
12267}
12268
12269static inline void
12270gc_prof_sweep_timer_stop(rb_objspace_t *objspace)
12271{
12272 RUBY_DTRACE_GC_HOOK(SWEEP_END);
12273
12274 if (gc_prof_enabled(objspace)) {
12275 double sweep_time;
12276 gc_profile_record *record = gc_prof_record(objspace);
12277
12278 if (record->gc_time > 0) {
12279 sweep_time = elapsed_time_from(objspace->profile.gc_sweep_start_time);
12280 /* need to accumulate GC time for lazy sweep after gc() */
12281 record->gc_time += sweep_time;
12282 record->gc_wall_time = rb_hrtime_add(record->gc_wall_time,
12283 elapsed_hrtime_from(objspace->profile.gc_sweep_wall_start_time));
12284 }
12285 else if (GC_PROFILE_MORE_DETAIL) {
12286 sweep_time = elapsed_time_from(objspace->profile.gc_sweep_start_time);
12287 }
12288
12289#if GC_PROFILE_MORE_DETAIL
12290 record->gc_sweep_time += sweep_time;
12291 if (heap_pages_deferred_final) record->flags |= GPR_FLAG_HAVE_FINALIZE;
12292#endif
12293 if (heap_pages_deferred_final) objspace->profile.latest_gc_info |= GPR_FLAG_HAVE_FINALIZE;
12294 }
12295}
12296
12297static inline void
12298gc_prof_set_malloc_info(rb_objspace_t *objspace)
12299{
12300#if GC_PROFILE_MORE_DETAIL
12301 if (gc_prof_enabled(objspace)) {
12302 gc_profile_record *record = gc_prof_record(objspace);
12303 record->allocate_increase = malloc_increase;
12304 record->allocate_limit = malloc_limit;
12305 }
12306#endif
12307}
12308
12309static inline void
12310gc_prof_set_heap_info(rb_objspace_t *objspace)
12311{
12312 if (gc_prof_enabled(objspace)) {
12313 gc_profile_record *record = gc_prof_record(objspace);
12314
12315 /* Sum across all size pools since each has a different slot size. */
12316 size_t total = 0;
12317 size_t use_size = 0;
12318 size_t total_size = 0;
12319 for (int i = 0; i < HEAP_COUNT; i++) {
12320 rb_heap_t *heap = &heaps[i];
12321 size_t heap_live = heap->total_allocated_objects - heap->total_freed_objects - heap->final_slots_count;
12322 total += heap->total_slots;
12323 use_size += heap_live * heap->slot_size;
12324 total_size += heap->total_slots * heap->slot_size;
12325 }
12326
12327#if GC_PROFILE_MORE_DETAIL
12328 size_t live = objspace->profile.total_allocated_objects_at_gc_start - total_freed_objects(objspace);
12329 record->heap_use_pages = objspace->profile.heap_used_at_gc_start;
12330 record->heap_live_objects = live;
12331 record->heap_free_objects = total - live;
12332#endif
12333
12334 record->heap_total_objects = total;
12335 record->heap_use_size = use_size;
12336 record->heap_total_size = total_size;
12337 }
12338}
12339
12340/*
12341 * call-seq:
12342 * GC::Profiler.clear -> nil
12343 *
12344 * Clears the \GC profiler data.
12345 *
12346 */
12347
12348static VALUE
12349gc_profile_clear(VALUE _)
12350{
12351 rb_objspace_t *objspace = rb_gc_get_objspace();
12352 gc_profile_records_free(objspace);
12353 return Qnil;
12354}
12355
12356/*
12357 * call-seq:
12358 * GC::Profiler.configure(max_records: 4096) -> nil
12359 *
12360 * Configures how many raw profile records are retained by
12361 * GC::Profiler.raw_data.
12362 *
12363 * The profiler keeps at most +max_records+ records in a bounded ring buffer.
12364 * When the buffer is full, newer GC records overwrite the oldest retained
12365 * records. The default limit is 4096 records.
12366 *
12367 * Pass +nil+ to restore the historical unbounded behavior:
12368 *
12369 * GC::Profiler.configure(max_records: nil)
12370 *
12371 * Changing +max_records+ clears existing raw profile data. This method does
12372 * not enable or disable the profiler; use GC::Profiler.enable and
12373 * GC::Profiler.disable for that.
12374 */
12375
12376static VALUE
12377gc_profile_configure(int argc, VALUE *argv, VALUE _)
12378{
12379 static ID keywords[1] = {0};
12380 VALUE options, max_records;
12381 rb_objspace_t *objspace = rb_gc_get_objspace();
12382
12383 if (!keywords[0]) {
12384 keywords[0] = rb_intern("max_records");
12385 }
12386
12387 rb_scan_args_kw(rb_keyword_given_p(), argc, argv, ":", &options);
12388 rb_get_kwargs(options, keywords, 0, 1, &max_records);
12389
12390 if (max_records == Qundef) {
12391 return Qnil;
12392 }
12393 else if (NIL_P(max_records)) {
12394 objspace->profile.max_records = GC_PROFILE_RECORD_UNBOUNDED;
12395 }
12396 else {
12397 long value = NUM2LONG(max_records);
12398 if (value <= 0) {
12399 rb_raise(rb_eArgError, "max_records must be positive or nil");
12400 }
12401 objspace->profile.max_records = (size_t)value;
12402 }
12403
12404 gc_profile_records_free(objspace);
12405 return Qnil;
12406}
12407
12408/*
12409 * call-seq:
12410 * GC::Profiler.raw_data(limit: nil, since: nil) -> [Hash, ...]
12411 *
12412 * Returns an Array of retained raw profile data Hashes ordered from earliest
12413 * to latest by +:GC_INVOKE_TIME+. +limit:+ returns at most the newest
12414 * retained records. +since:+ returns records with +:GC_SEQUENCE+ greater
12415 * than the given sequence.
12416 *
12417 * For example:
12418 *
12419 * [
12420 * {
12421 * :GC_TIME=>1.3000000000000858e-05,
12422 * :GC_INVOKE_TIME=>0.010634999999999999,
12423 * :GC_WALL_TIME=>1.4000000000000001e-05,
12424 * :GC_INVOKE_WALL_TIME=>0.010640000000000000,
12425 * :GC_PAUSE_TIME=>1.5000000000000000e-05,
12426 * :GC_STOP_TIME=>1.0000000000000000e-06,
12427 * :GC_STW_TIME=>1.4000000000000001e-05,
12428 * :GC_MARK_WALL_TIME=>9.0000000000000002e-06,
12429 * :GC_SWEEP_WALL_TIME=>5.0000000000000004e-06,
12430 * :GC_COMPACT_WALL_TIME=>0.0000000000000000e+00,
12431 * :HEAP_USE_SIZE=>289640,
12432 * :HEAP_TOTAL_SIZE=>588960,
12433 * :HEAP_TOTAL_OBJECTS=>14724,
12434 * :GC_IS_MARKED=>false
12435 * },
12436 * # ...
12437 * ]
12438 *
12439 * The keys mean:
12440 *
12441 * +:GC_SEQUENCE+::
12442 * Monotonically increasing sequence number for this profiler record.
12443 * +:GC_TIME+::
12444 * CPU time elapsed in seconds for this GC run. This is process CPU time,
12445 * not elapsed wall-clock time.
12446 * +:GC_INVOKE_TIME+::
12447 * CPU time elapsed in seconds from startup to when the GC was invoked.
12448 * +:GC_WALL_TIME+::
12449 * Monotonic wall-clock counterpart to +:GC_TIME+ for this GC record.
12450 * This does not include time spent stopping other ractors before the VM
12451 * enters GC. Use the phase wall-clock fields below for mark, sweep, and
12452 * compaction attribution.
12453 * +:GC_INVOKE_WALL_TIME+::
12454 * Monotonic wall-clock time elapsed in seconds from startup to when the GC
12455 * was invoked.
12456 * +:GC_PAUSE_TIME+::
12457 * Monotonic wall-clock time elapsed in seconds while user execution was
12458 * blocked by this GC entry, including time to stop other ractors. This
12459 * may include time from incremental marking or lazy sweeping continuation
12460 * charged to this record.
12461 * +:GC_STOP_TIME+::
12462 * Monotonic wall-clock time elapsed in seconds stopping other ractors.
12463 * +:GC_STW_TIME+::
12464 * Monotonic wall-clock time elapsed in seconds after other ractors have
12465 * stopped and before the VM exits GC.
12466 * +:GC_MARK_WALL_TIME+::
12467 * Monotonic wall-clock time elapsed in seconds spent marking for this GC
12468 * record, accumulated across incremental marking continuations.
12469 * +:GC_SWEEP_WALL_TIME+::
12470 * Monotonic wall-clock time elapsed in seconds spent sweeping for this GC
12471 * record, accumulated across lazy sweeping continuations. This does not
12472 * include compaction time, which is reported separately as
12473 * +:GC_COMPACT_WALL_TIME+.
12474 * +:GC_COMPACT_WALL_TIME+::
12475 * Monotonic wall-clock time elapsed in seconds spent compacting for this GC
12476 * record, or +0.0+ if this GC did not compact.
12477 * +:HEAP_USE_SIZE+::
12478 * Total bytes of heap used
12479 * +:HEAP_TOTAL_SIZE+::
12480 * Total size of heap in bytes
12481 * +:HEAP_TOTAL_OBJECTS+::
12482 * Total number of objects
12483 * +:GC_IS_MARKED+::
12484 * Returns +true+ if the GC is in mark phase
12485 *
12486 * The wall-clock timing fields relate to each other as follows:
12487 *
12488 * GC_PAUSE_TIME == GC_STOP_TIME + GC_STW_TIME
12489 *
12490 * +:GC_MARK_WALL_TIME+, +:GC_SWEEP_WALL_TIME+, and +:GC_COMPACT_WALL_TIME+
12491 * report separate phase timings and must not be added to +:GC_WALL_TIME+.
12492 *
12493 * +:GC_WALL_TIME+ is the wall-clock counterpart to +:GC_TIME+ and is nested
12494 * inside +:GC_STW_TIME+, so it must not be added to +:GC_STW_TIME+. The difference
12495 * +GC_STW_TIME - GC_WALL_TIME+ is VM overhead inside the stopped interval
12496 * (GC event hooks, bookkeeping, consistency checks, and continuation work).
12497 *
12498 * If ruby was built with +GC_PROFILE_MORE_DETAIL+, you will also have access
12499 * to the following hash keys:
12500 *
12501 * +:GC_MARK_TIME+::
12502 * +:GC_SWEEP_TIME+::
12503 * +:ALLOCATE_INCREASE+::
12504 * +:ALLOCATE_LIMIT+::
12505 * +:HEAP_USE_PAGES+::
12506 * +:HEAP_LIVE_OBJECTS+::
12507 * +:HEAP_FREE_OBJECTS+::
12508 * +:HAVE_FINALIZE+::
12509 *
12510 */
12511
12512static VALUE
12513gc_profile_record_get(int argc, VALUE *argv, VALUE _)
12514{
12515 static ID keywords[2] = {0};
12516 VALUE prof, options, limit_value, since_value;
12517 VALUE gc_profile = rb_ary_new();
12518 size_t i, count, matching = 0, skip = 0, limit = SIZE_MAX, since = 0;
12519 bool use_since = false;
12520 rb_objspace_t *objspace = rb_gc_get_objspace();
12521
12522 if (!keywords[0]) {
12523 keywords[0] = rb_intern("limit");
12524 keywords[1] = rb_intern("since");
12525 }
12526
12527 rb_scan_args_kw(rb_keyword_given_p(), argc, argv, ":", &options);
12528 VALUE values[2] = {Qundef, Qundef};
12529 rb_get_kwargs(options, keywords, 0, 2, values);
12530 limit_value = values[0];
12531 since_value = values[1];
12532
12533 if (limit_value != Qundef && !NIL_P(limit_value)) {
12534 long value = NUM2LONG(limit_value);
12535 if (value < 0) {
12536 rb_raise(rb_eArgError, "limit must be non-negative");
12537 }
12538 limit = (size_t)value;
12539 }
12540 if (since_value != Qundef && !NIL_P(since_value)) {
12541 long value = NUM2LONG(since_value);
12542 if (value < 0) {
12543 rb_raise(rb_eArgError, "since must be non-negative");
12544 }
12545 since = (size_t)value;
12546 use_since = true;
12547 }
12548
12549 if (!objspace->profile.run) {
12550 return Qnil;
12551 }
12552
12553 count = gc_profile_record_count(objspace);
12554 for (i = 0; i < count; i++) {
12555 gc_profile_record *record = &objspace->profile.records[gc_profile_record_index(objspace, i)];
12556 if (!use_since || record->sequence > since) {
12557 matching++;
12558 }
12559 }
12560 if (limit < matching) {
12561 skip = matching - limit;
12562 }
12563
12564 for (i = 0; i < count; i++) {
12565 gc_profile_record *record = &objspace->profile.records[gc_profile_record_index(objspace, i)];
12566 if (use_since && record->sequence <= since) {
12567 continue;
12568 }
12569 if (skip > 0) {
12570 skip--;
12571 continue;
12572 }
12573
12574 prof = rb_hash_new();
12575 rb_hash_aset(prof, ID2SYM(rb_intern("GC_FLAGS")), gc_info_decode(objspace, rb_hash_new(), record->flags));
12576 rb_hash_aset(prof, ID2SYM(rb_intern("GC_SEQUENCE")), SIZET2NUM(record->sequence));
12577 rb_hash_aset(prof, ID2SYM(rb_intern("GC_TIME")), DBL2NUM(record->gc_time));
12578 rb_hash_aset(prof, ID2SYM(rb_intern("GC_INVOKE_TIME")), DBL2NUM(record->gc_invoke_time));
12579 rb_hash_aset(prof, ID2SYM(rb_intern("GC_WALL_TIME")),
12580 DBL2NUM(hrtime_to_sec(record->gc_wall_time)));
12581 rb_hash_aset(prof, ID2SYM(rb_intern("GC_INVOKE_WALL_TIME")),
12582 DBL2NUM(hrtime_to_sec(record->gc_invoke_wall_time)));
12583 rb_hash_aset(prof, ID2SYM(rb_intern("GC_PAUSE_TIME")),
12584 DBL2NUM(hrtime_to_sec(record->gc_pause_time)));
12585 rb_hash_aset(prof, ID2SYM(rb_intern("GC_STOP_TIME")),
12586 DBL2NUM(hrtime_to_sec(record->gc_stop_time)));
12587 rb_hash_aset(prof, ID2SYM(rb_intern("GC_STW_TIME")),
12588 DBL2NUM(hrtime_to_sec(record->gc_stw_time)));
12589 rb_hash_aset(prof, ID2SYM(rb_intern("GC_MARK_WALL_TIME")),
12590 DBL2NUM(hrtime_to_sec(record->gc_mark_wall_time)));
12591 rb_hash_aset(prof, ID2SYM(rb_intern("GC_SWEEP_WALL_TIME")),
12592 DBL2NUM(hrtime_to_sec(record->gc_sweep_wall_time)));
12593 rb_hash_aset(prof, ID2SYM(rb_intern("GC_COMPACT_WALL_TIME")),
12594 DBL2NUM(hrtime_to_sec(record->gc_compact_wall_time)));
12595 rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_USE_SIZE")), SIZET2NUM(record->heap_use_size));
12596 rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_TOTAL_SIZE")), SIZET2NUM(record->heap_total_size));
12597 rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_TOTAL_OBJECTS")), SIZET2NUM(record->heap_total_objects));
12598 rb_hash_aset(prof, ID2SYM(rb_intern("MOVED_OBJECTS")), SIZET2NUM(record->moved_objects));
12599 rb_hash_aset(prof, ID2SYM(rb_intern("GC_IS_MARKED")), Qtrue);
12600#if GC_PROFILE_MORE_DETAIL
12601 rb_hash_aset(prof, ID2SYM(rb_intern("GC_MARK_TIME")), DBL2NUM(record->gc_mark_time));
12602 rb_hash_aset(prof, ID2SYM(rb_intern("GC_SWEEP_TIME")), DBL2NUM(record->gc_sweep_time));
12603 rb_hash_aset(prof, ID2SYM(rb_intern("ALLOCATE_INCREASE")), SIZET2NUM(record->allocate_increase));
12604 rb_hash_aset(prof, ID2SYM(rb_intern("ALLOCATE_LIMIT")), SIZET2NUM(record->allocate_limit));
12605 rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_USE_PAGES")), SIZET2NUM(record->heap_use_pages));
12606 rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_LIVE_OBJECTS")), SIZET2NUM(record->heap_live_objects));
12607 rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_FREE_OBJECTS")), SIZET2NUM(record->heap_free_objects));
12608
12609 rb_hash_aset(prof, ID2SYM(rb_intern("REMOVING_OBJECTS")), SIZET2NUM(record->removing_objects));
12610 rb_hash_aset(prof, ID2SYM(rb_intern("EMPTY_OBJECTS")), SIZET2NUM(record->empty_objects));
12611
12612 rb_hash_aset(prof, ID2SYM(rb_intern("HAVE_FINALIZE")), (record->flags & GPR_FLAG_HAVE_FINALIZE) ? Qtrue : Qfalse);
12613#endif
12614
12615#if RGENGC_PROFILE > 0
12616 rb_hash_aset(prof, ID2SYM(rb_intern("OLD_OBJECTS")), SIZET2NUM(record->old_objects));
12617 rb_hash_aset(prof, ID2SYM(rb_intern("REMEMBERED_NORMAL_OBJECTS")), SIZET2NUM(record->remembered_normal_objects));
12618 rb_hash_aset(prof, ID2SYM(rb_intern("REMEMBERED_SHADY_OBJECTS")), SIZET2NUM(record->remembered_shady_objects));
12619#endif
12620 rb_ary_push(gc_profile, prof);
12621 }
12622
12623 return gc_profile;
12624}
12625
12626#if GC_PROFILE_MORE_DETAIL
12627#define MAJOR_REASON_MAX 0x10
12628
12629static char *
12630gc_profile_dump_major_reason(unsigned int flags, char *buff)
12631{
12632 unsigned int reason = flags & GPR_FLAG_MAJOR_MASK;
12633 int i = 0;
12634
12635 if (reason == GPR_FLAG_NONE) {
12636 buff[0] = '-';
12637 buff[1] = 0;
12638 }
12639 else {
12640#define C(x, s) \
12641 if (reason & GPR_FLAG_MAJOR_BY_##x) { \
12642 buff[i++] = #x[0]; \
12643 if (i >= MAJOR_REASON_MAX) rb_bug("gc_profile_dump_major_reason: overflow"); \
12644 buff[i] = 0; \
12645 }
12646 C(NOFREE, N);
12647 C(OLDGEN, O);
12648 C(SHADY, S);
12649#if RGENGC_ESTIMATE_OLDMALLOC
12650 C(OLDMALLOC, M);
12651#endif
12652#undef C
12653 }
12654 return buff;
12655}
12656#endif
12657
12658
12659
12660static void
12661gc_profile_dump_on(VALUE out, VALUE (*append)(VALUE, VALUE))
12662{
12663 rb_objspace_t *objspace = rb_gc_get_objspace();
12664 size_t count = gc_profile_record_count(objspace);
12665#ifdef MAJOR_REASON_MAX
12666 char reason_str[MAJOR_REASON_MAX];
12667#endif
12668
12669 if (objspace->profile.run && count /* > 1 */) {
12670 size_t i;
12671 const gc_profile_record *record;
12672
12673 append(out, rb_sprintf("GC %"PRIuSIZE" invokes.\n", objspace->profile.count));
12674 append(out, rb_str_new_cstr("Index Invoke Time(sec) Use Size(byte) Total Size(byte) Total Object GC Time(ms)\n"));
12675
12676 for (i = 0; i < count; i++) {
12677 record = &objspace->profile.records[gc_profile_record_index(objspace, i)];
12678 append(out, rb_sprintf("%5"PRIuSIZE" %19.3f %20"PRIuSIZE" %20"PRIuSIZE" %20"PRIuSIZE" %30.20f\n",
12679 i+1, record->gc_invoke_time, record->heap_use_size,
12680 record->heap_total_size, record->heap_total_objects, record->gc_time*1000));
12681 }
12682
12683#if GC_PROFILE_MORE_DETAIL
12684 const char *str = "\n\n" \
12685 "More detail.\n" \
12686 "Prepare Time = Previously GC's rest sweep time\n"
12687 "Index Flags Allocate Inc. Allocate Limit"
12688#if CALC_EXACT_MALLOC_SIZE
12689 " Allocated Size"
12690#endif
12691 " Use Page Mark Time(ms) Sweep Time(ms) Prepare Time(ms) LivingObj FreeObj RemovedObj EmptyObj"
12692#if RGENGC_PROFILE
12693 " OldgenObj RemNormObj RemShadObj"
12694#endif
12695#if GC_PROFILE_DETAIL_MEMORY
12696 " MaxRSS(KB) MinorFLT MajorFLT"
12697#endif
12698 "\n";
12699 append(out, rb_str_new_cstr(str));
12700
12701 for (i = 0; i < count; i++) {
12702 record = &objspace->profile.records[gc_profile_record_index(objspace, i)];
12703 append(out, rb_sprintf("%5"PRIuSIZE" %4s/%c/%6s%c %13"PRIuSIZE" %15"PRIuSIZE
12704#if CALC_EXACT_MALLOC_SIZE
12705 " %15"PRIuSIZE
12706#endif
12707 " %9"PRIuSIZE" %17.12f %17.12f %17.12f %10"PRIuSIZE" %10"PRIuSIZE" %10"PRIuSIZE" %10"PRIuSIZE
12708#if RGENGC_PROFILE
12709 "%10"PRIuSIZE" %10"PRIuSIZE" %10"PRIuSIZE
12710#endif
12711#if GC_PROFILE_DETAIL_MEMORY
12712 "%11ld %8ld %8ld"
12713#endif
12714
12715 "\n",
12716 i+1,
12717 gc_profile_dump_major_reason(record->flags, reason_str),
12718 (record->flags & GPR_FLAG_HAVE_FINALIZE) ? 'F' : '.',
12719 (record->flags & GPR_FLAG_NEWOBJ) ? "NEWOBJ" :
12720 (record->flags & GPR_FLAG_MALLOC) ? "MALLOC" :
12721 (record->flags & GPR_FLAG_METHOD) ? "METHOD" :
12722 (record->flags & GPR_FLAG_CAPI) ? "CAPI__" : "??????",
12723 (record->flags & GPR_FLAG_STRESS) ? '!' : ' ',
12724 record->allocate_increase, record->allocate_limit,
12725#if CALC_EXACT_MALLOC_SIZE
12726 record->allocated_size,
12727#endif
12728 record->heap_use_pages,
12729 record->gc_mark_time*1000,
12730 record->gc_sweep_time*1000,
12731 record->prepare_time*1000,
12732
12733 record->heap_live_objects,
12734 record->heap_free_objects,
12735 record->removing_objects,
12736 record->empty_objects
12737#if RGENGC_PROFILE
12738 ,
12739 record->old_objects,
12740 record->remembered_normal_objects,
12741 record->remembered_shady_objects
12742#endif
12743#if GC_PROFILE_DETAIL_MEMORY
12744 ,
12745 record->maxrss / 1024,
12746 record->minflt,
12747 record->majflt
12748#endif
12749
12750 ));
12751 }
12752#endif
12753 }
12754}
12755
12756/*
12757 * call-seq:
12758 * GC::Profiler.result -> String
12759 *
12760 * Returns a profile data report such as:
12761 *
12762 * GC 1 invokes.
12763 * Index Invoke Time(sec) Use Size(byte) Total Size(byte) Total Object GC time(ms)
12764 * 1 0.012 159240 212940 10647 0.00000000000001530000
12765 */
12766
12767static VALUE
12768gc_profile_result(VALUE _)
12769{
12770 VALUE str = rb_str_buf_new(0);
12771 gc_profile_dump_on(str, rb_str_buf_append);
12772 return str;
12773}
12774
12775/*
12776 * call-seq:
12777 * GC::Profiler.report
12778 * GC::Profiler.report(io)
12779 *
12780 * Writes the GC::Profiler.result to <tt>$stdout</tt> or the given IO object.
12781 *
12782 */
12783
12784static VALUE
12785gc_profile_report(int argc, VALUE *argv, VALUE self)
12786{
12787 VALUE out;
12788
12789 out = (!rb_check_arity(argc, 0, 1) ? rb_stdout : argv[0]);
12790 gc_profile_dump_on(out, rb_io_write);
12791
12792 return Qnil;
12793}
12794
12795/*
12796 * call-seq:
12797 * GC::Profiler.total_time -> float
12798 *
12799 * The total time used for garbage collection in seconds
12800 */
12801
12802static VALUE
12803gc_profile_total_time(VALUE self)
12804{
12805 double time = 0;
12806 rb_objspace_t *objspace = rb_gc_get_objspace();
12807
12808 if (objspace->profile.run && gc_profile_record_count(objspace) > 0) {
12809 size_t i;
12810 size_t count = gc_profile_record_count(objspace);
12811
12812 for (i = 0; i < count; i++) {
12813 time += objspace->profile.records[gc_profile_record_index(objspace, i)].gc_time;
12814 }
12815 }
12816 return DBL2NUM(time);
12817}
12818
12819/*
12820 * call-seq:
12821 * GC::Profiler.enabled? -> true or false
12822 *
12823 * The current status of \GC profile mode.
12824 */
12825
12826static VALUE
12827gc_profile_enable_get(VALUE self)
12828{
12829 rb_objspace_t *objspace = rb_gc_get_objspace();
12830 return objspace->profile.run ? Qtrue : Qfalse;
12831}
12832
12833/*
12834 * call-seq:
12835 * GC::Profiler.enable -> nil
12836 *
12837 * Starts the \GC profiler.
12838 *
12839 */
12840
12841static VALUE
12842gc_profile_enable(VALUE _)
12843{
12844 rb_objspace_t *objspace = rb_gc_get_objspace();
12845 objspace->profile.run = TRUE;
12846 objspace->profile.current_record = 0;
12847 return Qnil;
12848}
12849
12850/*
12851 * call-seq:
12852 * GC::Profiler.disable -> nil
12853 *
12854 * Stops the \GC profiler.
12855 *
12856 */
12857
12858static VALUE
12859gc_profile_disable(VALUE _)
12860{
12861 rb_objspace_t *objspace = rb_gc_get_objspace();
12862
12863 objspace->profile.run = FALSE;
12864 objspace->profile.current_record = 0;
12865 return Qnil;
12866}
12867
12868static void
12869rb_gc_verify_internal_consistency(void)
12870{
12871 gc_verify_internal_consistency(rb_gc_get_objspace());
12872}
12873
12874/*
12875 * call-seq:
12876 * GC.verify_internal_consistency -> nil
12877 *
12878 * Verifies internal consistency of the GC.
12879 * This method should only be used for debugging.
12880 *
12881 * This method is only expected to work on CRuby.
12882 */
12883static VALUE
12884gc_verify_internal_consistency_m(VALUE dummy)
12885{
12886 rb_gc_verify_internal_consistency();
12887 return Qnil;
12888}
12889
12890#if GC_CAN_COMPILE_COMPACTION
12891/*
12892 * call-seq:
12893 * GC.auto_compact = flag
12894 *
12895 * Updates automatic compaction mode.
12896 *
12897 * When enabled, the compactor will execute on every major collection.
12898 *
12899 * Enabling compaction will degrade performance on major collections.
12900 */
12901static VALUE
12902gc_set_auto_compact(VALUE _, VALUE v)
12903{
12904 GC_ASSERT(GC_COMPACTION_SUPPORTED);
12905
12906 ruby_enable_autocompact = RTEST(v);
12907
12908#if RGENGC_CHECK_MODE
12909 ruby_autocompact_compare_func = NULL;
12910
12911 if (SYMBOL_P(v)) {
12912 ID id = RB_SYM2ID(v);
12913 if (id == rb_intern("empty")) {
12914 ruby_autocompact_compare_func = compare_free_slots;
12915 }
12916 }
12917#endif
12918
12919 return v;
12920}
12921#else
12922# define gc_set_auto_compact rb_f_notimplement
12923#endif
12924
12925#if GC_CAN_COMPILE_COMPACTION
12926/*
12927 * call-seq:
12928 * GC.auto_compact -> true or false
12929 *
12930 * Returns whether or not automatic compaction has been enabled.
12931 */
12932static VALUE
12933gc_get_auto_compact(VALUE _)
12934{
12935 return ruby_enable_autocompact ? Qtrue : Qfalse;
12936}
12937#else
12938# define gc_get_auto_compact rb_f_notimplement
12939#endif
12940
12941#if GC_CAN_COMPILE_COMPACTION
12942/*
12943 * call-seq:
12944 * GC.latest_compact_info -> hash
12945 *
12946 * Returns information about object moved in the most recent \GC compaction.
12947 *
12948 * The returned +hash+ contains the following keys:
12949 *
12950 * [considered]
12951 * Hash containing the type of the object as the key and the number of
12952 * objects of that type that were considered for movement.
12953 * [moved]
12954 * Hash containing the type of the object as the key and the number of
12955 * objects of that type that were actually moved.
12956 * [moved_up]
12957 * Hash containing the type of the object as the key and the number of
12958 * objects of that type that were increased in size.
12959 * [moved_down]
12960 * Hash containing the type of the object as the key and the number of
12961 * objects of that type that were decreased in size.
12962 *
12963 * Some objects can't be moved (due to pinning) so these numbers can be used to
12964 * calculate compaction efficiency.
12965 */
12966static VALUE
12967gc_compact_stats(VALUE self)
12968{
12969 rb_objspace_t *objspace = rb_gc_get_objspace();
12970 VALUE h = rb_hash_new();
12971 VALUE considered = rb_hash_new();
12972 VALUE moved = rb_hash_new();
12973 VALUE moved_up = rb_hash_new();
12974 VALUE moved_down = rb_hash_new();
12975
12976 for (size_t i = 0; i < T_MASK; i++) {
12977 if (objspace->rcompactor.considered_count_table[i]) {
12978 rb_hash_aset(considered, type_sym(i), SIZET2NUM(objspace->rcompactor.considered_count_table[i]));
12979 }
12980
12981 if (objspace->rcompactor.moved_count_table[i]) {
12982 rb_hash_aset(moved, type_sym(i), SIZET2NUM(objspace->rcompactor.moved_count_table[i]));
12983 }
12984
12985 if (objspace->rcompactor.moved_up_count_table[i]) {
12986 rb_hash_aset(moved_up, type_sym(i), SIZET2NUM(objspace->rcompactor.moved_up_count_table[i]));
12987 }
12988
12989 if (objspace->rcompactor.moved_down_count_table[i]) {
12990 rb_hash_aset(moved_down, type_sym(i), SIZET2NUM(objspace->rcompactor.moved_down_count_table[i]));
12991 }
12992 }
12993
12994 rb_hash_aset(h, ID2SYM(rb_intern("considered")), considered);
12995 rb_hash_aset(h, ID2SYM(rb_intern("moved")), moved);
12996 rb_hash_aset(h, ID2SYM(rb_intern("moved_up")), moved_up);
12997 rb_hash_aset(h, ID2SYM(rb_intern("moved_down")), moved_down);
12998
12999 return h;
13000}
13001#else
13002# define gc_compact_stats rb_f_notimplement
13003#endif
13004
13005#if GC_CAN_COMPILE_COMPACTION
13006/*
13007 * call-seq:
13008 * GC.compact -> hash
13009 *
13010 * This function compacts objects together in Ruby's heap. It eliminates
13011 * unused space (or fragmentation) in the heap by moving objects in to that
13012 * unused space. If there is more than 1 running Ractor, it runs a global
13013 * GC compaction (all object spaces).
13014 *
13015 * The returned +hash+ contains statistics about the objects that were moved;
13016 * see GC.latest_compact_info.
13017 *
13018 * This method is only expected to work on CRuby.
13019 *
13020 * To test whether \GC compaction is supported, use the idiom:
13021 *
13022 * GC.respond_to?(:compact)
13023 */
13024static VALUE
13025gc_compact(VALUE self)
13026{
13027 rb_objspace_t *objspace = rb_gc_get_objspace();
13028 int full_marking_p = gc_config_full_mark_val;
13029 gc_config_full_mark_set(TRUE);
13030
13031 /* Run GC with compaction enabled */
13032 rb_gc_impl_start(rb_gc_get_objspace(), true, true, true, true, true);
13033 gc_config_full_mark_set(full_marking_p);
13034
13035 return gc_compact_stats(self);
13036}
13037#else
13038# define gc_compact rb_f_notimplement
13039#endif
13040
13041#if GC_CAN_COMPILE_COMPACTION
13042struct desired_compaction_pages_i_data {
13044 size_t required_slots[HEAP_COUNT];
13045};
13046
13047static int
13048desired_compaction_pages_i(struct heap_page *page, void *data)
13049{
13050 struct desired_compaction_pages_i_data *tdata = data;
13051 rb_objspace_t *objspace = tdata->objspace;
13052 VALUE vstart = (VALUE)page->start;
13053 VALUE vend = vstart + (VALUE)(page->total_slots * page->heap->slot_size);
13054
13055
13056 for (VALUE v = vstart; v != vend; v += page->heap->slot_size) {
13057 asan_unpoisoning_object(v) {
13058 /* skip T_NONEs; they won't be moved */
13059 if (BUILTIN_TYPE(v) != T_NONE) {
13060 rb_heap_t *dest_pool = gc_compact_destination_pool(objspace, page->heap, v);
13061 size_t dest_pool_idx = dest_pool - heaps;
13062 tdata->required_slots[dest_pool_idx]++;
13063 }
13064 }
13065 }
13066
13067 return 0;
13068}
13069
13070/* call-seq:
13071 * GC.verify_compaction_references(toward: nil, double_heap: false) -> hash
13072 *
13073 * Verify compaction reference consistency.
13074 *
13075 * This method is implementation specific. During compaction, objects that
13076 * were moved are replaced with T_MOVED objects. No object should have a
13077 * reference to a T_MOVED object after compaction.
13078 *
13079 * This function expands the heap to ensure room to move all objects,
13080 * compacts the heap to make sure everything moves, updates all references,
13081 * then performs a full \GC. If any object contains a reference to a T_MOVED
13082 * object, that object should be pushed on the mark stack, and will
13083 * make a SEGV.
13084 */
13085static VALUE
13086gc_verify_compaction_references(int argc, VALUE* argv, VALUE self)
13087{
13088 static ID keywords[3] = {0};
13089 if (!keywords[0]) {
13090 keywords[0] = rb_intern("toward");
13091 keywords[1] = rb_intern("double_heap");
13092 keywords[2] = rb_intern("expand_heap");
13093 }
13094
13095 VALUE options;
13096 rb_scan_args_kw(rb_keyword_given_p(), argc, argv, ":", &options);
13097
13098 VALUE arguments[3] = { Qnil, Qfalse, Qfalse };
13099 int kwarg_count = rb_get_kwargs(options, keywords, 0, 3, arguments);
13100 bool toward_empty = kwarg_count > 0 && SYMBOL_P(arguments[0]) && SYM2ID(arguments[0]) == rb_intern("empty");
13101 bool expand_heap = (kwarg_count > 1 && RTEST(arguments[1])) || (kwarg_count > 2 && RTEST(arguments[2]));
13102
13103 rb_objspace_t *objspace = rb_gc_get_objspace();
13104
13105 /* This verification machinery (heap expansion, toward_empty page ordering, the
13106 * moved-reference walk) is built for a single objspace, so with several demote it
13107 * to a plain full GC. Plain GC.compact does compact them via the global GC. */
13108 if (!rb_gc_single_objspace_p()) {
13109 rb_gc_impl_start(objspace, true, true, true, false, false);
13110 return gc_compact_stats(self);
13111 }
13112
13113 /* Clear the heap. */
13114 rb_gc_impl_start(objspace, true, true, true, false, false);
13115
13116 unsigned int lev = RB_GC_VM_LOCK();
13117 {
13118 gc_rest(objspace);
13119
13120 /* if both double_heap and expand_heap are set, expand_heap takes precedence */
13121 if (expand_heap) {
13122 struct desired_compaction_pages_i_data desired_compaction = {
13123 .objspace = objspace,
13124 .required_slots = {0},
13125 };
13126 /* Work out how many objects want to be in each size pool, taking account of moves */
13127 objspace_each_pages(objspace, desired_compaction_pages_i, &desired_compaction, TRUE);
13128
13129 /* Find out which pool has the most pages */
13130 size_t max_existing_pages = 0;
13131 for (int i = 0; i < HEAP_COUNT; i++) {
13132 rb_heap_t *heap = &heaps[i];
13133 max_existing_pages = MAX(max_existing_pages, heap->total_pages);
13134 }
13135
13136 /* Add pages to each size pool so that compaction is guaranteed to move every object */
13137 for (int i = 0; i < HEAP_COUNT; i++) {
13138 rb_heap_t *heap = &heaps[i];
13139
13140 size_t pages_to_add = 0;
13141 /*
13142 * Step 1: Make sure every pool has the same number of pages, by adding empty pages
13143 * to smaller pools. This is required to make sure the compact cursor can advance
13144 * through all of the pools in `gc_sweep_compact` without hitting the "sweep &
13145 * compact cursors met" condition on some pools before fully compacting others
13146 */
13147 pages_to_add += max_existing_pages - heap->total_pages;
13148 /*
13149 * Step 2: Now add additional free pages to each size pool sufficient to hold all objects
13150 * that want to be in that size pool, whether moved into it or moved within it
13151 */
13152 objspace->heap_pages.allocatable_bytes = desired_compaction.required_slots[i] * heap->slot_size;
13153 while (objspace->heap_pages.allocatable_bytes > 0) {
13154 heap_page_allocate_and_initialize(objspace, heap);
13155 }
13156 /*
13157 * Step 3: Add two more pages so that the compact & sweep cursors will meet _after_ all objects
13158 * have been moved, and not on the last iteration of the `gc_sweep_compact` loop
13159 */
13160 pages_to_add += 2;
13161
13162 for (; pages_to_add > 0; pages_to_add--) {
13163 heap_page_allocate_and_initialize_force(objspace, heap);
13164 }
13165 }
13166 }
13167
13168 if (toward_empty) {
13169 objspace->rcompactor.compare_func = compare_free_slots;
13170 }
13171 }
13172 RB_GC_VM_UNLOCK(lev);
13173
13174 rb_gc_impl_start(rb_gc_get_objspace(), true, true, true, true, false);
13175
13176 rb_objspace_reachable_objects_from_root(root_obj_check_moved_i, objspace);
13177 objspace_each_objects(objspace, heap_check_moved_i, objspace, TRUE);
13178
13179 objspace->rcompactor.compare_func = NULL;
13180
13181 return gc_compact_stats(self);
13182}
13183#else
13184# define gc_verify_compaction_references rb_f_notimplement
13185#endif
13186
13187void
13188rb_gc_impl_objspace_free(void *objspace_ptr)
13189{
13190 rb_objspace_t *objspace = objspace_ptr;
13191
13192 if (is_lazy_sweeping(objspace))
13193 rb_bug("lazy sweeping underway when freeing object space");
13194
13195 free(objspace->profile.records);
13196 objspace->profile.records = NULL;
13197
13198 for (size_t i = 0; i < rb_darray_size(objspace->heap_pages.sorted); i++) {
13199 heap_page_free(objspace, rb_darray_get(objspace->heap_pages.sorted, i));
13200 }
13201 rb_darray_free_without_gc(objspace->heap_pages.sorted);
13202 heap_pages_lomem = 0;
13203 heap_pages_himem = 0;
13204
13205 for (int i = 0; i < HEAP_COUNT; i++) {
13206 rb_heap_t *heap = &heaps[i];
13207 heap->total_pages = 0;
13208 heap->total_slots = 0;
13209 }
13210
13211 free_stack_chunks(&objspace->mark_stack);
13212 mark_stack_free_cache(&objspace->mark_stack);
13213
13214 rb_darray_free_without_gc(objspace->weak_references);
13215
13216#ifdef MALLOC_COUNTERS_NEED_LOCK
13217 rb_native_mutex_destroy(&objspace->malloc_counters.lock);
13218#endif
13219
13220 rb_native_mutex_destroy(&objspace->process_stat.lock);
13221
13222 free(objspace);
13223}
13224
13225#if MALLOC_ALLOCATED_SIZE
13226/*
13227 * call-seq:
13228 * GC.malloc_allocated_size -> Integer
13229 *
13230 * Returns the size of memory allocated by malloc().
13231 *
13232 * Only available if ruby was built with +CALC_EXACT_MALLOC_SIZE+.
13233 */
13234
13235static VALUE
13236gc_malloc_allocated_size(VALUE self)
13237{
13238 rb_objspace_t *objspace = (rb_objspace_t *)rb_gc_get_objspace();
13239 return ULL2NUM(objspace->malloc_params.allocated_size);
13240}
13241
13242/*
13243 * call-seq:
13244 * GC.malloc_allocations -> Integer
13245 *
13246 * Returns the number of malloc() allocations.
13247 *
13248 * Only available if ruby was built with +CALC_EXACT_MALLOC_SIZE+.
13249 */
13250
13251static VALUE
13252gc_malloc_allocations(VALUE self)
13253{
13254 rb_objspace_t *objspace = (rb_objspace_t *)rb_gc_get_objspace();
13255 return ULL2NUM(objspace->malloc_params.allocations);
13256}
13257#endif
13258
13259void
13260rb_gc_impl_before_fork(void *objspace_ptr)
13261{
13262 rb_objspace_t *objspace = objspace_ptr;
13263
13264 objspace->fork_vm_lock_lev = RB_GC_VM_LOCK();
13265 rb_gc_vm_barrier();
13266}
13267
13268void
13269rb_gc_impl_after_fork(void *objspace_ptr, rb_pid_t pid)
13270{
13271 rb_objspace_t *objspace = objspace_ptr;
13272
13273 if (pid == 0) {
13274 rb_gc_vm_each_objspace(gc_process_stat_after_fork_i, NULL);
13275 }
13276
13277 RB_GC_VM_UNLOCK(objspace->fork_vm_lock_lev);
13278 objspace->fork_vm_lock_lev = 0;
13279
13280 if (pid == 0) { /* child process */
13281 heap_alloc_state_clear(objspace);
13282 /* The forking Ractor becomes the child process's main Ractor. */
13283 global_objspace->main_objspace = objspace;
13284 page_pool_lock_initialize(&rb_global_objspace_instance.page_pool.lock);
13285 }
13286}
13287
13288VALUE rb_ident_hash_new_capa(long size);
13289
13290#if GC_DEBUG_STRESS_TO_CLASS
13291/*
13292 * call-seq:
13293 * GC.add_stress_to_class(class[, ...])
13294 *
13295 * Raises NoMemoryError when allocating an instance of the given classes.
13296 *
13297 */
13298static VALUE
13299rb_gcdebug_add_stress_to_class(int argc, VALUE *argv, VALUE self)
13300{
13301 rb_objspace_t *objspace = rb_gc_get_objspace();
13302
13303 if (!stress_to_class) {
13304 set_stress_to_class(rb_ident_hash_new_capa(argc));
13305 }
13306
13307 for (int i = 0; i < argc; i++) {
13308 VALUE klass = argv[i];
13309 rb_hash_aset(stress_to_class, klass, Qtrue);
13310 }
13311
13312 return self;
13313}
13314
13315/*
13316 * call-seq:
13317 * GC.remove_stress_to_class(class[, ...])
13318 *
13319 * No longer raises NoMemoryError when allocating an instance of the
13320 * given classes.
13321 *
13322 */
13323static VALUE
13324rb_gcdebug_remove_stress_to_class(int argc, VALUE *argv, VALUE self)
13325{
13326 rb_objspace_t *objspace = rb_gc_get_objspace();
13327
13328 if (stress_to_class) {
13329 for (int i = 0; i < argc; ++i) {
13330 rb_hash_delete(stress_to_class, argv[i]);
13331 }
13332
13333 if (rb_hash_size(stress_to_class) == 0) {
13334 stress_to_class = 0;
13335 }
13336 }
13337
13338 return Qnil;
13339}
13340#endif
13341
13342void *
13343rb_gc_impl_objspace_alloc(void)
13344{
13345 global_objspace_init();
13346
13347 rb_objspace_t *objspace = calloc1(sizeof(rb_objspace_t));
13348 if (objspace) {
13349 rb_native_mutex_initialize(&objspace->process_stat.lock);
13350 }
13351
13352 return objspace;
13353}
13354
13355void
13356rb_gc_impl_objspace_init(void *objspace_ptr)
13357{
13358 rb_objspace_t *objspace = objspace_ptr;
13359
13360 gc_config_full_mark_set(TRUE);
13361
13362 malloc_limit = gc_params.malloc_limit_min;
13363 objspace->shareable_objects_limit = SHAREABLE_OBJECTS_LIMIT_MIN;
13364#ifdef MALLOC_COUNTERS_NEED_LOCK
13365 rb_native_mutex_initialize(&objspace->malloc_counters.lock);
13366#endif
13367 /* Shared by every objspace. preregister deduplicates on (func, data). */
13368 objspace->finalize_deferred_pjob = rb_postponed_job_preregister(0, gc_finalize_deferred, NULL);
13369 if (objspace->finalize_deferred_pjob == POSTPONED_JOB_HANDLE_INVALID) {
13370 rb_bug("Could not preregister postponed job for GC");
13371 }
13372
13373 gc_tdata_deferred_free_pjob_ensure();
13374
13375 /* A standard RVALUE (RBasic + embedded VALUEs + debug overhead) must fit
13376 * in at least one pool. In debug builds RVALUE_OVERHEAD can push this
13377 * beyond the 48-byte pool into the 64-byte pool, which is fine. */
13378 GC_ASSERT(rb_gc_impl_size_allocatable_p(sizeof(struct RBasic) + sizeof(VALUE[RBIMPL_RVALUE_EMBED_LEN_MAX])));
13379
13380 for (int i = 0; i < HEAP_COUNT; i++) {
13381 rb_heap_t *heap = &heaps[i];
13382
13383 heap->slot_size = pool_slot_sizes[i];
13384
13385 ccan_list_head_init(&heap->pages);
13386 }
13387
13388 if (global_objspace->main_objspace == NULL) {
13389 /* Single-threaded at boot and the first objspace is main's: compute process-wide
13390 * constants once here. A later objspace_init rewriting them, even with equal
13391 * values, would race other threads' lock-free reads. */
13392 global_objspace->main_objspace = objspace;
13393
13394 init_size_to_heap_idx();
13395
13396#if defined(INIT_HEAP_PAGE_ALLOC_USE_MMAP)
13397 /* Need to determine if we can use mmap at runtime. */
13398 heap_page_alloc_use_mmap = INIT_HEAP_PAGE_ALLOC_USE_MMAP;
13399#endif
13400 gc_params.heap_init_bytes = GC_HEAP_INIT_BYTES;
13401 gc_params.ractor_heap_init_bytes = GC_RACTOR_HEAP_INIT_BYTES ? GC_RACTOR_HEAP_INIT_BYTES
13402 : heap_init_bytes_min();
13403 }
13404 // GC.measure_total_time= sets the caller's objspace only; a new Ractor's follows
13405 // its creator's, which is the objspace running this init (main starts it on).
13406 objspace->flags.measure_gc = global_objspace->main_objspace == objspace ? true
13407 : ((rb_objspace_t *)rb_gc_get_objspace())->flags.measure_gc;
13408
13409 rb_darray_make_without_gc(&objspace->heap_pages.sorted, 0);
13410 rb_darray_make_without_gc(&objspace->weak_references, 0);
13411
13412#if RGENGC_ESTIMATE_OLDMALLOC
13413 objspace->rgengc.oldmalloc_increase_limit = gc_params.oldmalloc_limit_min;
13414#endif
13415
13416 init_mark_stack(&objspace->mark_stack);
13417
13418 objspace->profile.invoke_time = getrusage_time();
13419 objspace->profile.invoke_wall_time = rb_hrtime_now();
13420 objspace->profile.max_records = GC_PROFILE_RECORD_DEFAULT_MAX_RECORDS;
13421 finalizer_table = st_init_numtable();
13422
13423 gc_process_stat_publish(objspace);
13424}
13425
13426void
13427rb_gc_impl_init(void)
13428{
13429 /* Fill the symbol tables here, where no other ractor exists yet: they used to
13430 * be filled on first use, guarded by their own first element, so a second
13431 * ractor could see a half-filled table and GC.stat raised on the rest. */
13432 setup_gc_stat_symbols();
13433 setup_gc_stat_heap_symbols();
13434 setup_gc_latest_gc_info_symbols();
13435
13436 VALUE gc_constants = rb_hash_new();
13437 rb_hash_aset(gc_constants, ID2SYM(rb_intern("DEBUG")), GC_DEBUG ? Qtrue : Qfalse);
13438 /* Minimum slot size that fits a standard RVALUE */
13439 size_t rvalue_pool = 0;
13440 for (size_t i = 0; i < HEAP_COUNT; i++) {
13441 if (pool_slot_sizes[i] >= RVALUE_SLOT_SIZE) { rvalue_pool = pool_slot_sizes[i]; break; }
13442 }
13443 rb_hash_aset(gc_constants, ID2SYM(rb_intern("RVALUE_SIZE")), SIZET2NUM(rvalue_pool - RVALUE_OVERHEAD));
13444 rb_hash_aset(gc_constants, ID2SYM(rb_intern("RBASIC_SIZE")), SIZET2NUM(sizeof(struct RBasic)));
13445 rb_hash_aset(gc_constants, ID2SYM(rb_intern("RVALUE_OVERHEAD")), SIZET2NUM(RVALUE_OVERHEAD));
13446 rb_hash_aset(gc_constants, ID2SYM(rb_intern("HEAP_PAGE_BITMAP_SIZE")), SIZET2NUM(HEAP_PAGE_BITMAP_SIZE));
13447 rb_hash_aset(gc_constants, ID2SYM(rb_intern("HEAP_PAGE_SIZE")), SIZET2NUM(HEAP_PAGE_SIZE));
13448 rb_hash_aset(gc_constants, ID2SYM(rb_intern("HEAP_COUNT")), LONG2FIX(HEAP_COUNT));
13449 rb_hash_aset(gc_constants, ID2SYM(rb_intern("RVARGC_MAX_ALLOCATE_SIZE")), SIZET2NUM(rb_gc_impl_max_allocation_size()));
13450 rb_hash_aset(gc_constants, ID2SYM(rb_intern("RVALUE_OLD_AGE")), LONG2FIX(RVALUE_OLD_AGE));
13451 if (RB_BUG_INSTEAD_OF_RB_MEMERROR+0) {
13452 rb_hash_aset(gc_constants, ID2SYM(rb_intern("RB_BUG_INSTEAD_OF_RB_MEMERROR")), Qtrue);
13453 }
13454 OBJ_FREEZE(gc_constants);
13455 /* Internal constants in the garbage collector. */
13456 rb_define_const(rb_mGC, "INTERNAL_CONSTANTS", gc_constants);
13457
13458 if (GC_COMPACTION_SUPPORTED) {
13459 rb_define_singleton_method(rb_mGC, "compact", gc_compact, 0);
13460 rb_define_singleton_method(rb_mGC, "auto_compact", gc_get_auto_compact, 0);
13461 rb_define_singleton_method(rb_mGC, "auto_compact=", gc_set_auto_compact, 1);
13462 rb_define_singleton_method(rb_mGC, "latest_compact_info", gc_compact_stats, 0);
13463 rb_define_singleton_method(rb_mGC, "verify_compaction_references", gc_verify_compaction_references, -1);
13464 }
13465 else {
13469 rb_define_singleton_method(rb_mGC, "latest_compact_info", rb_f_notimplement, 0);
13470 rb_define_singleton_method(rb_mGC, "verify_compaction_references", rb_f_notimplement, -1);
13471 }
13472
13473#if GC_DEBUG_STRESS_TO_CLASS
13474 rb_define_singleton_method(rb_mGC, "add_stress_to_class", rb_gcdebug_add_stress_to_class, -1);
13475 rb_define_singleton_method(rb_mGC, "remove_stress_to_class", rb_gcdebug_remove_stress_to_class, -1);
13476#endif
13477
13478 /* internal methods */
13479 rb_define_singleton_method(rb_mGC, "verify_internal_consistency", gc_verify_internal_consistency_m, 0);
13480
13481#if MALLOC_ALLOCATED_SIZE
13482 rb_define_singleton_method(rb_mGC, "malloc_allocated_size", gc_malloc_allocated_size, 0);
13483 rb_define_singleton_method(rb_mGC, "malloc_allocations", gc_malloc_allocations, 0);
13484#endif
13485
13486 /* Document-class: GC::Profiler
13487 *
13488 * The GC profiler provides access to information on GC runs including time,
13489 * length and object space size.
13490 *
13491 * Example:
13492 *
13493 * GC::Profiler.enable
13494 *
13495 * require 'rdoc/rdoc'
13496 *
13497 * GC::Profiler.report
13498 *
13499 * pp GC::Profiler.raw_data
13500 *
13501 * GC::Profiler.disable
13502 *
13503 * GC::Profiler.raw_data returns one Hash per GC run, including CPU time
13504 * fields such as +:GC_TIME+ and wall-clock fields such as +:GC_WALL_TIME+,
13505 * +:GC_PAUSE_TIME+, +:GC_STOP_TIME+, and +:GC_STW_TIME+. +:GC_WALL_TIME+
13506 * is the wall-clock counterpart to +:GC_TIME+, while +:GC_PAUSE_TIME+
13507 * measures how long user execution was blocked by the GC entry.
13508 *
13509 * See also GC.count, GC.malloc_allocated_size and GC.malloc_allocations
13510 */
13511 VALUE rb_mProfiler = rb_define_module_under(rb_mGC, "Profiler");
13512 rb_define_singleton_method(rb_mProfiler, "enabled?", gc_profile_enable_get, 0);
13513 rb_define_singleton_method(rb_mProfiler, "enable", gc_profile_enable, 0);
13514 rb_define_singleton_method(rb_mProfiler, "raw_data", gc_profile_record_get, -1);
13515 rb_define_singleton_method(rb_mProfiler, "disable", gc_profile_disable, 0);
13516 rb_define_singleton_method(rb_mProfiler, "clear", gc_profile_clear, 0);
13517 rb_define_singleton_method(rb_mProfiler, "configure", gc_profile_configure, -1);
13518 rb_define_singleton_method(rb_mProfiler, "result", gc_profile_result, 0);
13519 rb_define_singleton_method(rb_mProfiler, "report", gc_profile_report, -1);
13520 rb_define_singleton_method(rb_mProfiler, "total_time", gc_profile_total_time, 0);
13521
13522 {
13523 VALUE opts;
13524 /* \GC build options */
13525 rb_define_const(rb_mGC, "OPTS", opts = rb_ary_new());
13526#define OPT(o) if (o) rb_ary_push(opts, rb_interned_str(#o, sizeof(#o) - 1))
13527 OPT(GC_DEBUG);
13528 OPT(USE_RGENGC);
13529 OPT(RGENGC_DEBUG);
13530 OPT(RGENGC_CHECK_MODE);
13531 OPT(RGENGC_PROFILE);
13532 OPT(RGENGC_ESTIMATE_OLDMALLOC);
13533 OPT(GC_PROFILE_MORE_DETAIL);
13534 OPT(GC_ENABLE_LAZY_SWEEP);
13535 OPT(CALC_EXACT_MALLOC_SIZE);
13536 OPT(MALLOC_ALLOCATED_SIZE);
13537 OPT(MALLOC_ALLOCATED_SIZE_CHECK);
13538 OPT(GC_PROFILE_DETAIL_MEMORY);
13539 OPT(GC_COMPACTION_SUPPORTED);
13540#undef OPT
13541 OBJ_FREEZE(opts);
13542 }
13543}
#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