Ruby 4.1.0dev (2026-08-15 revision d1c079751b80352d347452c8d134ffb177838adb)
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 int 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 /* Never write a foreign page's pinned bit (a global GC may: everyone is stopped). */
5790 if (gc_skip_foreign_object_p(objspace, obj)) return;
5791
5792 if (RB_UNLIKELY(objspace->flags.during_compacting)) {
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#define MARK_CHECKPOINT(category) do { \
5929 if (categoryp) *categoryp = category; \
5930} while (0)
5931
5932 /* Pinning shareable objects and shrefs runs at the end of marking (gc_marks_finish),
5933 * not here: after the full walk it only has to touch what ordinary marking missed,
5934 * which is both cheap and a useful retention metric. */
5935
5936 MARK_CHECKPOINT("objspace");
5937 gc_mark_set_parent_raw(objspace, Qundef, false);
5938
5939 if (objspace->flags.during_global_gc) {
5940 /* Pin the finalizer tables of every objspace, zombies included.
5941 * (finalizer_table is a macro over the local "objspace".) */
5942 rb_objspace_t *const driver = objspace;
5943 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
5944 rb_objspace_t *objspace = global_objspace->global_gc.objspaces[i];
5945 if (finalizer_table != NULL) {
5946 st_foreach(finalizer_table, pin_value, (st_data_t)driver);
5947 }
5948 }
5949 }
5950 else if (finalizer_table != NULL) {
5951 st_foreach(finalizer_table, pin_value, (st_data_t)objspace);
5952 }
5953
5954 if (stress_to_class) rb_gc_mark(stress_to_class);
5955
5956 rb_gc_save_machine_context();
5957 rb_gc_mark_roots(objspace, categoryp);
5958 gc_mark_set_parent_invalid(objspace);
5959}
5960
5961static void
5962gc_mark_children(rb_objspace_t *objspace, VALUE obj)
5963{
5964 gc_mark_set_parent(objspace, obj);
5965 rb_gc_mark_children(objspace, obj);
5966 gc_mark_set_parent_invalid(objspace);
5967}
5968
5973static inline int
5974gc_mark_stacked_objects(rb_objspace_t *objspace, int incremental, size_t count)
5975{
5976 mark_stack_t *mstack = &objspace->mark_stack;
5977 VALUE obj;
5978 size_t marked_slots_at_the_beginning = objspace->marked_slots;
5979 size_t popped_count = 0;
5980
5981 while (pop_mark_stack(mstack, &obj)) {
5982 if (obj == Qundef) continue; /* skip */
5983
5984 if (RGENGC_CHECK_MODE && !RVALUE_MARKED(objspace, obj)) {
5985 rb_bug("gc_mark_stacked_objects: %s is not marked.", rb_obj_info(obj));
5986 }
5987 gc_mark_children(objspace, obj);
5988
5989 popped_count++;
5990
5991 if (incremental) {
5992 if (RGENGC_CHECK_MODE && !RVALUE_MARKING(objspace, obj)) {
5993 rb_bug("gc_mark_stacked_objects: incremental, but marking bit is 0");
5994 }
5995 CLEAR_IN_BITMAP(GET_HEAP_MARKING_BITS(obj), obj);
5996
5997 if (popped_count + (objspace->marked_slots - marked_slots_at_the_beginning) > count) {
5998 break;
5999 }
6000 }
6001 else {
6002 /* just ignore marking bits */
6003 }
6004 }
6005
6006 RUBY_DTRACE_GC_HOOK(MARK_STACKED_OBJECTS, popped_count);
6007
6008 if (RGENGC_CHECK_MODE >= 3) gc_verify_internal_consistency(objspace);
6009
6010 if (is_mark_stack_empty(mstack)) {
6011 shrink_stack_chunk_cache(mstack);
6012 return TRUE;
6013 }
6014 else {
6015 return FALSE;
6016 }
6017}
6018
6019static int
6020gc_mark_stacked_objects_incremental(rb_objspace_t *objspace, size_t count)
6021{
6022 return gc_mark_stacked_objects(objspace, TRUE, count);
6023}
6024
6025static int
6026gc_mark_stacked_objects_all(rb_objspace_t *objspace)
6027{
6028 return gc_mark_stacked_objects(objspace, FALSE, 0);
6029}
6030
6031#if RGENGC_CHECK_MODE >= 4
6032
6033#define MAKE_ROOTSIG(obj) (((VALUE)(obj) << 1) | 0x01)
6034#define IS_ROOTSIG(obj) ((VALUE)(obj) & 0x01)
6035#define GET_ROOTSIG(obj) ((const char *)((VALUE)(obj) >> 1))
6036
6037struct reflist {
6038 VALUE *list;
6039 int pos;
6040 int size;
6041};
6042
6043static struct reflist *
6044reflist_create(VALUE obj)
6045{
6046 struct reflist *refs = xmalloc(sizeof(struct reflist));
6047 refs->size = 1;
6048 refs->list = ALLOC_N(VALUE, refs->size);
6049 refs->list[0] = obj;
6050 refs->pos = 1;
6051 return refs;
6052}
6053
6054static void
6055reflist_destruct(struct reflist *refs)
6056{
6057 xfree(refs->list);
6058 xfree(refs);
6059}
6060
6061static void
6062reflist_add(struct reflist *refs, VALUE obj)
6063{
6064 if (refs->pos == refs->size) {
6065 refs->size *= 2;
6066 SIZED_REALLOC_N(refs->list, VALUE, refs->size, refs->size/2);
6067 }
6068
6069 refs->list[refs->pos++] = obj;
6070}
6071
6072static void
6073reflist_dump(struct reflist *refs)
6074{
6075 int i;
6076 for (i=0; i<refs->pos; i++) {
6077 VALUE obj = refs->list[i];
6078 if (IS_ROOTSIG(obj)) { /* root */
6079 fprintf(stderr, "<root@%s>", GET_ROOTSIG(obj));
6080 }
6081 else {
6082 fprintf(stderr, "<%s>", rb_obj_info(obj));
6083 }
6084 if (i+1 < refs->pos) fprintf(stderr, ", ");
6085 }
6086}
6087
6088static int
6089reflist_referred_from_machine_context(struct reflist *refs)
6090{
6091 int i;
6092 for (i=0; i<refs->pos; i++) {
6093 VALUE obj = refs->list[i];
6094 if (IS_ROOTSIG(obj) && strcmp(GET_ROOTSIG(obj), "machine_context") == 0) return 1;
6095 }
6096 return 0;
6097}
6098
6099struct allrefs {
6101 /* a -> obj1
6102 * b -> obj1
6103 * c -> obj1
6104 * c -> obj2
6105 * d -> obj3
6106 * #=> {obj1 => [a, b, c], obj2 => [c, d]}
6107 */
6108 struct st_table *references;
6109 const char *category;
6110 VALUE root_obj;
6112};
6113
6114static int
6115allrefs_add(struct allrefs *data, VALUE obj)
6116{
6117 struct reflist *refs;
6118 st_data_t r;
6119
6120 if (st_lookup(data->references, obj, &r)) {
6121 refs = (struct reflist *)r;
6122 reflist_add(refs, data->root_obj);
6123 return 0;
6124 }
6125 else {
6126 refs = reflist_create(data->root_obj);
6127 st_insert(data->references, obj, (st_data_t)refs);
6128 return 1;
6129 }
6130}
6131
6132static void
6133allrefs_i(VALUE obj, void *ptr)
6134{
6135 struct allrefs *data = (struct allrefs *)ptr;
6136
6137 if (allrefs_add(data, obj)) {
6138 push_mark_stack(&data->mark_stack, obj);
6139 }
6140}
6141
6142static void
6143allrefs_roots_i(VALUE obj, void *ptr)
6144{
6145 struct allrefs *data = (struct allrefs *)ptr;
6146 if (strlen(data->category) == 0) rb_bug("!!!");
6147 data->root_obj = MAKE_ROOTSIG(data->category);
6148
6149 if (allrefs_add(data, obj)) {
6150 push_mark_stack(&data->mark_stack, obj);
6151 }
6152}
6153#define PUSH_MARK_FUNC_DATA(v) do { \
6154 struct gc_mark_func_data_struct *prev_mark_func_data = GET_VM()->gc.mark_func_data; \
6155 GET_VM()->gc.mark_func_data = (v);
6156
6157#define POP_MARK_FUNC_DATA() GET_VM()->gc.mark_func_data = prev_mark_func_data;} while (0)
6158
6159static st_table *
6160objspace_allrefs(rb_objspace_t *objspace)
6161{
6162 struct allrefs data;
6163 struct gc_mark_func_data_struct mfd;
6164 VALUE obj;
6165 int prev_dont_gc = dont_gc_val();
6166 dont_gc_on();
6167
6168 data.objspace = objspace;
6169 data.references = st_init_numtable();
6170 init_mark_stack(&data.mark_stack);
6171
6172 mfd.mark_func = allrefs_roots_i;
6173 mfd.data = &data;
6174
6175 /* traverse root objects */
6176 PUSH_MARK_FUNC_DATA(&mfd);
6177 GET_VM()->gc.mark_func_data = &mfd;
6178 mark_roots(objspace, &data.category);
6179 POP_MARK_FUNC_DATA();
6180
6181 /* traverse rest objects reachable from root objects */
6182 while (pop_mark_stack(&data.mark_stack, &obj)) {
6183 rb_objspace_reachable_objects_from(data.root_obj = obj, allrefs_i, &data);
6184 }
6185 free_stack_chunks(&data.mark_stack);
6186
6187 dont_gc_set(prev_dont_gc);
6188 return data.references;
6189}
6190
6191static int
6192objspace_allrefs_destruct_i(st_data_t key, st_data_t value, st_data_t ptr)
6193{
6194 struct reflist *refs = (struct reflist *)value;
6195 reflist_destruct(refs);
6196 return ST_CONTINUE;
6197}
6198
6199static void
6200objspace_allrefs_destruct(struct st_table *refs)
6201{
6202 st_foreach(refs, objspace_allrefs_destruct_i, 0);
6203 st_free_table(refs);
6204}
6205
6206#if RGENGC_CHECK_MODE >= 5
6207static int
6208allrefs_dump_i(st_data_t k, st_data_t v, st_data_t ptr)
6209{
6210 VALUE obj = (VALUE)k;
6211 struct reflist *refs = (struct reflist *)v;
6212 fprintf(stderr, "[allrefs_dump_i] %s <- ", rb_obj_info(obj));
6213 reflist_dump(refs);
6214 fprintf(stderr, "\n");
6215 return ST_CONTINUE;
6216}
6217
6218static void
6219allrefs_dump(rb_objspace_t *objspace)
6220{
6221 VALUE size = objspace->rgengc.allrefs_table->num_entries;
6222 fprintf(stderr, "[all refs] (size: %"PRIuVALUE")\n", size);
6223 st_foreach(objspace->rgengc.allrefs_table, allrefs_dump_i, 0);
6224}
6225#endif
6226
6227static int
6228gc_check_after_marks_i(st_data_t k, st_data_t v, st_data_t ptr)
6229{
6230 VALUE obj = k;
6231 struct reflist *refs = (struct reflist *)v;
6233
6234 /* object should be marked or oldgen */
6235 if (!RVALUE_MARKED(objspace, obj)) {
6236 fprintf(stderr, "gc_check_after_marks_i: %s is not marked and not oldgen.\n", rb_obj_info(obj));
6237 fprintf(stderr, "gc_check_after_marks_i: %p is referred from ", (void *)obj);
6238 reflist_dump(refs);
6239
6240 if (reflist_referred_from_machine_context(refs)) {
6241 fprintf(stderr, " (marked from machine stack).\n");
6242 /* marked from machine context can be false positive */
6243 }
6244 else {
6245 objspace->rgengc.error_count++;
6246 fprintf(stderr, "\n");
6247 }
6248 }
6249 return ST_CONTINUE;
6250}
6251
6252static void
6253gc_marks_check(rb_objspace_t *objspace, st_foreach_callback_func *checker_func, const char *checker_name)
6254{
6255 MALLOC_COUNTERS_LOCK(objspace);
6256 struct gc_malloc_bytes saved_malloc = {
6257 .malloc = gc_counter_load_relaxed(&objspace->malloc_counters.counters.malloc),
6258 .free = gc_counter_load_relaxed(&objspace->malloc_counters.counters.free),
6259 .malloc_at_last_gc = gc_counter_load_relaxed(&objspace->malloc_counters.counters.malloc_at_last_gc),
6260 .free_at_last_gc = gc_counter_load_relaxed(&objspace->malloc_counters.counters.free_at_last_gc),
6261 };
6262#if RGENGC_ESTIMATE_OLDMALLOC
6263 struct gc_malloc_bytes saved_oldmalloc = {
6264 .malloc = gc_counter_load_relaxed(&objspace->malloc_counters.oldcounters.malloc),
6265 .free = gc_counter_load_relaxed(&objspace->malloc_counters.oldcounters.free),
6266 .malloc_at_last_gc = gc_counter_load_relaxed(&objspace->malloc_counters.oldcounters.malloc_at_last_gc),
6267 .free_at_last_gc = gc_counter_load_relaxed(&objspace->malloc_counters.oldcounters.free_at_last_gc),
6268 };
6269#endif
6270 MALLOC_COUNTERS_UNLOCK(objspace);
6271 VALUE already_disabled = rb_objspace_gc_disable(objspace);
6272
6273 objspace->rgengc.allrefs_table = objspace_allrefs(objspace);
6274
6275 if (checker_func) {
6276 st_foreach(objspace->rgengc.allrefs_table, checker_func, (st_data_t)objspace);
6277 }
6278
6279 if (objspace->rgengc.error_count > 0) {
6280#if RGENGC_CHECK_MODE >= 5
6281 allrefs_dump(objspace);
6282#endif
6283 if (checker_name) rb_bug("%s: GC has problem.", checker_name);
6284 }
6285
6286 objspace_allrefs_destruct(objspace->rgengc.allrefs_table);
6287 objspace->rgengc.allrefs_table = 0;
6288
6289 if (already_disabled == Qfalse) rb_objspace_gc_enable(objspace);
6290 MALLOC_COUNTERS_LOCK(objspace);
6291 gc_counter_store_release(&objspace->malloc_counters.counters.malloc, saved_malloc.malloc);
6292 gc_counter_store_release(&objspace->malloc_counters.counters.free, saved_malloc.free);
6293 gc_counter_store_release(&objspace->malloc_counters.counters.malloc_at_last_gc, saved_malloc.malloc_at_last_gc);
6294 gc_counter_store_release(&objspace->malloc_counters.counters.free_at_last_gc, saved_malloc.free_at_last_gc);
6295#if RGENGC_ESTIMATE_OLDMALLOC
6296 gc_counter_store_release(&objspace->malloc_counters.oldcounters.malloc, saved_oldmalloc.malloc);
6297 gc_counter_store_release(&objspace->malloc_counters.oldcounters.free, saved_oldmalloc.free);
6298 gc_counter_store_release(&objspace->malloc_counters.oldcounters.malloc_at_last_gc, saved_oldmalloc.malloc_at_last_gc);
6299 gc_counter_store_release(&objspace->malloc_counters.oldcounters.free_at_last_gc, saved_oldmalloc.free_at_last_gc);
6300#endif
6301 MALLOC_COUNTERS_UNLOCK(objspace);
6302}
6303#endif /* RGENGC_CHECK_MODE >= 4 */
6304
6307 /* True only while the world is stopped: a GC.verify holding the VM lock and barrier,
6308 * or a global GC. Cross-objspace checks (walking every objspace's pages) are sound
6309 * only then. */
6310 bool world_stopped;
6311 int err_count;
6312 size_t live_object_count;
6313 size_t zombie_object_count;
6314
6315 VALUE parent;
6316 bool parent_shareable;
6317 size_t old_object_count;
6318 size_t remembered_shady_count;
6319};
6320
6321
6322static void
6323check_generation_i(const VALUE child, void *ptr)
6324{
6326 const VALUE parent = data->parent;
6327
6328 if (RGENGC_CHECK_MODE) GC_ASSERT(RVALUE_OLD_P(data->objspace, parent));
6329
6330 /* A cross-objspace edge is kept alive by the shareable/shref mechanism and is not
6331 * tracked in this objspace's remembered set. */
6332 if (GET_HEAP_OBJSPACE(child) != data->objspace) return;
6333
6334 /* Once the process goes multi-Ractor, the shareable world is managed by pinning and
6335 * shrefs rather than by the remembered set: the pinned walk at the end of a mark
6336 * re-marks every shareable object (and its shref'd children) each local cycle, and a
6337 * global GC rebuilds the generation state. So the generational old->young invariant
6338 * does not hold when either endpoint is shareable: an old constcache, cc_table or
6339 * interned string pointing at a core class that is young after a global GC is the
6340 * typical false positive. That state outlives the return to a single Ractor until
6341 * the next major (an old shareable singleton class pointing at a young
6342 * attached_object, say), so the test uses rb_gc_ever_multi_ractor_p(), which stays
6343 * true forever once multiple Ractors existed. A program that never goes multi keeps
6344 * the strict check, and ASAN catches what is left. */
6345 if (rb_gc_ever_multi_ractor_p() &&
6346 (MARKED_IN_BITMAP(GET_HEAP_SHAREABLE_BITS(parent), parent) ||
6347 MARKED_IN_BITMAP(GET_HEAP_SHAREABLE_BITS(child), child))) {
6348 return;
6349 }
6350
6351 if (!RVALUE_OLD_P(data->objspace, child)) {
6352 /* A young shareable child is pinned and kept alive by the local GC (only a
6353 * global GC collects it), so it survives even when the old parent does not
6354 * remember it. It is outside the generational remembered set, so exclude it
6355 * from the old->young check. */
6356 if (!RVALUE_REMEMBERED(data->objspace, parent) &&
6357 !RVALUE_REMEMBERED(data->objspace, child) &&
6358 !RVALUE_UNCOLLECTIBLE(data->objspace, child) &&
6360 fprintf(stderr, "verify_internal_consistency_reachable_i: WB miss (O->Y) %s -> %s\n", rb_obj_info(parent), rb_obj_info(child));
6361 data->err_count++;
6362 }
6363 }
6364}
6365
6366static void
6367check_color_i(const VALUE child, void *ptr)
6368{
6370 const VALUE parent = data->parent;
6371
6372 if (!RVALUE_WB_UNPROTECTED(data->objspace, parent) && RVALUE_WHITE_P(data->objspace, child)) {
6373 fprintf(stderr, "verify_internal_consistency_reachable_i: WB miss (B->W) - %s -> %s\n",
6374 rb_obj_info(parent), rb_obj_info(child));
6375 data->err_count++;
6376 }
6377}
6378
6379static void
6380check_children_i(const VALUE child, void *ptr)
6381{
6383
6384 /* Fast path: a child in this objspace (99.99% of all edges). */
6385 if (RB_LIKELY(is_pointer_to_heap(data->objspace, (void *)child))) {
6386 if (check_rvalue_consistency_force(data->objspace, child, FALSE) != 0) {
6387 fprintf(stderr, "check_children_i: %s has error (referenced from %s)\n",
6388 rb_obj_info(child), rb_obj_info(data->parent));
6389 data->err_count++;
6390 }
6391 return;
6392 }
6393
6394 /* The remaining cross-objspace check (verify_pointer_in_any_heap_p) walks every
6395 * objspace's pages, sound only with the world stopped: mid-local-GC other Ractors
6396 * change page structures concurrently. The next world-stopped verify re-checks. */
6397 if (!data->world_stopped) return;
6398
6399 /* A non-heap child reaches this callback only when a stale field was followed by a
6400 * plain rb_gc_mark (the dmark of a live but unreachable wrapper, say). Report it and
6401 * keep going rather than aborting. */
6402 if (!verify_pointer_in_any_heap_p((void *)child)) {
6403 /* The graph is in flux mid-merge, so a transient non-heap edge is expected; it
6404 * is re-checked after the merge. */
6405 if (global_objspace->during_absorb) return;
6406 fprintf(stderr, "VERIFY-NOTE: non-heap child %p (from %s)\n",
6407 (void *)child, rb_obj_info(data->parent));
6408 return;
6409 }
6410
6411 if (GET_HEAP_OBJSPACE(child) != data->objspace) {
6412 /* A legal cross-objspace edge either starts at a shareable object or is recorded
6413 * in the child's shref bit (an in-flight send or move payload kept alive across
6414 * its owner's local GC; root_scope_check_i honours the same record). An
6415 * unshareable parent holding an unrecorded foreign unshareable child would be
6416 * invisible to both local GCs. The exception is a box's top_self, which every
6417 * thread's th->top_self points at and which is VM-permanent. Skipped during a
6418 * global GC: it clears every shref bit and keeps in-flight payloads alive by
6419 * re-pinning, so the shref exemption would not fire, and its unified exact
6420 * stop-the-world mark makes the invariant itself moot. */
6421 if (!data->parent_shareable &&
6422 child != rb_gc_vm_top_self() &&
6423 !MARKED_IN_BITMAP(GET_HEAP_SHAREABLE_BITS(child), child) &&
6424 !MARKED_IN_BITMAP(GET_HEAP_SHREF_BITS(child), child) &&
6425 !rb_gc_impl_during_global_gc_p(data->objspace) &&
6426 !rb_gc_current_ractor_materializing_p() &&
6427 !global_objspace->during_absorb) {
6428 fprintf(stderr, "check_children_i: containment violation: "
6429 "unshareable %s (objspace %p) -> foreign unshareable %s (objspace %p)\n",
6430 rb_obj_info(data->parent), (void *)data->objspace,
6431 rb_obj_info(child), (void *)GET_HEAP_OBJSPACE(child));
6432 data->err_count++;
6433 }
6434
6435 /* The remaining per-objspace sanity rules belong to the owner. */
6436 return;
6437 }
6438}
6439
6440/* Whether a heap slot currently holds a live object. Returns false for empty
6441 * (T_NONE), moved (T_MOVED), and zombie (T_ZOMBIE) slots, and for garbage
6442 * objects about to be swept. */
6443static bool
6444gc_slot_live_object_p(rb_objspace_t *objspace, VALUE obj)
6445{
6446 switch (BUILTIN_TYPE(obj)) {
6447 case T_NONE:
6448 case T_MOVED:
6449 case T_ZOMBIE:
6450 return false;
6451 default:
6452 return !rb_gc_impl_garbage_object_p(objspace, obj);
6453 }
6454}
6455
6456/* Verifier only: does ptr point at a live slot in any objspace? The caller holds the VM
6457 * lock and the barrier, so page_index is stable. */
6458static bool
6459verify_pointer_in_any_heap_p(const void *ptr)
6460{
6461 return gc_global_pointer_to_heap_p(ptr);
6462}
6463
6464/* An exact root of the calling Ractor may only point at a shareable object, its own
6465 * objspace, or an in-flight payload with a recorded shref. Exempt: the conservative
6466 * machine scan (stale slots) and the VM-global containers that are cross-rooted by
6467 * design (every objspace scans them; the marker skips foreign entries). */
6468static void
6469root_scope_check_i(const char *category, VALUE obj, void *ptr)
6470{
6471 struct verify_internal_consistency_struct *data = ptr;
6472
6473 if (RB_SPECIAL_CONST_P(obj)) return;
6474 /* This check walks every objspace (verify_pointer_in_any_heap_p), so it is sound
6475 * only with the world stopped; a mid-local-GC verify races with other Ractors'
6476 * lock-free allocation. */
6477 if (!data->world_stopped) return;
6478 /* Mid-merge the VM-global root tables still point at the unmerged source (transient
6479 * non-heap or foreign roots); re-checked after the merge. */
6480 if (global_objspace->during_absorb) return;
6481 if (strcmp(category, "machine_context") == 0 ||
6482 strcmp(category, "vm_registered_objects") == 0 ||
6483 strcmp(category, "end_proc") == 0 ||
6484 strcmp(category, "trap_list") == 0 ||
6485 /* Every Ractor's root scan walks the one VM-wide registered-globals list (a slot
6486 * can hold another objspace's value); rb_gc_mark_maybe filters to its own
6487 * objspace, so a foreign entry here is by design, not a leak. */
6488 strcmp(category, "registered_globals") == 0) {
6489 return;
6490 }
6491
6492 if (!verify_pointer_in_any_heap_p((void *)obj)) {
6493 fprintf(stderr, "root_scope_check_i: root category \"%s\" names a non-heap pointer %p\n",
6494 category, (void *)obj);
6495 data->err_count++;
6496 return;
6497 }
6498
6499 if (GET_HEAP_OBJSPACE(obj) == data->objspace) return;
6500 if (MARKED_IN_BITMAP(GET_HEAP_SHAREABLE_BITS(obj), obj)) return;
6501 if (MARKED_IN_BITMAP(GET_HEAP_SHREF_BITS(obj), obj)) return;
6502 if (obj == rb_gc_vm_top_self()) return; /* VM-permanent (see check_children_i) */
6503 /* A sender-resident snapshot being materialized by a receive is rooted through
6504 * sync.materializing_copies: a foreign-unshareable root that is valid only while
6505 * the copy runs (see check_children_i). */
6506 if (rb_gc_current_ractor_materializing_p()) return;
6507
6508 fprintf(stderr, "root_scope_check_i: root category \"%s\" names a foreign "
6509 "unshareable without a shref record: %s (owner %p, self %p)\n",
6510 category, rb_obj_info(obj),
6511 (void *)GET_HEAP_OBJSPACE(obj), (void *)data->objspace);
6512 data->err_count++;
6513}
6514
6515static int
6516verify_internal_consistency_i(void *page_start, void *page_end, size_t stride,
6518{
6519 VALUE obj;
6520 rb_objspace_t *objspace = data->objspace;
6521
6522 for (obj = (VALUE)page_start; obj != (VALUE)page_end; obj += stride) {
6523 asan_unpoisoning_object(obj) {
6524 bool sh_bit = MARKED_IN_BITMAP(GET_HEAP_SHAREABLE_BITS(obj), obj) != 0;
6525 bool sr_bit = MARKED_IN_BITMAP(GET_HEAP_SHREF_BITS(obj), obj) != 0;
6526
6527 if (gc_slot_live_object_p(objspace, obj)) {
6528 /* count objects */
6529 data->live_object_count++;
6530 data->parent = obj;
6531 data->parent_shareable = sh_bit;
6532
6533 /* Bitmap invariants: a page's shareable bit matches FL_SHAREABLE
6534 * exactly, and a shref record only ever points at an unshareable
6535 * object. */
6536 if (sh_bit != !!RB_FL_TEST_RAW(obj, RUBY_FL_SHAREABLE)) {
6537 fprintf(stderr, "verify_internal_consistency_i: shareable bit %d "
6538 "disagrees with FL_SHAREABLE on %s\n", (int)sh_bit, rb_obj_info(obj));
6539 data->err_count++;
6540 }
6541 if (sr_bit && sh_bit) {
6542 fprintf(stderr, "verify_internal_consistency_i: shref bit on a shareable: %s\n",
6543 rb_obj_info(obj));
6544 data->err_count++;
6545 }
6546
6547 /* Normally, we don't expect T_MOVED objects to be in the heap.
6548 * But they can stay alive on the stack, */
6549 if (!gc_object_moved_p(objspace, obj)) {
6550 /* moved slots don't have children */
6551 rb_objspace_reachable_objects_from(obj, check_children_i, (void *)data);
6552 }
6553
6554 /* check health of children */
6555 if (RVALUE_OLD_P(objspace, obj)) data->old_object_count++;
6556 if (RVALUE_WB_UNPROTECTED(objspace, obj) && RVALUE_UNCOLLECTIBLE(objspace, obj)) data->remembered_shady_count++;
6557
6558 if (!is_marking(objspace) && RVALUE_OLD_P(objspace, obj)) {
6559 /* reachable objects from an oldgen object should be old or (young with remember) */
6560 data->parent = obj;
6561 rb_objspace_reachable_objects_from(obj, check_generation_i, (void *)data);
6562 }
6563
6564 if (!is_marking(objspace) && rb_gc_obj_shareable_p(obj)) {
6565 rb_gc_verify_shareable(obj);
6566 }
6567
6568 if (is_incremental_marking(objspace)) {
6569 if (RVALUE_BLACK_P(objspace, obj)) {
6570 /* reachable objects from black objects should be black or grey objects */
6571 data->parent = obj;
6572 rb_objspace_reachable_objects_from(obj, check_color_i, (void *)data);
6573 }
6574 }
6575 }
6576 else {
6577 /* A freed slot must not carry its old pin bit into the next object born
6578 * there (a dead object not swept yet legitimately keeps it until the
6579 * sweep arrives). */
6580 if (BUILTIN_TYPE(obj) == T_NONE && (sh_bit || sr_bit)) {
6581 fprintf(stderr, "verify_internal_consistency_i: T_NONE slot carries "
6582 "shareable=%d shref=%d bits\n", (int)sh_bit, (int)sr_bit);
6583 data->err_count++;
6584 }
6585
6586 if (BUILTIN_TYPE(obj) == T_ZOMBIE) {
6587 data->zombie_object_count++;
6588
6589 if ((RBASIC(obj)->flags & ~ZOMBIE_OBJ_KEPT_FLAGS) != T_ZOMBIE) {
6590 fprintf(stderr, "verify_internal_consistency_i: T_ZOMBIE has extra flags set: %s\n",
6591 rb_obj_info(obj));
6592 data->err_count++;
6593 }
6594
6595 if (!!FL_TEST(obj, FL_FINALIZE) != !!st_is_member(finalizer_table, obj)) {
6596 fprintf(stderr, "verify_internal_consistency_i: FL_FINALIZE %s but %s finalizer_table: %s\n",
6597 FL_TEST(obj, FL_FINALIZE) ? "set" : "not set", st_is_member(finalizer_table, obj) ? "in" : "not in",
6598 rb_obj_info(obj));
6599 data->err_count++;
6600 }
6601 }
6602 }
6603 }
6604 }
6605
6606 return 0;
6607}
6608
6609static int
6610gc_verify_heap_page(rb_objspace_t *objspace, struct heap_page *page, VALUE obj)
6611{
6612 unsigned int has_remembered_shady = FALSE;
6613 unsigned int has_remembered_old = FALSE;
6614 int remembered_old_objects = 0;
6615 int free_objects = 0;
6616 int zombie_objects = 0;
6617
6618 short slot_size = page->slot_size;
6619 uintptr_t start = (uintptr_t)page->start;
6620 uintptr_t end = start + page->total_slots * slot_size;
6621
6622 for (uintptr_t ptr = start; ptr < end; ptr += slot_size) {
6623 VALUE val = (VALUE)ptr;
6624 asan_unpoisoning_object(val) {
6625 enum ruby_value_type type = BUILTIN_TYPE(val);
6626
6627 if (type == T_NONE) free_objects++;
6628 if (type == T_ZOMBIE) zombie_objects++;
6629 if (RVALUE_PAGE_UNCOLLECTIBLE(page, val) && RVALUE_PAGE_WB_UNPROTECTED(page, val)) {
6630 has_remembered_shady = TRUE;
6631 }
6632 if (RVALUE_PAGE_MARKING(page, val)) {
6633 has_remembered_old = TRUE;
6634 remembered_old_objects++;
6635 }
6636 }
6637 }
6638
6639 if (!is_incremental_marking(objspace) &&
6640 page->flags.has_remembered_objects == FALSE && has_remembered_old == TRUE) {
6641
6642 for (uintptr_t ptr = start; ptr < end; ptr += slot_size) {
6643 VALUE val = (VALUE)ptr;
6644 if (RVALUE_PAGE_MARKING(page, val)) {
6645 fprintf(stderr, "marking -> %s\n", rb_obj_info(val));
6646 }
6647 }
6648 rb_bug("page %p's has_remembered_objects should be false, but there are remembered old objects (%d). %s",
6649 (void *)page, remembered_old_objects, obj ? rb_obj_info(obj) : "");
6650 }
6651
6652 if (page->flags.has_uncollectible_wb_unprotected_objects == FALSE && has_remembered_shady == TRUE) {
6653 rb_bug("page %p's has_remembered_shady should be false, but there are remembered shady objects. %s",
6654 (void *)page, obj ? rb_obj_info(obj) : "");
6655 }
6656
6657 if (0) {
6658 /* free_slots may not equal to free_objects */
6659 if (page->free_slots != free_objects) {
6660 rb_bug("page %p's free_slots should be %d, but %d", (void *)page, page->free_slots, free_objects);
6661 }
6662 }
6663 if (page->final_slots != zombie_objects) {
6664 rb_bug("page %p's final_slots should be %d, but %d", (void *)page, page->final_slots, zombie_objects);
6665 }
6666
6667 return remembered_old_objects;
6668}
6669
6670static int
6671gc_verify_heap_pages_(rb_objspace_t *objspace, struct ccan_list_head *head)
6672{
6673 int remembered_old_objects = 0;
6674 struct heap_page *page = 0;
6675
6676 ccan_list_for_each(head, page, page_node) {
6677 asan_unlock_freelist(page);
6678 struct free_region *region = page->free_region;
6679 while (region) {
6680 VALUE vp = (VALUE)region;
6681 rb_asan_unpoison_object(vp, false);
6682 if (BUILTIN_TYPE(vp) != T_NONE) {
6683 fprintf(stderr, "free region head expected to be T_NONE but was: %s\n", rb_obj_info(vp));
6684 }
6685 struct free_region *next = region->next;
6686 rb_asan_poison_object(vp);
6687 region = next;
6688 }
6689 asan_lock_freelist(page);
6690
6691 if (page->flags.has_remembered_objects == FALSE) {
6692 remembered_old_objects += gc_verify_heap_page(objspace, page, Qfalse);
6693 }
6694 }
6695
6696 return remembered_old_objects;
6697}
6698
6699static int
6700gc_verify_heap_pages(rb_objspace_t *objspace)
6701{
6702 int remembered_old_objects = 0;
6703 for (int i = 0; i < HEAP_COUNT; i++) {
6704 remembered_old_objects += gc_verify_heap_pages_(objspace, &((&heaps[i])->pages));
6705 }
6706 return remembered_old_objects;
6707}
6708
6709static void
6710gc_verify_internal_consistency_(rb_objspace_t *objspace, bool world_stopped)
6711{
6712 struct verify_internal_consistency_struct data = {0};
6713
6714 data.objspace = objspace;
6715 data.world_stopped = world_stopped;
6716 gc_report(5, objspace, "gc_verify_internal_consistency: start\n");
6717
6718 /* check relations */
6719 for (size_t i = 0; i < rb_darray_size(objspace->heap_pages.sorted); i++) {
6720 struct heap_page *page = rb_darray_get(objspace->heap_pages.sorted, i);
6721 short slot_size = page->slot_size;
6722
6723 uintptr_t start = (uintptr_t)page->start;
6724 uintptr_t end = start + page->total_slots * slot_size;
6725
6726 verify_internal_consistency_i((void *)start, (void *)end, slot_size, &data);
6727 }
6728
6729 /* Check the calling Ractor's root scoping (only when verifying the current
6730 * objspace). Skipped during a global GC, which deliberately spans every Ractor's
6731 * roots and legitimately reaches foreign objects: containment does not apply. */
6732 if (!rb_gc_single_objspace_p() && objspace == rb_gc_get_objspace() &&
6733 !rb_gc_impl_during_global_gc_p(objspace)) {
6734 rb_objspace_reachable_objects_from_root(root_scope_check_i, &data);
6735 }
6736
6737 if (data.err_count != 0) {
6738#if RGENGC_CHECK_MODE >= 5
6739 objspace->rgengc.error_count = data.err_count;
6740 gc_marks_check(objspace, NULL, NULL);
6741 allrefs_dump(objspace);
6742#endif
6743 rb_bug("gc_verify_internal_consistency: found internal inconsistency.");
6744 }
6745
6746 /* check heap_page status */
6747 gc_verify_heap_pages(objspace);
6748
6749 /* check counters */
6750
6751 if (!is_lazy_sweeping(objspace) &&
6752 !finalizing &&
6753 !rb_gc_multi_ractor_p()) {
6754 if (objspace_live_slots(objspace) != data.live_object_count) {
6755 fprintf(stderr, "heap_pages_final_slots: %"PRIdSIZE", total_freed_objects: %"PRIdSIZE"\n",
6756 total_final_slots_count(objspace), total_freed_objects(objspace));
6757 rb_bug("inconsistent live slot number: expect %"PRIuSIZE", but %"PRIuSIZE".",
6758 objspace_live_slots(objspace), data.live_object_count);
6759 }
6760 }
6761
6762 if (!is_marking(objspace)) {
6763 if (objspace->rgengc.old_objects != data.old_object_count) {
6764 rb_bug("inconsistent old slot number: expect %"PRIuSIZE", but %"PRIuSIZE".",
6765 objspace->rgengc.old_objects, data.old_object_count);
6766 }
6767 if (objspace->rgengc.uncollectible_wb_unprotected_objects != data.remembered_shady_count) {
6768 rb_bug("inconsistent number of wb unprotected objects: expect %"PRIuSIZE", but %"PRIuSIZE".",
6769 objspace->rgengc.uncollectible_wb_unprotected_objects, data.remembered_shady_count);
6770 }
6771 }
6772
6773 if (!finalizing) {
6774 size_t list_count = 0;
6775
6776 {
6777 VALUE z = heap_pages_deferred_final;
6778 while (z) {
6779 list_count++;
6780 z = RZOMBIE(z)->next;
6781 }
6782 }
6783
6784 if (total_final_slots_count(objspace) != data.zombie_object_count ||
6785 total_final_slots_count(objspace) != list_count) {
6786
6787 rb_bug("inconsistent finalizing object count:\n"
6788 " expect %"PRIuSIZE"\n"
6789 " but %"PRIuSIZE" zombies\n"
6790 " heap_pages_deferred_final list has %"PRIuSIZE" items.",
6791 total_final_slots_count(objspace),
6792 data.zombie_object_count,
6793 list_count);
6794 }
6795 }
6796
6797 gc_report(5, objspace, "gc_verify_internal_consistency: OK\n");
6798}
6799
6800/* The `during_gc` macro expands a bare identifier to `objspace->flags.during_gc`, so a
6801 * foreign objspace's flag cannot be written directly; these helpers reach it through the
6802 * `objspace` argument. */
6803static inline unsigned int
6804gc_during_gc_get(const rb_objspace_t *objspace)
6805{
6806 return during_gc;
6807}
6808
6809static inline void
6810gc_during_gc_set(rb_objspace_t *objspace, unsigned int v)
6811{
6812 during_gc = v;
6813}
6814
6815/* Run the check with during_gc cleared in both the verified objspace and the current
6816 * Ractor's: rb_objspace_reachable_objects_from() decides on rb_gc_get_objspace(), and
6817 * under a global GC the driver verifies foreign objspaces, so the driver's during_gc
6818 * needs clearing too (a no-op when cur == objspace). */
6819static void
6820gc_verify_internal_consistency_body(rb_objspace_t *objspace, bool world_stopped)
6821{
6822 const unsigned int prev_during_gc = during_gc;
6823 during_gc = FALSE; // stop gc here
6824
6825 rb_objspace_t *const cur = rb_gc_get_objspace();
6826 const unsigned int prev_cur_during_gc = (cur != objspace) ? gc_during_gc_get(cur) : 0;
6827 if (cur != objspace) gc_during_gc_set(cur, FALSE);
6828 {
6829 gc_verify_internal_consistency_(objspace, world_stopped);
6830 }
6831 if (cur != objspace) gc_during_gc_set(cur, prev_cur_during_gc);
6832 during_gc = prev_during_gc;
6833}
6834
6835static void
6836gc_verify_internal_consistency(void *objspace_ptr)
6837{
6838 rb_objspace_t *objspace = objspace_ptr;
6839
6840 /* Called mid-GC, take neither the VM lock nor the barrier: waiting would join a
6841 * pending global barrier mid-collection (a GC must never take the VM lock) and let
6842 * the global GC sweep the heap this mark is walking. The barrier is unnecessary
6843 * anyway; the objspace is single-writer, this verify runs on its owner thread, and
6844 * the global driver that sets during_gc everywhere already holds both. */
6845 if (during_gc) {
6846 /* The world is stopped only when the global GC's driver runs this while holding
6847 * the barrier; a non-main Ractor's local GC does not stop other Ractors. */
6848 gc_verify_internal_consistency_body(objspace, rb_gc_impl_during_global_gc_p(objspace));
6849 return;
6850 }
6851
6852 unsigned int lev = RB_GC_VM_LOCK();
6853 {
6854 rb_gc_vm_barrier(); // stop other ractors
6855 gc_verify_internal_consistency_body(objspace, true); // holding the barrier, so walking every objspace is sound
6856 }
6857 RB_GC_VM_UNLOCK(lev);
6858}
6859
6860static void
6861heap_move_pooled_pages_to_free_pages(rb_heap_t *heap)
6862{
6863 if (heap->pooled_pages) {
6864 if (heap->free_pages) {
6865 struct heap_page *free_pages_tail = heap->free_pages;
6866 while (free_pages_tail->free_next) {
6867 free_pages_tail = free_pages_tail->free_next;
6868 }
6869 free_pages_tail->free_next = heap->pooled_pages;
6870 }
6871 else {
6872 heap->free_pages = heap->pooled_pages;
6873 }
6874
6875 heap->pooled_pages = NULL;
6876 }
6877}
6878
6879static int
6880gc_remember_unprotected(rb_objspace_t *objspace, VALUE obj)
6881{
6882 struct heap_page *page = GET_HEAP_PAGE(obj);
6883 bits_t *uncollectible_bits = &page->uncollectible_bits[0];
6884
6885 if (!MARKED_IN_BITMAP(uncollectible_bits, obj)) {
6886 page->flags.has_uncollectible_wb_unprotected_objects = TRUE;
6887 MARK_IN_BITMAP(uncollectible_bits, obj);
6888 /* Like RVALUE_PAGE_OLD_UNCOLLECTIBLE_SET, count it in the object's own objspace. */
6889 page->objspace->rgengc.uncollectible_wb_unprotected_objects++;
6890
6891#if RGENGC_PROFILE > 0
6892 objspace->profile.total_remembered_shady_object_count++;
6893#if RGENGC_PROFILE >= 2
6894 objspace->profile.remembered_shady_object_count_types[BUILTIN_TYPE(obj)]++;
6895#endif
6896#endif
6897 return TRUE;
6898 }
6899 else {
6900 return FALSE;
6901 }
6902}
6903
6904static inline void
6905gc_marks_wb_unprotected_objects_plane(rb_objspace_t *objspace, uintptr_t p, bits_t bits, short slot_size)
6906{
6907 if (bits) {
6908 do {
6909 if (bits & 1) {
6910 gc_report(2, objspace, "gc_marks_wb_unprotected_objects: marked shady: %s\n", rb_obj_info((VALUE)p));
6911 GC_ASSERT(RVALUE_WB_UNPROTECTED(objspace, (VALUE)p));
6912 GC_ASSERT(RVALUE_MARKED(objspace, (VALUE)p));
6913 gc_mark_children(objspace, (VALUE)p);
6914 }
6915 p += slot_size;
6916 bits >>= 1;
6917 } while (bits);
6918 }
6919}
6920
6921static void
6922gc_marks_wb_unprotected_objects(rb_objspace_t *objspace, rb_heap_t *heap)
6923{
6924 struct heap_page *page = 0;
6925
6926 ccan_list_for_each(&heap->pages, page, page_node) {
6927 bits_t *mark_bits = page->mark_bits;
6928 bits_t *wbun_bits = page->wb_unprotected_bits;
6929 uintptr_t p = page->start;
6930 short slot_size = page->slot_size;
6931 int total_slots = page->total_slots;
6932 int bitmap_plane_count = CEILDIV(total_slots, BITS_BITLENGTH);
6933 size_t j;
6934
6935 for (j=0; j<(size_t)bitmap_plane_count; j++) {
6936 bits_t bits = mark_bits[j] & wbun_bits[j];
6937 gc_marks_wb_unprotected_objects_plane(objspace, p, bits, slot_size);
6938 p += BITS_BITLENGTH * slot_size;
6939 }
6940 }
6941
6942 gc_mark_stacked_objects_all(objspace);
6943}
6944
6945void
6946rb_gc_impl_declare_weak_references(void *objspace_ptr, VALUE obj)
6947{
6949}
6950
6951bool
6952rb_gc_impl_handle_weak_references_alive_p(void *objspace_ptr, VALUE obj)
6953{
6954 rb_objspace_t *objspace = objspace_ptr;
6955
6956 /* A local GC cannot decide a foreign object's liveness, so treat it as live; its
6957 * owner or the global GC decides (a global GC's unified mark is exact). */
6958 if (gc_skip_foreign_object_p(objspace, obj)) return true;
6959
6960 bool marked = RVALUE_MARKED(objspace, obj);
6961
6962 if (marked) {
6963 rgengc_check_relation(objspace, obj);
6964 }
6965
6966 return marked;
6967}
6968
6969static void
6970gc_update_weak_references(rb_objspace_t *objspace)
6971{
6972 VALUE *obj_ptr;
6973 rb_darray_foreach(objspace->weak_references, i, obj_ptr) {
6974 gc_mark_set_parent(objspace, *obj_ptr);
6975 rb_gc_handle_weak_references(*obj_ptr);
6976 gc_mark_set_parent_invalid(objspace);
6977 }
6978
6979 size_t capa = rb_darray_capa(objspace->weak_references);
6980 size_t size = rb_darray_size(objspace->weak_references);
6981
6982 objspace->profile.weak_references_count = size;
6983
6984 rb_darray_clear(objspace->weak_references);
6985
6986 /* If the darray has capacity for more than four times the amount used, we
6987 * shrink it down to half of that capacity. */
6988 if (capa > size * 4) {
6989 rb_darray_resize_capa_without_gc(&objspace->weak_references, size * 2);
6990 }
6991}
6992
6993static void
6994gc_marks_finish(rb_objspace_t *objspace)
6995{
6996 /* finish incremental GC */
6997 if (is_incremental_marking(objspace)) {
6998 if (RGENGC_CHECK_MODE && is_mark_stack_empty(&objspace->mark_stack) == 0) {
6999 rb_bug("gc_marks_finish: mark stack is not empty (%"PRIdSIZE").",
7000 mark_stack_size(&objspace->mark_stack));
7001 }
7002
7003 mark_roots(objspace, NULL);
7004 while (gc_mark_stacked_objects_incremental(objspace, INT_MAX) == false);
7005
7006#if RGENGC_CHECK_MODE >= 2
7007 if (gc_verify_heap_pages(objspace) != 0) {
7008 rb_bug("gc_marks_finish (incremental): there are remembered old objects.");
7009 }
7010#endif
7011
7012 objspace->flags.during_incremental_marking = FALSE;
7013 /* check children of all marked wb-unprotected objects */
7014 for (int i = 0; i < HEAP_COUNT; i++) {
7015 gc_marks_wb_unprotected_objects(objspace, &heaps[i]);
7016 }
7017 }
7018
7019 /* Pin the shareable objects and shrefs ordinary marking missed: a local GC must free
7020 * neither (another objspace may hold them). Running after the full walk makes the
7021 * pin count a retention metric: an upper bound on the garbage only a global GC can
7022 * reclaim. A global GC's exact mark does not pin. (The allrefs comparison of
7023 * RGENGC_CHECK_MODE >= 4 does not model these pins; it reports false positives.) */
7024 objspace->last_cycle_pinned = 0;
7025 if (!rb_gc_single_objspace_p() && !objspace->flags.during_global_gc) {
7026 objspace->last_cycle_pinned = 1;
7027 gc_mark_set_parent_raw(objspace, Qundef, false);
7028 for (int i = 0; i < HEAP_COUNT; i++) {
7029 pinned_roots_mark(objspace, &heaps[i]);
7030 }
7031 /* And everything they keep alive. */
7032 gc_mark_stacked_objects_all(objspace);
7033 }
7034
7035 gc_update_weak_references(objspace);
7036
7037#if RGENGC_CHECK_MODE >= 4
7038 during_gc = FALSE;
7039 gc_marks_check(objspace, gc_check_after_marks_i, "after_marks");
7040 during_gc = TRUE;
7041#endif
7042
7043 {
7044 const unsigned long ractor_cnt = rb_gc_vm_ractor_count();
7045 const unsigned long r_mul = ractor_cnt > 8 ? 8 : ractor_cnt; // upto 8
7046
7047 size_t total_slots = objspace_available_slots(objspace);
7048 size_t sweep_slots = total_slots - objspace->marked_slots; /* will be swept slots */
7049 size_t max_free_slots = (size_t)(total_slots * gc_params.heap_free_slots_max_ratio);
7050 size_t min_free_slots = (size_t)(total_slots * gc_params.heap_free_slots_min_ratio);
7051 if (min_free_slots < gc_params.heap_free_slots * r_mul) {
7052 min_free_slots = gc_params.heap_free_slots * r_mul;
7053 }
7054
7055 int full_marking = is_full_marking(objspace);
7056
7057 GC_ASSERT(objspace_available_slots(objspace) >= objspace->marked_slots);
7058
7059 /* Setup freeable slots. */
7060 size_t total_init_slots = 0;
7061 for (int i = 0; i < HEAP_COUNT; i++) {
7062 total_init_slots += (gc_params.heap_init_bytes / heaps[i].slot_size) * r_mul;
7063 }
7064
7065 if (max_free_slots < total_init_slots) {
7066 max_free_slots = total_init_slots;
7067 }
7068
7069 /* Approximate freeable pages using the average slots-per-pages across all heaps */
7070 if (sweep_slots > max_free_slots) {
7071 size_t excess_slots = sweep_slots - max_free_slots;
7072 size_t total_heap_pages = heap_eden_total_pages(objspace);
7073 heap_pages_freeable_pages = total_heap_pages > 0
7074 ? excess_slots * total_heap_pages / total_slots
7075 : 0;
7076 }
7077 else {
7078 heap_pages_freeable_pages = 0;
7079 }
7080
7081 if (objspace->heap_pages.allocatable_bytes == 0 && sweep_slots < min_free_slots) {
7082 if (!full_marking && sweep_slots < min_free_slots * 7 / 8) {
7083 if (objspace->profile.count - objspace->rgengc.last_major_gc < RVALUE_OLD_AGE) {
7084 full_marking = TRUE;
7085 }
7086 else {
7087 gc_report(1, objspace, "gc_marks_finish: next is full GC!!)\n");
7088 gc_needs_major_flags |= GPR_FLAG_MAJOR_BY_NOFREE;
7089 }
7090 }
7091
7092 if (full_marking) {
7093 heap_allocatable_bytes_expand(objspace, NULL, sweep_slots, total_slots, heaps[0].slot_size);
7094 }
7095 }
7096
7097 if (full_marking) {
7098 /* See the comment about RUBY_GC_HEAP_OLDOBJECT_LIMIT_FACTOR */
7099 const double r = gc_params.oldobject_limit_factor;
7100 objspace->rgengc.uncollectible_wb_unprotected_objects_limit = MAX(
7101 (size_t)(objspace->rgengc.uncollectible_wb_unprotected_objects * r),
7102 (size_t)(objspace->rgengc.old_objects * gc_params.uncollectible_wb_unprotected_objects_limit_ratio)
7103 );
7104 objspace->rgengc.old_objects_limit = (size_t)(objspace->rgengc.old_objects * r);
7105 }
7106
7107 if (objspace->rgengc.uncollectible_wb_unprotected_objects > objspace->rgengc.uncollectible_wb_unprotected_objects_limit) {
7108 gc_needs_major_flags |= GPR_FLAG_MAJOR_BY_SHADY;
7109 }
7110 if (objspace->rgengc.old_objects > objspace->rgengc.old_objects_limit) {
7111 gc_needs_major_flags |= GPR_FLAG_MAJOR_BY_OLDGEN;
7112 }
7113
7114 gc_report(1, objspace, "gc_marks_finish (marks %"PRIdSIZE" objects, "
7115 "old %"PRIdSIZE" objects, total %"PRIdSIZE" slots, "
7116 "sweep %"PRIdSIZE" slots, allocatable %"PRIdSIZE" bytes, next GC: %s)\n",
7117 objspace->marked_slots, objspace->rgengc.old_objects, objspace_available_slots(objspace), sweep_slots, objspace->heap_pages.allocatable_bytes,
7118 gc_needs_major_flags ? "major" : "minor");
7119 }
7120
7121 // TODO: refactor so we don't need to call this
7122 rb_ractor_finish_marking();
7123
7125}
7126
7127static bool
7128gc_compact_heap_cursors_met_p(rb_heap_t *heap)
7129{
7130 return heap->sweeping_page == heap->compact_cursor;
7131}
7132
7133
7134static rb_heap_t *
7135gc_compact_destination_pool(rb_objspace_t *objspace, rb_heap_t *src_pool, VALUE obj)
7136{
7137 size_t obj_size = rb_gc_obj_optimal_size(obj);
7138 if (obj_size == 0) {
7139 return src_pool;
7140 }
7141
7142 GC_ASSERT(rb_gc_impl_size_allocatable_p(obj_size));
7143
7144 size_t idx = heap_idx_for_size(obj_size);
7145
7146 return &heaps[idx];
7147}
7148
7149static bool
7150gc_compact_move(rb_objspace_t *objspace, rb_heap_t *heap, VALUE src)
7151{
7152 GC_ASSERT(BUILTIN_TYPE(src) != T_MOVED);
7153 GC_ASSERT(gc_is_moveable_obj(objspace, src));
7154
7155 rb_heap_t *dest_pool = gc_compact_destination_pool(objspace, heap, src);
7156 if (gc_compact_heap_cursors_met_p(dest_pool)) {
7157 return dest_pool != heap;
7158 }
7159
7160 while (!try_move(objspace, dest_pool, dest_pool->free_pages, src)) {
7161 struct gc_sweep_context ctx = {
7162 .page = dest_pool->sweeping_page,
7163 .final_slots = 0,
7164 .freed_slots = 0,
7165 .empty_slots = 0,
7166 };
7167
7168 /* The page of src could be partially compacted, so it may contain
7169 * T_MOVED. Sweeping a page may read objects on this page, so we
7170 * need to lock the page. */
7171 lock_page_body(objspace, GET_PAGE_BODY(src));
7172 gc_sweep_page(objspace, dest_pool, &ctx);
7173 unlock_page_body(objspace, GET_PAGE_BODY(src));
7174
7175 if (dest_pool->sweeping_page->free_slots > 0) {
7176 heap_add_freepage(dest_pool, dest_pool->sweeping_page);
7177 }
7178
7179 dest_pool->sweeping_page = ccan_list_next(&dest_pool->pages, dest_pool->sweeping_page, page_node);
7180 if (gc_compact_heap_cursors_met_p(dest_pool)) {
7181 return dest_pool != heap;
7182 }
7183 }
7184
7185 return true;
7186}
7187
7188static bool
7189gc_compact_plane(rb_objspace_t *objspace, rb_heap_t *heap, uintptr_t p, bits_t bitset, struct heap_page *page)
7190{
7191 short slot_size = page->slot_size;
7192
7193 do {
7194 VALUE vp = (VALUE)p;
7195 GC_ASSERT(vp % sizeof(VALUE) == 0);
7196
7197 if (bitset & 1) {
7198 objspace->rcompactor.considered_count_table[BUILTIN_TYPE(vp)]++;
7199
7200 if (gc_is_moveable_obj(objspace, vp)) {
7201 if (!gc_compact_move(objspace, heap, vp)) {
7202 //the cursors met. bubble up
7203 return false;
7204 }
7205 }
7206 }
7207 p += slot_size;
7208 bitset >>= 1;
7209 } while (bitset);
7210
7211 return true;
7212}
7213
7214// Iterate up all the objects in page, moving them to where they want to go
7215static bool
7216gc_compact_page(rb_objspace_t *objspace, rb_heap_t *heap, struct heap_page *page)
7217{
7218 GC_ASSERT(page == heap->compact_cursor);
7219
7220 bits_t *mark_bits, *pin_bits;
7221 bits_t bitset;
7222 uintptr_t p = page->start;
7223 short slot_size = page->slot_size;
7224 int total_slots = page->total_slots;
7225 int bitmap_plane_count = CEILDIV(total_slots, BITS_BITLENGTH);
7226
7227 mark_bits = page->mark_bits;
7228 pin_bits = page->pinned_bits;
7229
7230 for (int j = 0; j < bitmap_plane_count; j++) {
7231 // objects that can be moved are marked and not pinned
7232 bitset = (mark_bits[j] & ~pin_bits[j]);
7233 if (bitset) {
7234 if (!gc_compact_plane(objspace, heap, (uintptr_t)p, bitset, page))
7235 return false;
7236 }
7237 p += BITS_BITLENGTH * slot_size;
7238 }
7239
7240 return true;
7241}
7242
7243static bool
7244gc_compact_all_compacted_p(rb_objspace_t *objspace)
7245{
7246 for (int i = 0; i < HEAP_COUNT; i++) {
7247 rb_heap_t *heap = &heaps[i];
7248
7249 if (heap->total_pages > 0 &&
7250 !gc_compact_heap_cursors_met_p(heap)) {
7251 return false;
7252 }
7253 }
7254
7255 return true;
7256}
7257
7258/* Compaction's move phase: relocate this objspace's movable objects and leave T_MOVED
7259 * forwarding behind without updating references yet. A global GC calls this for every
7260 * objspace before updating any of them (two phases), so a cross-objspace reference to a
7261 * moved object is rewritten exactly once, after all forwarding exists. */
7262static void
7263gc_compact_relocate(rb_objspace_t *objspace)
7264{
7265 gc_compact_start(objspace);
7266
7267 while (!gc_compact_all_compacted_p(objspace)) {
7268 for (int i = 0; i < HEAP_COUNT; i++) {
7269 rb_heap_t *heap = &heaps[i];
7270
7271 if (gc_compact_heap_cursors_met_p(heap)) {
7272 continue;
7273 }
7274
7275 struct heap_page *start_page = heap->compact_cursor;
7276
7277 if (!gc_compact_page(objspace, heap, start_page)) {
7278 lock_page_body(objspace, start_page->body);
7279
7280 continue;
7281 }
7282
7283 // If we get here, we've finished moving all objects on the compact_cursor page
7284 // So we can lock it and move the cursor on to the next one.
7285 lock_page_body(objspace, start_page->body);
7286 heap->compact_cursor = ccan_list_prev(&heap->pages, heap->compact_cursor, page_node);
7287 }
7288 }
7289}
7290
7291static void
7292gc_sweep_compact(rb_objspace_t *objspace)
7293{
7294 gc_compact_relocate(objspace);
7295 /* A compacting global GC defers the finish (reference update) to the second phase,
7296 * after every objspace has been relocated. */
7297 if (!global_objspace->global_gc.compacting) {
7298 gc_compact_finish(objspace);
7299 }
7300}
7301
7302static void
7303gc_marks_rest(rb_objspace_t *objspace)
7304{
7305 gc_report(1, objspace, "gc_marks_rest\n");
7306
7307 for (int i = 0; i < HEAP_COUNT; i++) {
7308 (&heaps[i])->pooled_pages = NULL;
7309 }
7310
7311 if (is_incremental_marking(objspace)) {
7312 while (gc_mark_stacked_objects_incremental(objspace, INT_MAX) == FALSE);
7313 }
7314 else {
7315 gc_mark_stacked_objects_all(objspace);
7316 }
7317
7318 gc_marks_finish(objspace);
7319}
7320
7321static bool
7322gc_marks_step(rb_objspace_t *objspace, size_t slots)
7323{
7324 bool marking_finished = false;
7325
7326 GC_ASSERT(is_marking(objspace));
7327 if (gc_mark_stacked_objects_incremental(objspace, slots)) {
7328 gc_marks_finish(objspace);
7329
7330 marking_finished = true;
7331 }
7332
7333 return marking_finished;
7334}
7335
7336static bool
7337gc_marks_continue(rb_objspace_t *objspace, rb_heap_t *heap)
7338{
7339 GC_ASSERT(dont_gc_val() == FALSE || objspace->profile.latest_gc_info & GPR_FLAG_METHOD);
7340 bool marking_finished = true;
7341
7342 gc_marking_enter(objspace);
7343
7344 if (heap->free_pages) {
7345 gc_report(2, objspace, "gc_marks_continue: has pooled pages");
7346
7347 marking_finished = gc_marks_step(objspace, objspace->rincgc.step_slots);
7348 }
7349 else {
7350 gc_report(2, objspace, "gc_marks_continue: no more pooled pages (stack depth: %"PRIdSIZE").\n",
7351 mark_stack_size(&objspace->mark_stack));
7352 heap->force_incremental_marking_finish_count++;
7353 gc_marks_rest(objspace);
7354 }
7355
7356 gc_marking_exit(objspace);
7357
7358 return marking_finished;
7359}
7360
7361/* Mark the following as roots of this objspace.
7362 * - Every shareable object: another objspace may hold the only reference, invisible to a
7363 * local GC. Marking them rather than skipping them in the sweep preserves the
7364 * generational invariants (a pinned object ages and gets promoted like any live one).
7365 * Only a global GC decides that a shareable object is dead.
7366 * - Every shref (an unshareable object referenced from a shareable one): the referring
7367 * shareable object can live in another objspace or in an in-flight message queue. The
7368 * write barrier maintains them.
7369 * Skipped while the VM has a single Ractor: a local GC is then a whole-world GC and
7370 * shareable objects may die normally. */
7371static void
7372pinned_roots_mark(rb_objspace_t *objspace, rb_heap_t *heap)
7373{
7374 struct heap_page *page = NULL;
7375
7376 /* Runs before mark_roots, so rgengc_check_relation sees a valid (absent) parent rather
7377 * than the poison left by the previous GC. */
7378 gc_mark_set_parent_raw(objspace, Qundef, false);
7379
7380 /* A local GC never frees or traverses a shareable object, and keeps its unshareable
7381 * children alive through their shref bits, so:
7382 * - a shareable object only gets its mark bit set (like an old object), which keeps
7383 * the sweep off it, and is not traversed;
7384 * - a shref is marked and traversed, like a remembered old->young target: without
7385 * that, the referring shareable object is never walked and it would look
7386 * unreachable.
7387 * Objects can become shareable between GCs, so this pass scans the bitmaps in every
7388 * mark (gc_marks_finish) instead of maintaining a pin set across the sweep. */
7389 ccan_list_for_each(&heap->pages, page, page_node) {
7390 if (!(page->flags.has_shareable_objects | page->flags.has_shref_objects)) continue;
7391
7392 uintptr_t p = page->start;
7393 short slot_size = page->slot_size;
7394 int total_slots = page->total_slots;
7395 int bitmap_plane_count = CEILDIV(total_slots, BITS_BITLENGTH);
7396
7397 for (int j = 0; j < bitmap_plane_count; j++) {
7398 bits_t sr_bits = page->shref_bits[j];
7399 /* Only the pins ordinary marking left unmarked need work here: an already
7400 * marked object (reached by traversal, or pre-marked because it is old) is a
7401 * no-op in gc_mark_set, so skip visiting it. */
7402 bits_t bitset = (page->shareable_bits[j] | sr_bits) & ~page->mark_bits[j];
7403 uintptr_t pp = p;
7404 while (bitset) {
7405 if (bitset & 1) {
7406 VALUE obj = (VALUE)pp;
7407 asan_unpoisoning_object(obj) {
7408 switch (BUILTIN_TYPE(obj)) {
7409 case T_NONE:
7410 case T_ZOMBIE:
7411 case T_MOVED:
7412 /* A dead slot (a zombie awaiting its finalizer) is not a root. */
7413 break;
7414 default:
7415 gc_report(2, objspace, "pinned_roots_mark: mark %s\n", rb_obj_info(obj));
7416 if (sr_bits & 1) {
7417 gc_mark(objspace, obj); /* shref: root + traverse */
7418 }
7419 else if (gc_mark_set(objspace, obj)) {
7420 gc_aging(objspace, obj); /* shareable: mark, no traverse */
7421 /* Pin as well when compaction runs alongside: if a shareable
7422 * object moved, the C-struct slots of other Ractors (a
7423 * port in sync, say) are not updated and go stale. */
7424 gc_pin(objspace, obj);
7425 }
7426 break;
7427 }
7428 }
7429 }
7430 pp += slot_size;
7431 bitset >>= 1;
7432 sr_bits >>= 1;
7433 }
7434 p += BITS_BITLENGTH * slot_size;
7435 }
7436 }
7437}
7438
7439static void
7440gc_marks_start(rb_objspace_t *objspace, int full_mark)
7441{
7442 /* start marking */
7443 gc_report(1, objspace, "gc_marks_start: (%s)\n", full_mark ? "full" : "minor");
7444 gc_mode_transition(objspace, gc_mode_marking);
7445
7446 if (full_mark) {
7447 size_t incremental_marking_steps = (objspace->rincgc.pooled_slots / INCREMENTAL_MARK_STEP_ALLOCATIONS) + 1;
7448 objspace->rincgc.step_slots = (objspace->marked_slots * 2) / incremental_marking_steps;
7449
7450 if (0) fprintf(stderr, "objspace->marked_slots: %"PRIdSIZE", "
7451 "objspace->rincgc.pooled_page_num: %"PRIdSIZE", "
7452 "objspace->rincgc.step_slots: %"PRIdSIZE", \n",
7453 objspace->marked_slots, objspace->rincgc.pooled_slots, objspace->rincgc.step_slots);
7454 objspace->flags.during_minor_gc = FALSE;
7455 if (ruby_enable_autocompact && rb_gc_single_objspace_p()) {
7456 objspace->flags.during_compacting |= TRUE;
7457 }
7458 objspace->profile.major_gc_count++;
7459 objspace->rgengc.uncollectible_wb_unprotected_objects = 0;
7460 objspace->rgengc.old_objects = 0;
7461 objspace->rgengc.last_major_gc = objspace->profile.count;
7462 objspace->marked_slots = 0;
7463
7464 for (int i = 0; i < HEAP_COUNT; i++) {
7465 rb_heap_t *heap = &heaps[i];
7466 gc_bitmaps_clear(objspace, heap, false);
7467 heap_move_pooled_pages_to_free_pages(heap);
7468
7469 if (objspace->flags.during_compacting) {
7470 struct heap_page *page = NULL;
7471
7472 ccan_list_for_each(&heap->pages, page, page_node) {
7473 page->pinned_slots = 0;
7474 }
7475 }
7476 }
7477 }
7478 else {
7479 objspace->flags.during_minor_gc = TRUE;
7480 objspace->marked_slots =
7481 objspace->rgengc.old_objects + objspace->rgengc.uncollectible_wb_unprotected_objects; /* uncollectible objects are marked already */
7482 objspace->profile.minor_gc_count++;
7483
7484 for (int i = 0; i < HEAP_COUNT; i++) {
7485 rgengc_rememberset_mark(objspace, &heaps[i]);
7486 }
7487 }
7488
7489 mark_roots(objspace, NULL);
7490
7491 gc_report(1, objspace, "gc_marks_start: (%s) end, stack in %"PRIdSIZE"\n",
7492 full_mark ? "full" : "minor", mark_stack_size(&objspace->mark_stack));
7493}
7494
7495static bool
7496gc_marks(rb_objspace_t *objspace, int full_mark)
7497{
7498 gc_marking_enter(objspace);
7499
7500 bool marking_finished = false;
7501
7502 /* setup marking */
7503
7504 gc_marks_start(objspace, full_mark);
7505 if (!is_incremental_marking(objspace)) {
7506 gc_marks_rest(objspace);
7507 marking_finished = true;
7508 }
7509
7510#if RGENGC_PROFILE > 0
7511 if (gc_prof_record(objspace)) {
7512 gc_profile_record *record = gc_prof_record(objspace);
7513 record->old_objects = objspace->rgengc.old_objects;
7514 }
7515#endif
7516
7517 gc_marking_exit(objspace);
7518
7519 return marking_finished;
7520}
7521
7522/* RGENGC */
7523
7524static void
7525gc_report_body(int level, rb_objspace_t *objspace, const char *fmt, ...)
7526{
7527 if (level <= RGENGC_DEBUG) {
7528 char buf[1024];
7529 FILE *out = stderr;
7530 va_list args;
7531 const char *status = " ";
7532
7533 if (during_gc) {
7534 status = is_full_marking(objspace) ? "+" : "-";
7535 }
7536 else {
7537 if (is_lazy_sweeping(objspace)) {
7538 status = "S";
7539 }
7540 if (is_incremental_marking(objspace)) {
7541 status = "M";
7542 }
7543 }
7544
7545 va_start(args, fmt);
7546 vsnprintf(buf, 1024, fmt, args);
7547 va_end(args);
7548
7549 fprintf(out, "%s|", status);
7550 fputs(buf, out);
7551 }
7552}
7553
7554/* bit operations */
7555
7556static int
7557rgengc_remembersetbits_set(rb_objspace_t *objspace, VALUE obj)
7558{
7559 struct heap_page *page = GET_HEAP_PAGE(obj);
7560 bits_t *bits = &page->remembered_bits[0];
7561
7562 /* remembered_bits writers are always serialized: the write barrier only remembers a
7563 * local a (under its Ractor's GVL) and a global GC writes from the driver alone.
7564 * Set the bit before the page flag so a page pending re-scan stays in
7565 * rememberset_mark. */
7566 const bool newly = !_MARKED_IN_BITMAP(bits, page, obj);
7567 _MARK_IN_BITMAP(bits, page, obj);
7568 page->flags.has_remembered_objects = TRUE;
7569 return newly ? TRUE : FALSE;
7570}
7571
7572/* wb, etc */
7573
7574/* return FALSE if already remembered */
7575static int
7576rgengc_remember(rb_objspace_t *objspace, VALUE obj)
7577{
7578 gc_report(6, objspace, "rgengc_remember: %s %s\n", rb_obj_info(obj),
7579 RVALUE_REMEMBERED(objspace, obj) ? "was already remembered" : "is remembered now");
7580
7581 check_rvalue_consistency(objspace, obj);
7582
7583 if (RGENGC_CHECK_MODE) {
7584 if (RVALUE_WB_UNPROTECTED(objspace, obj)) rb_bug("rgengc_remember: %s is not wb protected.", rb_obj_info(obj));
7585 }
7586
7587#if RGENGC_PROFILE > 0
7588 if (!RVALUE_REMEMBERED(objspace, obj)) {
7589 if (RVALUE_WB_UNPROTECTED(objspace, obj) == 0) {
7590 objspace->profile.total_remembered_normal_object_count++;
7591#if RGENGC_PROFILE >= 2
7592 objspace->profile.remembered_normal_object_count_types[BUILTIN_TYPE(obj)]++;
7593#endif
7594 }
7595 }
7596#endif /* RGENGC_PROFILE > 0 */
7597
7598 return rgengc_remembersetbits_set(objspace, obj);
7599}
7600
7601#ifndef PROFILE_REMEMBERSET_MARK
7602#define PROFILE_REMEMBERSET_MARK 0
7603#endif
7604
7605static inline void
7606rgengc_rememberset_mark_plane(rb_objspace_t *objspace, uintptr_t p, bits_t bitset, short slot_size)
7607{
7608 if (bitset) {
7609 do {
7610 if (bitset & 1) {
7611 VALUE obj = (VALUE)p;
7612 gc_report(2, objspace, "rgengc_rememberset_mark: mark %s\n", rb_obj_info(obj));
7613 GC_ASSERT(RVALUE_UNCOLLECTIBLE(objspace, obj));
7614 GC_ASSERT(RVALUE_OLD_P(objspace, obj) || RVALUE_WB_UNPROTECTED(objspace, obj));
7615
7616 gc_mark_children(objspace, obj);
7617
7619 rb_darray_append_without_gc(&objspace->weak_references, obj);
7620 }
7621 }
7622 p += slot_size;
7623 bitset >>= 1;
7624 } while (bitset);
7625 }
7626}
7627
7628static void
7629rgengc_rememberset_mark(rb_objspace_t *objspace, rb_heap_t *heap)
7630{
7631 size_t j;
7632 struct heap_page *page = 0;
7633#if PROFILE_REMEMBERSET_MARK
7634 int has_old = 0, has_shady = 0, has_both = 0, skip = 0;
7635#endif
7636 gc_report(1, objspace, "rgengc_rememberset_mark: start\n");
7637
7638 ccan_list_for_each(&heap->pages, page, page_node) {
7639 if (page->flags.has_remembered_objects | page->flags.has_uncollectible_wb_unprotected_objects) {
7640 uintptr_t p = page->start;
7641 short slot_size = page->slot_size;
7642 int total_slots = page->total_slots;
7643 int bitmap_plane_count = CEILDIV(total_slots, BITS_BITLENGTH);
7644 bits_t bitset, bits[HEAP_PAGE_BITMAP_LIMIT];
7645 bits_t *remembered_bits = page->remembered_bits;
7646 bits_t *uncollectible_bits = page->uncollectible_bits;
7647 bits_t *wb_unprotected_bits = page->wb_unprotected_bits;
7648#if PROFILE_REMEMBERSET_MARK
7649 if (page->flags.has_remembered_objects && page->flags.has_uncollectible_wb_unprotected_objects) has_both++;
7650 else if (page->flags.has_remembered_objects) has_old++;
7651 else if (page->flags.has_uncollectible_wb_unprotected_objects) has_shady++;
7652#endif
7653 /* Clear has_remembered_objects before draining the bits. A concurrent
7654 * lock-free write barrier (another Ractor remembering a shareable object on
7655 * this page) sets the bit first and the flag second, so clearing the flag first
7656 * keeps the page scheduled for re-scan even if that set interleaves. The
7657 * per-word drain is an atomic read-and-clear, so an interleaved set is not lost
7658 * (it lands in the zeroed word). */
7659 page->flags.has_remembered_objects = FALSE;
7660 for (j=0; j < (size_t)bitmap_plane_count; j++) {
7661 bits[j] = RUBY_ATOMIC_SIZE_EXCHANGE(*(volatile size_t *)&remembered_bits[j], 0)
7662 | (uncollectible_bits[j] & wb_unprotected_bits[j]);
7663 }
7664
7665 for (j=0; j < (size_t)bitmap_plane_count; j++) {
7666 bitset = bits[j];
7667 rgengc_rememberset_mark_plane(objspace, p, bitset, slot_size);
7668 p += BITS_BITLENGTH * slot_size;
7669 }
7670 }
7671#if PROFILE_REMEMBERSET_MARK
7672 else {
7673 skip++;
7674 }
7675#endif
7676 }
7677
7678#if PROFILE_REMEMBERSET_MARK
7679 fprintf(stderr, "%d\t%d\t%d\t%d\n", has_both, has_old, has_shady, skip);
7680#endif
7681 gc_report(1, objspace, "rgengc_rememberset_mark: finished\n");
7682}
7683
7684static void
7685gc_bitmaps_clear(rb_objspace_t *objspace, rb_heap_t *heap, bool clear_shref)
7686{
7687 struct heap_page *page = 0;
7688
7689 ccan_list_for_each(&heap->pages, page, page_node) {
7690 memset(&page->mark_bits[0], 0, HEAP_PAGE_BITMAP_SIZE);
7691 memset(&page->uncollectible_bits[0], 0, HEAP_PAGE_BITMAP_SIZE);
7692 memset(&page->marking_bits[0], 0, HEAP_PAGE_BITMAP_SIZE);
7693 /* A plain memset can lose a concurrent remember, but only a shareable object can
7694 * be remembered from another Ractor's thread, and pinned_roots_mark re-marks
7695 * those every local cycle, and this clear precedes a major that re-scans all. */
7696 memset(&page->remembered_bits[0], 0, HEAP_PAGE_BITMAP_SIZE);
7697 memset(&page->pinned_bits[0], 0, HEAP_PAGE_BITMAP_SIZE);
7698 page->flags.has_uncollectible_wb_unprotected_objects = FALSE;
7699 page->flags.has_remembered_objects = FALSE;
7700 /* A shref is a local GC's root, so only a stop-the-world global GC may clear them:
7701 * its unified mark re-derives them from every shareable -> unshareable edge. */
7702 if (clear_shref) {
7703 memset(&page->shref_bits[0], 0, HEAP_PAGE_BITMAP_SIZE);
7704 page->flags.has_shref_objects = FALSE;
7705 }
7706 }
7707}
7708
7709/* RGENGC: APIs */
7710
7711NOINLINE(static void gc_writebarrier_generational(VALUE a, VALUE b, rb_objspace_t *objspace));
7712
7713static void
7714gc_writebarrier_generational(VALUE a, VALUE b, rb_objspace_t *objspace)
7715{
7716 if (RGENGC_CHECK_MODE) {
7717 if (!RVALUE_OLD_P(objspace, a)) rb_bug("gc_writebarrier_generational: %s is not an old object.", rb_obj_info(a));
7718 if ( RVALUE_OLD_P(objspace, b)) rb_bug("gc_writebarrier_generational: %s is an old object.", rb_obj_info(b));
7719 if (is_incremental_marking(objspace)) rb_bug("gc_writebarrier_generational: called while incremental marking: %s -> %s", rb_obj_info(a), rb_obj_info(b));
7720 }
7721
7722 /* Mark and remember a (the default behaviour).
7723 * No lock: setting a remembered bit is atomic (rgengc_remembersetbits_set), and that is
7724 * the only place a concurrent local GC or another Ractor's write barrier can race. */
7725 if (!RVALUE_REMEMBERED(objspace, a)) {
7726 rgengc_remember(objspace, a);
7727
7728 gc_report(1, objspace, "gc_writebarrier_generational: %s (remembered) -> %s\n", rb_obj_info(a), rb_obj_info(b));
7729 }
7730
7731 check_rvalue_consistency(objspace, a);
7732 check_rvalue_consistency(objspace, b);
7733}
7734
7735static void
7736gc_mark_from(rb_objspace_t *objspace, VALUE obj, VALUE parent)
7737{
7738 gc_mark_set_parent(objspace, parent);
7739 rgengc_check_relation(objspace, obj);
7740 if (gc_mark_set(objspace, obj) != FALSE) {
7741 gc_aging(objspace, obj);
7742 gc_grey(objspace, obj);
7743 }
7744 gc_mark_set_parent_invalid(objspace);
7745}
7746
7747NOINLINE(static void gc_writebarrier_incremental(VALUE a, VALUE b, rb_objspace_t *objspace));
7748
7749static void
7750gc_writebarrier_incremental(VALUE a, VALUE b, rb_objspace_t *objspace)
7751{
7752 gc_report(2, objspace, "gc_writebarrier_incremental: [LG] %p -> %s\n", (void *)a, rb_obj_info(b));
7753
7754 if (RVALUE_BLACK_P(objspace, a)) {
7755 if (RVALUE_WHITE_P(objspace, b)) {
7756 if (!RVALUE_WB_UNPROTECTED(objspace, a)) {
7757 gc_report(2, objspace, "gc_writebarrier_incremental: [IN] %p -> %s\n", (void *)a, rb_obj_info(b));
7758 gc_mark_from(objspace, b, a);
7759 }
7760 }
7761 else if (RVALUE_OLD_P(objspace, a) && !RVALUE_OLD_P(objspace, b)) {
7762 rgengc_remember(objspace, a);
7763 }
7764
7765 if (RB_UNLIKELY(objspace->flags.during_compacting)) {
7766 MARK_IN_BITMAP(GET_HEAP_PINNED_BITS(b), b);
7767 }
7768 }
7769}
7770
7771void
7772rb_gc_impl_writebarrier(void *objspace_ptr, VALUE a, VALUE b)
7773{
7774 rb_objspace_t *objspace = objspace_ptr;
7775
7776#if RGENGC_CHECK_MODE
7777 if (SPECIAL_CONST_P(a)) rb_bug("rb_gc_writebarrier: a is special const: %"PRIxVALUE, a);
7778 if (SPECIAL_CONST_P(b)) rb_bug("rb_gc_writebarrier: b is special const: %"PRIxVALUE, b);
7779#else
7782#endif
7783
7784 GC_ASSERT(!during_gc);
7785 GC_ASSERT(RB_BUILTIN_TYPE(a) != T_NONE);
7786 GC_ASSERT(RB_BUILTIN_TYPE(a) != T_MOVED);
7787 GC_ASSERT(RB_BUILTIN_TYPE(a) != T_ZOMBIE);
7788 GC_ASSERT(RB_BUILTIN_TYPE(b) != T_NONE);
7789 GC_ASSERT(RB_BUILTIN_TYPE(b) != T_MOVED);
7790 GC_ASSERT(RB_BUILTIN_TYPE(b) != T_ZOMBIE);
7791
7792 /* A shareable object now references an unshareable one: record b as a shref so its
7793 * owner's local GC roots it (the parent may live in another objspace, untraversed
7794 * there). Only b's owner stores this, on its own page: a plain store suffices. */
7795 if (RB_UNLIKELY(RB_FL_TEST_RAW(a, RUBY_FL_SHAREABLE)) &&
7797 struct heap_page *bpage = GET_HEAP_PAGE(b);
7798 if (!_MARKED_IN_BITMAP(bpage->shref_bits, bpage, b)) {
7799 _MARK_IN_BITMAP(bpage->shref_bits, bpage, b);
7800 bpage->flags.has_shref_objects = TRUE;
7801 }
7802 }
7803
7804 retry:
7805 if (!is_incremental_marking(objspace)) {
7806 /* The generational barrier covers old->young edges within one objspace only; a
7807 * foreign a or b has age bits another objspace mutates, unsafe to read, so check
7808 * locality first when multi-Ractor (a foreign a is shareable and the shref above
7809 * already keeps b alive). With a single Ractor nothing is foreign. */
7810 if ((rb_gc_multi_ractor_p() &&
7811 (GET_HEAP_OBJSPACE(a) != objspace || GET_HEAP_OBJSPACE(b) != objspace)) ||
7812 !RVALUE_OLD_P(objspace, a) || RVALUE_OLD_P(objspace, b)) {
7813 // do nothing
7814 }
7815 else {
7816 gc_writebarrier_generational(a, b, objspace);
7817 }
7818 }
7819 else {
7820 /* Slow path, no lock: incremental marking only runs while the process has a single
7821 * objspace, so the owning Ractor's GVL already serializes this barrier against its
7822 * own GC. */
7823 if (is_incremental_marking(objspace)) {
7824 gc_writebarrier_incremental(a, b, objspace);
7825 }
7826 else {
7827 goto retry;
7828 }
7829 }
7830 return;
7831}
7832
7833void
7834rb_gc_impl_obj_became_shareable(void *objspace_ptr, VALUE obj)
7835{
7836 /* An object becomes shareable on its owner thread, so this page update is
7837 * single-writer. */
7838 struct heap_page *page = GET_HEAP_PAGE(obj);
7839 if (_MARKED_IN_BITMAP(page->shareable_bits, page, obj)) return;
7840 gc_page_add_shareable(page, obj);
7841
7842 /* The shref bits recorded while the object was unshareable are now covered by the
7843 * shareable pin, and a shref only points at an unshareable object. The owner thread is
7844 * the only writer, so a plain clear is enough. */
7845 if (_MARKED_IN_BITMAP(page->shref_bits, page, obj)) {
7846 _CLEAR_IN_BITMAP(page->shref_bits, page, obj);
7847 }
7848}
7849
7850void
7851rb_gc_impl_pin_in_flight_message(void *objspace_ptr, VALUE obj)
7852{
7853 if (RB_FL_TEST_RAW(obj, RUBY_FL_SHAREABLE)) return; /* pinned anyway */
7854
7855 /* The payload's pages belong to the sender, so a plain store is enough. */
7856 struct heap_page *page = GET_HEAP_PAGE(obj);
7857 if (!_MARKED_IN_BITMAP(page->shref_bits, page, obj)) {
7858 _MARK_IN_BITMAP(page->shref_bits, page, obj);
7859 page->flags.has_shref_objects = TRUE;
7860 }
7861 /* A shref bit only makes the object a root for the next local GC; it does not affect an
7862 * in-progress global compaction's move decision (pinned_bits). Moving a payload node
7863 * would break the address-keyed maps, dedup tables and pin lists, so pin it as well. */
7864 rb_objspace_t *objspace = objspace_ptr;
7865 if (objspace->flags.during_global_gc) {
7866 gc_pin(objspace, obj);
7867 }
7868}
7869
7870void
7871rb_gc_impl_writebarrier_unprotect(void *objspace_ptr, VALUE obj)
7872{
7873 rb_objspace_t *objspace = objspace_ptr;
7874
7875 /* A shareable object is never WB-unprotected. Keeping shrefs correct relies on every
7876 * store into s->u going through the write barrier, which keeps wb_unprotected_bits
7877 * single-writer (only the owner thread can unprotect its own unshareable objects). */
7878 GC_ASSERT(!RB_FL_TEST_RAW(obj, RUBY_FL_SHAREABLE));
7879
7880 if (RVALUE_WB_UNPROTECTED(objspace, obj)) {
7881 return;
7882 }
7883 else {
7884 gc_report(2, objspace, "rb_gc_writebarrier_unprotect: %s %s\n", rb_obj_info(obj),
7885 RVALUE_REMEMBERED(objspace, obj) ? " (already remembered)" : "");
7886
7887 /* No lock: per the assert obj is our own unshareable, so these bits
7888 * (wb_unprotected, uncollectible, age) are single-writer on an owned page, and
7889 * RVALUE_DEMOTE's remembered-bit clear is atomic against word-sharing writers. */
7890 if (RVALUE_OLD_P(objspace, obj)) {
7891 gc_report(1, objspace, "rb_gc_writebarrier_unprotect: %s\n", rb_obj_info(obj));
7892 RVALUE_DEMOTE(objspace, obj);
7893 gc_mark_set(objspace, obj);
7894 gc_remember_unprotected(objspace, obj);
7895
7896#if RGENGC_PROFILE
7897 objspace->profile.total_shade_operation_count++;
7898#if RGENGC_PROFILE >= 2
7899 objspace->profile.shade_operation_count_types[BUILTIN_TYPE(obj)]++;
7900#endif /* RGENGC_PROFILE >= 2 */
7901#endif /* RGENGC_PROFILE */
7902 }
7903 else {
7904 RVALUE_AGE_RESET(obj);
7905 }
7906
7907 RB_DEBUG_COUNTER_INC(obj_wb_unprotect);
7908 MARK_IN_BITMAP(GET_HEAP_WB_UNPROTECTED_BITS(obj), obj);
7909 }
7910}
7911
7912void
7913rb_gc_impl_copy_attributes(void *objspace_ptr, VALUE dest, VALUE obj)
7914{
7915 rb_objspace_t *objspace = objspace_ptr;
7916
7917 if (RVALUE_WB_UNPROTECTED(objspace, obj)) {
7918 rb_gc_impl_writebarrier_unprotect(objspace, dest);
7919 }
7920 rb_gc_impl_copy_finalizer(objspace, dest, obj);
7921}
7922
7923const char *
7924rb_gc_impl_active_gc_name(void)
7925{
7926 return "default";
7927}
7928
7929void
7930rb_gc_impl_writebarrier_remember(void *objspace_ptr, VALUE obj)
7931{
7932 rb_objspace_t *objspace = objspace_ptr;
7933
7934 gc_report(1, objspace, "rb_gc_writebarrier_remember: %s\n", rb_obj_info(obj));
7935
7936 /* No lock, for the same reason as rb_gc_impl_writebarrier: remembering is an atomic
7937 * bitmap set, and the incremental branch only runs with a single objspace, where the
7938 * Ractor's GVL serializes it against its own GC. */
7939 if (is_incremental_marking(objspace)) {
7940 if (RVALUE_BLACK_P(objspace, obj)) {
7941 gc_grey(objspace, obj);
7942 }
7943 }
7944 else if (RVALUE_OLD_P(objspace, obj)) {
7945 rgengc_remember(objspace, obj);
7946 }
7947}
7948
7950 // Must be ID only
7951 ID ID_wb_protected, ID_age, ID_old, ID_uncollectible, ID_marking,
7952 ID_marked, ID_pinned, ID_remembered, ID_object_id, ID_shareable;
7953};
7954
7955#define RB_GC_OBJECT_METADATA_ENTRY_COUNT (sizeof(struct rb_gc_object_metadata_names) / sizeof(ID))
7956static struct rb_gc_object_metadata_entry object_metadata_entries[RB_GC_OBJECT_METADATA_ENTRY_COUNT + 1];
7957
7959rb_gc_impl_object_metadata(void *objspace_ptr, VALUE obj)
7960{
7961 rb_objspace_t *objspace = objspace_ptr;
7962 size_t n = 0;
7963 static struct rb_gc_object_metadata_names names;
7964
7965 if (!names.ID_marked) {
7966#define I(s) names.ID_##s = rb_intern(#s)
7967 I(wb_protected);
7968 I(age);
7969 I(old);
7970 I(uncollectible);
7971 I(marking);
7972 I(marked);
7973 I(pinned);
7974 I(remembered);
7975 I(object_id);
7976 I(shareable);
7977#undef I
7978 }
7979
7980#define SET_ENTRY(na, v) do { \
7981 GC_ASSERT(n <= RB_GC_OBJECT_METADATA_ENTRY_COUNT); \
7982 object_metadata_entries[n].name = names.ID_##na; \
7983 object_metadata_entries[n].val = v; \
7984 n++; \
7985} while (0)
7986
7987 if (!RVALUE_WB_UNPROTECTED(objspace, obj)) SET_ENTRY(wb_protected, Qtrue);
7988 SET_ENTRY(age, INT2FIX(RVALUE_AGE_GET(obj)));
7989 if (RVALUE_OLD_P(objspace, obj)) SET_ENTRY(old, Qtrue);
7990 if (RVALUE_UNCOLLECTIBLE(objspace, obj)) SET_ENTRY(uncollectible, Qtrue);
7991 if (RVALUE_MARKING(objspace, obj)) SET_ENTRY(marking, Qtrue);
7992 if (RVALUE_MARKED(objspace, obj)) SET_ENTRY(marked, Qtrue);
7993 if (RVALUE_PINNED(objspace, obj)) SET_ENTRY(pinned, Qtrue);
7994 if (RVALUE_REMEMBERED(objspace, obj)) SET_ENTRY(remembered, Qtrue);
7995 if (rb_obj_id_p(obj)) SET_ENTRY(object_id, rb_obj_id(obj));
7996 if (FL_TEST(obj, FL_SHAREABLE)) SET_ENTRY(shareable, Qtrue);
7997
7998 object_metadata_entries[n].name = 0;
7999 object_metadata_entries[n].val = 0;
8000#undef SET_ENTRY
8001
8002 return object_metadata_entries;
8003}
8004
8005void *
8006rb_gc_impl_ractor_cache_alloc(void *objspace_ptr, void *ractor)
8007{
8008 /* No cache needed: allocation happens in a per-Ractor objspace. */
8009 return NULL;
8010}
8011
8012void
8013rb_gc_impl_ractor_cache_free(void *objspace_ptr, void *cache)
8014{
8015 GC_ASSERT(cache == NULL);
8016}
8017
8018/* The terminating Ractor's final local GC, on its own thread: roots are minimal, so the
8019 * mark is tiny, and it reclaims what the joining side would otherwise inherit. Never
8020 * promotes to a global GC (that would STW on every Ractor death); empty pages go
8021 * straight back to the page pool. */
8022/* Finalize the zombies whose cleanup is pure C (a dfree, no Ruby-level finalizer);
8023 * the caller has no Ruby execution context any more, so zombies with a Ruby
8024 * finalizer stay deferred and travel to the inheritor as before. Returns whether
8025 * anything was finalized (those pages then need one more sweep to detach). */
8026static bool
8027finalize_deferred_dfree_only(rb_objspace_t *objspace)
8028{
8029 VALUE dfree_only = 0;
8030 VALUE zombie = RUBY_ATOMIC_VALUE_EXCHANGE(heap_pages_deferred_final, 0);
8031 while (zombie) {
8032 rb_asan_unpoison_object(zombie, false);
8033 VALUE next = RZOMBIE(zombie)->next;
8034 if (FL_TEST_RAW(zombie, FL_FINALIZE)) {
8035 /* re-defer, with the same push as rb_gc_impl_make_zombie */
8036 VALUE prev2, next2 = heap_pages_deferred_final;
8037 do {
8038 RZOMBIE(zombie)->next = prev2 = next2;
8039 next2 = RUBY_ATOMIC_VALUE_CAS(heap_pages_deferred_final, prev2, zombie);
8040 } while (next2 != prev2);
8041 rb_asan_poison_object(zombie);
8042 }
8043 else {
8044 RZOMBIE(zombie)->next = dfree_only;
8045 dfree_only = zombie;
8046 }
8047 zombie = next;
8048 }
8049 if (dfree_only) finalize_list(objspace, dfree_only);
8050 return dfree_only != 0;
8051}
8052
8053void
8054rb_gc_impl_objspace_retire_gc(void *objspace_ptr)
8055{
8056 rb_objspace_t *objspace = objspace_ptr;
8057
8058 /* The dying thread's stack is already torn down here, so the root scan must skip
8059 * its machine context (rb_gc_mark_roots). */
8060 objspace->flags.during_postmortem = 1;
8061
8062 gc_rest(objspace);
8063 gc_start_body(objspace, GPR_FLAG_FULL_MARK | GPR_FLAG_IMMEDIATE_MARK | GPR_FLAG_IMMEDIATE_SWEEP,
8064 false);
8065
8066 /* The sweep above turned this heap's dead IO and the like into deferred zombies
8067 * (the per-Ractor stdio holds a page per Ractor otherwise); finalize the C-only
8068 * ones here and re-sweep the nearly-empty heap so their pages detach as empty. */
8069 if (finalize_deferred_dfree_only(objspace)) {
8070 gc_start_body(objspace, GPR_FLAG_FULL_MARK | GPR_FLAG_IMMEDIATE_MARK | GPR_FLAG_IMMEDIATE_SWEEP,
8071 false);
8072 }
8073
8074 heap_pages_freeable_pages = objspace->empty_pages_count;
8075 heap_pages_free_unused_pages(objspace);
8076
8077 objspace->flags.during_postmortem = 0;
8078}
8079
8080bool
8081rb_gc_impl_during_postmortem_p(void *objspace_ptr)
8082{
8083 rb_objspace_t *objspace = objspace_ptr;
8084 return objspace->flags.during_postmortem != 0;
8085}
8086
8087static void
8088heap_ready_to_gc(rb_objspace_t *objspace, rb_heap_t *heap)
8089{
8090 if (!heap->free_pages) {
8091 if (!heap_page_allocate_and_initialize(objspace, heap)) {
8092 objspace->heap_pages.allocatable_bytes = HEAP_PAGE_SIZE;
8093 heap_page_allocate_and_initialize(objspace, heap);
8094 }
8095 }
8096}
8097
8098static int
8099ready_to_gc(rb_objspace_t *objspace)
8100{
8101 if (rb_gc_gc_disabled_global_p() || dont_gc_val() || during_gc) {
8102 for (int i = 0; i < HEAP_COUNT; i++) {
8103 rb_heap_t *heap = &heaps[i];
8104 heap_ready_to_gc(objspace, heap);
8105 }
8106 return FALSE;
8107 }
8108 else {
8109 return TRUE;
8110 }
8111}
8112
8113static void
8114gc_reset_malloc_info(rb_objspace_t *objspace, bool full_mark)
8115{
8116 gc_prof_set_malloc_info(objspace);
8117 {
8118 int64_t inc = gc_malloc_counters_increase(objspace, &objspace->malloc_counters.counters);
8119 gc_malloc_counters_snapshot(objspace, &objspace->malloc_counters.counters);
8120 size_t old_limit = malloc_limit;
8121
8122 /* A net-negative `inc` (more freed than malloc'd since last GC) is
8123 * treated the same as "allocated less than malloc_limit".
8124 * This matches what we were doing pre-monotonic counters, but is it right? */
8125 if (inc > 0 && (size_t)inc > malloc_limit) {
8126 malloc_limit = (size_t)((size_t)inc * gc_params.malloc_limit_growth_factor);
8127 if (malloc_limit > gc_params.malloc_limit_max) {
8128 malloc_limit = gc_params.malloc_limit_max;
8129 }
8130 }
8131 else {
8132 malloc_limit = (size_t)(malloc_limit * 0.98); /* magic number */
8133 if (malloc_limit < gc_params.malloc_limit_min) {
8134 malloc_limit = gc_params.malloc_limit_min;
8135 }
8136 }
8137
8138 if (0) {
8139 if (old_limit != malloc_limit) {
8140 fprintf(stderr, "[%"PRIuSIZE"] malloc_limit: %"PRIuSIZE" -> %"PRIuSIZE"\n",
8141 rb_gc_count(), old_limit, malloc_limit);
8142 }
8143 else {
8144 fprintf(stderr, "[%"PRIuSIZE"] malloc_limit: not changed (%"PRIuSIZE")\n",
8145 rb_gc_count(), malloc_limit);
8146 }
8147 }
8148 }
8149
8150 /* reset oldmalloc info */
8151#if RGENGC_ESTIMATE_OLDMALLOC
8152 if (!full_mark) {
8153 /* No full snapshot on minor GC: oldmalloc_increase accumulates across
8154 * minors and resets at major GC. (gc_sweep_finish still advances the
8155 * free baseline after every sweep.) */
8156 int64_t oldmalloc_increase = gc_malloc_counters_increase(objspace, &objspace->malloc_counters.oldcounters);
8157 if (oldmalloc_increase > 0 &&
8158 (uint64_t)oldmalloc_increase > objspace->rgengc.oldmalloc_increase_limit) {
8159 gc_needs_major_flags |= GPR_FLAG_MAJOR_BY_OLDMALLOC;
8160 objspace->rgengc.oldmalloc_increase_limit =
8161 (size_t)(objspace->rgengc.oldmalloc_increase_limit * gc_params.oldmalloc_limit_growth_factor);
8162
8163 if (objspace->rgengc.oldmalloc_increase_limit > gc_params.oldmalloc_limit_max) {
8164 objspace->rgengc.oldmalloc_increase_limit = gc_params.oldmalloc_limit_max;
8165 }
8166 }
8167
8168 if (0) fprintf(stderr, "%"PRIdSIZE"\t%d\t%"PRId64"\t%"PRIuSIZE"\t%"PRIdSIZE"\n",
8169 rb_gc_count(),
8170 gc_needs_major_flags,
8171 oldmalloc_increase,
8172 objspace->rgengc.oldmalloc_increase_limit,
8173 gc_params.oldmalloc_limit_max);
8174 }
8175 else {
8176 gc_malloc_counters_snapshot(objspace, &objspace->malloc_counters.oldcounters);
8177
8178 if ((objspace->profile.latest_gc_info & GPR_FLAG_MAJOR_BY_OLDMALLOC) == 0) {
8179 objspace->rgengc.oldmalloc_increase_limit =
8180 (size_t)(objspace->rgengc.oldmalloc_increase_limit / ((gc_params.oldmalloc_limit_growth_factor - 1)/10 + 1));
8181 if (objspace->rgengc.oldmalloc_increase_limit < gc_params.oldmalloc_limit_min) {
8182 objspace->rgengc.oldmalloc_increase_limit = gc_params.oldmalloc_limit_min;
8183 }
8184 }
8185 }
8186#endif
8187}
8188
8189/* What a collection records about itself before it runs. A global collection reports the
8190 * driver's objspace, so it comes through here too. */
8191static void
8192gc_start_record(rb_objspace_t *objspace, unsigned int reason, bool full_mark)
8193{
8194 objspace->profile.latest_gc_info = reason;
8195#if GC_PROFILE_MORE_DETAIL
8196 objspace->profile.total_allocated_objects_at_gc_start = total_allocated_objects(objspace);
8197 objspace->profile.heap_used_at_gc_start = rb_darray_size(objspace->heap_pages.sorted);
8198#endif
8199 objspace->profile.weak_references_count = 0;
8200 gc_prof_setup_new_record(objspace, reason);
8201 gc_reset_malloc_info(objspace, full_mark);
8202}
8203
8204static bool gc_start_global(rb_objspace_t *driver, unsigned int reason, bool compact, bool allow_skip);
8205
8206/* Decide whether this collection has to be global. A local GC can reclaim neither
8207 * shareable objects nor zombie objspaces, so once those grow past their limits only a
8208 * global GC makes progress. All inputs belong to this objspace. */
8209static bool
8210gc_need_global_p(rb_objspace_t *objspace)
8211{
8212 if (rb_gc_single_objspace_p()) return false;
8213 if (objspace->shareable_objects > objspace->shareable_objects_limit) return true;
8214 /* A zombie's garbage only a global cycle reclaims, but what survived the last one
8215 * is live data, so retrigger only once TRIGGER more pages accumulate on top of it.
8216 * Otherwise one live-heavy unjoined zombie turns every GC stop-the-world forever. */
8217 {
8218 size_t zp = rb_gc_vm_zombie_total_pages();
8219 size_t base = global_objspace->zombie_pages_survivors < zp ? global_objspace->zombie_pages_survivors : zp;
8220 if (zp - base >= ZOMBIE_PAGES_TRIGGER) return true;
8221 }
8222 return false;
8223}
8224
8225static int
8226garbage_collect(rb_objspace_t *objspace, unsigned int reason)
8227{
8228 int ret;
8229
8230#if GC_PROFILE_MORE_DETAIL
8231 objspace->profile.prepare_time = getrusage_time();
8232#endif
8233
8234 gc_rest(objspace);
8235
8236#if GC_PROFILE_MORE_DETAIL
8237 objspace->profile.prepare_time = getrusage_time() - objspace->profile.prepare_time;
8238#endif
8239
8240 ret = gc_start(objspace, reason);
8241
8242 return ret;
8243}
8244
8245static int
8246gc_start_body(rb_objspace_t *objspace, unsigned int reason, bool allow_global)
8247{
8248 unsigned int do_full_mark = !!(reason & GPR_FLAG_FULL_MARK);
8249
8250 if (!rb_darray_size(objspace->heap_pages.sorted)) return TRUE; /* heap is not ready */
8251 if (!(reason & GPR_FLAG_METHOD) && !ready_to_gc(objspace)) return TRUE; /* GC is not allowed */
8252
8253 /* Every local GC entry asks whether a global cycle is needed instead, including the
8254 * allocation slow path, or an allocation-driven workload slips past every threshold
8255 * (only a global cycle reclaims dead shareable objects and zombie pages). The
8256 * exception is the retire GC, which never promotes: a Ractor's death must not STW. */
8257 if (allow_global && gc_need_global_p(objspace)) {
8258 if (gc_start_global(objspace, reason, false, true)) {
8259 return TRUE;
8260 }
8261 // Fall through to a local GC
8262 }
8263
8264 rb_gc_initialize_vm_context(&objspace->vm_context);
8265
8266 GC_ASSERT(gc_mode(objspace) == gc_mode_none, "gc_mode is %s\n", gc_mode_name(gc_mode(objspace)));
8267 GC_ASSERT(!is_lazy_sweeping(objspace));
8268 GC_ASSERT(!is_incremental_marking(objspace));
8269
8270 /* reason may be clobbered, later, so keep set immediate_sweep here */
8271 objspace->flags.immediate_sweep = !!(reason & GPR_FLAG_IMMEDIATE_SWEEP);
8272
8273 if (ruby_gc_stressful) {
8274 int flag = FIXNUM_P(ruby_gc_stress_mode) ? FIX2INT(ruby_gc_stress_mode) : 0;
8275
8276 if ((flag & (1 << gc_stress_no_major)) == 0) {
8277 do_full_mark = TRUE;
8278 }
8279
8280 objspace->flags.immediate_sweep = !(flag & (1<<gc_stress_no_immediate_sweep));
8281 }
8282
8283 if (gc_needs_major_flags) {
8284 reason |= gc_needs_major_flags;
8285 do_full_mark = TRUE;
8286 }
8287
8288 /* if major gc has been disabled, never do a full mark */
8289 if (!gc_config_full_mark_val) {
8290 do_full_mark = FALSE;
8291 }
8292 gc_needs_major_flags = GPR_FLAG_NONE;
8293
8294 if (do_full_mark && (reason & GPR_FLAG_MAJOR_MASK) == 0) {
8295 reason |= GPR_FLAG_MAJOR_BY_FORCE; /* GC by CAPI, METHOD, and so on. */
8296 }
8297
8298 if (objspace->flags.dont_incremental ||
8299 reason & GPR_FLAG_IMMEDIATE_MARK ||
8300 ruby_gc_stressful ||
8301 /* No incremental marking while multiple objspaces exist: between steps another
8302 * Ractor can create and share objects behind this objspace's already-scanned
8303 * roots. */
8304 !rb_gc_single_objspace_p()) {
8305 objspace->flags.during_incremental_marking = FALSE;
8306 }
8307 else {
8308 objspace->flags.during_incremental_marking = do_full_mark;
8309 }
8310
8311 /* Compaction on the local GC path (autocompact) runs only with a single objspace:
8312 * without the stop-the-world barrier, moving objects would break cross-objspace
8313 * references. With multiple objspaces GC.compact and autocompact go through the
8314 * compacting global GC instead (rb_gc_impl_start -> gc_start_global). */
8315 if (do_full_mark && ruby_enable_autocompact && rb_gc_single_objspace_p()) {
8316 objspace->flags.during_compacting = TRUE;
8317#if RGENGC_CHECK_MODE
8318 objspace->rcompactor.compare_func = ruby_autocompact_compare_func;
8319#endif
8320 }
8321 else {
8322 objspace->flags.during_compacting = !!(reason & GPR_FLAG_COMPACT);
8323 /* The local path was chosen with a single objspace, but another Ractor can be
8324 * born before this point; local compaction would then move shareable objects and
8325 * leave other Ractors' C-struct slots stale, so give up. */
8326 if (objspace->flags.during_compacting && !rb_gc_single_objspace_p()) {
8327 objspace->flags.during_compacting = FALSE;
8328 }
8329 }
8330
8331 if (!GC_ENABLE_LAZY_SWEEP || objspace->flags.dont_incremental) {
8332 objspace->flags.immediate_sweep = TRUE;
8333 }
8334
8335 if (objspace->flags.immediate_sweep) reason |= GPR_FLAG_IMMEDIATE_SWEEP;
8336
8337 /* Enter after during_compacting is decided: gc_local_gc_holds_vm_lock reads it. */
8338 unsigned int lock_lev;
8339 gc_enter(objspace, gc_enter_event_start, &lock_lev);
8340
8341 gc_report(1, objspace, "gc_start(reason: %x) => %u, %d, %d\n",
8342 reason,
8343 do_full_mark, !is_incremental_marking(objspace), objspace->flags.immediate_sweep);
8344
8345 RB_DEBUG_COUNTER_INC(gc_count);
8346
8347 if (reason & GPR_FLAG_MAJOR_MASK) {
8348 (void)RB_DEBUG_COUNTER_INC_IF(gc_major_nofree, reason & GPR_FLAG_MAJOR_BY_NOFREE);
8349 (void)RB_DEBUG_COUNTER_INC_IF(gc_major_oldgen, reason & GPR_FLAG_MAJOR_BY_OLDGEN);
8350 (void)RB_DEBUG_COUNTER_INC_IF(gc_major_shady, reason & GPR_FLAG_MAJOR_BY_SHADY);
8351 (void)RB_DEBUG_COUNTER_INC_IF(gc_major_force, reason & GPR_FLAG_MAJOR_BY_FORCE);
8352#if RGENGC_ESTIMATE_OLDMALLOC
8353 (void)RB_DEBUG_COUNTER_INC_IF(gc_major_oldmalloc, reason & GPR_FLAG_MAJOR_BY_OLDMALLOC);
8354#endif
8355 }
8356 else {
8357 (void)RB_DEBUG_COUNTER_INC_IF(gc_minor_newobj, reason & GPR_FLAG_NEWOBJ);
8358 (void)RB_DEBUG_COUNTER_INC_IF(gc_minor_malloc, reason & GPR_FLAG_MALLOC);
8359 (void)RB_DEBUG_COUNTER_INC_IF(gc_minor_method, reason & GPR_FLAG_METHOD);
8360 (void)RB_DEBUG_COUNTER_INC_IF(gc_minor_capi, reason & GPR_FLAG_CAPI);
8361 (void)RB_DEBUG_COUNTER_INC_IF(gc_minor_stress, reason & GPR_FLAG_STRESS);
8362 }
8363
8364 objspace->profile.count++;
8365 gc_start_record(objspace, reason, do_full_mark);
8366
8367 gc_event_hook(objspace, RUBY_INTERNAL_EVENT_GC_START);
8368
8369 GC_ASSERT(during_gc);
8370
8371 gc_prof_timer_start(objspace);
8372 {
8373 if (gc_marks(objspace, do_full_mark)) {
8374 gc_sweep(objspace);
8375 }
8376 }
8377 gc_prof_timer_stop(objspace);
8378
8379 gc_exit(objspace, gc_enter_event_start, &lock_lev);
8380
8381 /* Verify after the GC, at a real safepoint with during_gc cleared: mid-GC it would
8382 * call rb_objspace_reachable_objects_from, whose barrier VM lock would join another
8383 * Ractor's global GC barrier and let it collect on this half-collected heap. */
8384#if RGENGC_CHECK_MODE >= 2
8385 gc_verify_internal_consistency(objspace);
8386#endif
8387 return TRUE;
8388}
8389
8390static int
8391gc_start(rb_objspace_t *objspace, unsigned int reason)
8392{
8393 return gc_start_body(objspace, reason, true);
8394}
8395
8396static void
8397gc_rest(rb_objspace_t *objspace)
8398{
8399 if (is_incremental_marking(objspace) || is_lazy_sweeping(objspace)) {
8400 unsigned int lock_lev;
8401 gc_enter(objspace, gc_enter_event_rest, &lock_lev);
8402
8403 if (is_incremental_marking(objspace)) {
8404 gc_marking_enter(objspace);
8405 gc_marks_rest(objspace);
8406 gc_marking_exit(objspace);
8407
8408 gc_sweep(objspace);
8409 }
8410
8411 if (is_lazy_sweeping(objspace)) {
8412 gc_sweeping_enter(objspace);
8413 gc_sweep_rest(objspace);
8414 gc_sweeping_exit(objspace);
8415 }
8416
8417 gc_exit(objspace, gc_enter_event_rest, &lock_lev);
8418
8419 if (RGENGC_CHECK_MODE >= 2) gc_verify_internal_consistency(objspace); /* after GC, see gc_start */
8420 }
8421}
8422
8425 unsigned int reason;
8426};
8427
8428static void
8429gc_current_status_fill(rb_objspace_t *objspace, char *buff)
8430{
8431 int i = 0;
8432 if (is_marking(objspace)) {
8433 buff[i++] = 'M';
8434 if (is_full_marking(objspace)) buff[i++] = 'F';
8435 if (is_incremental_marking(objspace)) buff[i++] = 'I';
8436 }
8437 else if (is_sweeping(objspace)) {
8438 buff[i++] = 'S';
8439 if (is_lazy_sweeping(objspace)) buff[i++] = 'L';
8440 }
8441 else {
8442 buff[i++] = 'N';
8443 }
8444 buff[i] = '\0';
8445}
8446
8447static const char *
8448gc_current_status(rb_objspace_t *objspace)
8449{
8450 static char buff[0x10];
8451 gc_current_status_fill(objspace, buff);
8452 return buff;
8453}
8454
8455#if PRINT_ENTER_EXIT_TICK
8456
8457static tick_t last_exit_tick;
8458static tick_t enter_tick;
8459static int enter_count = 0;
8460static char last_gc_status[0x10];
8461
8462static inline void
8463gc_record(rb_objspace_t *objspace, int direction, const char *event)
8464{
8465 if (direction == 0) { /* enter */
8466 enter_count++;
8467 enter_tick = tick();
8468 gc_current_status_fill(objspace, last_gc_status);
8469 }
8470 else { /* exit */
8471 tick_t exit_tick = tick();
8472 char current_gc_status[0x10];
8473 gc_current_status_fill(objspace, current_gc_status);
8474#if 1
8475 /* [last mutator time] [gc time] [event] */
8476 fprintf(stderr, "%"PRItick"\t%"PRItick"\t%s\t[%s->%s|%c]\n",
8477 enter_tick - last_exit_tick,
8478 exit_tick - enter_tick,
8479 event,
8480 last_gc_status, current_gc_status,
8481 (objspace->profile.latest_gc_info & GPR_FLAG_MAJOR_MASK) ? '+' : '-');
8482 last_exit_tick = exit_tick;
8483#else
8484 /* [enter_tick] [gc time] [event] */
8485 fprintf(stderr, "%"PRItick"\t%"PRItick"\t%s\t[%s->%s|%c]\n",
8486 enter_tick,
8487 exit_tick - enter_tick,
8488 event,
8489 last_gc_status, current_gc_status,
8490 (objspace->profile.latest_gc_info & GPR_FLAG_MAJOR_MASK) ? '+' : '-');
8491#endif
8492 }
8493}
8494#else /* PRINT_ENTER_EXIT_TICK */
8495static inline void
8496gc_record(rb_objspace_t *objspace, int direction, const char *event)
8497{
8498 /* null */
8499}
8500#endif /* PRINT_ENTER_EXIT_TICK */
8501
8502static const char *
8503gc_enter_event_cstr(enum gc_enter_event event)
8504{
8505 switch (event) {
8506 case gc_enter_event_start: return "start";
8507 case gc_enter_event_continue: return "continue";
8508 case gc_enter_event_rest: return "rest";
8509 case gc_enter_event_finalizer: return "finalizer";
8510 case gc_enter_event_global: return "global";
8511 case gc_enter_event_global_auto: return "global_auto";
8512 }
8513 return NULL;
8514}
8515
8516static void
8517gc_enter_count(enum gc_enter_event event)
8518{
8519 switch (event) {
8520 case gc_enter_event_start: RB_DEBUG_COUNTER_INC(gc_enter_start); break;
8521 case gc_enter_event_continue: RB_DEBUG_COUNTER_INC(gc_enter_continue); break;
8522 case gc_enter_event_rest: RB_DEBUG_COUNTER_INC(gc_enter_rest); break;
8523 case gc_enter_event_finalizer: RB_DEBUG_COUNTER_INC(gc_enter_finalizer); break;
8524 case gc_enter_event_global: RB_DEBUG_COUNTER_INC(gc_enter_start); break;
8525 case gc_enter_event_global_auto: RB_DEBUG_COUNTER_INC(gc_enter_start); break;
8526 }
8527}
8528
8529static bool current_process_time(struct timespec *ts);
8530
8531static void
8532gc_clock_start(struct timespec *ts)
8533{
8534 if (!current_process_time(ts)) {
8535 ts->tv_sec = 0;
8536 ts->tv_nsec = 0;
8537 }
8538}
8539
8540static unsigned long long
8541gc_clock_end(struct timespec *ts)
8542{
8543 struct timespec end_time;
8544
8545 if ((ts->tv_sec > 0 || ts->tv_nsec > 0) &&
8546 current_process_time(&end_time) &&
8547 end_time.tv_sec >= ts->tv_sec) {
8548 return (unsigned long long)(end_time.tv_sec - ts->tv_sec) * (1000 * 1000 * 1000) +
8549 (end_time.tv_nsec - ts->tv_nsec);
8550 }
8551
8552 return 0;
8553}
8554
8555/* Whether a non-global local GC holds the no-barrier VM lock for its whole run. Main's
8556 * ordinary local GC is lock-free; only compaction holds it (see the comment in the
8557 * function body). */
8558static inline bool
8559gc_local_gc_holds_vm_lock(const rb_objspace_t *objspace)
8560{
8561 /* Main's local GC is lock-free at the gc_enter level. The VM-global roots and JIT
8562 * root marks that need the VM lock take a bounded no-barrier window in rb_gc_mark_roots.
8563 * (JIT iseq payload marks and frees are not reached during a local GC: iseqs are born
8564 * shareable and a local GC never traverses or frees them.) Compaction takes its
8565 * barrier lock separately (gc_enter handles it before this function runs). */
8566 return objspace == global_objspace->main_objspace &&
8567 objspace->flags.during_compacting;
8568}
8569
8570static inline bool
8571gc_enter(rb_objspace_t *objspace, enum gc_enter_event event, unsigned int *lock_lev)
8572{
8573 /* A local GC runs on its owner thread and takes neither the VM lock nor a barrier:
8574 * containment makes the heap single-writer (only a stop-the-world global GC writes pages
8575 * across objspaces).
8576 *
8577 * Main's local GC walks VM-global roots (rb_vm_mark) and JIT root marks that change under
8578 * the VM lock but takes the lock in rb_gc_mark_roots rather than holding it for the full GC.
8579 *
8580 * NOTE: The GC must never take the barrier VM lock from inside itself: the waiter could
8581 * join a pending barrier mid-collection and expose its half-collected heap to the global
8582 * GC. A no-barrier lock is safe. Other shared structures the GC paths touch use their own
8583 * native mutexes or the page-pool lock. */
8584 *lock_lev = 0;
8585
8586 RUBY_DTRACE_GC_HOOK(ENTER, event);
8587
8588 if (objspace->profile.run) {
8589 switch (event) {
8590 case gc_enter_event_start:
8591 case gc_enter_event_continue:
8592 case gc_enter_event_rest:
8593 case gc_enter_event_global:
8594 case gc_enter_event_global_auto:
8595 /* A global GC is the longest pause the process takes, so it is the last thing
8596 * the profiler may leave unmeasured. The switch below stops the world for it,
8597 * which is exactly the interval gc_stop_time is meant to name, so start the
8598 * clock here like a local collection does. */
8599 objspace->profile.gc_pause_start_time = rb_hrtime_now();
8600 break;
8601 case gc_enter_event_finalizer:
8602 break;
8603 }
8604 }
8605 switch (event) {
8606 case gc_enter_event_global:
8607 *lock_lev = RB_GC_VM_LOCK();
8608 // stop other ractors
8609 rb_gc_vm_barrier();
8610 break;
8611 case gc_enter_event_global_auto:
8612 *lock_lev = RB_GC_VM_LOCK();
8613 if (!gc_need_global_p(objspace)) {
8614 RB_GC_VM_UNLOCK(*lock_lev);
8615 *lock_lev = 0;
8616 objspace->profile.gc_pause_start_time = 0;
8617 return false;
8618 }
8619 rb_gc_vm_barrier();
8620 break;
8621 case gc_enter_event_finalizer:
8622 /* Shutdown finalizers read VM-global tables (fstring, symbol) and free T_DATA that
8623 * is not thread-safe, so take the no-barrier VM lock. */
8624 *lock_lev = RB_GC_VM_LOCK_NO_BARRIER();
8625 break;
8626 default:
8627 objspace->flags.gc_lock_barrier = FALSE;
8628 if (objspace->flags.during_compacting) {
8629 /* Compaction relocates objects and rewrites every Ractor's JIT and global
8630 * references, so it stops the world with a barrier VM lock. rb_gc_vm_barrier is
8631 * a reentrant no-op with a single Ractor, so an inner barrier request during the
8632 * move folds into this one and gc_exit ends it. */
8633 *lock_lev = RB_GC_VM_LOCK();
8634 rb_gc_vm_barrier();
8635 objspace->flags.gc_lock_barrier = TRUE;
8636 }
8637 else if (gc_local_gc_holds_vm_lock(objspace)) {
8638 *lock_lev = RB_GC_VM_LOCK_NO_BARRIER();
8639 }
8640 break;
8641 }
8642
8643 if (objspace->profile.gc_pause_start_time) {
8644 objspace->profile.gc_stw_start_time = rb_hrtime_now();
8645 objspace->profile.gc_stop_time = rb_hrtime_sub(
8646 objspace->profile.gc_stw_start_time,
8647 objspace->profile.gc_pause_start_time);
8648 }
8649
8650 gc_enter_count(event);
8651 if (RB_UNLIKELY(during_gc != 0)) rb_bug("during_gc != 0");
8652 if (RGENGC_CHECK_MODE >= 3) gc_verify_internal_consistency(objspace);
8653
8654 during_gc = TRUE;
8655 RUBY_DEBUG_LOG("%s (%s)",gc_enter_event_cstr(event), gc_current_status(objspace));
8656 gc_report(1, objspace, "gc_enter: %s [%s]\n", gc_enter_event_cstr(event), gc_current_status(objspace));
8657 gc_record(objspace, 0, gc_enter_event_cstr(event));
8658
8659 gc_event_hook(objspace, RUBY_INTERNAL_EVENT_GC_ENTER);
8660 return true;
8661}
8662
8663static inline void
8664gc_exit(rb_objspace_t *objspace, enum gc_enter_event event, unsigned int *lock_lev)
8665{
8666 GC_ASSERT(during_gc != 0);
8667
8668 RUBY_DTRACE_GC_HOOK(EXIT, event);
8669
8670 gc_event_hook(objspace, RUBY_INTERNAL_EVENT_GC_EXIT);
8671
8672 if (objspace->profile.gc_pause_start_time) {
8673 if (gc_prof_enabled(objspace)) {
8674 rb_hrtime_t now = rb_hrtime_now();
8675 gc_profile_record *record = gc_prof_record(objspace);
8676 record->gc_pause_time = rb_hrtime_add(record->gc_pause_time,
8677 rb_hrtime_sub(now, objspace->profile.gc_pause_start_time));
8678 record->gc_stop_time = rb_hrtime_add(record->gc_stop_time,
8679 objspace->profile.gc_stop_time);
8680 record->gc_stw_time = rb_hrtime_add(record->gc_stw_time,
8681 rb_hrtime_sub(now, objspace->profile.gc_stw_start_time));
8682 }
8683 objspace->profile.gc_pause_start_time = 0;
8684 objspace->profile.gc_stw_start_time = 0;
8685 objspace->profile.gc_stop_time = 0;
8686 }
8687
8688 gc_record(objspace, 1, gc_enter_event_cstr(event));
8689 RUBY_DEBUG_LOG("%s (%s)", gc_enter_event_cstr(event), gc_current_status(objspace));
8690 gc_report(1, objspace, "gc_exit: %s [%s]\n", gc_enter_event_cstr(event), gc_current_status(objspace));
8691 during_gc = FALSE;
8692
8693 switch (event) {
8694 case gc_enter_event_global:
8695 case gc_enter_event_global_auto:
8696 RB_GC_VM_UNLOCK(*lock_lev);
8697 break;
8698 case gc_enter_event_finalizer:
8699 RB_GC_VM_UNLOCK_NO_BARRIER(*lock_lev);
8700 break;
8701 default:
8702 if (*lock_lev != 0) {
8703 if (objspace->flags.gc_lock_barrier) {
8704 objspace->flags.gc_lock_barrier = FALSE;
8705 RB_GC_VM_UNLOCK(*lock_lev);
8706 }
8707 else {
8708 RB_GC_VM_UNLOCK_NO_BARRIER(*lock_lev);
8709 }
8710 }
8711 break;
8712 }
8713}
8714
8715#ifndef MEASURE_GC
8716#define MEASURE_GC (objspace->flags.measure_gc)
8717#endif
8718
8719static void
8720gc_marking_enter(rb_objspace_t *objspace)
8721{
8722 GC_ASSERT(during_gc != 0);
8723
8724 gc_prof_mark_timer_start(objspace);
8725
8726 if (gc_prof_enabled(objspace)) {
8727 objspace->profile.gc_mark_phase_wall_start_time = rb_hrtime_now();
8728 }
8729
8730 if (MEASURE_GC) {
8731 gc_clock_start(&objspace->profile.marking_start_time);
8732 }
8733
8734 rb_gc_initialize_vm_context(&objspace->vm_context);
8735}
8736
8737static void
8738gc_marking_exit(rb_objspace_t *objspace)
8739{
8740 GC_ASSERT(during_gc != 0);
8741
8742 if (MEASURE_GC) {
8743 objspace->profile.marking_time_ns += gc_clock_end(&objspace->profile.marking_start_time);
8744 }
8745
8746 if (gc_prof_enabled(objspace)) {
8747 gc_profile_record *record = gc_prof_record(objspace);
8748 record->gc_mark_wall_time = rb_hrtime_add(record->gc_mark_wall_time,
8749 elapsed_hrtime_from(objspace->profile.gc_mark_phase_wall_start_time));
8750 }
8751
8752 gc_prof_mark_timer_stop(objspace);
8753}
8754
8755static void
8756gc_sweeping_enter(rb_objspace_t *objspace)
8757{
8758 GC_ASSERT(during_gc != 0);
8759
8760 if (gc_prof_enabled(objspace)) {
8761 objspace->profile.gc_sweep_phase_wall_start_time = rb_hrtime_now();
8762 objspace->profile.gc_sweep_excluded_wall_time = 0;
8763 }
8764
8765 if (MEASURE_GC) {
8766 gc_clock_start(&objspace->profile.sweeping_start_time);
8767 }
8768
8769 rb_gc_initialize_vm_context(&objspace->vm_context);
8770}
8771
8772static void
8773gc_sweeping_exit(rb_objspace_t *objspace)
8774{
8775 GC_ASSERT(during_gc != 0);
8776
8777 if (MEASURE_GC) {
8778 objspace->profile.sweeping_time_ns += gc_clock_end(&objspace->profile.sweeping_start_time);
8779 }
8780
8781 if (gc_prof_enabled(objspace)) {
8782 rb_hrtime_t sweep_wall_time = elapsed_hrtime_from(objspace->profile.gc_sweep_phase_wall_start_time);
8783 gc_profile_record *record = gc_prof_record(objspace);
8784 sweep_wall_time = rb_hrtime_sub(sweep_wall_time,
8785 objspace->profile.gc_sweep_excluded_wall_time);
8786 record->gc_sweep_wall_time = rb_hrtime_add(record->gc_sweep_wall_time,
8787 sweep_wall_time);
8788 objspace->profile.gc_sweep_excluded_wall_time = 0;
8789 }
8790}
8791
8792static void *
8793gc_with_gvl(void *ptr)
8794{
8795 struct objspace_and_reason *oar = (struct objspace_and_reason *)ptr;
8796 return (void *)(VALUE)garbage_collect(oar->objspace, oar->reason);
8797}
8798
8799int ruby_thread_has_gvl_p(void);
8800
8801static int
8802garbage_collect_with_gvl(rb_objspace_t *objspace, unsigned int reason)
8803{
8804 if (rb_gc_gc_disabled_global_p() || dont_gc_val()) {
8805 return TRUE;
8806 }
8807 else if (!ruby_native_thread_p()) {
8808 return TRUE;
8809 }
8810 else if (!ruby_thread_has_gvl_p()) {
8811 void *ret;
8812 struct objspace_and_reason oar;
8813 oar.objspace = objspace;
8814 oar.reason = reason;
8815 ret = rb_thread_call_with_gvl(gc_with_gvl, (void *)&oar);
8816
8817 return !!ret;
8818 }
8819 else {
8820 return garbage_collect(objspace, reason);
8821 }
8822}
8823
8824static int
8825gc_set_candidate_object_i(void *vstart, void *vend, size_t stride, void *data)
8826{
8828
8829 VALUE v = (VALUE)vstart;
8830 for (; v != (VALUE)vend; v += stride) {
8831 asan_unpoisoning_object(v) {
8832 switch (BUILTIN_TYPE(v)) {
8833 case T_NONE:
8834 case T_ZOMBIE:
8835 break;
8836 default:
8837 rb_gc_prepare_heap_process_object(v);
8838 if (!RVALUE_OLD_P(objspace, v) && !RVALUE_WB_UNPROTECTED(objspace, v)) {
8839 RVALUE_AGE_SET_CANDIDATE(objspace, v);
8840 }
8841 }
8842 }
8843 }
8844
8845 return 0;
8846}
8847
8848bool
8849rb_gc_impl_multi_objspace_p(void)
8850{
8851 return true;
8852}
8853
8854bool
8855rb_gc_impl_during_global_gc_p(void *objspace_ptr)
8856{
8857 rb_objspace_t *objspace = objspace_ptr;
8858 return objspace->flags.during_global_gc != 0;
8859}
8860
8861bool
8862rb_gc_impl_obj_foreign_p(void *objspace_ptr, VALUE obj)
8863{
8864 return gc_foreign_object_p(objspace_ptr, obj);
8865}
8866
8867
8868/* Whether obj is recorded as an unshareable object referenced from a shareable one. For
8869 * the verifier: a shareable -> unshareable edge is only accepted if the write barrier
8870 * recorded it here. */
8871bool
8872rb_gc_impl_shref_marked_p(void *objspace_ptr, VALUE obj)
8873{
8874 return MARKED_IN_BITMAP(GET_HEAP_SHREF_BITS(obj), obj) != 0;
8875}
8876
8877/* The objspace's current page count (used for the zombie_objspaces page accounting). */
8878size_t
8879rb_gc_impl_heap_page_count(void *objspace_ptr)
8880{
8881 rb_objspace_t *objspace = objspace_ptr;
8882 return rb_darray_size(objspace->heap_pages.sorted);
8883}
8884
8885static void
8886gc_global_objspaces_i(void *os, void *data)
8887{
8888 if (global_objspace->global_gc.n_objspaces == global_objspace->global_gc.objspaces_capa) {
8889 size_t new_capa = global_objspace->global_gc.objspaces_capa ? global_objspace->global_gc.objspaces_capa * 2 : 16;
8890 struct rb_objspace **new_list = realloc(global_objspace->global_gc.objspaces, new_capa * sizeof(*new_list));
8891 if (new_list == NULL) rb_bug("gc_global_objspaces_i: realloc failed");
8892 global_objspace->global_gc.objspaces = new_list;
8893 global_objspace->global_gc.objspaces_capa = new_capa;
8894 }
8895 global_objspace->global_gc.objspaces[global_objspace->global_gc.n_objspaces++] = os;
8896}
8897
8898/* Re-snapshot every objspace this cycle covers, zombies included. The objspaces/capa
8899 * buffer is reused from the previous cycle. */
8900static void
8901gc_global_snapshot_objspaces(void)
8902{
8903 global_objspace->global_gc.n_objspaces = 0;
8904 rb_gc_vm_each_objspace(gc_global_objspaces_i, NULL);
8905
8906#if RGENGC_CHECK_MODE
8907 /* Check that the incrementally maintained page_index agrees with the per-objspace
8908 * sorted arrays. */
8909 size_t total = 0;
8910 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
8911 total += rb_darray_size(global_objspace->global_gc.objspaces[i]->heap_pages.sorted);
8912 }
8913 GC_ASSERT(total == global_objspace->page_index.n_pages);
8914#endif
8915}
8916
8917/* Global GC: stop every Ractor and clear/mark/sweep all objspaces as one heap. It is the
8918 * only collector that can free shareable objects and decide cross-objspace reachability
8919 * precisely. */
8920/* The global GC's generic_fields weak pass, after the unified mark fixpoint, before the
8921 * sweep. Per-object rb_mark_generic_ivar is a no-op during a global GC (the driver has
8922 * GET_RACTOR() != owner); the whole table is swept here instead. Weak-KEY: mark the val
8923 * (fields_obj, a strong child) only for a live key, drain dead keys' entries. Marking a
8924 * val can make another key live, so repeat to a fixpoint. */
8927 bool progress;
8928};
8929
8930static int
8931genfields_mark_i(VALUE key, VALUE val, void *arg)
8932{
8933 struct genfields_mark_arg *a = (struct genfields_mark_arg *)arg;
8934 if (RB_SPECIAL_CONST_P(val) || !RVALUE_MARKED_BITMAP(key)) {
8935 return ST_CONTINUE;
8936 }
8937 /* Record the old(key)->young(val) edge with the host (key) as parent, even when val
8938 * is already marked: a conservative machine-stack scan can mark a fresh fields_obj
8939 * parentless before this pass, and branching on the mark bit would leave the key
8940 * unremembered, so the next minor GC misses the young val ("WB miss (O->Y)").
8941 * gc_mark runs rgengc_check_relation before its already-marked return: call always. */
8942 bool newly = !RVALUE_MARKED_BITMAP(val);
8943 gc_mark_set_parent(a->objspace, key);
8944 gc_mark(a->objspace, val);
8945 if (newly) a->progress = true;
8946 return ST_CONTINUE;
8947}
8948
8949static bool
8950genfields_dead_p(VALUE key)
8951{
8952 return RVALUE_MARKED_BITMAP(key) == 0;
8953}
8954
8955static void
8956gc_global_mark_generic_fields(rb_objspace_t *driver)
8957{
8958 struct genfields_mark_arg arg = { driver, false };
8959 do {
8960 arg.progress = false;
8961 /* Each entry's mark sets parent=key (genfields_mark_i) so the generational WB is
8962 * recorded correctly. gc_mark_stacked_objects_all sets its own per-object parent,
8963 * so restore the invalid parent (the poison contract) before calling it. */
8964 rb_gc_vm_generic_fields_mark_foreach(genfields_mark_i, &arg);
8965 gc_mark_set_parent_invalid(driver);
8966 if (arg.progress) {
8967 gc_mark_stacked_objects_all(driver);
8968 }
8969 } while (arg.progress);
8970
8971 rb_gc_vm_generic_fields_drain_dead(genfields_dead_p);
8972}
8973
8974/* Two Ractors choosing a global GC at once are serialized by the VM lock in gc_enter. If two
8975 * globals start concurrently, only one global will run and the other will run a local GC after
8976 * the barrier ends. */
8977static bool
8978gc_start_global(rb_objspace_t *driver, unsigned int reason, bool compact, bool allow_skip)
8979{
8980 unsigned int lock_lev;
8981 enum gc_enter_event event = allow_skip ? gc_enter_event_global_auto : gc_enter_event_global;
8982 if (!gc_enter(driver, event, &lock_lev)) {
8983 return false;
8984 }
8985
8986 /* A global GC is a collection of the driver's objspace too, and its profile.count
8987 * below says so, so report it like a local one. The driver is the objspace whose
8988 * count moves, which is the one a hook reading GC.stat would compare against. For
8989 * the same reason it records a profile entry and reports what triggered it. */
8990 gc_start_record(driver, reason, true);
8991 gc_event_hook(driver, RUBY_INTERNAL_EVENT_GC_START);
8992 gc_prof_timer_start(driver);
8993
8994 GC_ASSERT(is_mark_stack_empty(&driver->mark_stack));
8995
8996 gc_global_snapshot_objspaces();
8997
8998 /* Mark every objspace as in a global GC before step 3 settles the lazy sweeps: the
8999 * settle frees other objspaces' garbage on the driver thread, and
9000 * rb_free_generic_ivar must see "global GC in progress" to defer generic_fields
9001 * removal to the weak-pass drain. */
9002 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
9003 global_objspace->global_gc.objspaces[i]->flags.during_global_gc = TRUE;
9004 }
9005
9006 /* A global GC collects every objspace, so each needs the malloc-counter reset the
9007 * driver got in gc_start_record; without it, gc_sweep_finish advancing free_at_last_gc
9008 * (step 9) would leave their malloc_increase overstated by everything swept here. */
9009 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
9010 rb_objspace_t *const os = global_objspace->global_gc.objspaces[i];
9011 if (os != driver) {
9012 os->profile.latest_gc_info = reason;
9013 gc_reset_malloc_info(os, true);
9014 }
9015 }
9016
9017 /* step 3: settle every lazy sweep so the mark bits' meaning is fixed before the clear
9018 * below. (during_gc is a macro over the local "objspace".) rb_gc_get_ec() resolves
9019 * through objspace->vm_context during a GC, so initialize it for all: the driver
9020 * thread runs every objspace's phases. */
9021 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
9022 rb_objspace_t *objspace = global_objspace->global_gc.objspaces[i];
9023 /* No objspace can be mid-incremental-mark here: that only runs single-objspace
9024 * and vm_insert_ractor0 settles it on the transition. Clearing flags in step 5
9025 * under a live gray stack would break the owner's GC state machine. */
9026 GC_ASSERT(!is_incremental_marking(objspace));
9027 GC_ASSERT(is_mark_stack_empty(&objspace->mark_stack));
9028 rb_gc_initialize_vm_context(&objspace->vm_context);
9029 if (objspace != driver) during_gc = TRUE;
9030 gc_sweep_rest(objspace);
9031 }
9032
9033 /* step 5: clear every objspace's mark bits, remembered sets, generation counters and
9034 * shrefs (missing even one leaves a stale mark bit and a UAF). (heaps is a macro over
9035 * the local "objspace".) */
9036 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
9037 rb_objspace_t *objspace = global_objspace->global_gc.objspaces[i];
9038 objspace->flags.during_minor_gc = FALSE;
9039 objspace->flags.during_incremental_marking = FALSE;
9040 /* The unified mark is precise and does not pin, so the per-objspace sweep below must
9041 * not re-check against a stale local cycle. */
9042 objspace->last_cycle_pinned = 0;
9043 objspace->rgengc.uncollectible_wb_unprotected_objects = 0;
9044 objspace->rgengc.old_objects = 0;
9045 objspace->rgengc.last_major_gc = objspace->profile.count;
9046 objspace->marked_slots = 0;
9047 for (int h = 0; h < HEAP_COUNT; h++) {
9048 rb_heap_t *heap = &heaps[h];
9049 gc_bitmaps_clear(objspace, heap, true);
9050 heap_move_pooled_pages_to_free_pages(heap);
9051 }
9052 }
9053 driver->profile.major_gc_count++;
9054
9055 /* Enable compaction in every objspace before the mark: the unified conservative root
9056 * scan then pins machine-stack referents (gc_pin only pins while during_compacting)
9057 * and step 9's sweep relocates the rest. global_gc.compacting defers the
9058 * reference-update phase to phase 2 below (two phases, safe across objspaces). */
9059 global_objspace->global_gc.compacting = compact;
9060 if (compact) {
9061 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
9062 rb_objspace_t *objspace = global_objspace->global_gc.objspaces[i];
9063 objspace->flags.during_compacting = TRUE;
9064 /* A global GC skips gc_marks_start, which is what resets pinned_slots for a
9065 * compacting local GC, so reset it here. step 5 cleared pinned_bits; the
9066 * conservative mark re-pins machine-stack referents. */
9067 for (int h = 0; h < HEAP_COUNT; h++) {
9068 struct heap_page *page = NULL;
9069 ccan_list_for_each(&heaps[h].pages, page, page_node) {
9070 page->pinned_slots = 0;
9071 }
9072 }
9073 }
9074 }
9075
9076 /* steps 6-7: every Ractor's roots (gc.c walks them all and re-pins in-flight payloads),
9077 * then one unified precise mark. A global GC does not go through gc_marks, so the marking
9078 * phase is opened here instead; it closes after rb_ractor_finish_marking below, which is
9079 * where gc_marks_finish ends for a local collection. */
9080 gc_marking_enter(driver);
9081
9082 mark_roots(driver, NULL);
9083 gc_mark_stacked_objects_all(driver);
9084
9085 /* Run the generic_fields weak pass after the mark fixpoint: mark the vals (fields_obj)
9086 * of live keys and drain the entries of dead ones. The per-object rb_mark_generic_ivar
9087 * is a no-op during a global GC, so this is the only path that marks generic_fields. */
9088 gc_global_mark_generic_fields(driver);
9089
9090 gc_event_hook(driver, RUBY_INTERNAL_EVENT_GC_END_MARK);
9091
9092 /* step 8 */
9093 gc_update_weak_references(driver);
9094
9095 /* This cycle's root pass over every Ractor has swept the deleted ractor-local keys out of
9096 * each storage. Free the key structs while still inside the barrier (a local GC never
9097 * can; see rb_ractor_finish_marking). */
9098 rb_ractor_finish_marking();
9099
9100 gc_marking_exit(driver);
9101
9102 /* step 9: sweep every objspace inside the barrier, not lazily. Dead shareable objects
9103 * are reclaimed here and emptied pages go back to the pool. */
9104 if (!compact) {
9105 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
9106 rb_objspace_t *os = global_objspace->global_gc.objspaces[i];
9107 unsigned int prev_immediate = os->flags.immediate_sweep;
9108 os->flags.immediate_sweep = TRUE;
9109 gc_sweep(os);
9110 os->flags.immediate_sweep = prev_immediate;
9111 }
9112 }
9113 else {
9114 /* The move -> update-references -> free flow runs as three passes across ALL
9115 * objspaces, not per objspace: (a) updating references must see every objspace's
9116 * forwarding (a reference can point at a moved foreign object), and (b) freeing
9117 * source pages must wait until everyone is updated (or another objspace's update
9118 * reads a freed T_MOVED). The read barrier is installed once for all passes. */
9119 install_handlers();
9120
9121 /* Only the driver records a profile entry for a global GC (gc_start_record), so time
9122 * only the driver's compaction work. The move/update/free below runs inside the
9123 * driver's sweep phase (gc_sweeping_enter/exit); attribute it to GC_COMPACT_WALL_TIME
9124 * and exclude it from the driver's sweep wall time so the two do not double-count,
9125 * mirroring the compacting branch of the local gc_sweep(). */
9126 const bool driver_prof = gc_prof_enabled(driver);
9127 rb_hrtime_t driver_compact_wall_time = 0;
9128
9129 /* pass 1 (move): relocate every objspace and leave T_MOVED forwarding behind. */
9130 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
9131 rb_objspace_t *os = global_objspace->global_gc.objspaces[i];
9132 gc_sweeping_enter(os);
9133 gc_sweep_start(os); /* mode -> sweeping, order the heap for compaction */
9134 rb_hrtime_t t0 = (os == driver && driver_prof) ? rb_hrtime_now() : 0;
9135 gc_compact_relocate(os); /* mode -> compacting, move */
9136 if (os == driver && driver_prof) {
9137 driver_compact_wall_time = rb_hrtime_add(driver_compact_wall_time, elapsed_hrtime_from(t0));
9138 }
9139 }
9140
9141 /* pass 2 (update): all forwarding now exists, so update every objspace's
9142 * references (cross-objspace ones resolve too); gc_compact_finish also unprotects
9143 * pages and clears during_compacting. The move-or-mark decision reads
9144 * rb_gc_get_objspace()'s during_reference_updating: set it on every objspace. */
9145 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
9146 global_objspace->global_gc.objspaces[i]->flags.during_reference_updating = TRUE;
9147 }
9148 rb_gc_before_updating_jit_code();
9149 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
9150 rb_objspace_t *os = global_objspace->global_gc.objspaces[i];
9151 rb_hrtime_t t0 = (os == driver && driver_prof) ? rb_hrtime_now() : 0;
9152 gc_compact_finish(os);
9153 if (os == driver && driver_prof) {
9154 driver_compact_wall_time = rb_hrtime_add(driver_compact_wall_time, elapsed_hrtime_from(t0));
9155 }
9156 }
9157 /* The VM-global / weak-table side of the reference update runs once (each objspace's
9158 * heap side already ran in gc_compact_finish above). */
9159 {
9160 rb_hrtime_t t0 = driver_prof ? rb_hrtime_now() : 0;
9161 gc_update_references_global(driver);
9162 if (driver_prof) {
9163 driver_compact_wall_time = rb_hrtime_add(driver_compact_wall_time, elapsed_hrtime_from(t0));
9164 }
9165 }
9166 rb_gc_after_updating_jit_code();
9167 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
9168 global_objspace->global_gc.objspaces[i]->flags.during_reference_updating = FALSE;
9169 global_objspace->global_gc.objspaces[i]->flags.during_compacting = FALSE;
9170 }
9171 global_objspace->global_gc.compacting = false;
9172 uninstall_handlers();
9173
9174 /* Record the driver's compaction time and exclude it from the driver's sweep phase.
9175 * gc_sweeping_exit(driver) in pass 3 subtracts gc_sweep_excluded_wall_time from the
9176 * sweep wall time, so this must be set before it runs. The excluded value is a sum
9177 * of sub-intervals of the driver's sweep phase, so the subtraction cannot underflow. */
9178 if (driver_prof) {
9179 gc_profile_record *const record = gc_prof_record(driver);
9180 record->gc_compact_wall_time = rb_hrtime_add(record->gc_compact_wall_time,
9181 driver_compact_wall_time);
9182 driver->profile.gc_sweep_excluded_wall_time = rb_hrtime_add(
9183 driver->profile.gc_sweep_excluded_wall_time, driver_compact_wall_time);
9184 }
9185
9186 /* pass 3 (free): page-sweep every objspace, freeing dead objects and the source pages
9187 * that are now empty. during_compacting is already cleared, so the sweep treats
9188 * T_MOVED as usual. */
9189 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
9190 rb_objspace_t *os = global_objspace->global_gc.objspaces[i];
9191 gc_sweep_rest(os);
9192 gc_sweeping_exit(os);
9193 }
9194 }
9195 global_objspace->global_gc.compacting = false;
9196
9197 /* A global GC never calls gc_marks_finish, which budgets heap growth
9198 * (allocatable_bytes). An objspace still full after the global sweep (materializing
9199 * a large received copy, say) has no free pages, no empty pages, budget 0, and its next
9200 * allocation would hit newobj_refill's "cannot create a new page after a major GC".
9201 * Give every objspace stuck like that the growth budget gc_marks_finish would. */
9202 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
9203 rb_objspace_t *objspace = global_objspace->global_gc.objspaces[i];
9204 if (objspace->heap_pages.allocatable_bytes != 0 || objspace->empty_pages_count != 0) {
9205 continue;
9206 }
9207 bool stuck = false;
9208 for (int h = 0; h < HEAP_COUNT; h++) {
9209 if (heaps[h].free_pages == NULL) { stuck = true; break; }
9210 }
9211 if (stuck) {
9212 heap_allocatable_bytes_expand(objspace, NULL, 0,
9213 objspace_available_slots(objspace), heaps[0].slot_size);
9214 }
9215 }
9216
9217 /* Recount the surviving shareable objects (the sweep already folded the dead ones out of
9218 * shareable_bits) and reset each trigger limit. */
9219 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
9220 rb_objspace_t *objspace = global_objspace->global_gc.objspaces[i];
9221 size_t survivors = 0;
9222 for (int h = 0; h < HEAP_COUNT; h++) {
9223 struct heap_page *page = NULL;
9224 ccan_list_for_each(&heaps[h].pages, page, page_node) {
9225 if (!page->flags.has_shareable_objects) continue;
9226 for (int j = 0; j < HEAP_PAGE_BITMAP_LIMIT; j++) {
9227 survivors += rb_popcount_intptr(page->shareable_bits[j]);
9228 }
9229 }
9230 }
9231 objspace->shareable_objects = survivors;
9232 size_t new_limit = (size_t)(survivors * SHAREABLE_OBJECTS_LIMIT_FACTOR);
9233 if (new_limit < SHAREABLE_OBJECTS_LIMIT_MIN) new_limit = SHAREABLE_OBJECTS_LIMIT_MIN;
9234 objspace->shareable_objects_limit = new_limit;
9235 }
9236 driver->profile.count++;
9237
9238 /* step 10 */
9239 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
9240 rb_objspace_t *objspace = global_objspace->global_gc.objspaces[i];
9241 objspace->flags.during_global_gc = FALSE;
9242 if (objspace != driver) during_gc = FALSE;
9243 }
9244
9245 /* The unified mark re-established the reachability of absorbed shareable objects, so a
9246 * single objspace's local mark is trustworthy again (pinning can be skipped until the
9247 * next absorb). */
9248 rb_gc_reset_absorbed_since_global_gc();
9249
9250 /* Re-measure the zombie_objspaces table now that the garbage is gone; entries are stable
9251 * inside the barrier. Without this, the page trigger above keeps firing on the stale
9252 * numbers left when a joinable (slotted) zombie retires without any pass merging it. */
9253 rb_gc_vm_refresh_zombie_pages();
9254 global_objspace->zombie_pages_survivors = rb_gc_vm_zombie_total_pages();
9255
9256 /* If the sweep above collected an unjoined Ractor object, ractor_free disowned its
9257 * zombie_objspaces entry and posted the merge to main as a postponed job; the objspace
9258 * stays enumerable until main absorbs it at its next safepoint. */
9259
9260 gc_prof_timer_stop(driver);
9261 gc_exit(driver, event, &lock_lev);
9262 return true;
9263}
9264
9265static int
9266absorb_finalizer_i(st_data_t key, st_data_t val, st_data_t data)
9267{
9269 st_insert(finalizer_table, key, val);
9270 return ST_CONTINUE;
9271}
9272
9273/* Merge a dead Ractor's objspace into dst under the VM lock. src has no owner thread and
9274 * dst is the calling thread's own objspace (join/value) or main with everyone stopped
9275 * (global GC), so single-writer holds throughout. Pages move whole (their bits describe
9276 * objects, not the objspace), and dst's next collection is forced full to rebuild the
9277 * generational state. */
9278static void
9279objspace_absorb(rb_objspace_t *dst, rb_objspace_t *src)
9280{
9281 GC_ASSERT(dst != src);
9282
9283 /* Suppress the cross-objspace verifier checks while the graph is in flux (see
9284 * global_objspace->during_absorb). */
9285 const bool prev_absorb = global_objspace->during_absorb;
9286 global_objspace->during_absorb = true;
9287
9288 /* Settle dst first: adding pages under a walking lazy-sweep cursor, or into a
9289 * half-marked incremental heap, would sweep the merged pages with src's stale mark
9290 * bits and free live objects. (Normally settled already: vm_insert_ractor0's settle
9291 * means no objspace is incremental while a zombie waits to be absorbed.) */
9292 gc_rest(dst);
9293
9294 /* Settle src: no lazy sweep and no in-progress allocation page. */
9295 {
9296 rb_objspace_t *objspace = src;
9297 during_gc = TRUE;
9298 gc_sweep_rest(objspace);
9299 during_gc = FALSE;
9300 heap_alloc_state_clear(objspace);
9301 /* gc_sweep_finish leaves swept pages "pooled" for a coming incremental mark; src
9302 * never runs one (it is about to be merged), so return them to its free list now,
9303 * restoring the pooled_pages == NULL the page merge below assumes (mirrors
9304 * gc_start_global step 3). */
9305 for (int h = 0; h < HEAP_COUNT; h++) {
9306 heap_move_pooled_pages_to_free_pages(&heaps[h]);
9307 }
9308 }
9309
9310 /* From here the merge must not run dst's GC: the finalizer st_insert below can cross
9311 * the malloc-accounting threshold, and a GC then would sweep src's detached finalizer
9312 * procs, reachable only from this C frame, into dangling VALUEs. Page/darray moves
9313 * allocate nothing (_without_gc), so disabling costs nothing and makes the splice
9314 * atomic. (The two settles above deliberately collect: they stay outside.) */
9315 const bool dst_gc_was_enabled = rb_gc_impl_gc_enabled_p(dst);
9316 if (dst_gc_was_enabled) rb_gc_impl_gc_disable(dst, false);
9317
9318 /* Hand over the pages size pool by size pool. ("heaps" is a macro over the local
9319 * objspace, so the arrays are taken through scoped locals.) */
9320 rb_heap_t *dst_heaps;
9321 rb_heap_t *src_heaps;
9322 {
9323 rb_objspace_t *objspace = dst;
9324 dst_heaps = heaps;
9325 }
9326 {
9327 rb_objspace_t *objspace = src;
9328 src_heaps = heaps;
9329 }
9330 for (int h = 0; h < HEAP_COUNT; h++) {
9331 rb_heap_t *dheap = &dst_heaps[h];
9332 rb_heap_t *sheap = &src_heaps[h];
9333 struct heap_page *page = NULL;
9334
9335 GC_ASSERT(sheap->sweeping_page == NULL);
9336 GC_ASSERT(sheap->pooled_pages == NULL);
9337
9338 ccan_list_for_each(&sheap->pages, page, page_node) {
9339 page->objspace = dst;
9340 page->heap = dheap;
9341 }
9342 ccan_list_append_list(&dheap->pages, &sheap->pages);
9343
9344 /* Append the free-page chain to the tail. */
9345 if (sheap->free_pages) {
9346 struct heap_page **tail = &dheap->free_pages;
9347 while (*tail) tail = &(*tail)->free_next;
9348 *tail = sheap->free_pages;
9349 sheap->free_pages = NULL;
9350 }
9351
9352 dheap->total_pages += sheap->total_pages;
9353 dheap->total_slots += sheap->total_slots;
9354 dheap->total_allocated_pages += sheap->total_allocated_pages;
9355 dheap->total_allocated_objects += sheap->total_allocated_objects;
9356 dheap->total_freed_objects += sheap->total_freed_objects;
9357 dheap->final_slots_count += sheap->final_slots_count;
9358 }
9359
9360 /* The objspace-wide page bookkeeping. */
9361 {
9362 rb_objspace_t *objspace = dst; /* for the heap_pages_* macros */
9363 struct heap_page *page = NULL;
9364 size_t srcn = rb_darray_size(src->heap_pages.sorted);
9365 for (size_t i = 0; i < srcn; i++) {
9366 page = rb_darray_get(src->heap_pages.sorted, i);
9367 /* Residents of the empty pool (no live objects) are returned to page_pool rather
9368 * than inherited; dst's allocation demand is cheaply met from the shared pool's
9369 * free list. */
9370 if (heap_page_in_global_empty_pages_pool(src, page)) {
9371 heap_page_free(src, page);
9372 continue;
9373 }
9374 uintptr_t body = (uintptr_t)page->body;
9375 uintptr_t start = body + sizeof(struct heap_page_header);
9376 uintptr_t end = body + HEAP_PAGE_SIZE;
9377
9378 /* Keep the array ordered by page BODY address: heap_page_for_ptr bsearches
9379 * body ranges, and a detached empty page has start == 0, so ordering by
9380 * page->start would miss live pages (a global GC would then fail to mark a
9381 * registered root and sweep it). */
9382 size_t lo = 0;
9383 size_t hi = rb_darray_size(objspace->heap_pages.sorted);
9384 while (lo < hi) {
9385 size_t mid = (lo + hi) / 2;
9386 struct heap_page *mid_page = rb_darray_get(objspace->heap_pages.sorted, mid);
9387 if ((uintptr_t)mid_page->body < body) lo = mid + 1;
9388 else hi = mid;
9389 }
9390 rb_darray_insert_without_gc(&objspace->heap_pages.sorted, hi, page);
9391
9392 if (heap_pages_lomem == 0 || heap_pages_lomem > start) heap_pages_lomem = start;
9393 if (heap_pages_himem < end) heap_pages_himem = end;
9394 }
9395 objspace->heap_pages.allocated_pages += src->heap_pages.allocated_pages;
9396 objspace->heap_pages.freed_pages += src->heap_pages.freed_pages;
9397 rb_darray_free_without_gc(src->heap_pages.sorted);
9398 src->heap_pages.sorted = NULL;
9399 /* The empty_pages chain's structs were freed in the loop above. */
9400 src->empty_pages = NULL;
9401 src->empty_pages_count = 0;
9402 }
9403
9404 /* Finalizers: move the table's entries, and the dead Ractor's deferred zombies are run
9405 * by dst's thread from now on. */
9406 {
9407 st_table *src_finalizers;
9408 {
9409 rb_objspace_t *objspace = src;
9410 src_finalizers = finalizer_table;
9411 finalizer_table = NULL;
9412 }
9413 if (src_finalizers) {
9414 rb_objspace_t *objspace = dst;
9415 if (finalizer_table == NULL) {
9416 finalizer_table = src_finalizers;
9417 }
9418 else {
9419 st_foreach(src_finalizers, absorb_finalizer_i, (st_data_t)dst);
9420 st_free_table(src_finalizers);
9421 }
9422 }
9423 }
9424 {
9425 VALUE src_deferred = RUBY_ATOMIC_VALUE_EXCHANGE(src->heap_pages.deferred_final, 0);
9426 if (src_deferred) {
9427 VALUE tail_obj = src_deferred;
9428 rb_asan_unpoison_object(tail_obj, false);
9429 while (RZOMBIE(tail_obj)->next) {
9430 VALUE next_obj = RZOMBIE(tail_obj)->next;
9431 rb_asan_poison_object(tail_obj);
9432 tail_obj = next_obj;
9433 rb_asan_unpoison_object(tail_obj, false);
9434 }
9435 VALUE prev;
9436 do {
9437 prev = dst->heap_pages.deferred_final;
9438 RZOMBIE(tail_obj)->next = prev;
9439 } while (RUBY_ATOMIC_VALUE_CAS(dst->heap_pages.deferred_final, prev, src_deferred) != prev);
9440 rb_asan_poison_object(tail_obj);
9441 /* No owner was left to run these zombies (register's owner walk misses a dead
9442 * Ractor). dst runs this merge, so schedule dst's job here; otherwise they wait
9443 * until dst's next GC. */
9444 rb_postponed_job_trigger(dst->finalize_deferred_pjob);
9445 }
9446 }
9447
9448 /* Counters inherited by dst. */
9449 dst->rgengc.old_objects += src->rgengc.old_objects;
9450 dst->rgengc.uncollectible_wb_unprotected_objects += src->rgengc.uncollectible_wb_unprotected_objects;
9451 dst->shareable_objects += src->shareable_objects;
9452
9453 /* Merged pages carry src's mark/age state, so dst rebuilds its view at the next
9454 * collection. */
9455 dst->rgengc.need_major_gc |= GPR_FLAG_MAJOR_BY_FORCE;
9456
9457 /* src's outstanding malloc pressure moves with the xmalloc'd buffers. Later frees are
9458 * charged to dst, so without this transfer dst underestimates its own heap and delays
9459 * GCs. dst is live, so take its counter lock where gc_counter_add is not atomic. */
9460 {
9461 int64_t inc = gc_malloc_counters_increase(src, &src->malloc_counters.counters);
9462#if RGENGC_ESTIMATE_OLDMALLOC
9463 int64_t oldinc = gc_malloc_counters_increase(src, &src->malloc_counters.oldcounters);
9464#endif
9465 MALLOC_COUNTERS_LOCK(dst);
9466 if (inc > 0) gc_counter_add(&dst->malloc_counters.counters.malloc, (size_t)inc);
9467#if RGENGC_ESTIMATE_OLDMALLOC
9468 if (oldinc > 0) gc_counter_add(&dst->malloc_counters.oldcounters.malloc, (size_t)oldinc);
9469#endif
9470 MALLOC_COUNTERS_UNLOCK(dst);
9471 }
9472
9473 /* Free the shell (as rb_gc_impl_objspace_free does). */
9474 free(src->profile.records);
9475 free_stack_chunks(&src->mark_stack);
9476 mark_stack_free_cache(&src->mark_stack);
9477 GC_ASSERT(rb_darray_size(src->weak_references) == 0);
9478 rb_darray_free_without_gc(src->weak_references);
9479#ifdef MALLOC_COUNTERS_NEED_LOCK
9480 rb_native_mutex_destroy(&src->malloc_counters.lock);
9481#endif
9482 free(src);
9483
9484 if (dst_gc_was_enabled) rb_gc_impl_gc_enable(dst);
9485
9486 /* Return the empty pages inheritance piled up in dst (mostly from the dead Ractor's
9487 * teardown material) to the pool with no budget. An empty page is by definition safe to
9488 * release, and re-acquiring one from the pool is cheap. */
9489 {
9490 rb_objspace_t *objspace = dst;
9491 heap_pages_freeable_pages = objspace->empty_pages_count;
9492 heap_pages_free_unused_pages(objspace);
9493 }
9494
9495 global_objspace->during_absorb = prev_absorb;
9496}
9497
9498void
9499rb_gc_impl_objspace_absorb(void *dst_ptr, void *src_ptr)
9500{
9501 objspace_absorb(dst_ptr, src_ptr);
9502}
9503
9504void
9505rb_gc_impl_start(void *objspace_ptr, bool full_mark, bool immediate_mark, bool immediate_sweep, bool compact)
9506{
9507 rb_objspace_t *objspace = objspace_ptr;
9508 unsigned int reason = (GPR_FLAG_FULL_MARK |
9509 GPR_FLAG_IMMEDIATE_MARK |
9510 GPR_FLAG_IMMEDIATE_SWEEP |
9511 GPR_FLAG_METHOD);
9512
9513 int full_marking_p = gc_config_full_mark_val;
9514 gc_config_full_mark_set(TRUE);
9515
9516 /* With multiple objspaces the global GC's barrier makes relocation and the two-phase
9517 * reference update safe across all of them (gc_start_global with compact=true below);
9518 * single-objspace compaction takes the usual local path (gc_start w/ during_compacting). */
9519
9520 /* For now, compact implies full mark / sweep, so ignore other flags */
9521 if (compact) {
9522 GC_ASSERT(GC_COMPACTION_SUPPORTED);
9523
9524 reason |= GPR_FLAG_COMPACT;
9525 }
9526 else {
9527 if (!full_mark) reason &= ~GPR_FLAG_FULL_MARK;
9528 if (!immediate_mark) reason &= ~GPR_FLAG_IMMEDIATE_MARK;
9529 if (!immediate_sweep) reason &= ~GPR_FLAG_IMMEDIATE_SWEEP;
9530 }
9531
9532 /* An explicit full GC.start with multiple objspaces runs a global GC, the only
9533 * collector that reclaims shareable and cross-objspace garbage. It stops the world,
9534 * so auto_compact is honoured here too (mirroring full mark x autocompact locally). */
9535 if (!rb_gc_single_objspace_p() && (reason & GPR_FLAG_FULL_MARK)) {
9536 gc_start_global(objspace, reason, compact || ruby_enable_autocompact, false);
9537 }
9538 else {
9539 garbage_collect(objspace, reason);
9540 }
9541
9542 gc_finalize_deferred(objspace);
9543 gc_config_full_mark_set(full_marking_p);
9544}
9545
9546void
9547rb_gc_impl_prepare_heap(void *objspace_ptr)
9548{
9549 rb_objspace_t *objspace = objspace_ptr;
9550
9551 size_t orig_total_slots = objspace_available_slots(objspace);
9552 size_t orig_allocatable_bytes = objspace->heap_pages.allocatable_bytes;
9553
9554 rb_gc_impl_each_objects(objspace, gc_set_candidate_object_i, objspace_ptr);
9555
9556 double orig_max_free_slots = gc_params.heap_free_slots_max_ratio;
9557 /* Ensure that all empty pages are moved onto empty_pages. */
9558 gc_params.heap_free_slots_max_ratio = 0.0;
9559 rb_gc_impl_start(objspace, true, true, true, true);
9560 gc_params.heap_free_slots_max_ratio = orig_max_free_slots;
9561
9562 objspace->heap_pages.allocatable_bytes = 0;
9563 heap_pages_freeable_pages = objspace->empty_pages_count;
9564 heap_pages_free_unused_pages(objspace_ptr);
9565 GC_ASSERT(heap_pages_freeable_pages == 0);
9566 GC_ASSERT(objspace->empty_pages_count == 0);
9567 objspace->heap_pages.allocatable_bytes = orig_allocatable_bytes;
9568
9569 size_t total_slots = objspace_available_slots(objspace);
9570 if (orig_total_slots > total_slots) {
9571 objspace->heap_pages.allocatable_bytes += (orig_total_slots - total_slots) * heaps[0].slot_size;
9572 }
9573
9574#if defined(HAVE_MALLOC_TRIM) && !defined(RUBY_ALTERNATIVE_MALLOC_HEADER)
9575 malloc_trim(0);
9576#endif
9577}
9578
9579static int
9580gc_is_moveable_obj(rb_objspace_t *objspace, VALUE obj)
9581{
9582 GC_ASSERT(!SPECIAL_CONST_P(obj));
9583
9584 switch (BUILTIN_TYPE(obj)) {
9585 case T_NONE:
9586 case T_MOVED:
9587 case T_ZOMBIE:
9588 return FALSE;
9589 case T_SYMBOL:
9590 case T_STRING:
9591 case T_OBJECT:
9592 case T_FLOAT:
9593 case T_IMEMO:
9594 case T_ARRAY:
9595 case T_BIGNUM:
9596 case T_ICLASS:
9597 case T_MODULE:
9598 case T_REGEXP:
9599 case T_DATA:
9600 case T_MATCH:
9601 case T_STRUCT:
9602 case T_HASH:
9603 case T_FILE:
9604 case T_COMPLEX:
9605 case T_RATIONAL:
9606 case T_NODE:
9607 case T_CLASS:
9608 if (FL_TEST_RAW(obj, FL_FINALIZE)) {
9609 /* The finalizer table is a numtable. It looks up objects by address.
9610 * We can't mark the keys in the finalizer table because that would
9611 * prevent the objects from being collected. This check prevents
9612 * objects that are keys in the finalizer table from being moved
9613 * without directly pinning them. */
9614 GC_ASSERT(st_is_member(finalizer_table, obj));
9615
9616 return FALSE;
9617 }
9618 GC_ASSERT(RVALUE_MARKED(objspace, obj));
9619 GC_ASSERT(!RVALUE_PINNED(objspace, obj));
9620
9621 return TRUE;
9622
9623 default:
9624 rb_bug("gc_is_moveable_obj: unreachable (%d)", (int)BUILTIN_TYPE(obj));
9625 break;
9626 }
9627
9628 return FALSE;
9629}
9630
9631void rb_mv_generic_ivar(VALUE src, VALUE dst);
9632
9633static VALUE
9634gc_move(rb_objspace_t *objspace, VALUE src, VALUE dest, struct heap_page *src_page, struct heap_page *dest_page)
9635{
9636 size_t src_slot_size = src_page->slot_size;
9637 size_t slot_size = dest_page->slot_size;
9638
9639 int marked;
9640 int wb_unprotected;
9641 int uncollectible;
9642 int age;
9643
9644 gc_report(4, objspace, "Moving object: %p -> %p\n", (void *)src, (void *)dest);
9645
9646 GC_ASSERT(BUILTIN_TYPE(src) != T_NONE);
9647 GC_ASSERT(!MARKED_IN_BITMAP(GET_HEAP_MARK_BITS(dest), dest));
9648
9649 GC_ASSERT(!RVALUE_MARKING(objspace, src));
9650
9651 /* Save off bits for current object. */
9652 marked = RVALUE_MARKED(objspace, src);
9653 wb_unprotected = RVALUE_WB_UNPROTECTED(objspace, src);
9654 uncollectible = RVALUE_UNCOLLECTIBLE(objspace, src);
9655 bool remembered = RVALUE_REMEMBERED(objspace, src);
9656 /* Pin bits travel with the object. Losing one during single-objspace compaction would
9657 * silently unpin it once the process goes multi-objspace, letting a local GC free a method
9658 * entry or shref target that another Ractor references. */
9659 bool shareable = MARKED_IN_BITMAP(GET_HEAP_SHAREABLE_BITS(src), src) != 0;
9660 bool shref = MARKED_IN_BITMAP(GET_HEAP_SHREF_BITS(src), src) != 0;
9661 age = RVALUE_AGE_GET(src);
9662
9663 /* Clear bits for eventual T_MOVED */
9664 CLEAR_IN_BITMAP(GET_HEAP_MARK_BITS(src), src);
9665 CLEAR_IN_BITMAP(GET_HEAP_WB_UNPROTECTED_BITS(src), src);
9666 CLEAR_IN_BITMAP(GET_HEAP_UNCOLLECTIBLE_BITS(src), src);
9667 CLEAR_IN_BITMAP(GET_HEAP_PAGE(src)->remembered_bits, src);
9668 CLEAR_IN_BITMAP(GET_HEAP_SHAREABLE_BITS(src), src);
9669 CLEAR_IN_BITMAP(GET_HEAP_SHREF_BITS(src), src);
9670
9671 /* Move the object */
9672 memcpy((void *)dest, (void *)src, MIN(src_slot_size, slot_size));
9673
9674 if (src_slot_size != slot_size) {
9675 rb_gc_obj_changed_slot_size(dest, slot_size - RVALUE_OVERHEAD);
9676 }
9677
9678 if (RVALUE_OVERHEAD > 0) {
9679 void *dest_overhead = (void *)(((uintptr_t)dest) + slot_size - RVALUE_OVERHEAD);
9680 void *src_overhead = (void *)(((uintptr_t)src) + src_slot_size - RVALUE_OVERHEAD);
9681
9682 memcpy(dest_overhead, src_overhead, RVALUE_OVERHEAD);
9683 }
9684
9685 memset((void *)src, 0, src_slot_size);
9686 RVALUE_AGE_SET_BITMAP(src, 0);
9687
9688 /* Set bits for object in new location */
9689 if (remembered) {
9690 MARK_IN_BITMAP(GET_HEAP_PAGE(dest)->remembered_bits, dest);
9691 }
9692 else {
9693 CLEAR_IN_BITMAP(GET_HEAP_PAGE(dest)->remembered_bits, dest);
9694 }
9695
9696 if (marked) {
9697 MARK_IN_BITMAP(GET_HEAP_MARK_BITS(dest), dest);
9698 }
9699 else {
9700 CLEAR_IN_BITMAP(GET_HEAP_MARK_BITS(dest), dest);
9701 }
9702
9703 if (wb_unprotected) {
9704 MARK_IN_BITMAP(GET_HEAP_WB_UNPROTECTED_BITS(dest), dest);
9705 }
9706 else {
9707 CLEAR_IN_BITMAP(GET_HEAP_WB_UNPROTECTED_BITS(dest), dest);
9708 }
9709
9710 if (uncollectible) {
9711 MARK_IN_BITMAP(GET_HEAP_UNCOLLECTIBLE_BITS(dest), dest);
9712 }
9713 else {
9714 CLEAR_IN_BITMAP(GET_HEAP_UNCOLLECTIBLE_BITS(dest), dest);
9715 }
9716
9717 if (shareable) {
9718 MARK_IN_BITMAP(GET_HEAP_SHAREABLE_BITS(dest), dest);
9719 GET_HEAP_PAGE(dest)->flags.has_shareable_objects = TRUE;
9720 }
9721 else {
9722 CLEAR_IN_BITMAP(GET_HEAP_SHAREABLE_BITS(dest), dest);
9723 }
9724
9725 if (shref) {
9726 MARK_IN_BITMAP(GET_HEAP_SHREF_BITS(dest), dest);
9727 GET_HEAP_PAGE(dest)->flags.has_shref_objects = TRUE;
9728 }
9729 else {
9730 CLEAR_IN_BITMAP(GET_HEAP_SHREF_BITS(dest), dest);
9731 }
9732
9733 RVALUE_AGE_SET(dest, age);
9734
9735 /* A re-embedded object (rb_gc_obj_changed_slot_size) references its
9736 * former fields_obj's contents directly; the write-barrier history
9737 * lived on the discarded fields_obj, so remember the object. */
9738 if (src_slot_size != slot_size && age >= RVALUE_OLD_AGE && !remembered) {
9739 rgengc_remember(objspace, dest);
9740 }
9741
9742 /* Assign forwarding address */
9743 RMOVED(src)->flags = T_MOVED;
9744 RMOVED(src)->dummy = Qundef;
9745 RMOVED(src)->destination = dest;
9746 GC_ASSERT(BUILTIN_TYPE(dest) != T_NONE);
9747
9748 GET_HEAP_PAGE(src)->heap->total_freed_objects++;
9749 GET_HEAP_PAGE(dest)->heap->total_allocated_objects++;
9750
9751 return src;
9752}
9753
9754#if GC_CAN_COMPILE_COMPACTION
9755static int
9756compare_pinned_slots(const void *left, const void *right, void *dummy)
9757{
9758 struct heap_page *left_page;
9759 struct heap_page *right_page;
9760
9761 left_page = *(struct heap_page * const *)left;
9762 right_page = *(struct heap_page * const *)right;
9763
9764 return left_page->pinned_slots - right_page->pinned_slots;
9765}
9766
9767static int
9768compare_free_slots(const void *left, const void *right, void *dummy)
9769{
9770 struct heap_page *left_page;
9771 struct heap_page *right_page;
9772
9773 left_page = *(struct heap_page * const *)left;
9774 right_page = *(struct heap_page * const *)right;
9775
9776 return left_page->free_slots - right_page->free_slots;
9777}
9778
9779static void
9780gc_sort_heap_by_compare_func(rb_objspace_t *objspace, gc_compact_compare_func compare_func)
9781{
9782 for (int j = 0; j < HEAP_COUNT; j++) {
9783 rb_heap_t *heap = &heaps[j];
9784
9785 size_t total_pages = heap->total_pages;
9786 size_t size = rb_size_mul_or_raise(total_pages, sizeof(struct heap_page *), rb_eRuntimeError);
9787 struct heap_page *page = 0, **page_list = malloc(size);
9788 size_t i = 0;
9789
9790 heap->free_pages = NULL;
9791 ccan_list_for_each(&heap->pages, page, page_node) {
9792 page_list[i++] = page;
9793 GC_ASSERT(page);
9794 }
9795
9796 GC_ASSERT((size_t)i == total_pages);
9797
9798 /* Sort the heap so "filled pages" are first. `heap_add_page` adds to the
9799 * head of the list, so empty pages will end up at the start of the heap */
9800 ruby_qsort(page_list, total_pages, sizeof(struct heap_page *), compare_func, NULL);
9801
9802 /* Reset the eden heap */
9803 ccan_list_head_init(&heap->pages);
9804
9805 for (i = 0; i < total_pages; i++) {
9806 ccan_list_add(&heap->pages, &page_list[i]->page_node);
9807 if (page_list[i]->free_slots != 0) {
9808 heap_add_freepage(heap, page_list[i]);
9809 }
9810 }
9811
9812 free(page_list);
9813 }
9814}
9815#endif
9816
9817void
9818rb_gc_impl_register_pinning_obj(void *objspace_ptr, VALUE obj)
9819{
9820 /* no-op */
9821}
9822
9823bool
9824rb_gc_impl_object_moved_p(void *objspace_ptr, VALUE obj)
9825{
9826 return gc_object_moved_p(objspace_ptr, obj);
9827}
9828
9829static int
9830gc_ref_update(void *vstart, void *vend, size_t stride, rb_objspace_t *objspace, struct heap_page *page)
9831{
9832 VALUE v = (VALUE)vstart;
9833
9834 page->flags.has_uncollectible_wb_unprotected_objects = FALSE;
9835 page->flags.has_remembered_objects = FALSE;
9836
9837 /* For each object on the page */
9838 for (; v != (VALUE)vend; v += stride) {
9839 asan_unpoisoning_object(v) {
9840 switch (BUILTIN_TYPE(v)) {
9841 case T_NONE:
9842 case T_MOVED:
9843 case T_ZOMBIE:
9844 break;
9845 default:
9846 if (RVALUE_WB_UNPROTECTED(objspace, v)) {
9847 page->flags.has_uncollectible_wb_unprotected_objects = TRUE;
9848 }
9849 if (RVALUE_REMEMBERED(objspace, v)) {
9850 page->flags.has_remembered_objects = TRUE;
9851 }
9852 if (page->flags.before_sweep) {
9853 if (RVALUE_MARKED(objspace, v)) {
9854 rb_gc_update_object_references(objspace, v);
9855 }
9856 }
9857 else {
9858 rb_gc_update_object_references(objspace, v);
9859 }
9860 }
9861 }
9862 }
9863
9864 return 0;
9865}
9866
9867static int
9868gc_update_references_weak_table_i(VALUE obj, void *data)
9869{
9870 int ret;
9871 asan_unpoisoning_object(obj) {
9872 ret = BUILTIN_TYPE(obj) == T_MOVED ? ST_REPLACE : ST_CONTINUE;
9873 }
9874 return ret;
9875}
9876
9877static int
9878gc_update_references_weak_table_replace_i(VALUE *obj, void *data)
9879{
9880 *obj = rb_gc_location(*obj);
9881
9882 return ST_CONTINUE;
9883}
9884
9885/* The per-objspace side of the reference update: walk this objspace's heap objects and rewrite
9886 * moved references (following T_MOVED forwarding across objspaces). A compacting global GC
9887 * runs this for every objspace. */
9888static void
9889gc_update_references_heap(rb_objspace_t *objspace)
9890{
9891 struct heap_page *page = NULL;
9892
9893 for (int i = 0; i < HEAP_COUNT; i++) {
9894 bool should_set_mark_bits = TRUE;
9895 rb_heap_t *heap = &heaps[i];
9896
9897 ccan_list_for_each(&heap->pages, page, page_node) {
9898 uintptr_t start = (uintptr_t)page->start;
9899 uintptr_t end = start + (page->total_slots * heap->slot_size);
9900
9901 gc_ref_update((void *)start, (void *)end, heap->slot_size, objspace, page);
9902 if (page == heap->sweeping_page) {
9903 should_set_mark_bits = FALSE;
9904 }
9905 if (should_set_mark_bits) {
9906 gc_setup_mark_bits(page);
9907 }
9908 }
9909 }
9910}
9911
9912/* The VM-global side of the reference update (finalizer table, every Ractor's VM roots,
9913 * weak tables). Process-wide, so a compacting global GC runs it once after every heap
9914 * side: rb_gc_update_vm_references and the weak tables' mark_and_move are not idempotent. */
9915static void
9916gc_update_references_global(rb_objspace_t *objspace)
9917{
9918 gc_update_table_refs(finalizer_table);
9919
9920 rb_gc_update_vm_references((void *)objspace);
9921
9922 for (int table = 0; table < RB_GC_VM_WEAK_TABLE_COUNT; table++) {
9923 rb_gc_vm_weak_table_foreach(
9924 gc_update_references_weak_table_i,
9925 gc_update_references_weak_table_replace_i,
9926 NULL,
9927 false,
9928 table
9929 );
9930 }
9931}
9932
9933static void
9934gc_update_references(rb_objspace_t *objspace)
9935{
9936 objspace->flags.during_reference_updating = true;
9937
9938 rb_gc_before_updating_jit_code();
9939
9940 gc_update_references_heap(objspace);
9941 gc_update_references_global(objspace);
9942
9943 rb_gc_after_updating_jit_code();
9944
9945 objspace->flags.during_reference_updating = false;
9946}
9947
9948#if GC_CAN_COMPILE_COMPACTION
9949static void
9950root_obj_check_moved_i(const char *category, VALUE obj, void *data)
9951{
9952 rb_objspace_t *objspace = data;
9953
9954 if (gc_object_moved_p(objspace, obj)) {
9955 rb_bug("ROOT %s points to MOVED: %p -> %s", category, (void *)obj, rb_obj_info(rb_gc_impl_location(objspace, obj)));
9956 }
9957}
9958
9959static void
9960reachable_object_check_moved_i(VALUE ref, void *data)
9961{
9962 VALUE parent = (VALUE)data;
9963 if (gc_object_moved_p(rb_gc_get_objspace(), ref)) {
9964 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)));
9965 }
9966}
9967
9968static int
9969heap_check_moved_i(void *vstart, void *vend, size_t stride, void *data)
9970{
9971 rb_objspace_t *objspace = data;
9972
9973 VALUE v = (VALUE)vstart;
9974 for (; v != (VALUE)vend; v += stride) {
9975 if (gc_object_moved_p(objspace, v)) {
9976 /* Moved object still on the heap, something may have a reference. */
9977 }
9978 else {
9979 asan_unpoisoning_object(v) {
9980 switch (BUILTIN_TYPE(v)) {
9981 case T_NONE:
9982 case T_ZOMBIE:
9983 break;
9984 default:
9985 if (!rb_gc_impl_garbage_object_p(objspace, v)) {
9986 rb_objspace_reachable_objects_from(v, reachable_object_check_moved_i, (void *)v);
9987 }
9988 }
9989 }
9990 }
9991 }
9992
9993 return 0;
9994}
9995#endif
9996
9997bool
9998rb_gc_impl_during_gc_p(void *objspace_ptr)
9999{
10000 rb_objspace_t *objspace = objspace_ptr;
10001
10002 return during_gc;
10003}
10004
10005#if RGENGC_PROFILE >= 2
10006
10007static const char*
10008type_name(int type, VALUE obj)
10009{
10010 switch ((enum ruby_value_type)type) {
10011 case RUBY_T_NONE: return "T_NONE";
10012 case RUBY_T_OBJECT: return "T_OBJECT";
10013 case RUBY_T_CLASS: return "T_CLASS";
10014 case RUBY_T_MODULE: return "T_MODULE";
10015 case RUBY_T_FLOAT: return "T_FLOAT";
10016 case RUBY_T_STRING: return "T_STRING";
10017 case RUBY_T_REGEXP: return "T_REGEXP";
10018 case RUBY_T_ARRAY: return "T_ARRAY";
10019 case RUBY_T_HASH: return "T_HASH";
10020 case RUBY_T_STRUCT: return "T_STRUCT";
10021 case RUBY_T_BIGNUM: return "T_BIGNUM";
10022 case RUBY_T_FILE: return "T_FILE";
10023 case RUBY_T_DATA: return "T_DATA";
10024 case RUBY_T_MATCH: return "T_MATCH";
10025 case RUBY_T_COMPLEX: return "T_COMPLEX";
10026 case RUBY_T_RATIONAL: return "T_RATIONAL";
10027 case RUBY_T_NIL: return "T_NIL";
10028 case RUBY_T_TRUE: return "T_TRUE";
10029 case RUBY_T_FALSE: return "T_FALSE";
10030 case RUBY_T_SYMBOL: return "T_SYMBOL";
10031 case RUBY_T_FIXNUM: return "T_FIXNUM";
10032 case RUBY_T_UNDEF: return "T_UNDEF";
10033 case RUBY_T_IMEMO: return "T_IMEMO";
10034 case RUBY_T_NODE: return "T_NODE";
10035 case RUBY_T_ICLASS: return "T_ICLASS";
10036 case RUBY_T_ZOMBIE: return "T_ZOMBIE";
10037 case RUBY_T_MOVED: return "T_MOVED";
10038 default: return "unknown";
10039 }
10040}
10041
10042static void
10043gc_count_add_each_types(VALUE hash, const char *name, const size_t *types)
10044{
10045 VALUE result = rb_hash_new_with_size(T_MASK);
10046 int i;
10047 for (i=0; i<T_MASK; i++) {
10048 const char *type = type_name(i, 0);
10049 rb_hash_aset(result, ID2SYM(rb_intern(type)), SIZET2NUM(types[i]));
10050 }
10051 rb_hash_aset(hash, ID2SYM(rb_intern(name)), result);
10052}
10053#endif
10054
10055size_t
10056rb_gc_impl_gc_count(void *objspace_ptr)
10057{
10058 rb_objspace_t *objspace = objspace_ptr;
10059
10060 return objspace->profile.count;
10061}
10062
10063static VALUE
10064gc_info_decode(rb_objspace_t *objspace, const VALUE hash_or_key, const unsigned int orig_flags)
10065{
10066 static VALUE sym_major_by = Qnil, sym_gc_by, sym_immediate_sweep, sym_have_finalizer, sym_state, sym_need_major_by;
10067 static VALUE sym_nofree, sym_oldgen, sym_shady, sym_force, sym_stress;
10068#if RGENGC_ESTIMATE_OLDMALLOC
10069 static VALUE sym_oldmalloc;
10070#endif
10071 static VALUE sym_newobj, sym_malloc, sym_method, sym_capi;
10072 static VALUE sym_none, sym_marking, sym_sweeping;
10073 static VALUE sym_weak_references_count;
10074 VALUE hash = Qnil, key = Qnil;
10075 VALUE major_by, need_major_by;
10076 unsigned int flags = orig_flags ? orig_flags : objspace->profile.latest_gc_info;
10077
10078 if (SYMBOL_P(hash_or_key)) {
10079 key = hash_or_key;
10080 }
10081 else if (RB_TYPE_P(hash_or_key, T_HASH)) {
10082 hash = hash_or_key;
10083 }
10084 else {
10085 rb_bug("gc_info_decode: non-hash or symbol given");
10086 }
10087
10088 if (NIL_P(sym_major_by)) {
10089#define S(s) sym_##s = ID2SYM(rb_intern_const(#s))
10090 S(major_by);
10091 S(gc_by);
10092 S(immediate_sweep);
10093 S(have_finalizer);
10094 S(state);
10095 S(need_major_by);
10096
10097 S(stress);
10098 S(nofree);
10099 S(oldgen);
10100 S(shady);
10101 S(force);
10102#if RGENGC_ESTIMATE_OLDMALLOC
10103 S(oldmalloc);
10104#endif
10105 S(newobj);
10106 S(malloc);
10107 S(method);
10108 S(capi);
10109
10110 S(none);
10111 S(marking);
10112 S(sweeping);
10113
10114 S(weak_references_count);
10115#undef S
10116 }
10117
10118#define SET(name, attr) \
10119 if (key == sym_##name) \
10120 return (attr); \
10121 else if (hash != Qnil) \
10122 rb_hash_aset(hash, sym_##name, (attr));
10123
10124 major_by =
10125 (flags & GPR_FLAG_MAJOR_BY_NOFREE) ? sym_nofree :
10126 (flags & GPR_FLAG_MAJOR_BY_OLDGEN) ? sym_oldgen :
10127 (flags & GPR_FLAG_MAJOR_BY_SHADY) ? sym_shady :
10128 (flags & GPR_FLAG_MAJOR_BY_FORCE) ? sym_force :
10129#if RGENGC_ESTIMATE_OLDMALLOC
10130 (flags & GPR_FLAG_MAJOR_BY_OLDMALLOC) ? sym_oldmalloc :
10131#endif
10132 Qnil;
10133 SET(major_by, major_by);
10134
10135 if (orig_flags == 0) { /* set need_major_by only if flags not set explicitly */
10136 unsigned int need_major_flags = gc_needs_major_flags;
10137 need_major_by =
10138 (need_major_flags & GPR_FLAG_MAJOR_BY_NOFREE) ? sym_nofree :
10139 (need_major_flags & GPR_FLAG_MAJOR_BY_OLDGEN) ? sym_oldgen :
10140 (need_major_flags & GPR_FLAG_MAJOR_BY_SHADY) ? sym_shady :
10141 (need_major_flags & GPR_FLAG_MAJOR_BY_FORCE) ? sym_force :
10142#if RGENGC_ESTIMATE_OLDMALLOC
10143 (need_major_flags & GPR_FLAG_MAJOR_BY_OLDMALLOC) ? sym_oldmalloc :
10144#endif
10145 Qnil;
10146 SET(need_major_by, need_major_by);
10147 }
10148
10149 SET(gc_by,
10150 (flags & GPR_FLAG_NEWOBJ) ? sym_newobj :
10151 (flags & GPR_FLAG_MALLOC) ? sym_malloc :
10152 (flags & GPR_FLAG_METHOD) ? sym_method :
10153 (flags & GPR_FLAG_CAPI) ? sym_capi :
10154 (flags & GPR_FLAG_STRESS) ? sym_stress :
10155 Qnil
10156 );
10157
10158 SET(have_finalizer, (flags & GPR_FLAG_HAVE_FINALIZE) ? Qtrue : Qfalse);
10159 SET(immediate_sweep, (flags & GPR_FLAG_IMMEDIATE_SWEEP) ? Qtrue : Qfalse);
10160
10161 if (orig_flags == 0) {
10162 SET(state, gc_mode(objspace) == gc_mode_none ? sym_none :
10163 gc_mode(objspace) == gc_mode_marking ? sym_marking : sym_sweeping);
10164 }
10165
10166 SET(weak_references_count, LONG2FIX(objspace->profile.weak_references_count));
10167#undef SET
10168
10169 if (!NIL_P(key)) {
10170 // Matched key should return above
10171 return Qundef;
10172 }
10173
10174 return hash;
10175}
10176
10177VALUE
10178rb_gc_impl_latest_gc_info(void *objspace_ptr, VALUE key)
10179{
10180 rb_objspace_t *objspace = objspace_ptr;
10181
10182 return gc_info_decode(objspace, key, 0);
10183}
10184
10185
10186enum gc_stat_sym {
10187 gc_stat_sym_count,
10188 gc_stat_sym_time,
10189 gc_stat_sym_marking_time,
10190 gc_stat_sym_sweeping_time,
10191 gc_stat_sym_heap_allocated_pages,
10192 gc_stat_sym_heap_empty_pages,
10193 gc_stat_sym_heap_allocatable_bytes,
10194 gc_stat_sym_heap_available_slots,
10195 gc_stat_sym_heap_live_slots,
10196 gc_stat_sym_heap_free_slots,
10197 gc_stat_sym_heap_final_slots,
10198 gc_stat_sym_heap_marked_slots,
10199 gc_stat_sym_heap_eden_pages,
10200 gc_stat_sym_total_allocated_pages,
10201 gc_stat_sym_total_freed_pages,
10202 gc_stat_sym_total_allocated_objects,
10203 gc_stat_sym_total_freed_objects,
10204 gc_stat_sym_total_malloc_bytes,
10205 gc_stat_sym_total_free_bytes,
10206 gc_stat_sym_malloc_increase_bytes,
10207 gc_stat_sym_malloc_increase_bytes_limit,
10208 gc_stat_sym_minor_gc_count,
10209 gc_stat_sym_major_gc_count,
10210 gc_stat_sym_compact_count,
10211 gc_stat_sym_read_barrier_faults,
10212 gc_stat_sym_total_moved_objects,
10213 gc_stat_sym_remembered_wb_unprotected_objects,
10214 gc_stat_sym_remembered_wb_unprotected_objects_limit,
10215 gc_stat_sym_old_objects,
10216 gc_stat_sym_old_objects_limit,
10217#if RGENGC_ESTIMATE_OLDMALLOC
10218 gc_stat_sym_oldmalloc_increase_bytes,
10219 gc_stat_sym_oldmalloc_increase_bytes_limit,
10220#endif
10221#if RGENGC_PROFILE
10222 gc_stat_sym_total_generated_normal_object_count,
10223 gc_stat_sym_total_generated_shady_object_count,
10224 gc_stat_sym_total_shade_operation_count,
10225 gc_stat_sym_total_promoted_count,
10226 gc_stat_sym_total_remembered_normal_object_count,
10227 gc_stat_sym_total_remembered_shady_object_count,
10228#endif
10229 gc_stat_sym_page_pool_arenas,
10230 gc_stat_sym_page_pool_arenas_freed,
10231 gc_stat_sym_page_pool_total_pages,
10232 gc_stat_sym_page_pool_discarded_pages,
10233 gc_stat_sym_last
10234};
10235
10236static VALUE gc_stat_symbols[gc_stat_sym_last];
10237
10238static void
10239setup_gc_stat_symbols(void)
10240{
10241 if (gc_stat_symbols[0] == 0) {
10242#define S(s) gc_stat_symbols[gc_stat_sym_##s] = ID2SYM(rb_intern_const(#s))
10243 S(count);
10244 S(time);
10245 S(marking_time),
10246 S(sweeping_time),
10247 S(heap_allocated_pages);
10248 S(heap_empty_pages);
10249 S(heap_allocatable_bytes);
10250 S(heap_available_slots);
10251 S(heap_live_slots);
10252 S(heap_free_slots);
10253 S(heap_final_slots);
10254 S(heap_marked_slots);
10255 S(heap_eden_pages);
10256 S(total_allocated_pages);
10257 S(total_freed_pages);
10258 S(total_allocated_objects);
10259 S(total_freed_objects);
10260 S(total_malloc_bytes);
10261 S(total_free_bytes);
10262 S(malloc_increase_bytes);
10263 S(malloc_increase_bytes_limit);
10264 S(minor_gc_count);
10265 S(major_gc_count);
10266 S(compact_count);
10267 S(read_barrier_faults);
10268 S(total_moved_objects);
10269 S(remembered_wb_unprotected_objects);
10270 S(remembered_wb_unprotected_objects_limit);
10271 S(old_objects);
10272 S(old_objects_limit);
10273#if RGENGC_ESTIMATE_OLDMALLOC
10274 S(oldmalloc_increase_bytes);
10275 S(oldmalloc_increase_bytes_limit);
10276#endif
10277#if RGENGC_PROFILE
10278 S(total_generated_normal_object_count);
10279 S(total_generated_shady_object_count);
10280 S(total_shade_operation_count);
10281 S(total_promoted_count);
10282 S(total_remembered_normal_object_count);
10283 S(total_remembered_shady_object_count);
10284#endif /* RGENGC_PROFILE */
10285 S(page_pool_arenas);
10286 S(page_pool_arenas_freed);
10287 S(page_pool_total_pages);
10288 S(page_pool_discarded_pages);
10289#undef S
10290 }
10291}
10292
10293static uint64_t
10294ns_to_ms(uint64_t ns)
10295{
10296 return ns / (1000 * 1000);
10297}
10298
10299static void malloc_increase_local_flush(rb_objspace_t *objspace);
10300
10301VALUE
10302rb_gc_impl_stat(void *objspace_ptr, VALUE hash_or_sym)
10303{
10304 rb_objspace_t *objspace = objspace_ptr;
10305 VALUE hash = Qnil, key = Qnil;
10306
10307 setup_gc_stat_symbols();
10308
10309 malloc_increase_local_flush(objspace);
10310
10311 if (RB_TYPE_P(hash_or_sym, T_HASH)) {
10312 hash = hash_or_sym;
10313 }
10314 else if (SYMBOL_P(hash_or_sym)) {
10315 key = hash_or_sym;
10316 }
10317 else {
10318 rb_bug("non-hash or symbol given");
10319 }
10320
10321#define SET(name, attr) \
10322 if (key == gc_stat_symbols[gc_stat_sym_##name]) \
10323 return SIZET2NUM(attr); \
10324 else if (hash != Qnil) \
10325 rb_hash_aset(hash, gc_stat_symbols[gc_stat_sym_##name], SIZET2NUM(attr));
10326#define SET64(name, attr) \
10327 if (key == gc_stat_symbols[gc_stat_sym_##name]) \
10328 return ULL2NUM(attr); \
10329 else if (hash != Qnil) \
10330 rb_hash_aset(hash, gc_stat_symbols[gc_stat_sym_##name], ULL2NUM(attr));
10331
10332 SET(count, objspace->profile.count);
10333 SET(time, (size_t)ns_to_ms(objspace->profile.marking_time_ns + objspace->profile.sweeping_time_ns)); // TODO: UINT64T2NUM
10334 SET(marking_time, (size_t)ns_to_ms(objspace->profile.marking_time_ns));
10335 SET(sweeping_time, (size_t)ns_to_ms(objspace->profile.sweeping_time_ns));
10336
10337 {
10338 uint64_t total_malloc = (uint64_t)gc_counter_load_relaxed(&objspace->malloc_counters.counters.malloc);
10339 uint64_t total_free = (uint64_t)gc_counter_load_relaxed(&objspace->malloc_counters.counters.free);
10340 SET64(total_malloc_bytes, total_malloc);
10341 SET64(total_free_bytes, total_free);
10342 }
10343
10344 /* implementation dependent counters (small / fixnum-safe) */
10345 SET(heap_allocated_pages, rb_darray_size(objspace->heap_pages.sorted));
10346 SET(heap_empty_pages, objspace->empty_pages_count)
10347 SET(heap_allocatable_bytes, objspace->heap_pages.allocatable_bytes);
10348 SET(heap_eden_pages, heap_eden_total_pages(objspace));
10349 SET(total_allocated_pages, objspace->heap_pages.allocated_pages);
10350 SET(total_freed_pages, objspace->heap_pages.freed_pages);
10351 SET(malloc_increase_bytes, gc_malloc_counters_increase_unsigned(objspace, &objspace->malloc_counters.counters));
10352 SET(malloc_increase_bytes_limit, malloc_limit);
10353 SET(minor_gc_count, objspace->profile.minor_gc_count);
10354 SET(major_gc_count, objspace->profile.major_gc_count);
10355 SET(compact_count, objspace->profile.compact_count);
10356 SET(read_barrier_faults, objspace->profile.read_barrier_faults);
10357 SET(total_moved_objects, objspace->rcompactor.total_moved);
10358 SET(remembered_wb_unprotected_objects, objspace->rgengc.uncollectible_wb_unprotected_objects);
10359 SET(remembered_wb_unprotected_objects_limit, objspace->rgengc.uncollectible_wb_unprotected_objects_limit);
10360 SET(old_objects, objspace->rgengc.old_objects);
10361 SET(old_objects_limit, objspace->rgengc.old_objects_limit);
10362#if RGENGC_ESTIMATE_OLDMALLOC
10363 SET(oldmalloc_increase_bytes, gc_malloc_counters_increase_unsigned(objspace, &objspace->malloc_counters.oldcounters));
10364 SET(oldmalloc_increase_bytes_limit, objspace->rgengc.oldmalloc_increase_limit);
10365#endif
10366
10367 SET(total_allocated_objects, total_allocated_objects(objspace));
10368 SET(total_freed_objects, total_freed_objects(objspace));
10369 SET(heap_available_slots, objspace_available_slots(objspace));
10370 SET(heap_live_slots, objspace_live_slots(objspace));
10371 SET(heap_free_slots, objspace_free_slots(objspace));
10372 SET(heap_final_slots, total_final_slots_count(objspace));
10373 SET(heap_marked_slots, objspace->marked_slots);
10374
10375 SET(page_pool_arenas, global_objspace->page_pool.arena_count);
10376 SET(page_pool_arenas_freed, global_objspace->page_pool.arenas_unmapped);
10377 SET(page_pool_total_pages, (size_t)global_objspace->page_pool.arena_count * PAGE_POOL_ARENA_BODIES);
10378 SET(page_pool_discarded_pages, global_objspace->page_pool.advised_count);
10379
10380#if RGENGC_PROFILE
10381 SET(total_generated_normal_object_count, objspace->profile.total_generated_normal_object_count);
10382 SET(total_generated_shady_object_count, objspace->profile.total_generated_shady_object_count);
10383 SET(total_shade_operation_count, objspace->profile.total_shade_operation_count);
10384 SET(total_promoted_count, objspace->profile.total_promoted_count);
10385 SET(total_remembered_normal_object_count, objspace->profile.total_remembered_normal_object_count);
10386 SET(total_remembered_shady_object_count, objspace->profile.total_remembered_shady_object_count);
10387#endif /* RGENGC_PROFILE */
10388#undef SET
10389#undef SET64
10390
10391 if (!NIL_P(key)) {
10392 // Matched key should return above
10393 return Qundef;
10394 }
10395
10396#if defined(RGENGC_PROFILE) && RGENGC_PROFILE >= 2
10397 if (hash != Qnil) {
10398 gc_count_add_each_types(hash, "generated_normal_object_count_types", objspace->profile.generated_normal_object_count_types);
10399 gc_count_add_each_types(hash, "generated_shady_object_count_types", objspace->profile.generated_shady_object_count_types);
10400 gc_count_add_each_types(hash, "shade_operation_count_types", objspace->profile.shade_operation_count_types);
10401 gc_count_add_each_types(hash, "promoted_types", objspace->profile.promoted_types);
10402 gc_count_add_each_types(hash, "remembered_normal_object_count_types", objspace->profile.remembered_normal_object_count_types);
10403 gc_count_add_each_types(hash, "remembered_shady_object_count_types", objspace->profile.remembered_shady_object_count_types);
10404 }
10405#endif
10406
10407 return hash;
10408}
10409
10410enum gc_stat_heap_sym {
10411 gc_stat_heap_sym_slot_size,
10412 gc_stat_heap_sym_heap_live_slots,
10413 gc_stat_heap_sym_heap_free_slots,
10414 gc_stat_heap_sym_heap_final_slots,
10415 gc_stat_heap_sym_heap_eden_pages,
10416 gc_stat_heap_sym_heap_eden_slots,
10417 gc_stat_heap_sym_total_allocated_pages,
10418 gc_stat_heap_sym_force_major_gc_count,
10419 gc_stat_heap_sym_force_incremental_marking_finish_count,
10420 gc_stat_heap_sym_heap_allocatable_slots,
10421 gc_stat_heap_sym_total_allocated_objects,
10422 gc_stat_heap_sym_total_freed_objects,
10423 gc_stat_heap_sym_last
10424};
10425
10426static VALUE gc_stat_heap_symbols[gc_stat_heap_sym_last];
10427
10428static void
10429setup_gc_stat_heap_symbols(void)
10430{
10431 if (gc_stat_heap_symbols[0] == 0) {
10432#define S(s) gc_stat_heap_symbols[gc_stat_heap_sym_##s] = ID2SYM(rb_intern_const(#s))
10433 S(slot_size);
10434 S(heap_live_slots);
10435 S(heap_free_slots);
10436 S(heap_final_slots);
10437 S(heap_eden_pages);
10438 S(heap_eden_slots);
10439 S(heap_allocatable_slots);
10440 S(total_allocated_pages);
10441 S(force_major_gc_count);
10442 S(force_incremental_marking_finish_count);
10443 S(total_allocated_objects);
10444 S(total_freed_objects);
10445#undef S
10446 }
10447}
10448
10449static VALUE
10450stat_one_heap(rb_objspace_t *objspace, rb_heap_t *heap, VALUE hash, VALUE key)
10451{
10452#define SET(name, attr) \
10453 if (key == gc_stat_heap_symbols[gc_stat_heap_sym_##name]) \
10454 return SIZET2NUM(attr); \
10455 else if (hash != Qnil) \
10456 rb_hash_aset(hash, gc_stat_heap_symbols[gc_stat_heap_sym_##name], SIZET2NUM(attr));
10457
10458 SET(slot_size, heap->slot_size);
10459 SET(heap_live_slots, heap->total_allocated_objects - heap->total_freed_objects - heap->final_slots_count);
10460 SET(heap_free_slots, heap->total_slots - (heap->total_allocated_objects - heap->total_freed_objects));
10461 SET(heap_final_slots, heap->final_slots_count);
10462 SET(heap_eden_pages, heap->total_pages);
10463 SET(heap_eden_slots, heap->total_slots);
10464 SET(heap_allocatable_slots, objspace->heap_pages.allocatable_bytes / heap->slot_size);
10465 SET(total_allocated_pages, heap->total_allocated_pages);
10466 SET(force_major_gc_count, heap->force_major_gc_count);
10467 SET(force_incremental_marking_finish_count, heap->force_incremental_marking_finish_count);
10468 SET(total_allocated_objects, heap->total_allocated_objects);
10469 SET(total_freed_objects, heap->total_freed_objects);
10470#undef SET
10471
10472 if (!NIL_P(key)) {
10473 // Matched key should return above
10474 return Qundef;
10475 }
10476
10477 return hash;
10478}
10479
10480VALUE
10481rb_gc_impl_stat_heap(void *objspace_ptr, VALUE heap_name, VALUE hash_or_sym)
10482{
10483 rb_objspace_t *objspace = objspace_ptr;
10484
10485 setup_gc_stat_heap_symbols();
10486
10487 if (NIL_P(heap_name)) {
10488 if (!RB_TYPE_P(hash_or_sym, T_HASH)) {
10489 rb_bug("non-hash given");
10490 }
10491
10492 for (int i = 0; i < HEAP_COUNT; i++) {
10493 VALUE hash = rb_hash_aref(hash_or_sym, INT2FIX(i));
10494 if (NIL_P(hash)) {
10495 hash = rb_hash_new();
10496 rb_hash_aset(hash_or_sym, INT2FIX(i), hash);
10497 }
10498
10499 stat_one_heap(objspace, &heaps[i], hash, Qnil);
10500 }
10501 }
10502 else if (FIXNUM_P(heap_name)) {
10503 int heap_idx = FIX2INT(heap_name);
10504
10505 if (heap_idx < 0 || heap_idx >= HEAP_COUNT) {
10506 rb_raise(rb_eArgError, "size pool index out of range");
10507 }
10508
10509 if (SYMBOL_P(hash_or_sym)) {
10510 return stat_one_heap(objspace, &heaps[heap_idx], Qnil, hash_or_sym);
10511 }
10512 else if (RB_TYPE_P(hash_or_sym, T_HASH)) {
10513 return stat_one_heap(objspace, &heaps[heap_idx], hash_or_sym, Qnil);
10514 }
10515 else {
10516 rb_bug("non-hash or symbol given");
10517 }
10518 }
10519 else {
10520 rb_bug("heap_name must be nil or an Integer");
10521 }
10522
10523 return hash_or_sym;
10524}
10525
10526/* I could include internal.h for this, but doing so undefines some Array macros
10527 * necessary for initialising objects, and I don't want to include all the array
10528 * headers to get them back
10529 * TODO: Investigate why RARRAY_AREF gets undefined in internal.h
10530 */
10531#ifndef RBOOL
10532#define RBOOL(v) (v ? Qtrue : Qfalse)
10533#endif
10534
10535VALUE
10536rb_gc_impl_config_get(void *objspace_ptr)
10537{
10538#define sym(name) ID2SYM(rb_intern_const(name))
10539 rb_objspace_t *objspace = objspace_ptr;
10540 VALUE hash = rb_hash_new();
10541
10542 rb_hash_aset(hash, sym("rgengc_allow_full_mark"), RBOOL(gc_config_full_mark_val));
10543
10544 return hash;
10545}
10546
10547static int
10548gc_config_set_key(VALUE key, VALUE value, VALUE data)
10549{
10551 if (rb_sym2id(key) == rb_intern("rgengc_allow_full_mark")) {
10552 gc_rest(objspace);
10553 gc_config_full_mark_set(RTEST(value));
10554 }
10555 return ST_CONTINUE;
10556}
10557
10558void
10559rb_gc_impl_config_set(void *objspace_ptr, VALUE hash)
10560{
10561 rb_objspace_t *objspace = objspace_ptr;
10562
10563 if (!RB_TYPE_P(hash, T_HASH)) {
10564 rb_raise(rb_eArgError, "expected keyword arguments");
10565 }
10566
10567 rb_hash_foreach(hash, gc_config_set_key, (st_data_t)objspace);
10568}
10569
10570VALUE
10571rb_gc_impl_stress_get(void *objspace_ptr)
10572{
10573 return ruby_gc_stress_mode;
10574}
10575
10576void
10577rb_gc_impl_stress_set(void *objspace_ptr, VALUE flag)
10578{
10579 global_objspace->gc_stressful = RTEST(flag);
10580 global_objspace->gc_stress_mode = flag;
10581}
10582
10583static int
10584get_envparam_size(const char *name, size_t *default_value, size_t lower_bound)
10585{
10586 const char *ptr = getenv(name);
10587 ssize_t val;
10588
10589 if (ptr != NULL && *ptr) {
10590 size_t unit = 0;
10591 char *end;
10592#if SIZEOF_SIZE_T == SIZEOF_LONG_LONG
10593 val = strtoll(ptr, &end, 0);
10594#else
10595 val = strtol(ptr, &end, 0);
10596#endif
10597 switch (*end) {
10598 case 'k': case 'K':
10599 unit = 1024;
10600 ++end;
10601 break;
10602 case 'm': case 'M':
10603 unit = 1024*1024;
10604 ++end;
10605 break;
10606 case 'g': case 'G':
10607 unit = 1024*1024*1024;
10608 ++end;
10609 break;
10610 }
10611 while (*end && isspace((unsigned char)*end)) end++;
10612 if (*end) {
10613 if (RTEST(ruby_verbose)) fprintf(stderr, "invalid string for %s: %s\n", name, ptr);
10614 return 0;
10615 }
10616 if (unit > 0) {
10617 if (val < -(ssize_t)(SIZE_MAX / 2 / unit) || (ssize_t)(SIZE_MAX / 2 / unit) < val) {
10618 if (RTEST(ruby_verbose)) fprintf(stderr, "%s=%s is ignored because it overflows\n", name, ptr);
10619 return 0;
10620 }
10621 val *= unit;
10622 }
10623 if (val > 0 && (size_t)val > lower_bound) {
10624 if (RTEST(ruby_verbose)) {
10625 fprintf(stderr, "%s=%"PRIdSIZE" (default value: %"PRIuSIZE")\n", name, val, *default_value);
10626 }
10627 *default_value = (size_t)val;
10628 return 1;
10629 }
10630 else {
10631 if (RTEST(ruby_verbose)) {
10632 fprintf(stderr, "%s=%"PRIdSIZE" (default value: %"PRIuSIZE") is ignored because it must be greater than %"PRIuSIZE".\n",
10633 name, val, *default_value, lower_bound);
10634 }
10635 return 0;
10636 }
10637 }
10638 return 0;
10639}
10640
10641static int
10642get_envparam_double(const char *name, double *default_value, double lower_bound, double upper_bound, int accept_zero)
10643{
10644 const char *ptr = getenv(name);
10645 double val;
10646
10647 if (ptr != NULL && *ptr) {
10648 char *end;
10649 val = strtod(ptr, &end);
10650 if (!*ptr || *end) {
10651 if (RTEST(ruby_verbose)) fprintf(stderr, "invalid string for %s: %s\n", name, ptr);
10652 return 0;
10653 }
10654
10655 if (accept_zero && val == 0.0) {
10656 goto accept;
10657 }
10658 else if (val <= lower_bound) {
10659 if (RTEST(ruby_verbose)) {
10660 fprintf(stderr, "%s=%f (default value: %f) is ignored because it must be greater than %f.\n",
10661 name, val, *default_value, lower_bound);
10662 }
10663 }
10664 else if (upper_bound != 0.0 && /* ignore upper_bound if it is 0.0 */
10665 val > upper_bound) {
10666 if (RTEST(ruby_verbose)) {
10667 fprintf(stderr, "%s=%f (default value: %f) is ignored because it must be lower than %f.\n",
10668 name, val, *default_value, upper_bound);
10669 }
10670 }
10671 else {
10672 goto accept;
10673 }
10674 }
10675 return 0;
10676
10677 accept:
10678 if (RTEST(ruby_verbose)) fprintf(stderr, "%s=%f (default value: %f)\n", name, val, *default_value);
10679 *default_value = val;
10680 return 1;
10681}
10682
10683/*
10684 * GC tuning environment variables
10685 *
10686 * * RUBY_GC_HEAP_FREE_SLOTS
10687 * - Prepare at least this amount of slots after GC.
10688 * - Allocate slots if there are not enough slots.
10689 * * RUBY_GC_HEAP_GROWTH_FACTOR (new from 2.1)
10690 * - Allocate slots by this factor.
10691 * - (next slots number) = (current slots number) * (this factor)
10692 * * RUBY_GC_HEAP_GROWTH_MAX_BYTES (was RUBY_GC_HEAP_GROWTH_MAX_SLOTS)
10693 * - Allocation rate is limited to this number of bytes.
10694 * * RUBY_GC_HEAP_FREE_SLOTS_MIN_RATIO (new from 2.4)
10695 * - Allocate additional pages when the number of free slots is
10696 * lower than the value (total_slots * (this ratio)).
10697 * * RUBY_GC_HEAP_FREE_SLOTS_GOAL_RATIO (new from 2.4)
10698 * - Allocate slots to satisfy this formula:
10699 * free_slots = total_slots * goal_ratio
10700 * - In other words, prepare (total_slots * goal_ratio) free slots.
10701 * - if this value is 0.0, then use RUBY_GC_HEAP_GROWTH_FACTOR directly.
10702 * * RUBY_GC_HEAP_FREE_SLOTS_MAX_RATIO (new from 2.4)
10703 * - Allow to free pages when the number of free slots is
10704 * greater than the value (total_slots * (this ratio)).
10705 * * RUBY_GC_HEAP_OLDOBJECT_LIMIT_FACTOR (new from 2.1.1)
10706 * - Do full GC when the number of old objects is more than R * N
10707 * where R is this factor and
10708 * N is the number of old objects just after last full GC.
10709 *
10710 * * obsolete
10711 * * RUBY_FREE_MIN -> RUBY_GC_HEAP_FREE_SLOTS (from 2.1)
10712 * * RUBY_HEAP_MIN_SLOTS -> RUBY_GC_HEAP_INIT_SLOTS (from 2.1) -> RUBY_GC_HEAP_INIT_BYTES
10713 *
10714 * * RUBY_GC_MALLOC_LIMIT
10715 * * RUBY_GC_MALLOC_LIMIT_MAX (new from 2.1)
10716 * * RUBY_GC_MALLOC_LIMIT_GROWTH_FACTOR (new from 2.1)
10717 *
10718 * * RUBY_GC_OLDMALLOC_LIMIT (new from 2.1)
10719 * * RUBY_GC_OLDMALLOC_LIMIT_MAX (new from 2.1)
10720 * * RUBY_GC_OLDMALLOC_LIMIT_GROWTH_FACTOR (new from 2.1)
10721 */
10722
10723void
10724rb_gc_impl_set_params(void *objspace_ptr)
10725{
10726 rb_objspace_t *objspace = objspace_ptr;
10727 get_envparam_size("RUBY_GC_HEAP_FREE_SLOTS", &gc_params.heap_free_slots, 0);
10728
10729 get_envparam_size("RUBY_GC_HEAP_INIT_BYTES", &gc_params.heap_init_bytes, 0);
10730
10731 get_envparam_double("RUBY_GC_HEAP_GROWTH_FACTOR", &gc_params.growth_factor, 1.0, 0.0, FALSE);
10732 get_envparam_size ("RUBY_GC_HEAP_GROWTH_MAX_BYTES", &gc_params.growth_max_bytes, 0);
10733 get_envparam_double("RUBY_GC_HEAP_FREE_SLOTS_MIN_RATIO", &gc_params.heap_free_slots_min_ratio,
10734 0.0, 1.0, FALSE);
10735 get_envparam_double("RUBY_GC_HEAP_FREE_SLOTS_MAX_RATIO", &gc_params.heap_free_slots_max_ratio,
10736 gc_params.heap_free_slots_min_ratio, 1.0, FALSE);
10737 get_envparam_double("RUBY_GC_HEAP_FREE_SLOTS_GOAL_RATIO", &gc_params.heap_free_slots_goal_ratio,
10738 gc_params.heap_free_slots_min_ratio, gc_params.heap_free_slots_max_ratio, TRUE);
10739 get_envparam_double("RUBY_GC_HEAP_OLDOBJECT_LIMIT_FACTOR", &gc_params.oldobject_limit_factor, 0.0, 0.0, TRUE);
10740 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);
10741
10742 if (get_envparam_size("RUBY_GC_MALLOC_LIMIT", &gc_params.malloc_limit_min, 0)) {
10743 malloc_limit = gc_params.malloc_limit_min;
10744 }
10745 get_envparam_size ("RUBY_GC_MALLOC_LIMIT_MAX", &gc_params.malloc_limit_max, 0);
10746 if (!gc_params.malloc_limit_max) { /* ignore max-check if 0 */
10747 gc_params.malloc_limit_max = SIZE_MAX;
10748 }
10749 get_envparam_double("RUBY_GC_MALLOC_LIMIT_GROWTH_FACTOR", &gc_params.malloc_limit_growth_factor, 1.0, 0.0, FALSE);
10750
10751#if RGENGC_ESTIMATE_OLDMALLOC
10752 if (get_envparam_size("RUBY_GC_OLDMALLOC_LIMIT", &gc_params.oldmalloc_limit_min, 0)) {
10753 objspace->rgengc.oldmalloc_increase_limit = gc_params.oldmalloc_limit_min;
10754 }
10755 get_envparam_size ("RUBY_GC_OLDMALLOC_LIMIT_MAX", &gc_params.oldmalloc_limit_max, 0);
10756 get_envparam_double("RUBY_GC_OLDMALLOC_LIMIT_GROWTH_FACTOR", &gc_params.oldmalloc_limit_growth_factor, 1.0, 0.0, FALSE);
10757#endif
10758}
10759
10760static inline size_t
10761objspace_malloc_size(rb_objspace_t *objspace, void *ptr, size_t hint)
10762{
10763#ifdef HAVE_MALLOC_USABLE_SIZE
10764 if (!hint) {
10765 hint = malloc_usable_size(ptr);
10766 }
10767#endif
10768 return hint;
10769}
10770
10771enum memop_type {
10772 MEMOP_TYPE_MALLOC = 0,
10773 MEMOP_TYPE_FREE,
10774 MEMOP_TYPE_REALLOC
10775};
10776
10777static inline void
10778atomic_sub_nounderflow(size_t *var, size_t sub)
10779{
10780 if (sub == 0) return;
10781
10782 while (1) {
10783 size_t val = *var;
10784 if (val < sub) sub = val;
10785 if (RUBY_ATOMIC_SIZE_CAS(*var, val, val-sub) == val) break;
10786 }
10787}
10788
10789#define gc_stress_full_mark_after_malloc_p() \
10790 (FIXNUM_P(ruby_gc_stress_mode) && (FIX2LONG(ruby_gc_stress_mode) & (1<<gc_stress_full_mark_after_malloc)))
10791
10792static void
10793objspace_malloc_gc_stress(rb_objspace_t *objspace)
10794{
10795 if (ruby_gc_stressful && ruby_native_thread_p()) {
10796 unsigned int reason = (GPR_FLAG_IMMEDIATE_MARK | GPR_FLAG_IMMEDIATE_SWEEP |
10797 GPR_FLAG_STRESS | GPR_FLAG_MALLOC);
10798
10799 if (gc_stress_full_mark_after_malloc_p()) {
10800 reason |= GPR_FLAG_FULL_MARK;
10801 }
10802 garbage_collect_with_gvl(objspace, reason);
10803 }
10804}
10805
10806static void
10807malloc_increase_commit(rb_objspace_t *objspace, size_t new_size, size_t old_size)
10808{
10809 if (new_size > old_size) {
10810 size_t delta = new_size - old_size;
10811 MALLOC_COUNTERS_LOCK(objspace);
10812 gc_counter_add(&objspace->malloc_counters.counters.malloc, delta);
10813#if RGENGC_ESTIMATE_OLDMALLOC
10814 gc_counter_add(&objspace->malloc_counters.oldcounters.malloc, delta);
10815#endif
10816 MALLOC_COUNTERS_UNLOCK(objspace);
10817 }
10818 else if (old_size > new_size) {
10819 size_t delta = old_size - new_size;
10820 MALLOC_COUNTERS_LOCK(objspace);
10821 gc_counter_add(&objspace->malloc_counters.counters.free, delta);
10822#if RGENGC_ESTIMATE_OLDMALLOC
10823 gc_counter_add(&objspace->malloc_counters.oldcounters.free, delta);
10824#endif
10825 MALLOC_COUNTERS_UNLOCK(objspace);
10826 }
10827}
10828
10829#if USE_MALLOC_INCREASE_LOCAL
10830static void
10831malloc_increase_local_flush(rb_objspace_t *objspace)
10832{
10833 int delta = malloc_increase_local;
10834 if (delta == 0) return;
10835
10836 malloc_increase_local = 0;
10837 if (delta > 0) {
10838 malloc_increase_commit(objspace, (size_t)delta, 0);
10839 }
10840 else {
10841 malloc_increase_commit(objspace, 0, (size_t)(-delta));
10842 }
10843}
10844#else
10845static void
10846malloc_increase_local_flush(rb_objspace_t *objspace)
10847{
10848}
10849#endif
10850
10851static inline bool
10852objspace_malloc_increase_report(rb_objspace_t *objspace, void *mem, size_t new_size, size_t old_size, enum memop_type type, bool gc_allowed)
10853{
10854 if (0) fprintf(stderr, "increase - ptr: %p, type: %s, new_size: %"PRIdSIZE", old_size: %"PRIdSIZE"\n",
10855 mem,
10856 type == MEMOP_TYPE_MALLOC ? "malloc" :
10857 type == MEMOP_TYPE_FREE ? "free " :
10858 type == MEMOP_TYPE_REALLOC ? "realloc": "error",
10859 new_size, old_size);
10860 return false;
10861}
10862
10863static bool
10864objspace_malloc_increase_body(rb_objspace_t *objspace, void *mem, size_t new_size, size_t old_size, enum memop_type type, bool gc_allowed)
10865{
10866#if USE_MALLOC_INCREASE_LOCAL
10867 if (new_size < GC_MALLOC_INCREASE_LOCAL_THRESHOLD &&
10868 old_size < GC_MALLOC_INCREASE_LOCAL_THRESHOLD) {
10869 malloc_increase_local += (int)new_size - (int)old_size;
10870
10871 if (malloc_increase_local >= GC_MALLOC_INCREASE_LOCAL_THRESHOLD ||
10872 malloc_increase_local <= -GC_MALLOC_INCREASE_LOCAL_THRESHOLD) {
10873 malloc_increase_local_flush(objspace);
10874 }
10875 }
10876 else {
10877 malloc_increase_local_flush(objspace);
10878 malloc_increase_commit(objspace, new_size, old_size);
10879 }
10880#else
10881 malloc_increase_commit(objspace, new_size, old_size);
10882#endif
10883
10884 if (type == MEMOP_TYPE_MALLOC && gc_allowed) {
10885 retry:
10886 if (malloc_increase > malloc_limit && ruby_native_thread_p() && !dont_gc_val() && !rb_gc_gc_disabled_global_p()) {
10887 if (ruby_thread_has_gvl_p() && is_lazy_sweeping(objspace)) {
10888 gc_sweep_step_for_malloc(objspace); /* sweeping frees may reduce malloc_increase */
10889 goto retry;
10890 }
10891 garbage_collect_with_gvl(objspace, GPR_FLAG_MALLOC);
10892 }
10893 }
10894
10895#if MALLOC_ALLOCATED_SIZE
10896 if (new_size >= old_size) {
10897 RUBY_ATOMIC_SIZE_ADD(objspace->malloc_params.allocated_size, new_size - old_size);
10898 }
10899 else {
10900 size_t dec_size = old_size - new_size;
10901
10902#if MALLOC_ALLOCATED_SIZE_CHECK
10903 size_t allocated_size = objspace->malloc_params.allocated_size;
10904 if (allocated_size < dec_size) {
10905 rb_bug("objspace_malloc_increase: underflow malloc_params.allocated_size.");
10906 }
10907#endif
10908 atomic_sub_nounderflow(&objspace->malloc_params.allocated_size, dec_size);
10909 }
10910
10911 switch (type) {
10912 case MEMOP_TYPE_MALLOC:
10913 RUBY_ATOMIC_SIZE_INC(objspace->malloc_params.allocations);
10914 break;
10915 case MEMOP_TYPE_FREE:
10916 {
10917 size_t allocations = objspace->malloc_params.allocations;
10918 if (allocations > 0) {
10919 atomic_sub_nounderflow(&objspace->malloc_params.allocations, 1);
10920 }
10921#if MALLOC_ALLOCATED_SIZE_CHECK
10922 else {
10923 GC_ASSERT(objspace->malloc_params.allocations > 0);
10924 }
10925#endif
10926 }
10927 break;
10928 case MEMOP_TYPE_REALLOC: /* ignore */ break;
10929 }
10930#endif
10931 return true;
10932}
10933
10934#define objspace_malloc_increase(...) \
10935 for (bool malloc_increase_done = objspace_malloc_increase_report(__VA_ARGS__); \
10936 !malloc_increase_done; \
10937 malloc_increase_done = objspace_malloc_increase_body(__VA_ARGS__))
10938
10939struct malloc_obj_info { /* 4 words */
10940 size_t size;
10941};
10942
10943static inline size_t
10944objspace_malloc_prepare(rb_objspace_t *objspace, size_t size)
10945{
10946 if (size == 0) size = 1;
10947
10948#if CALC_EXACT_MALLOC_SIZE
10949 size += sizeof(struct malloc_obj_info);
10950#endif
10951
10952 return size;
10953}
10954
10955static bool
10956malloc_during_gc_p(rb_objspace_t *objspace)
10957{
10958 /* malloc is not allowed during GC when we're not using multiple ractors
10959 * (since ractors can run while another thread is sweeping) and when we
10960 * have the GVL (since if we don't have the GVL, we'll try to acquire the
10961 * GVL which will block and ensure the other thread finishes GC). */
10962 return during_gc && !dont_gc_val() && !rb_gc_multi_ractor_p() && ruby_thread_has_gvl_p();
10963}
10964
10965static inline void *
10966objspace_malloc_fixup(rb_objspace_t *objspace, void *mem, size_t size, bool gc_allowed)
10967{
10968 size = objspace_malloc_size(objspace, mem, size);
10969 objspace_malloc_increase(objspace, mem, size, 0, MEMOP_TYPE_MALLOC, gc_allowed) {}
10970
10971#if CALC_EXACT_MALLOC_SIZE
10972 {
10973 struct malloc_obj_info *info = mem;
10974 info->size = size;
10975 mem = info + 1;
10976 }
10977#endif
10978
10979 return mem;
10980}
10981
10982#if defined(__GNUC__) && RUBY_DEBUG
10983#define RB_BUG_INSTEAD_OF_RB_MEMERROR 1
10984#endif
10985
10986#ifndef RB_BUG_INSTEAD_OF_RB_MEMERROR
10987# define RB_BUG_INSTEAD_OF_RB_MEMERROR 0
10988#endif
10989
10990#define GC_MEMERROR(...) \
10991 ((RB_BUG_INSTEAD_OF_RB_MEMERROR+0) ? rb_bug("" __VA_ARGS__) : (void)0)
10992
10993#define TRY_WITH_GC(siz, expr) do { \
10994 const gc_profile_record_flag gpr = \
10995 GPR_FLAG_FULL_MARK | \
10996 GPR_FLAG_IMMEDIATE_MARK | \
10997 GPR_FLAG_IMMEDIATE_SWEEP | \
10998 GPR_FLAG_MALLOC; \
10999 /* stress GC must also honor gc_allowed (malloc_gc_disabled) */ \
11000 if (gc_allowed) objspace_malloc_gc_stress(objspace); \
11001 \
11002 if (RB_LIKELY((expr))) { \
11003 /* Success on 1st try */ \
11004 } \
11005 else if (gc_allowed && !garbage_collect_with_gvl(objspace, gpr)) { \
11006 /* @shyouhei thinks this doesn't happen */ \
11007 GC_MEMERROR("TRY_WITH_GC: could not GC"); \
11008 } \
11009 else if ((expr)) { \
11010 /* Success on 2nd try */ \
11011 } \
11012 else { \
11013 GC_MEMERROR("TRY_WITH_GC: could not allocate:" \
11014 "%"PRIdSIZE" bytes for %s", \
11015 siz, # expr); \
11016 } \
11017 } while (0)
11018
11019static void
11020check_malloc_not_in_gc(rb_objspace_t *objspace, const char *msg)
11021{
11022 if (RB_UNLIKELY(malloc_during_gc_p(objspace))) {
11023 dont_gc_on();
11024 during_gc = false;
11025 rb_bug("Cannot %s during GC", msg);
11026 }
11027}
11028
11029void
11030rb_gc_impl_free(void *objspace_ptr, void *ptr, size_t old_size)
11031{
11032 rb_objspace_t *objspace = objspace_ptr;
11033
11034 if (!ptr) {
11035 /*
11036 * ISO/IEC 9899 says "If ptr is a null pointer, no action occurs" since
11037 * its first version. We would better follow.
11038 */
11039 return;
11040 }
11041#if CALC_EXACT_MALLOC_SIZE
11042 struct malloc_obj_info *info = (struct malloc_obj_info *)ptr - 1;
11043#if VERIFY_FREE_SIZE
11044 if (!info->size) {
11045 rb_bug("buffer %p has no recorded size. Was it allocated with ruby_mimalloc? If so it should be freed with ruby_mimfree", ptr);
11046 }
11047
11048 if (old_size && (old_size + sizeof(struct malloc_obj_info)) != info->size) {
11049 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));
11050 }
11051#endif
11052 ptr = info;
11053 old_size = info->size;
11054#endif
11055 old_size = objspace_malloc_size(objspace, ptr, old_size);
11056
11057 objspace_malloc_increase(objspace, ptr, 0, old_size, MEMOP_TYPE_FREE, true) {
11058 free(ptr);
11059 ptr = NULL;
11060 RB_DEBUG_COUNTER_INC(heap_xfree);
11061 }
11062}
11063
11064void *
11065rb_gc_impl_malloc(void *objspace_ptr, size_t size, bool gc_allowed)
11066{
11067 rb_objspace_t *objspace = objspace_ptr;
11068 check_malloc_not_in_gc(objspace, "malloc");
11069
11070 void *mem;
11071
11072 size = objspace_malloc_prepare(objspace, size);
11073 TRY_WITH_GC(size, mem = malloc(size));
11074 RB_DEBUG_COUNTER_INC(heap_xmalloc);
11075 if (!mem) return mem;
11076 return objspace_malloc_fixup(objspace, mem, size, gc_allowed);
11077}
11078
11079void *
11080rb_gc_impl_calloc(void *objspace_ptr, size_t size, bool gc_allowed)
11081{
11082 rb_objspace_t *objspace = objspace_ptr;
11083
11084 if (RB_UNLIKELY(malloc_during_gc_p(objspace))) {
11085 rb_warn("calloc during GC detected, this could cause crashes if it triggers another GC");
11086#if RGENGC_CHECK_MODE || RUBY_DEBUG
11087 rb_bug("Cannot calloc during GC");
11088#endif
11089 }
11090
11091 void *mem;
11092
11093 size = objspace_malloc_prepare(objspace, size);
11094 TRY_WITH_GC(size, mem = calloc1(size));
11095 if (!mem) return mem;
11096 return objspace_malloc_fixup(objspace, mem, size, gc_allowed);
11097}
11098
11099void *
11100rb_gc_impl_realloc(void *objspace_ptr, void *ptr, size_t new_size, size_t old_size, bool gc_allowed)
11101{
11102 rb_objspace_t *objspace = objspace_ptr;
11103
11104 check_malloc_not_in_gc(objspace, "realloc");
11105
11106 void *mem;
11107
11108 if (!ptr) return rb_gc_impl_malloc(objspace, new_size, gc_allowed);
11109
11110 /*
11111 * The behavior of realloc(ptr, 0) is implementation defined.
11112 * Therefore we don't use realloc(ptr, 0) for portability reason.
11113 * see http://www.open-std.org/jtc1/sc22/wg14/www/docs/dr_400.htm
11114 */
11115 if (new_size == 0) {
11116 if ((mem = rb_gc_impl_malloc(objspace, 0, gc_allowed)) != NULL) {
11117 /*
11118 * - OpenBSD's malloc(3) man page says that when 0 is passed, it
11119 * returns a non-NULL pointer to an access-protected memory page.
11120 * The returned pointer cannot be read / written at all, but
11121 * still be a valid argument of free().
11122 *
11123 * https://man.openbsd.org/malloc.3
11124 *
11125 * - Linux's malloc(3) man page says that it _might_ perhaps return
11126 * a non-NULL pointer when its argument is 0. That return value
11127 * is safe (and is expected) to be passed to free().
11128 *
11129 * https://man7.org/linux/man-pages/man3/malloc.3.html
11130 *
11131 * - As I read the implementation jemalloc's malloc() returns fully
11132 * normal 16 bytes memory region when its argument is 0.
11133 *
11134 * - As I read the implementation musl libc's malloc() returns
11135 * fully normal 32 bytes memory region when its argument is 0.
11136 *
11137 * - Other malloc implementations can also return non-NULL.
11138 */
11139 rb_gc_impl_free(objspace, ptr, old_size);
11140 return mem;
11141 }
11142 else {
11143 /*
11144 * It is dangerous to return NULL here, because that could lead to
11145 * RCE. Fallback to 1 byte instead of zero.
11146 *
11147 * https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2019-11932
11148 */
11149 new_size = 1;
11150 }
11151 }
11152
11153#if CALC_EXACT_MALLOC_SIZE
11154 {
11155 struct malloc_obj_info *info = (struct malloc_obj_info *)ptr - 1;
11156 new_size += sizeof(struct malloc_obj_info);
11157 ptr = info;
11158#if VERIFY_FREE_SIZE
11159 if (old_size && (old_size + sizeof(struct malloc_obj_info)) != info->size) {
11160 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));
11161 }
11162#endif
11163 old_size = info->size;
11164 }
11165#endif
11166
11167 old_size = objspace_malloc_size(objspace, ptr, old_size);
11168 TRY_WITH_GC(new_size, mem = RB_GNUC_EXTENSION_BLOCK(realloc(ptr, new_size)));
11169 if (!mem) return mem;
11170 new_size = objspace_malloc_size(objspace, mem, new_size);
11171
11172#if CALC_EXACT_MALLOC_SIZE
11173 {
11174 struct malloc_obj_info *info = mem;
11175 info->size = new_size;
11176 mem = info + 1;
11177 }
11178#endif
11179
11180 objspace_malloc_increase(objspace, mem, new_size, old_size, MEMOP_TYPE_REALLOC, gc_allowed);
11181
11182 RB_DEBUG_COUNTER_INC(heap_xrealloc);
11183 return mem;
11184}
11185
11186void
11187rb_gc_impl_adjust_memory_usage(void *objspace_ptr, ssize_t diff)
11188{
11189 rb_objspace_t *objspace = objspace_ptr;
11190
11191 if (diff > 0) {
11192 objspace_malloc_increase(objspace, 0, diff, 0, MEMOP_TYPE_REALLOC, true);
11193 }
11194 else if (diff < 0) {
11195 objspace_malloc_increase(objspace, 0, 0, -diff, MEMOP_TYPE_REALLOC, true);
11196 }
11197}
11198
11199// TODO: move GC profiler stuff back into gc.c
11200/*
11201 ------------------------------ GC profiler ------------------------------
11202*/
11203
11204#define GC_PROFILE_RECORD_DEFAULT_SIZE 100
11205#define GC_PROFILE_RECORD_DEFAULT_MAX_RECORDS 4096
11206#define GC_PROFILE_RECORD_UNBOUNDED 0
11207
11208static bool
11209current_process_time(struct timespec *ts)
11210{
11211#if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_PROCESS_CPUTIME_ID)
11212 {
11213 static int try_clock_gettime = 1;
11214 if (try_clock_gettime && clock_gettime(CLOCK_PROCESS_CPUTIME_ID, ts) == 0) {
11215 return true;
11216 }
11217 else {
11218 try_clock_gettime = 0;
11219 }
11220 }
11221#endif
11222
11223#ifdef RUSAGE_SELF
11224 {
11225 struct rusage usage;
11226 struct timeval time;
11227 if (getrusage(RUSAGE_SELF, &usage) == 0) {
11228 time = usage.ru_utime;
11229 ts->tv_sec = time.tv_sec;
11230 ts->tv_nsec = (int32_t)time.tv_usec * 1000;
11231 return true;
11232 }
11233 }
11234#endif
11235
11236#ifdef _WIN32
11237 {
11238 FILETIME creation_time, exit_time, kernel_time, user_time;
11239 ULARGE_INTEGER ui;
11240
11241 if (GetProcessTimes(GetCurrentProcess(),
11242 &creation_time, &exit_time, &kernel_time, &user_time) != 0) {
11243 memcpy(&ui, &user_time, sizeof(FILETIME));
11244#define PER100NSEC (uint64_t)(1000 * 1000 * 10)
11245 ts->tv_nsec = (long)(ui.QuadPart % PER100NSEC);
11246 ts->tv_sec = (time_t)(ui.QuadPart / PER100NSEC);
11247 return true;
11248 }
11249 }
11250#endif
11251
11252 return false;
11253}
11254
11255static double
11256getrusage_time(void)
11257{
11258 struct timespec ts;
11259 if (current_process_time(&ts)) {
11260 return ts.tv_sec + ts.tv_nsec * 1e-9;
11261 }
11262 else {
11263 return 0.0;
11264 }
11265}
11266
11267static inline double
11268hrtime_to_sec(rb_hrtime_t time)
11269{
11270 return (double)time / (double)RB_HRTIME_PER_SEC;
11271}
11272
11273static inline rb_hrtime_t
11274elapsed_hrtime_from(rb_hrtime_t start)
11275{
11276 return rb_hrtime_sub(rb_hrtime_now(), start);
11277}
11278
11279
11280static inline size_t
11281gc_profile_record_count(rb_objspace_t *objspace)
11282{
11283 return objspace->profile.record_count;
11284}
11285
11286static inline size_t
11287gc_profile_record_index(rb_objspace_t *objspace, size_t logical_index)
11288{
11289 if (objspace->profile.max_records != GC_PROFILE_RECORD_UNBOUNDED &&
11290 objspace->profile.record_count == objspace->profile.size) {
11291 return (objspace->profile.next_index + logical_index) % objspace->profile.size;
11292 }
11293 else {
11294 return logical_index;
11295 }
11296}
11297
11298static void
11299gc_profile_records_free(rb_objspace_t *objspace)
11300{
11301 void *p = objspace->profile.records;
11302 objspace->profile.records = NULL;
11303 objspace->profile.size = 0;
11304 objspace->profile.next_index = 0;
11305 objspace->profile.record_count = 0;
11306 objspace->profile.current_record = 0;
11307 free(p);
11308}
11309
11310static inline void
11311gc_prof_setup_new_record(rb_objspace_t *objspace, unsigned int reason)
11312{
11313 if (objspace->profile.run) {
11314 size_t index;
11315 gc_profile_record *record;
11316
11317 if (objspace->profile.max_records == GC_PROFILE_RECORD_UNBOUNDED) {
11318 index = objspace->profile.record_count++;
11319 objspace->profile.next_index = objspace->profile.record_count;
11320
11321 if (!objspace->profile.records) {
11322 objspace->profile.size = GC_PROFILE_RECORD_DEFAULT_SIZE;
11323 objspace->profile.records = malloc(xmalloc2_size(sizeof(gc_profile_record), objspace->profile.size));
11324 }
11325 if (index >= objspace->profile.size) {
11326 void *ptr;
11327 objspace->profile.size += 1000;
11328 ptr = realloc(objspace->profile.records, xmalloc2_size(sizeof(gc_profile_record), objspace->profile.size));
11329 if (!ptr) rb_memerror();
11330 objspace->profile.records = ptr;
11331 }
11332 }
11333 else {
11334 if (!objspace->profile.records) {
11335 objspace->profile.size = objspace->profile.max_records;
11336 objspace->profile.records = malloc(xmalloc2_size(sizeof(gc_profile_record), objspace->profile.size));
11337 }
11338 index = objspace->profile.next_index;
11339 objspace->profile.next_index = (objspace->profile.next_index + 1) % objspace->profile.size;
11340 if (objspace->profile.record_count < objspace->profile.size) {
11341 objspace->profile.record_count++;
11342 }
11343 }
11344
11345 if (!objspace->profile.records) {
11346 rb_bug("gc_profile malloc or realloc miss");
11347 }
11348 record = objspace->profile.current_record = &objspace->profile.records[index];
11349 MEMZERO(record, gc_profile_record, 1);
11350
11351 /* setup before-GC parameter */
11352 record->flags = reason | (ruby_gc_stressful ? GPR_FLAG_STRESS : 0);
11353 record->sequence = objspace->profile.record_sequence++;
11354 record->gc_invoke_wall_time = rb_hrtime_sub(rb_hrtime_now(),
11355 objspace->profile.invoke_wall_time);
11356#if MALLOC_ALLOCATED_SIZE
11357 record->allocated_size = malloc_allocated_size;
11358#endif
11359#if GC_PROFILE_MORE_DETAIL && GC_PROFILE_DETAIL_MEMORY
11360#ifdef RUSAGE_SELF
11361 {
11362 struct rusage usage;
11363 if (getrusage(RUSAGE_SELF, &usage) == 0) {
11364 record->maxrss = usage.ru_maxrss;
11365 record->minflt = usage.ru_minflt;
11366 record->majflt = usage.ru_majflt;
11367 }
11368 }
11369#endif
11370#endif
11371 }
11372}
11373
11374static inline void
11375gc_prof_timer_start(rb_objspace_t *objspace)
11376{
11377 if (gc_prof_enabled(objspace)) {
11378 gc_profile_record *record = gc_prof_record(objspace);
11379#if GC_PROFILE_MORE_DETAIL
11380 record->prepare_time = objspace->profile.prepare_time;
11381#endif
11382 record->gc_time = 0;
11383 record->gc_invoke_time = getrusage_time();
11384 objspace->profile.gc_wall_start_time = rb_hrtime_now();
11385 }
11386}
11387
11388static double
11389elapsed_time_from(double time)
11390{
11391 double now = getrusage_time();
11392 if (now > time) {
11393 return now - time;
11394 }
11395 else {
11396 return 0;
11397 }
11398}
11399
11400static inline void
11401gc_prof_timer_stop(rb_objspace_t *objspace)
11402{
11403 if (gc_prof_enabled(objspace)) {
11404 gc_profile_record *record = gc_prof_record(objspace);
11405 record->gc_time = elapsed_time_from(record->gc_invoke_time);
11406 record->gc_invoke_time -= objspace->profile.invoke_time;
11407 record->gc_wall_time = elapsed_hrtime_from(objspace->profile.gc_wall_start_time);
11408 }
11409}
11410
11411static inline void
11412gc_prof_mark_timer_start(rb_objspace_t *objspace)
11413{
11414 RUBY_DTRACE_GC_HOOK(MARK_BEGIN);
11415#if GC_PROFILE_MORE_DETAIL
11416 if (gc_prof_enabled(objspace)) {
11417 gc_prof_record(objspace)->gc_mark_time = getrusage_time();
11418 }
11419#endif
11420}
11421
11422static inline void
11423gc_prof_mark_timer_stop(rb_objspace_t *objspace)
11424{
11425 RUBY_DTRACE_GC_HOOK(MARK_END);
11426#if GC_PROFILE_MORE_DETAIL
11427 if (gc_prof_enabled(objspace)) {
11428 gc_profile_record *record = gc_prof_record(objspace);
11429 record->gc_mark_time = elapsed_time_from(record->gc_mark_time);
11430 }
11431#endif
11432}
11433
11434static inline void
11435gc_prof_sweep_timer_start(rb_objspace_t *objspace)
11436{
11437 RUBY_DTRACE_GC_HOOK(SWEEP_BEGIN);
11438 if (gc_prof_enabled(objspace)) {
11439 gc_profile_record *record = gc_prof_record(objspace);
11440
11441 if (record->gc_time > 0 || GC_PROFILE_MORE_DETAIL) {
11442 objspace->profile.gc_sweep_start_time = getrusage_time();
11443 objspace->profile.gc_sweep_wall_start_time = rb_hrtime_now();
11444 }
11445 }
11446}
11447
11448static inline void
11449gc_prof_sweep_timer_stop(rb_objspace_t *objspace)
11450{
11451 RUBY_DTRACE_GC_HOOK(SWEEP_END);
11452
11453 if (gc_prof_enabled(objspace)) {
11454 double sweep_time;
11455 gc_profile_record *record = gc_prof_record(objspace);
11456
11457 if (record->gc_time > 0) {
11458 sweep_time = elapsed_time_from(objspace->profile.gc_sweep_start_time);
11459 /* need to accumulate GC time for lazy sweep after gc() */
11460 record->gc_time += sweep_time;
11461 record->gc_wall_time = rb_hrtime_add(record->gc_wall_time,
11462 elapsed_hrtime_from(objspace->profile.gc_sweep_wall_start_time));
11463 }
11464 else if (GC_PROFILE_MORE_DETAIL) {
11465 sweep_time = elapsed_time_from(objspace->profile.gc_sweep_start_time);
11466 }
11467
11468#if GC_PROFILE_MORE_DETAIL
11469 record->gc_sweep_time += sweep_time;
11470 if (heap_pages_deferred_final) record->flags |= GPR_FLAG_HAVE_FINALIZE;
11471#endif
11472 if (heap_pages_deferred_final) objspace->profile.latest_gc_info |= GPR_FLAG_HAVE_FINALIZE;
11473 }
11474}
11475
11476static inline void
11477gc_prof_set_malloc_info(rb_objspace_t *objspace)
11478{
11479#if GC_PROFILE_MORE_DETAIL
11480 if (gc_prof_enabled(objspace)) {
11481 gc_profile_record *record = gc_prof_record(objspace);
11482 record->allocate_increase = malloc_increase;
11483 record->allocate_limit = malloc_limit;
11484 }
11485#endif
11486}
11487
11488static inline void
11489gc_prof_set_heap_info(rb_objspace_t *objspace)
11490{
11491 if (gc_prof_enabled(objspace)) {
11492 gc_profile_record *record = gc_prof_record(objspace);
11493
11494 /* Sum across all size pools since each has a different slot size. */
11495 size_t total = 0;
11496 size_t use_size = 0;
11497 size_t total_size = 0;
11498 for (int i = 0; i < HEAP_COUNT; i++) {
11499 rb_heap_t *heap = &heaps[i];
11500 size_t heap_live = heap->total_allocated_objects - heap->total_freed_objects - heap->final_slots_count;
11501 total += heap->total_slots;
11502 use_size += heap_live * heap->slot_size;
11503 total_size += heap->total_slots * heap->slot_size;
11504 }
11505
11506#if GC_PROFILE_MORE_DETAIL
11507 size_t live = objspace->profile.total_allocated_objects_at_gc_start - total_freed_objects(objspace);
11508 record->heap_use_pages = objspace->profile.heap_used_at_gc_start;
11509 record->heap_live_objects = live;
11510 record->heap_free_objects = total - live;
11511#endif
11512
11513 record->heap_total_objects = total;
11514 record->heap_use_size = use_size;
11515 record->heap_total_size = total_size;
11516 }
11517}
11518
11519/*
11520 * call-seq:
11521 * GC::Profiler.clear -> nil
11522 *
11523 * Clears the \GC profiler data.
11524 *
11525 */
11526
11527static VALUE
11528gc_profile_clear(VALUE _)
11529{
11530 rb_objspace_t *objspace = rb_gc_get_objspace();
11531 gc_profile_records_free(objspace);
11532 return Qnil;
11533}
11534
11535/*
11536 * call-seq:
11537 * GC::Profiler.configure(max_records: 4096) -> nil
11538 *
11539 * Configures how many raw profile records are retained by
11540 * GC::Profiler.raw_data.
11541 *
11542 * The profiler keeps at most +max_records+ records in a bounded ring buffer.
11543 * When the buffer is full, newer GC records overwrite the oldest retained
11544 * records. The default limit is 4096 records.
11545 *
11546 * Pass +nil+ to restore the historical unbounded behavior:
11547 *
11548 * GC::Profiler.configure(max_records: nil)
11549 *
11550 * Changing +max_records+ clears existing raw profile data. This method does
11551 * not enable or disable the profiler; use GC::Profiler.enable and
11552 * GC::Profiler.disable for that.
11553 */
11554
11555static VALUE
11556gc_profile_configure(int argc, VALUE *argv, VALUE _)
11557{
11558 static ID keywords[1] = {0};
11559 VALUE options, max_records;
11560 rb_objspace_t *objspace = rb_gc_get_objspace();
11561
11562 if (!keywords[0]) {
11563 keywords[0] = rb_intern("max_records");
11564 }
11565
11566 rb_scan_args_kw(rb_keyword_given_p(), argc, argv, ":", &options);
11567 rb_get_kwargs(options, keywords, 0, 1, &max_records);
11568
11569 if (max_records == Qundef) {
11570 return Qnil;
11571 }
11572 else if (NIL_P(max_records)) {
11573 objspace->profile.max_records = GC_PROFILE_RECORD_UNBOUNDED;
11574 }
11575 else {
11576 long value = NUM2LONG(max_records);
11577 if (value <= 0) {
11578 rb_raise(rb_eArgError, "max_records must be positive or nil");
11579 }
11580 objspace->profile.max_records = (size_t)value;
11581 }
11582
11583 gc_profile_records_free(objspace);
11584 return Qnil;
11585}
11586
11587/*
11588 * call-seq:
11589 * GC::Profiler.raw_data(limit: nil, since: nil) -> [Hash, ...]
11590 *
11591 * Returns an Array of retained raw profile data Hashes ordered from earliest
11592 * to latest by +:GC_INVOKE_TIME+. +limit:+ returns at most the newest
11593 * retained records. +since:+ returns records with +:GC_SEQUENCE+ greater
11594 * than the given sequence.
11595 *
11596 * For example:
11597 *
11598 * [
11599 * {
11600 * :GC_TIME=>1.3000000000000858e-05,
11601 * :GC_INVOKE_TIME=>0.010634999999999999,
11602 * :GC_WALL_TIME=>1.4000000000000001e-05,
11603 * :GC_INVOKE_WALL_TIME=>0.010640000000000000,
11604 * :GC_PAUSE_TIME=>1.5000000000000000e-05,
11605 * :GC_STOP_TIME=>1.0000000000000000e-06,
11606 * :GC_STW_TIME=>1.4000000000000001e-05,
11607 * :GC_MARK_WALL_TIME=>9.0000000000000002e-06,
11608 * :GC_SWEEP_WALL_TIME=>5.0000000000000004e-06,
11609 * :GC_COMPACT_WALL_TIME=>0.0000000000000000e+00,
11610 * :HEAP_USE_SIZE=>289640,
11611 * :HEAP_TOTAL_SIZE=>588960,
11612 * :HEAP_TOTAL_OBJECTS=>14724,
11613 * :GC_IS_MARKED=>false
11614 * },
11615 * # ...
11616 * ]
11617 *
11618 * The keys mean:
11619 *
11620 * +:GC_SEQUENCE+::
11621 * Monotonically increasing sequence number for this profiler record.
11622 * +:GC_TIME+::
11623 * CPU time elapsed in seconds for this GC run. This is process CPU time,
11624 * not elapsed wall-clock time.
11625 * +:GC_INVOKE_TIME+::
11626 * CPU time elapsed in seconds from startup to when the GC was invoked.
11627 * +:GC_WALL_TIME+::
11628 * Monotonic wall-clock counterpart to +:GC_TIME+ for this GC record.
11629 * This does not include time spent stopping other ractors before the VM
11630 * enters GC. Use the phase wall-clock fields below for mark, sweep, and
11631 * compaction attribution.
11632 * +:GC_INVOKE_WALL_TIME+::
11633 * Monotonic wall-clock time elapsed in seconds from startup to when the GC
11634 * was invoked.
11635 * +:GC_PAUSE_TIME+::
11636 * Monotonic wall-clock time elapsed in seconds while user execution was
11637 * blocked by this GC entry, including time to stop other ractors. This
11638 * may include time from incremental marking or lazy sweeping continuation
11639 * charged to this record.
11640 * +:GC_STOP_TIME+::
11641 * Monotonic wall-clock time elapsed in seconds stopping other ractors.
11642 * +:GC_STW_TIME+::
11643 * Monotonic wall-clock time elapsed in seconds after other ractors have
11644 * stopped and before the VM exits GC.
11645 * +:GC_MARK_WALL_TIME+::
11646 * Monotonic wall-clock time elapsed in seconds spent marking for this GC
11647 * record, accumulated across incremental marking continuations.
11648 * +:GC_SWEEP_WALL_TIME+::
11649 * Monotonic wall-clock time elapsed in seconds spent sweeping for this GC
11650 * record, accumulated across lazy sweeping continuations. This does not
11651 * include compaction time, which is reported separately as
11652 * +:GC_COMPACT_WALL_TIME+.
11653 * +:GC_COMPACT_WALL_TIME+::
11654 * Monotonic wall-clock time elapsed in seconds spent compacting for this GC
11655 * record, or +0.0+ if this GC did not compact.
11656 * +:HEAP_USE_SIZE+::
11657 * Total bytes of heap used
11658 * +:HEAP_TOTAL_SIZE+::
11659 * Total size of heap in bytes
11660 * +:HEAP_TOTAL_OBJECTS+::
11661 * Total number of objects
11662 * +:GC_IS_MARKED+::
11663 * Returns +true+ if the GC is in mark phase
11664 *
11665 * The wall-clock timing fields relate to each other as follows:
11666 *
11667 * GC_PAUSE_TIME == GC_STOP_TIME + GC_STW_TIME
11668 *
11669 * +:GC_MARK_WALL_TIME+, +:GC_SWEEP_WALL_TIME+, and +:GC_COMPACT_WALL_TIME+
11670 * report separate phase timings and must not be added to +:GC_WALL_TIME+.
11671 *
11672 * +:GC_WALL_TIME+ is the wall-clock counterpart to +:GC_TIME+ and is nested
11673 * inside +:GC_STW_TIME+, so it must not be added to +:GC_STW_TIME+. The difference
11674 * +GC_STW_TIME - GC_WALL_TIME+ is VM overhead inside the stopped interval
11675 * (GC event hooks, bookkeeping, consistency checks, and continuation work).
11676 *
11677 * If ruby was built with +GC_PROFILE_MORE_DETAIL+, you will also have access
11678 * to the following hash keys:
11679 *
11680 * +:GC_MARK_TIME+::
11681 * +:GC_SWEEP_TIME+::
11682 * +:ALLOCATE_INCREASE+::
11683 * +:ALLOCATE_LIMIT+::
11684 * +:HEAP_USE_PAGES+::
11685 * +:HEAP_LIVE_OBJECTS+::
11686 * +:HEAP_FREE_OBJECTS+::
11687 * +:HAVE_FINALIZE+::
11688 *
11689 */
11690
11691static VALUE
11692gc_profile_record_get(int argc, VALUE *argv, VALUE _)
11693{
11694 static ID keywords[2] = {0};
11695 VALUE prof, options, limit_value, since_value;
11696 VALUE gc_profile = rb_ary_new();
11697 size_t i, count, matching = 0, skip = 0, limit = SIZE_MAX, since = 0;
11698 bool use_since = false;
11699 rb_objspace_t *objspace = rb_gc_get_objspace();
11700
11701 if (!keywords[0]) {
11702 keywords[0] = rb_intern("limit");
11703 keywords[1] = rb_intern("since");
11704 }
11705
11706 rb_scan_args_kw(rb_keyword_given_p(), argc, argv, ":", &options);
11707 VALUE values[2] = {Qundef, Qundef};
11708 rb_get_kwargs(options, keywords, 0, 2, values);
11709 limit_value = values[0];
11710 since_value = values[1];
11711
11712 if (limit_value != Qundef && !NIL_P(limit_value)) {
11713 long value = NUM2LONG(limit_value);
11714 if (value < 0) {
11715 rb_raise(rb_eArgError, "limit must be non-negative");
11716 }
11717 limit = (size_t)value;
11718 }
11719 if (since_value != Qundef && !NIL_P(since_value)) {
11720 long value = NUM2LONG(since_value);
11721 if (value < 0) {
11722 rb_raise(rb_eArgError, "since must be non-negative");
11723 }
11724 since = (size_t)value;
11725 use_since = true;
11726 }
11727
11728 if (!objspace->profile.run) {
11729 return Qnil;
11730 }
11731
11732 count = gc_profile_record_count(objspace);
11733 for (i = 0; i < count; i++) {
11734 gc_profile_record *record = &objspace->profile.records[gc_profile_record_index(objspace, i)];
11735 if (!use_since || record->sequence > since) {
11736 matching++;
11737 }
11738 }
11739 if (limit < matching) {
11740 skip = matching - limit;
11741 }
11742
11743 for (i = 0; i < count; i++) {
11744 gc_profile_record *record = &objspace->profile.records[gc_profile_record_index(objspace, i)];
11745 if (use_since && record->sequence <= since) {
11746 continue;
11747 }
11748 if (skip > 0) {
11749 skip--;
11750 continue;
11751 }
11752
11753 prof = rb_hash_new();
11754 rb_hash_aset(prof, ID2SYM(rb_intern("GC_FLAGS")), gc_info_decode(objspace, rb_hash_new(), record->flags));
11755 rb_hash_aset(prof, ID2SYM(rb_intern("GC_SEQUENCE")), SIZET2NUM(record->sequence));
11756 rb_hash_aset(prof, ID2SYM(rb_intern("GC_TIME")), DBL2NUM(record->gc_time));
11757 rb_hash_aset(prof, ID2SYM(rb_intern("GC_INVOKE_TIME")), DBL2NUM(record->gc_invoke_time));
11758 rb_hash_aset(prof, ID2SYM(rb_intern("GC_WALL_TIME")),
11759 DBL2NUM(hrtime_to_sec(record->gc_wall_time)));
11760 rb_hash_aset(prof, ID2SYM(rb_intern("GC_INVOKE_WALL_TIME")),
11761 DBL2NUM(hrtime_to_sec(record->gc_invoke_wall_time)));
11762 rb_hash_aset(prof, ID2SYM(rb_intern("GC_PAUSE_TIME")),
11763 DBL2NUM(hrtime_to_sec(record->gc_pause_time)));
11764 rb_hash_aset(prof, ID2SYM(rb_intern("GC_STOP_TIME")),
11765 DBL2NUM(hrtime_to_sec(record->gc_stop_time)));
11766 rb_hash_aset(prof, ID2SYM(rb_intern("GC_STW_TIME")),
11767 DBL2NUM(hrtime_to_sec(record->gc_stw_time)));
11768 rb_hash_aset(prof, ID2SYM(rb_intern("GC_MARK_WALL_TIME")),
11769 DBL2NUM(hrtime_to_sec(record->gc_mark_wall_time)));
11770 rb_hash_aset(prof, ID2SYM(rb_intern("GC_SWEEP_WALL_TIME")),
11771 DBL2NUM(hrtime_to_sec(record->gc_sweep_wall_time)));
11772 rb_hash_aset(prof, ID2SYM(rb_intern("GC_COMPACT_WALL_TIME")),
11773 DBL2NUM(hrtime_to_sec(record->gc_compact_wall_time)));
11774 rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_USE_SIZE")), SIZET2NUM(record->heap_use_size));
11775 rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_TOTAL_SIZE")), SIZET2NUM(record->heap_total_size));
11776 rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_TOTAL_OBJECTS")), SIZET2NUM(record->heap_total_objects));
11777 rb_hash_aset(prof, ID2SYM(rb_intern("MOVED_OBJECTS")), SIZET2NUM(record->moved_objects));
11778 rb_hash_aset(prof, ID2SYM(rb_intern("GC_IS_MARKED")), Qtrue);
11779#if GC_PROFILE_MORE_DETAIL
11780 rb_hash_aset(prof, ID2SYM(rb_intern("GC_MARK_TIME")), DBL2NUM(record->gc_mark_time));
11781 rb_hash_aset(prof, ID2SYM(rb_intern("GC_SWEEP_TIME")), DBL2NUM(record->gc_sweep_time));
11782 rb_hash_aset(prof, ID2SYM(rb_intern("ALLOCATE_INCREASE")), SIZET2NUM(record->allocate_increase));
11783 rb_hash_aset(prof, ID2SYM(rb_intern("ALLOCATE_LIMIT")), SIZET2NUM(record->allocate_limit));
11784 rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_USE_PAGES")), SIZET2NUM(record->heap_use_pages));
11785 rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_LIVE_OBJECTS")), SIZET2NUM(record->heap_live_objects));
11786 rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_FREE_OBJECTS")), SIZET2NUM(record->heap_free_objects));
11787
11788 rb_hash_aset(prof, ID2SYM(rb_intern("REMOVING_OBJECTS")), SIZET2NUM(record->removing_objects));
11789 rb_hash_aset(prof, ID2SYM(rb_intern("EMPTY_OBJECTS")), SIZET2NUM(record->empty_objects));
11790
11791 rb_hash_aset(prof, ID2SYM(rb_intern("HAVE_FINALIZE")), (record->flags & GPR_FLAG_HAVE_FINALIZE) ? Qtrue : Qfalse);
11792#endif
11793
11794#if RGENGC_PROFILE > 0
11795 rb_hash_aset(prof, ID2SYM(rb_intern("OLD_OBJECTS")), SIZET2NUM(record->old_objects));
11796 rb_hash_aset(prof, ID2SYM(rb_intern("REMEMBERED_NORMAL_OBJECTS")), SIZET2NUM(record->remembered_normal_objects));
11797 rb_hash_aset(prof, ID2SYM(rb_intern("REMEMBERED_SHADY_OBJECTS")), SIZET2NUM(record->remembered_shady_objects));
11798#endif
11799 rb_ary_push(gc_profile, prof);
11800 }
11801
11802 return gc_profile;
11803}
11804
11805#if GC_PROFILE_MORE_DETAIL
11806#define MAJOR_REASON_MAX 0x10
11807
11808static char *
11809gc_profile_dump_major_reason(unsigned int flags, char *buff)
11810{
11811 unsigned int reason = flags & GPR_FLAG_MAJOR_MASK;
11812 int i = 0;
11813
11814 if (reason == GPR_FLAG_NONE) {
11815 buff[0] = '-';
11816 buff[1] = 0;
11817 }
11818 else {
11819#define C(x, s) \
11820 if (reason & GPR_FLAG_MAJOR_BY_##x) { \
11821 buff[i++] = #x[0]; \
11822 if (i >= MAJOR_REASON_MAX) rb_bug("gc_profile_dump_major_reason: overflow"); \
11823 buff[i] = 0; \
11824 }
11825 C(NOFREE, N);
11826 C(OLDGEN, O);
11827 C(SHADY, S);
11828#if RGENGC_ESTIMATE_OLDMALLOC
11829 C(OLDMALLOC, M);
11830#endif
11831#undef C
11832 }
11833 return buff;
11834}
11835#endif
11836
11837
11838
11839static void
11840gc_profile_dump_on(VALUE out, VALUE (*append)(VALUE, VALUE))
11841{
11842 rb_objspace_t *objspace = rb_gc_get_objspace();
11843 size_t count = gc_profile_record_count(objspace);
11844#ifdef MAJOR_REASON_MAX
11845 char reason_str[MAJOR_REASON_MAX];
11846#endif
11847
11848 if (objspace->profile.run && count /* > 1 */) {
11849 size_t i;
11850 const gc_profile_record *record;
11851
11852 append(out, rb_sprintf("GC %"PRIuSIZE" invokes.\n", objspace->profile.count));
11853 append(out, rb_str_new_cstr("Index Invoke Time(sec) Use Size(byte) Total Size(byte) Total Object GC Time(ms)\n"));
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" %19.3f %20"PRIuSIZE" %20"PRIuSIZE" %20"PRIuSIZE" %30.20f\n",
11858 i+1, record->gc_invoke_time, record->heap_use_size,
11859 record->heap_total_size, record->heap_total_objects, record->gc_time*1000));
11860 }
11861
11862#if GC_PROFILE_MORE_DETAIL
11863 const char *str = "\n\n" \
11864 "More detail.\n" \
11865 "Prepare Time = Previously GC's rest sweep time\n"
11866 "Index Flags Allocate Inc. Allocate Limit"
11867#if CALC_EXACT_MALLOC_SIZE
11868 " Allocated Size"
11869#endif
11870 " Use Page Mark Time(ms) Sweep Time(ms) Prepare Time(ms) LivingObj FreeObj RemovedObj EmptyObj"
11871#if RGENGC_PROFILE
11872 " OldgenObj RemNormObj RemShadObj"
11873#endif
11874#if GC_PROFILE_DETAIL_MEMORY
11875 " MaxRSS(KB) MinorFLT MajorFLT"
11876#endif
11877 "\n";
11878 append(out, rb_str_new_cstr(str));
11879
11880 for (i = 0; i < count; i++) {
11881 record = &objspace->profile.records[gc_profile_record_index(objspace, i)];
11882 append(out, rb_sprintf("%5"PRIuSIZE" %4s/%c/%6s%c %13"PRIuSIZE" %15"PRIuSIZE
11883#if CALC_EXACT_MALLOC_SIZE
11884 " %15"PRIuSIZE
11885#endif
11886 " %9"PRIuSIZE" %17.12f %17.12f %17.12f %10"PRIuSIZE" %10"PRIuSIZE" %10"PRIuSIZE" %10"PRIuSIZE
11887#if RGENGC_PROFILE
11888 "%10"PRIuSIZE" %10"PRIuSIZE" %10"PRIuSIZE
11889#endif
11890#if GC_PROFILE_DETAIL_MEMORY
11891 "%11ld %8ld %8ld"
11892#endif
11893
11894 "\n",
11895 i+1,
11896 gc_profile_dump_major_reason(record->flags, reason_str),
11897 (record->flags & GPR_FLAG_HAVE_FINALIZE) ? 'F' : '.',
11898 (record->flags & GPR_FLAG_NEWOBJ) ? "NEWOBJ" :
11899 (record->flags & GPR_FLAG_MALLOC) ? "MALLOC" :
11900 (record->flags & GPR_FLAG_METHOD) ? "METHOD" :
11901 (record->flags & GPR_FLAG_CAPI) ? "CAPI__" : "??????",
11902 (record->flags & GPR_FLAG_STRESS) ? '!' : ' ',
11903 record->allocate_increase, record->allocate_limit,
11904#if CALC_EXACT_MALLOC_SIZE
11905 record->allocated_size,
11906#endif
11907 record->heap_use_pages,
11908 record->gc_mark_time*1000,
11909 record->gc_sweep_time*1000,
11910 record->prepare_time*1000,
11911
11912 record->heap_live_objects,
11913 record->heap_free_objects,
11914 record->removing_objects,
11915 record->empty_objects
11916#if RGENGC_PROFILE
11917 ,
11918 record->old_objects,
11919 record->remembered_normal_objects,
11920 record->remembered_shady_objects
11921#endif
11922#if GC_PROFILE_DETAIL_MEMORY
11923 ,
11924 record->maxrss / 1024,
11925 record->minflt,
11926 record->majflt
11927#endif
11928
11929 ));
11930 }
11931#endif
11932 }
11933}
11934
11935/*
11936 * call-seq:
11937 * GC::Profiler.result -> String
11938 *
11939 * Returns a profile data report such as:
11940 *
11941 * GC 1 invokes.
11942 * Index Invoke Time(sec) Use Size(byte) Total Size(byte) Total Object GC time(ms)
11943 * 1 0.012 159240 212940 10647 0.00000000000001530000
11944 */
11945
11946static VALUE
11947gc_profile_result(VALUE _)
11948{
11949 VALUE str = rb_str_buf_new(0);
11950 gc_profile_dump_on(str, rb_str_buf_append);
11951 return str;
11952}
11953
11954/*
11955 * call-seq:
11956 * GC::Profiler.report
11957 * GC::Profiler.report(io)
11958 *
11959 * Writes the GC::Profiler.result to <tt>$stdout</tt> or the given IO object.
11960 *
11961 */
11962
11963static VALUE
11964gc_profile_report(int argc, VALUE *argv, VALUE self)
11965{
11966 VALUE out;
11967
11968 out = (!rb_check_arity(argc, 0, 1) ? rb_stdout : argv[0]);
11969 gc_profile_dump_on(out, rb_io_write);
11970
11971 return Qnil;
11972}
11973
11974/*
11975 * call-seq:
11976 * GC::Profiler.total_time -> float
11977 *
11978 * The total time used for garbage collection in seconds
11979 */
11980
11981static VALUE
11982gc_profile_total_time(VALUE self)
11983{
11984 double time = 0;
11985 rb_objspace_t *objspace = rb_gc_get_objspace();
11986
11987 if (objspace->profile.run && gc_profile_record_count(objspace) > 0) {
11988 size_t i;
11989 size_t count = gc_profile_record_count(objspace);
11990
11991 for (i = 0; i < count; i++) {
11992 time += objspace->profile.records[gc_profile_record_index(objspace, i)].gc_time;
11993 }
11994 }
11995 return DBL2NUM(time);
11996}
11997
11998/*
11999 * call-seq:
12000 * GC::Profiler.enabled? -> true or false
12001 *
12002 * The current status of \GC profile mode.
12003 */
12004
12005static VALUE
12006gc_profile_enable_get(VALUE self)
12007{
12008 rb_objspace_t *objspace = rb_gc_get_objspace();
12009 return objspace->profile.run ? Qtrue : Qfalse;
12010}
12011
12012/*
12013 * call-seq:
12014 * GC::Profiler.enable -> nil
12015 *
12016 * Starts the \GC profiler.
12017 *
12018 */
12019
12020static VALUE
12021gc_profile_enable(VALUE _)
12022{
12023 rb_objspace_t *objspace = rb_gc_get_objspace();
12024 objspace->profile.run = TRUE;
12025 objspace->profile.current_record = 0;
12026 return Qnil;
12027}
12028
12029/*
12030 * call-seq:
12031 * GC::Profiler.disable -> nil
12032 *
12033 * Stops the \GC profiler.
12034 *
12035 */
12036
12037static VALUE
12038gc_profile_disable(VALUE _)
12039{
12040 rb_objspace_t *objspace = rb_gc_get_objspace();
12041
12042 objspace->profile.run = FALSE;
12043 objspace->profile.current_record = 0;
12044 return Qnil;
12045}
12046
12047static void
12048rb_gc_verify_internal_consistency(void)
12049{
12050 gc_verify_internal_consistency(rb_gc_get_objspace());
12051}
12052
12053/*
12054 * call-seq:
12055 * GC.verify_internal_consistency -> nil
12056 *
12057 * Verifies internal consistency of the GC.
12058 * This method should only be used for debugging.
12059 *
12060 * This method is only expected to work on CRuby.
12061 */
12062static VALUE
12063gc_verify_internal_consistency_m(VALUE dummy)
12064{
12065 rb_gc_verify_internal_consistency();
12066 return Qnil;
12067}
12068
12069#if GC_CAN_COMPILE_COMPACTION
12070/*
12071 * call-seq:
12072 * GC.auto_compact = flag
12073 *
12074 * Updates automatic compaction mode.
12075 *
12076 * When enabled, the compactor will execute on every major collection.
12077 *
12078 * Enabling compaction will degrade performance on major collections.
12079 */
12080static VALUE
12081gc_set_auto_compact(VALUE _, VALUE v)
12082{
12083 GC_ASSERT(GC_COMPACTION_SUPPORTED);
12084
12085 ruby_enable_autocompact = RTEST(v);
12086
12087#if RGENGC_CHECK_MODE
12088 ruby_autocompact_compare_func = NULL;
12089
12090 if (SYMBOL_P(v)) {
12091 ID id = RB_SYM2ID(v);
12092 if (id == rb_intern("empty")) {
12093 ruby_autocompact_compare_func = compare_free_slots;
12094 }
12095 }
12096#endif
12097
12098 return v;
12099}
12100#else
12101# define gc_set_auto_compact rb_f_notimplement
12102#endif
12103
12104#if GC_CAN_COMPILE_COMPACTION
12105/*
12106 * call-seq:
12107 * GC.auto_compact -> true or false
12108 *
12109 * Returns whether or not automatic compaction has been enabled.
12110 */
12111static VALUE
12112gc_get_auto_compact(VALUE _)
12113{
12114 return ruby_enable_autocompact ? Qtrue : Qfalse;
12115}
12116#else
12117# define gc_get_auto_compact rb_f_notimplement
12118#endif
12119
12120#if GC_CAN_COMPILE_COMPACTION
12121/*
12122 * call-seq:
12123 * GC.latest_compact_info -> hash
12124 *
12125 * Returns information about object moved in the most recent \GC compaction.
12126 *
12127 * The returned +hash+ contains the following keys:
12128 *
12129 * [considered]
12130 * Hash containing the type of the object as the key and the number of
12131 * objects of that type that were considered for movement.
12132 * [moved]
12133 * Hash containing the type of the object as the key and the number of
12134 * objects of that type that were actually moved.
12135 * [moved_up]
12136 * Hash containing the type of the object as the key and the number of
12137 * objects of that type that were increased in size.
12138 * [moved_down]
12139 * Hash containing the type of the object as the key and the number of
12140 * objects of that type that were decreased in size.
12141 *
12142 * Some objects can't be moved (due to pinning) so these numbers can be used to
12143 * calculate compaction efficiency.
12144 */
12145static VALUE
12146gc_compact_stats(VALUE self)
12147{
12148 rb_objspace_t *objspace = rb_gc_get_objspace();
12149 VALUE h = rb_hash_new();
12150 VALUE considered = rb_hash_new();
12151 VALUE moved = rb_hash_new();
12152 VALUE moved_up = rb_hash_new();
12153 VALUE moved_down = rb_hash_new();
12154
12155 for (size_t i = 0; i < T_MASK; i++) {
12156 if (objspace->rcompactor.considered_count_table[i]) {
12157 rb_hash_aset(considered, type_sym(i), SIZET2NUM(objspace->rcompactor.considered_count_table[i]));
12158 }
12159
12160 if (objspace->rcompactor.moved_count_table[i]) {
12161 rb_hash_aset(moved, type_sym(i), SIZET2NUM(objspace->rcompactor.moved_count_table[i]));
12162 }
12163
12164 if (objspace->rcompactor.moved_up_count_table[i]) {
12165 rb_hash_aset(moved_up, type_sym(i), SIZET2NUM(objspace->rcompactor.moved_up_count_table[i]));
12166 }
12167
12168 if (objspace->rcompactor.moved_down_count_table[i]) {
12169 rb_hash_aset(moved_down, type_sym(i), SIZET2NUM(objspace->rcompactor.moved_down_count_table[i]));
12170 }
12171 }
12172
12173 rb_hash_aset(h, ID2SYM(rb_intern("considered")), considered);
12174 rb_hash_aset(h, ID2SYM(rb_intern("moved")), moved);
12175 rb_hash_aset(h, ID2SYM(rb_intern("moved_up")), moved_up);
12176 rb_hash_aset(h, ID2SYM(rb_intern("moved_down")), moved_down);
12177
12178 return h;
12179}
12180#else
12181# define gc_compact_stats rb_f_notimplement
12182#endif
12183
12184#if GC_CAN_COMPILE_COMPACTION
12185/*
12186 * call-seq:
12187 * GC.compact -> hash
12188 *
12189 * This function compacts objects together in Ruby's heap. It eliminates
12190 * unused space (or fragmentation) in the heap by moving objects in to that
12191 * unused space.
12192 *
12193 * The returned +hash+ contains statistics about the objects that were moved;
12194 * see GC.latest_compact_info.
12195 *
12196 * This method is only expected to work on CRuby.
12197 *
12198 * To test whether \GC compaction is supported, use the idiom:
12199 *
12200 * GC.respond_to?(:compact)
12201 */
12202static VALUE
12203gc_compact(VALUE self)
12204{
12205 rb_objspace_t *objspace = rb_gc_get_objspace();
12206 int full_marking_p = gc_config_full_mark_val;
12207 gc_config_full_mark_set(TRUE);
12208
12209 /* Run GC with compaction enabled */
12210 rb_gc_impl_start(rb_gc_get_objspace(), true, true, true, true);
12211 gc_config_full_mark_set(full_marking_p);
12212
12213 return gc_compact_stats(self);
12214}
12215#else
12216# define gc_compact rb_f_notimplement
12217#endif
12218
12219#if GC_CAN_COMPILE_COMPACTION
12220struct desired_compaction_pages_i_data {
12222 size_t required_slots[HEAP_COUNT];
12223};
12224
12225static int
12226desired_compaction_pages_i(struct heap_page *page, void *data)
12227{
12228 struct desired_compaction_pages_i_data *tdata = data;
12229 rb_objspace_t *objspace = tdata->objspace;
12230 VALUE vstart = (VALUE)page->start;
12231 VALUE vend = vstart + (VALUE)(page->total_slots * page->heap->slot_size);
12232
12233
12234 for (VALUE v = vstart; v != vend; v += page->heap->slot_size) {
12235 asan_unpoisoning_object(v) {
12236 /* skip T_NONEs; they won't be moved */
12237 if (BUILTIN_TYPE(v) != T_NONE) {
12238 rb_heap_t *dest_pool = gc_compact_destination_pool(objspace, page->heap, v);
12239 size_t dest_pool_idx = dest_pool - heaps;
12240 tdata->required_slots[dest_pool_idx]++;
12241 }
12242 }
12243 }
12244
12245 return 0;
12246}
12247
12248/* call-seq:
12249 * GC.verify_compaction_references(toward: nil, double_heap: false) -> hash
12250 *
12251 * Verify compaction reference consistency.
12252 *
12253 * This method is implementation specific. During compaction, objects that
12254 * were moved are replaced with T_MOVED objects. No object should have a
12255 * reference to a T_MOVED object after compaction.
12256 *
12257 * This function expands the heap to ensure room to move all objects,
12258 * compacts the heap to make sure everything moves, updates all references,
12259 * then performs a full \GC. If any object contains a reference to a T_MOVED
12260 * object, that object should be pushed on the mark stack, and will
12261 * make a SEGV.
12262 */
12263static VALUE
12264gc_verify_compaction_references(int argc, VALUE* argv, VALUE self)
12265{
12266 static ID keywords[3] = {0};
12267 if (!keywords[0]) {
12268 keywords[0] = rb_intern("toward");
12269 keywords[1] = rb_intern("double_heap");
12270 keywords[2] = rb_intern("expand_heap");
12271 }
12272
12273 VALUE options;
12274 rb_scan_args_kw(rb_keyword_given_p(), argc, argv, ":", &options);
12275
12276 VALUE arguments[3] = { Qnil, Qfalse, Qfalse };
12277 int kwarg_count = rb_get_kwargs(options, keywords, 0, 3, arguments);
12278 bool toward_empty = kwarg_count > 0 && SYMBOL_P(arguments[0]) && SYM2ID(arguments[0]) == rb_intern("empty");
12279 bool expand_heap = (kwarg_count > 1 && RTEST(arguments[1])) || (kwarg_count > 2 && RTEST(arguments[2]));
12280
12281 rb_objspace_t *objspace = rb_gc_get_objspace();
12282
12283 /* This verification machinery (heap expansion, toward_empty page ordering, the
12284 * moved-reference walk) is built for a single objspace, so with several demote it
12285 * to a plain full GC. Plain GC.compact does compact them via the global GC. */
12286 if (!rb_gc_single_objspace_p()) {
12287 rb_gc_impl_start(objspace, true, true, true, false);
12288 return gc_compact_stats(self);
12289 }
12290
12291 /* Clear the heap. */
12292 rb_gc_impl_start(objspace, true, true, true, false);
12293
12294 unsigned int lev = RB_GC_VM_LOCK();
12295 {
12296 gc_rest(objspace);
12297
12298 /* if both double_heap and expand_heap are set, expand_heap takes precedence */
12299 if (expand_heap) {
12300 struct desired_compaction_pages_i_data desired_compaction = {
12301 .objspace = objspace,
12302 .required_slots = {0},
12303 };
12304 /* Work out how many objects want to be in each size pool, taking account of moves */
12305 objspace_each_pages(objspace, desired_compaction_pages_i, &desired_compaction, TRUE);
12306
12307 /* Find out which pool has the most pages */
12308 size_t max_existing_pages = 0;
12309 for (int i = 0; i < HEAP_COUNT; i++) {
12310 rb_heap_t *heap = &heaps[i];
12311 max_existing_pages = MAX(max_existing_pages, heap->total_pages);
12312 }
12313
12314 /* Add pages to each size pool so that compaction is guaranteed to move every object */
12315 for (int i = 0; i < HEAP_COUNT; i++) {
12316 rb_heap_t *heap = &heaps[i];
12317
12318 size_t pages_to_add = 0;
12319 /*
12320 * Step 1: Make sure every pool has the same number of pages, by adding empty pages
12321 * to smaller pools. This is required to make sure the compact cursor can advance
12322 * through all of the pools in `gc_sweep_compact` without hitting the "sweep &
12323 * compact cursors met" condition on some pools before fully compacting others
12324 */
12325 pages_to_add += max_existing_pages - heap->total_pages;
12326 /*
12327 * Step 2: Now add additional free pages to each size pool sufficient to hold all objects
12328 * that want to be in that size pool, whether moved into it or moved within it
12329 */
12330 objspace->heap_pages.allocatable_bytes = desired_compaction.required_slots[i] * heap->slot_size;
12331 while (objspace->heap_pages.allocatable_bytes > 0) {
12332 heap_page_allocate_and_initialize(objspace, heap);
12333 }
12334 /*
12335 * Step 3: Add two more pages so that the compact & sweep cursors will meet _after_ all objects
12336 * have been moved, and not on the last iteration of the `gc_sweep_compact` loop
12337 */
12338 pages_to_add += 2;
12339
12340 for (; pages_to_add > 0; pages_to_add--) {
12341 heap_page_allocate_and_initialize_force(objspace, heap);
12342 }
12343 }
12344 }
12345
12346 if (toward_empty) {
12347 objspace->rcompactor.compare_func = compare_free_slots;
12348 }
12349 }
12350 RB_GC_VM_UNLOCK(lev);
12351
12352 rb_gc_impl_start(rb_gc_get_objspace(), true, true, true, true);
12353
12354 rb_objspace_reachable_objects_from_root(root_obj_check_moved_i, objspace);
12355 objspace_each_objects(objspace, heap_check_moved_i, objspace, TRUE);
12356
12357 objspace->rcompactor.compare_func = NULL;
12358
12359 return gc_compact_stats(self);
12360}
12361#else
12362# define gc_verify_compaction_references rb_f_notimplement
12363#endif
12364
12365void
12366rb_gc_impl_objspace_free(void *objspace_ptr)
12367{
12368 rb_objspace_t *objspace = objspace_ptr;
12369
12370 if (is_lazy_sweeping(objspace))
12371 rb_bug("lazy sweeping underway when freeing object space");
12372
12373 free(objspace->profile.records);
12374 objspace->profile.records = NULL;
12375
12376 for (size_t i = 0; i < rb_darray_size(objspace->heap_pages.sorted); i++) {
12377 heap_page_free(objspace, rb_darray_get(objspace->heap_pages.sorted, i));
12378 }
12379 rb_darray_free_without_gc(objspace->heap_pages.sorted);
12380 heap_pages_lomem = 0;
12381 heap_pages_himem = 0;
12382
12383 for (int i = 0; i < HEAP_COUNT; i++) {
12384 rb_heap_t *heap = &heaps[i];
12385 heap->total_pages = 0;
12386 heap->total_slots = 0;
12387 }
12388
12389 free_stack_chunks(&objspace->mark_stack);
12390 mark_stack_free_cache(&objspace->mark_stack);
12391
12392 rb_darray_free_without_gc(objspace->weak_references);
12393
12394#ifdef MALLOC_COUNTERS_NEED_LOCK
12395 rb_native_mutex_destroy(&objspace->malloc_counters.lock);
12396#endif
12397
12398 free(objspace);
12399}
12400
12401#if MALLOC_ALLOCATED_SIZE
12402/*
12403 * call-seq:
12404 * GC.malloc_allocated_size -> Integer
12405 *
12406 * Returns the size of memory allocated by malloc().
12407 *
12408 * Only available if ruby was built with +CALC_EXACT_MALLOC_SIZE+.
12409 */
12410
12411static VALUE
12412gc_malloc_allocated_size(VALUE self)
12413{
12414 rb_objspace_t *objspace = (rb_objspace_t *)rb_gc_get_objspace();
12415 return ULL2NUM(objspace->malloc_params.allocated_size);
12416}
12417
12418/*
12419 * call-seq:
12420 * GC.malloc_allocations -> Integer
12421 *
12422 * Returns the number of malloc() allocations.
12423 *
12424 * Only available if ruby was built with +CALC_EXACT_MALLOC_SIZE+.
12425 */
12426
12427static VALUE
12428gc_malloc_allocations(VALUE self)
12429{
12430 rb_objspace_t *objspace = (rb_objspace_t *)rb_gc_get_objspace();
12431 return ULL2NUM(objspace->malloc_params.allocations);
12432}
12433#endif
12434
12435void
12436rb_gc_impl_before_fork(void *objspace_ptr)
12437{
12438 rb_objspace_t *objspace = objspace_ptr;
12439
12440 objspace->fork_vm_lock_lev = RB_GC_VM_LOCK();
12441 rb_gc_vm_barrier();
12442}
12443
12444void
12445rb_gc_impl_after_fork(void *objspace_ptr, rb_pid_t pid)
12446{
12447 rb_objspace_t *objspace = objspace_ptr;
12448
12449 RB_GC_VM_UNLOCK(objspace->fork_vm_lock_lev);
12450 objspace->fork_vm_lock_lev = 0;
12451
12452 if (pid == 0) { /* child process */
12453 heap_alloc_state_clear(objspace);
12454 /* The forking Ractor becomes the child process's main Ractor. */
12455 global_objspace->main_objspace = objspace;
12456 rb_native_mutex_initialize(&rb_global_objspace_instance.page_pool.lock);
12457 }
12458}
12459
12460VALUE rb_ident_hash_new_with_size(st_index_t size);
12461
12462#if GC_DEBUG_STRESS_TO_CLASS
12463/*
12464 * call-seq:
12465 * GC.add_stress_to_class(class[, ...])
12466 *
12467 * Raises NoMemoryError when allocating an instance of the given classes.
12468 *
12469 */
12470static VALUE
12471rb_gcdebug_add_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 set_stress_to_class(rb_ident_hash_new_with_size(argc));
12477 }
12478
12479 for (int i = 0; i < argc; i++) {
12480 VALUE klass = argv[i];
12481 rb_hash_aset(stress_to_class, klass, Qtrue);
12482 }
12483
12484 return self;
12485}
12486
12487/*
12488 * call-seq:
12489 * GC.remove_stress_to_class(class[, ...])
12490 *
12491 * No longer raises NoMemoryError when allocating an instance of the
12492 * given classes.
12493 *
12494 */
12495static VALUE
12496rb_gcdebug_remove_stress_to_class(int argc, VALUE *argv, VALUE self)
12497{
12498 rb_objspace_t *objspace = rb_gc_get_objspace();
12499
12500 if (stress_to_class) {
12501 for (int i = 0; i < argc; ++i) {
12502 rb_hash_delete(stress_to_class, argv[i]);
12503 }
12504
12505 if (rb_hash_size(stress_to_class) == 0) {
12506 stress_to_class = 0;
12507 }
12508 }
12509
12510 return Qnil;
12511}
12512#endif
12513
12514void *
12515rb_gc_impl_objspace_alloc(void)
12516{
12517 global_objspace_init();
12518
12519 rb_objspace_t *objspace = calloc1(sizeof(rb_objspace_t));
12520
12521 return objspace;
12522}
12523
12524void
12525rb_gc_impl_objspace_init(void *objspace_ptr)
12526{
12527 rb_objspace_t *objspace = objspace_ptr;
12528
12529 gc_config_full_mark_set(TRUE);
12530
12531 objspace->flags.measure_gc = true;
12532 malloc_limit = gc_params.malloc_limit_min;
12533 objspace->shareable_objects_limit = SHAREABLE_OBJECTS_LIMIT_MIN;
12534#ifdef MALLOC_COUNTERS_NEED_LOCK
12535 rb_native_mutex_initialize(&objspace->malloc_counters.lock);
12536#endif
12537 /* Shared by every objspace. preregister deduplicates on (func, data). */
12538 objspace->finalize_deferred_pjob = rb_postponed_job_preregister(0, gc_finalize_deferred, NULL);
12539 if (objspace->finalize_deferred_pjob == POSTPONED_JOB_HANDLE_INVALID) {
12540 rb_bug("Could not preregister postponed job for GC");
12541 }
12542
12543 /* A standard RVALUE (RBasic + embedded VALUEs + debug overhead) must fit
12544 * in at least one pool. In debug builds RVALUE_OVERHEAD can push this
12545 * beyond the 48-byte pool into the 64-byte pool, which is fine. */
12546 GC_ASSERT(rb_gc_impl_size_allocatable_p(sizeof(struct RBasic) + sizeof(VALUE[RBIMPL_RVALUE_EMBED_LEN_MAX])));
12547
12548 for (int i = 0; i < HEAP_COUNT; i++) {
12549 rb_heap_t *heap = &heaps[i];
12550
12551 heap->slot_size = pool_slot_sizes[i];
12552
12553 ccan_list_head_init(&heap->pages);
12554 }
12555
12556 if (global_objspace->main_objspace == NULL) {
12557 /* Single-threaded at boot and the first objspace is main's: compute process-wide
12558 * constants once here. A later objspace_init rewriting them, even with equal
12559 * values, would race other threads' lock-free reads. */
12560 global_objspace->main_objspace = objspace;
12561
12562 init_size_to_heap_idx();
12563
12564#if defined(INIT_HEAP_PAGE_ALLOC_USE_MMAP)
12565 /* Need to determine if we can use mmap at runtime. */
12566 heap_page_alloc_use_mmap = INIT_HEAP_PAGE_ALLOC_USE_MMAP;
12567#endif
12568 gc_params.heap_init_bytes = GC_HEAP_INIT_BYTES;
12569 }
12570
12571 rb_darray_make_without_gc(&objspace->heap_pages.sorted, 0);
12572 rb_darray_make_without_gc(&objspace->weak_references, 0);
12573
12574#if RGENGC_ESTIMATE_OLDMALLOC
12575 objspace->rgengc.oldmalloc_increase_limit = gc_params.oldmalloc_limit_min;
12576#endif
12577
12578 init_mark_stack(&objspace->mark_stack);
12579
12580 objspace->profile.invoke_time = getrusage_time();
12581 objspace->profile.invoke_wall_time = rb_hrtime_now();
12582 objspace->profile.max_records = GC_PROFILE_RECORD_DEFAULT_MAX_RECORDS;
12583 finalizer_table = st_init_numtable();
12584}
12585
12586void
12587rb_gc_impl_init(void)
12588{
12589 VALUE gc_constants = rb_hash_new();
12590 rb_hash_aset(gc_constants, ID2SYM(rb_intern("DEBUG")), GC_DEBUG ? Qtrue : Qfalse);
12591 /* Minimum slot size that fits a standard RVALUE */
12592 size_t rvalue_pool = 0;
12593 for (size_t i = 0; i < HEAP_COUNT; i++) {
12594 if (pool_slot_sizes[i] >= RVALUE_SLOT_SIZE) { rvalue_pool = pool_slot_sizes[i]; break; }
12595 }
12596 rb_hash_aset(gc_constants, ID2SYM(rb_intern("RVALUE_SIZE")), SIZET2NUM(rvalue_pool - RVALUE_OVERHEAD));
12597 rb_hash_aset(gc_constants, ID2SYM(rb_intern("RBASIC_SIZE")), SIZET2NUM(sizeof(struct RBasic)));
12598 rb_hash_aset(gc_constants, ID2SYM(rb_intern("RVALUE_OVERHEAD")), SIZET2NUM(RVALUE_OVERHEAD));
12599 rb_hash_aset(gc_constants, ID2SYM(rb_intern("HEAP_PAGE_BITMAP_SIZE")), SIZET2NUM(HEAP_PAGE_BITMAP_SIZE));
12600 rb_hash_aset(gc_constants, ID2SYM(rb_intern("HEAP_PAGE_SIZE")), SIZET2NUM(HEAP_PAGE_SIZE));
12601 rb_hash_aset(gc_constants, ID2SYM(rb_intern("HEAP_COUNT")), LONG2FIX(HEAP_COUNT));
12602 rb_hash_aset(gc_constants, ID2SYM(rb_intern("RVARGC_MAX_ALLOCATE_SIZE")), SIZET2NUM(rb_gc_impl_max_allocation_size()));
12603 rb_hash_aset(gc_constants, ID2SYM(rb_intern("RVALUE_OLD_AGE")), LONG2FIX(RVALUE_OLD_AGE));
12604 if (RB_BUG_INSTEAD_OF_RB_MEMERROR+0) {
12605 rb_hash_aset(gc_constants, ID2SYM(rb_intern("RB_BUG_INSTEAD_OF_RB_MEMERROR")), Qtrue);
12606 }
12607 OBJ_FREEZE(gc_constants);
12608 /* Internal constants in the garbage collector. */
12609 rb_define_const(rb_mGC, "INTERNAL_CONSTANTS", gc_constants);
12610
12611 if (GC_COMPACTION_SUPPORTED) {
12612 rb_define_singleton_method(rb_mGC, "compact", gc_compact, 0);
12613 rb_define_singleton_method(rb_mGC, "auto_compact", gc_get_auto_compact, 0);
12614 rb_define_singleton_method(rb_mGC, "auto_compact=", gc_set_auto_compact, 1);
12615 rb_define_singleton_method(rb_mGC, "latest_compact_info", gc_compact_stats, 0);
12616 rb_define_singleton_method(rb_mGC, "verify_compaction_references", gc_verify_compaction_references, -1);
12617 }
12618 else {
12622 rb_define_singleton_method(rb_mGC, "latest_compact_info", rb_f_notimplement, 0);
12623 rb_define_singleton_method(rb_mGC, "verify_compaction_references", rb_f_notimplement, -1);
12624 }
12625
12626#if GC_DEBUG_STRESS_TO_CLASS
12627 rb_define_singleton_method(rb_mGC, "add_stress_to_class", rb_gcdebug_add_stress_to_class, -1);
12628 rb_define_singleton_method(rb_mGC, "remove_stress_to_class", rb_gcdebug_remove_stress_to_class, -1);
12629#endif
12630
12631 /* internal methods */
12632 rb_define_singleton_method(rb_mGC, "verify_internal_consistency", gc_verify_internal_consistency_m, 0);
12633
12634#if MALLOC_ALLOCATED_SIZE
12635 rb_define_singleton_method(rb_mGC, "malloc_allocated_size", gc_malloc_allocated_size, 0);
12636 rb_define_singleton_method(rb_mGC, "malloc_allocations", gc_malloc_allocations, 0);
12637#endif
12638
12639 /* Document-class: GC::Profiler
12640 *
12641 * The GC profiler provides access to information on GC runs including time,
12642 * length and object space size.
12643 *
12644 * Example:
12645 *
12646 * GC::Profiler.enable
12647 *
12648 * require 'rdoc/rdoc'
12649 *
12650 * GC::Profiler.report
12651 *
12652 * pp GC::Profiler.raw_data
12653 *
12654 * GC::Profiler.disable
12655 *
12656 * GC::Profiler.raw_data returns one Hash per GC run, including CPU time
12657 * fields such as +:GC_TIME+ and wall-clock fields such as +:GC_WALL_TIME+,
12658 * +:GC_PAUSE_TIME+, +:GC_STOP_TIME+, and +:GC_STW_TIME+. +:GC_WALL_TIME+
12659 * is the wall-clock counterpart to +:GC_TIME+, while +:GC_PAUSE_TIME+
12660 * measures how long user execution was blocked by the GC entry.
12661 *
12662 * See also GC.count, GC.malloc_allocated_size and GC.malloc_allocations
12663 */
12664 VALUE rb_mProfiler = rb_define_module_under(rb_mGC, "Profiler");
12665 rb_define_singleton_method(rb_mProfiler, "enabled?", gc_profile_enable_get, 0);
12666 rb_define_singleton_method(rb_mProfiler, "enable", gc_profile_enable, 0);
12667 rb_define_singleton_method(rb_mProfiler, "raw_data", gc_profile_record_get, -1);
12668 rb_define_singleton_method(rb_mProfiler, "disable", gc_profile_disable, 0);
12669 rb_define_singleton_method(rb_mProfiler, "clear", gc_profile_clear, 0);
12670 rb_define_singleton_method(rb_mProfiler, "configure", gc_profile_configure, -1);
12671 rb_define_singleton_method(rb_mProfiler, "result", gc_profile_result, 0);
12672 rb_define_singleton_method(rb_mProfiler, "report", gc_profile_report, -1);
12673 rb_define_singleton_method(rb_mProfiler, "total_time", gc_profile_total_time, 0);
12674
12675 {
12676 VALUE opts;
12677 /* \GC build options */
12678 rb_define_const(rb_mGC, "OPTS", opts = rb_ary_new());
12679#define OPT(o) if (o) rb_ary_push(opts, rb_interned_str(#o, sizeof(#o) - 1))
12680 OPT(GC_DEBUG);
12681 OPT(USE_RGENGC);
12682 OPT(RGENGC_DEBUG);
12683 OPT(RGENGC_CHECK_MODE);
12684 OPT(RGENGC_PROFILE);
12685 OPT(RGENGC_ESTIMATE_OLDMALLOC);
12686 OPT(GC_PROFILE_MORE_DETAIL);
12687 OPT(GC_ENABLE_LAZY_SWEEP);
12688 OPT(CALC_EXACT_MALLOC_SIZE);
12689 OPT(MALLOC_ALLOCATED_SIZE);
12690 OPT(MALLOC_ALLOCATED_SIZE_CHECK);
12691 OPT(GC_PROFILE_DETAIL_MEMORY);
12692 OPT(GC_COMPACTION_SUPPORTED);
12693#undef OPT
12694 OBJ_FREEZE(opts);
12695 }
12696}
#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:3200
int rb_keyword_given_p(void)
Determines if the current method is given a keyword argument.
Definition eval.c:1042
int rb_get_kwargs(VALUE keyword_hash, const ID *table, int required, int optional, VALUE *values)
Keyword argument deconstructor.
Definition class.c:2976
#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:92
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:138
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:3846
VALUE rb_str_buf_new(long capa)
Allocates a "string buffer".
Definition string.c:1737
#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:2128
VALUE rb_f_notimplement(int argc, const VALUE *argv, VALUE obj, VALUE marker)
Raises rb_eNotImpError.
Definition vm_method.c:901
int rb_sourceline(void)
Resembles __LINE__.
Definition vm.c:2142
#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:1090
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:2256
#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:6050
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