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