Ruby 3.5.0dev (2025-09-18 revision 7e6f7fbf9e3e951bc4df351c8246f641999ea12c)
default.c
1#include "ruby/internal/config.h"
2
3#include <signal.h>
4
5#ifndef _WIN32
6# include <sys/mman.h>
7# include <unistd.h>
8# ifdef HAVE_SYS_PRCTL_H
9# include <sys/prctl.h>
10# endif
11#endif
12
13#if !defined(PAGE_SIZE) && defined(HAVE_SYS_USER_H)
14/* LIST_HEAD conflicts with sys/queue.h on macOS */
15# include <sys/user.h>
16#endif
17
18#ifdef BUILDING_MODULAR_GC
19# define nlz_int64(x) (x == 0 ? 64 : (unsigned int)__builtin_clzll((unsigned long long)x))
20#else
21# include "internal/bits.h"
22#endif
23
24#include "ruby/ruby.h"
25#include "ruby/atomic.h"
26#include "ruby/debug.h"
27#include "ruby/thread.h"
28#include "ruby/util.h"
29#include "ruby/vm.h"
31#include "ccan/list/list.h"
32#include "darray.h"
33#include "gc/gc.h"
34#include "gc/gc_impl.h"
35
36#ifndef BUILDING_MODULAR_GC
37# include "probes.h"
38#endif
39
40#ifdef BUILDING_MODULAR_GC
41# define RB_DEBUG_COUNTER_INC(_name) ((void)0)
42# define RB_DEBUG_COUNTER_INC_IF(_name, cond) (!!(cond))
43#else
44# include "debug_counter.h"
45#endif
46
47#ifdef BUILDING_MODULAR_GC
48# define rb_asan_poison_object(obj) ((void)(obj))
49# define rb_asan_unpoison_object(obj, newobj_p) ((void)(obj), (void)(newobj_p))
50# define asan_unpoisoning_object(obj) if ((obj) || true)
51# define asan_poison_memory_region(ptr, size) ((void)(ptr), (void)(size))
52# define asan_unpoison_memory_region(ptr, size, malloc_p) ((void)(ptr), (size), (malloc_p))
53# define asan_unpoisoning_memory_region(ptr, size) if ((ptr) || (size) || true)
54
55# define VALGRIND_MAKE_MEM_DEFINED(ptr, size) ((void)(ptr), (void)(size))
56# define VALGRIND_MAKE_MEM_UNDEFINED(ptr, size) ((void)(ptr), (void)(size))
57#else
58# include "internal/sanitizers.h"
59#endif
60
61/* MALLOC_HEADERS_BEGIN */
62#ifndef HAVE_MALLOC_USABLE_SIZE
63# ifdef _WIN32
64# define HAVE_MALLOC_USABLE_SIZE
65# define malloc_usable_size(a) _msize(a)
66# elif defined HAVE_MALLOC_SIZE
67# define HAVE_MALLOC_USABLE_SIZE
68# define malloc_usable_size(a) malloc_size(a)
69# endif
70#endif
71
72#ifdef HAVE_MALLOC_USABLE_SIZE
73# ifdef RUBY_ALTERNATIVE_MALLOC_HEADER
74/* Alternative malloc header is included in ruby/missing.h */
75# elif defined(HAVE_MALLOC_H)
76# include <malloc.h>
77# elif defined(HAVE_MALLOC_NP_H)
78# include <malloc_np.h>
79# elif defined(HAVE_MALLOC_MALLOC_H)
80# include <malloc/malloc.h>
81# endif
82#endif
83
84#ifdef HAVE_MALLOC_TRIM
85# include <malloc.h>
86
87# ifdef __EMSCRIPTEN__
88/* malloc_trim is defined in emscripten/emmalloc.h on emscripten. */
89# include <emscripten/emmalloc.h>
90# endif
91#endif
92
93#ifdef HAVE_MACH_TASK_EXCEPTION_PORTS
94# include <mach/task.h>
95# include <mach/mach_init.h>
96# include <mach/mach_port.h>
97#endif
98
99#ifndef VM_CHECK_MODE
100# define VM_CHECK_MODE RUBY_DEBUG
101#endif
102
103// From ractor_core.h
104#ifndef RACTOR_CHECK_MODE
105# define RACTOR_CHECK_MODE (VM_CHECK_MODE || RUBY_DEBUG) && (SIZEOF_UINT64_T == SIZEOF_VALUE)
106#endif
107
108#ifndef RUBY_DEBUG_LOG
109# define RUBY_DEBUG_LOG(...)
110#endif
111
112#ifndef GC_HEAP_INIT_SLOTS
113#define GC_HEAP_INIT_SLOTS 10000
114#endif
115#ifndef GC_HEAP_FREE_SLOTS
116#define GC_HEAP_FREE_SLOTS 4096
117#endif
118#ifndef GC_HEAP_GROWTH_FACTOR
119#define GC_HEAP_GROWTH_FACTOR 1.8
120#endif
121#ifndef GC_HEAP_GROWTH_MAX_SLOTS
122#define GC_HEAP_GROWTH_MAX_SLOTS 0 /* 0 is disable */
123#endif
124#ifndef GC_HEAP_REMEMBERED_WB_UNPROTECTED_OBJECTS_LIMIT_RATIO
125# define GC_HEAP_REMEMBERED_WB_UNPROTECTED_OBJECTS_LIMIT_RATIO 0.01
126#endif
127#ifndef GC_HEAP_OLDOBJECT_LIMIT_FACTOR
128#define GC_HEAP_OLDOBJECT_LIMIT_FACTOR 2.0
129#endif
130
131#ifndef GC_HEAP_FREE_SLOTS_MIN_RATIO
132#define GC_HEAP_FREE_SLOTS_MIN_RATIO 0.20
133#endif
134#ifndef GC_HEAP_FREE_SLOTS_GOAL_RATIO
135#define GC_HEAP_FREE_SLOTS_GOAL_RATIO 0.40
136#endif
137#ifndef GC_HEAP_FREE_SLOTS_MAX_RATIO
138#define GC_HEAP_FREE_SLOTS_MAX_RATIO 0.65
139#endif
140
141#ifndef GC_MALLOC_LIMIT_MIN
142#define GC_MALLOC_LIMIT_MIN (16 * 1024 * 1024 /* 16MB */)
143#endif
144#ifndef GC_MALLOC_LIMIT_MAX
145#define GC_MALLOC_LIMIT_MAX (32 * 1024 * 1024 /* 32MB */)
146#endif
147#ifndef GC_MALLOC_LIMIT_GROWTH_FACTOR
148#define GC_MALLOC_LIMIT_GROWTH_FACTOR 1.4
149#endif
150
151#ifndef GC_OLDMALLOC_LIMIT_MIN
152#define GC_OLDMALLOC_LIMIT_MIN (16 * 1024 * 1024 /* 16MB */)
153#endif
154#ifndef GC_OLDMALLOC_LIMIT_GROWTH_FACTOR
155#define GC_OLDMALLOC_LIMIT_GROWTH_FACTOR 1.2
156#endif
157#ifndef GC_OLDMALLOC_LIMIT_MAX
158#define GC_OLDMALLOC_LIMIT_MAX (128 * 1024 * 1024 /* 128MB */)
159#endif
160
161#ifndef GC_CAN_COMPILE_COMPACTION
162#if defined(__wasi__) /* WebAssembly doesn't support signals */
163# define GC_CAN_COMPILE_COMPACTION 0
164#else
165# define GC_CAN_COMPILE_COMPACTION 1
166#endif
167#endif
168
169#ifndef PRINT_ENTER_EXIT_TICK
170# define PRINT_ENTER_EXIT_TICK 0
171#endif
172#ifndef PRINT_ROOT_TICKS
173#define PRINT_ROOT_TICKS 0
174#endif
175
176#define USE_TICK_T (PRINT_ENTER_EXIT_TICK || PRINT_ROOT_TICKS)
177
178#ifndef HEAP_COUNT
179# define HEAP_COUNT 5
180#endif
181
183 struct free_slot *freelist;
184 struct heap_page *using_page;
185 size_t allocated_objects_count;
187
188typedef struct ractor_newobj_cache {
189 size_t incremental_mark_step_allocated_slots;
190 rb_ractor_newobj_heap_cache_t heap_caches[HEAP_COUNT];
192
193typedef struct {
194 size_t heap_init_slots[HEAP_COUNT];
195 size_t heap_free_slots;
196 double growth_factor;
197 size_t growth_max_slots;
198
199 double heap_free_slots_min_ratio;
200 double heap_free_slots_goal_ratio;
201 double heap_free_slots_max_ratio;
202 double uncollectible_wb_unprotected_objects_limit_ratio;
203 double oldobject_limit_factor;
204
205 size_t malloc_limit_min;
206 size_t malloc_limit_max;
207 double malloc_limit_growth_factor;
208
209 size_t oldmalloc_limit_min;
210 size_t oldmalloc_limit_max;
211 double oldmalloc_limit_growth_factor;
213
214static ruby_gc_params_t gc_params = {
215 { GC_HEAP_INIT_SLOTS },
216 GC_HEAP_FREE_SLOTS,
217 GC_HEAP_GROWTH_FACTOR,
218 GC_HEAP_GROWTH_MAX_SLOTS,
219
220 GC_HEAP_FREE_SLOTS_MIN_RATIO,
221 GC_HEAP_FREE_SLOTS_GOAL_RATIO,
222 GC_HEAP_FREE_SLOTS_MAX_RATIO,
223 GC_HEAP_REMEMBERED_WB_UNPROTECTED_OBJECTS_LIMIT_RATIO,
224 GC_HEAP_OLDOBJECT_LIMIT_FACTOR,
225
226 GC_MALLOC_LIMIT_MIN,
227 GC_MALLOC_LIMIT_MAX,
228 GC_MALLOC_LIMIT_GROWTH_FACTOR,
229
230 GC_OLDMALLOC_LIMIT_MIN,
231 GC_OLDMALLOC_LIMIT_MAX,
232 GC_OLDMALLOC_LIMIT_GROWTH_FACTOR,
233};
234
235/* GC_DEBUG:
236 * enable to embed GC debugging information.
237 */
238#ifndef GC_DEBUG
239#define GC_DEBUG 0
240#endif
241
242/* RGENGC_DEBUG:
243 * 1: basic information
244 * 2: remember set operation
245 * 3: mark
246 * 4:
247 * 5: sweep
248 */
249#ifndef RGENGC_DEBUG
250#ifdef RUBY_DEVEL
251#define RGENGC_DEBUG -1
252#else
253#define RGENGC_DEBUG 0
254#endif
255#endif
256#if RGENGC_DEBUG < 0 && !defined(_MSC_VER)
257# define RGENGC_DEBUG_ENABLED(level) (-(RGENGC_DEBUG) >= (level) && ruby_rgengc_debug >= (level))
258#elif defined(HAVE_VA_ARGS_MACRO)
259# define RGENGC_DEBUG_ENABLED(level) ((RGENGC_DEBUG) >= (level))
260#else
261# define RGENGC_DEBUG_ENABLED(level) 0
262#endif
263int ruby_rgengc_debug;
264
265/* RGENGC_PROFILE
266 * 0: disable RGenGC profiling
267 * 1: enable profiling for basic information
268 * 2: enable profiling for each types
269 */
270#ifndef RGENGC_PROFILE
271# define RGENGC_PROFILE 0
272#endif
273
274/* RGENGC_ESTIMATE_OLDMALLOC
275 * Enable/disable to estimate increase size of malloc'ed size by old objects.
276 * If estimation exceeds threshold, then will invoke full GC.
277 * 0: disable estimation.
278 * 1: enable estimation.
279 */
280#ifndef RGENGC_ESTIMATE_OLDMALLOC
281# define RGENGC_ESTIMATE_OLDMALLOC 1
282#endif
283
284#ifndef GC_PROFILE_MORE_DETAIL
285# define GC_PROFILE_MORE_DETAIL 0
286#endif
287#ifndef GC_PROFILE_DETAIL_MEMORY
288# define GC_PROFILE_DETAIL_MEMORY 0
289#endif
290#ifndef GC_ENABLE_LAZY_SWEEP
291# define GC_ENABLE_LAZY_SWEEP 1
292#endif
293#ifndef CALC_EXACT_MALLOC_SIZE
294# define CALC_EXACT_MALLOC_SIZE 0
295#endif
296#if defined(HAVE_MALLOC_USABLE_SIZE) || CALC_EXACT_MALLOC_SIZE > 0
297# ifndef MALLOC_ALLOCATED_SIZE
298# define MALLOC_ALLOCATED_SIZE 0
299# endif
300#else
301# define MALLOC_ALLOCATED_SIZE 0
302#endif
303#ifndef MALLOC_ALLOCATED_SIZE_CHECK
304# define MALLOC_ALLOCATED_SIZE_CHECK 0
305#endif
306
307#ifndef GC_DEBUG_STRESS_TO_CLASS
308# define GC_DEBUG_STRESS_TO_CLASS 1
309#endif
310
311typedef enum {
312 GPR_FLAG_NONE = 0x000,
313 /* major reason */
314 GPR_FLAG_MAJOR_BY_NOFREE = 0x001,
315 GPR_FLAG_MAJOR_BY_OLDGEN = 0x002,
316 GPR_FLAG_MAJOR_BY_SHADY = 0x004,
317 GPR_FLAG_MAJOR_BY_FORCE = 0x008,
318#if RGENGC_ESTIMATE_OLDMALLOC
319 GPR_FLAG_MAJOR_BY_OLDMALLOC = 0x020,
320#endif
321 GPR_FLAG_MAJOR_MASK = 0x0ff,
322
323 /* gc reason */
324 GPR_FLAG_NEWOBJ = 0x100,
325 GPR_FLAG_MALLOC = 0x200,
326 GPR_FLAG_METHOD = 0x400,
327 GPR_FLAG_CAPI = 0x800,
328 GPR_FLAG_STRESS = 0x1000,
329
330 /* others */
331 GPR_FLAG_IMMEDIATE_SWEEP = 0x2000,
332 GPR_FLAG_HAVE_FINALIZE = 0x4000,
333 GPR_FLAG_IMMEDIATE_MARK = 0x8000,
334 GPR_FLAG_FULL_MARK = 0x10000,
335 GPR_FLAG_COMPACT = 0x20000,
336
337 GPR_DEFAULT_REASON =
338 (GPR_FLAG_FULL_MARK | GPR_FLAG_IMMEDIATE_MARK |
339 GPR_FLAG_IMMEDIATE_SWEEP | GPR_FLAG_CAPI),
340} gc_profile_record_flag;
341
342typedef struct gc_profile_record {
343 unsigned int flags;
344
345 double gc_time;
346 double gc_invoke_time;
347
348 size_t heap_total_objects;
349 size_t heap_use_size;
350 size_t heap_total_size;
351 size_t moved_objects;
352
353#if GC_PROFILE_MORE_DETAIL
354 double gc_mark_time;
355 double gc_sweep_time;
356
357 size_t heap_use_pages;
358 size_t heap_live_objects;
359 size_t heap_free_objects;
360
361 size_t allocate_increase;
362 size_t allocate_limit;
363
364 double prepare_time;
365 size_t removing_objects;
366 size_t empty_objects;
367#if GC_PROFILE_DETAIL_MEMORY
368 long maxrss;
369 long minflt;
370 long majflt;
371#endif
372#endif
373#if MALLOC_ALLOCATED_SIZE
374 size_t allocated_size;
375#endif
376
377#if RGENGC_PROFILE > 0
378 size_t old_objects;
379 size_t remembered_normal_objects;
380 size_t remembered_shady_objects;
381#endif
383
384struct RMoved {
385 VALUE flags;
386 VALUE dummy;
387 VALUE destination;
388 uint32_t original_shape_id;
389};
390
391#define RMOVED(obj) ((struct RMoved *)(obj))
392
393typedef uintptr_t bits_t;
394enum {
395 BITS_SIZE = sizeof(bits_t),
396 BITS_BITLENGTH = ( BITS_SIZE * CHAR_BIT )
397};
398
400 struct heap_page *page;
401};
402
404 struct heap_page_header header;
405 /* char gap[]; */
406 /* RVALUE values[]; */
407};
408
409#define STACK_CHUNK_SIZE 500
410
411typedef struct stack_chunk {
412 VALUE data[STACK_CHUNK_SIZE];
413 struct stack_chunk *next;
415
416typedef struct mark_stack {
417 stack_chunk_t *chunk;
418 stack_chunk_t *cache;
419 int index;
420 int limit;
421 size_t cache_size;
422 size_t unused_cache_size;
424
425typedef int (*gc_compact_compare_func)(const void *l, const void *r, void *d);
426
427typedef struct rb_heap_struct {
428 short slot_size;
429
430 /* Basic statistics */
431 size_t total_allocated_pages;
432 size_t force_major_gc_count;
433 size_t force_incremental_marking_finish_count;
434 size_t total_allocated_objects;
435 size_t total_freed_objects;
436 size_t final_slots_count;
437
438 /* Sweeping statistics */
439 size_t freed_slots;
440 size_t empty_slots;
441
442 struct heap_page *free_pages;
443 struct ccan_list_head pages;
444 struct heap_page *sweeping_page; /* iterator for .pages */
445 struct heap_page *compact_cursor;
446 uintptr_t compact_cursor_index;
447 struct heap_page *pooled_pages;
448 size_t total_pages; /* total page count in a heap */
449 size_t total_slots; /* total slot count (about total_pages * HEAP_PAGE_OBJ_LIMIT) */
450
451} rb_heap_t;
452
453enum {
454 gc_stress_no_major,
455 gc_stress_no_immediate_sweep,
456 gc_stress_full_mark_after_malloc,
457 gc_stress_max
458};
459
460enum gc_mode {
461 gc_mode_none,
462 gc_mode_marking,
463 gc_mode_sweeping,
464 gc_mode_compacting,
465};
466
467typedef struct rb_objspace {
468 struct {
469 size_t limit;
470 size_t increase;
471#if MALLOC_ALLOCATED_SIZE
472 size_t allocated_size;
473 size_t allocations;
474#endif
475 } malloc_params;
476
478 bool full_mark;
479 } gc_config;
480
481 struct {
482 unsigned int mode : 2;
483 unsigned int immediate_sweep : 1;
484 unsigned int dont_gc : 1;
485 unsigned int dont_incremental : 1;
486 unsigned int during_gc : 1;
487 unsigned int during_compacting : 1;
488 unsigned int during_reference_updating : 1;
489 unsigned int gc_stressful: 1;
490 unsigned int has_newobj_hook: 1;
491 unsigned int during_minor_gc : 1;
492 unsigned int during_incremental_marking : 1;
493 unsigned int measure_gc : 1;
494 } flags;
495
496 rb_event_flag_t hook_events;
497
498 rb_heap_t heaps[HEAP_COUNT];
499 size_t empty_pages_count;
500 struct heap_page *empty_pages;
501
502 struct {
503 rb_atomic_t finalizing;
504 } atomic_flags;
505
507 size_t marked_slots;
508
509 struct {
510 rb_darray(struct heap_page *) sorted;
511
512 size_t allocated_pages;
513 size_t freed_pages;
514 uintptr_t range[2];
515 size_t freeable_pages;
516
517 size_t allocatable_slots;
518
519 /* final */
520 VALUE deferred_final;
521 } heap_pages;
522
523 st_table *finalizer_table;
524
525 struct {
526 int run;
527 unsigned int latest_gc_info;
528 gc_profile_record *records;
529 gc_profile_record *current_record;
530 size_t next_index;
531 size_t size;
532
533#if GC_PROFILE_MORE_DETAIL
534 double prepare_time;
535#endif
536 double invoke_time;
537
538 size_t minor_gc_count;
539 size_t major_gc_count;
540 size_t compact_count;
541 size_t read_barrier_faults;
542#if RGENGC_PROFILE > 0
543 size_t total_generated_normal_object_count;
544 size_t total_generated_shady_object_count;
545 size_t total_shade_operation_count;
546 size_t total_promoted_count;
547 size_t total_remembered_normal_object_count;
548 size_t total_remembered_shady_object_count;
549
550#if RGENGC_PROFILE >= 2
551 size_t generated_normal_object_count_types[RUBY_T_MASK];
552 size_t generated_shady_object_count_types[RUBY_T_MASK];
553 size_t shade_operation_count_types[RUBY_T_MASK];
554 size_t promoted_types[RUBY_T_MASK];
555 size_t remembered_normal_object_count_types[RUBY_T_MASK];
556 size_t remembered_shady_object_count_types[RUBY_T_MASK];
557#endif
558#endif /* RGENGC_PROFILE */
559
560 /* temporary profiling space */
561 double gc_sweep_start_time;
562 size_t total_allocated_objects_at_gc_start;
563 size_t heap_used_at_gc_start;
564
565 /* basic statistics */
566 size_t count;
567 unsigned long long marking_time_ns;
568 struct timespec marking_start_time;
569 unsigned long long sweeping_time_ns;
570 struct timespec sweeping_start_time;
571
572 /* Weak references */
573 size_t weak_references_count;
574 size_t retained_weak_references_count;
575 } profile;
576
577 VALUE gc_stress_mode;
578
579 struct {
580 VALUE parent_object;
581 int need_major_gc;
582 size_t last_major_gc;
583 size_t uncollectible_wb_unprotected_objects;
584 size_t uncollectible_wb_unprotected_objects_limit;
585 size_t old_objects;
586 size_t old_objects_limit;
587
588#if RGENGC_ESTIMATE_OLDMALLOC
589 size_t oldmalloc_increase;
590 size_t oldmalloc_increase_limit;
591#endif
592
593#if RGENGC_CHECK_MODE >= 2
594 struct st_table *allrefs_table;
595 size_t error_count;
596#endif
597 } rgengc;
598
599 struct {
600 size_t considered_count_table[T_MASK];
601 size_t moved_count_table[T_MASK];
602 size_t moved_up_count_table[T_MASK];
603 size_t moved_down_count_table[T_MASK];
604 size_t total_moved;
605
606 /* This function will be used, if set, to sort the heap prior to compaction */
607 gc_compact_compare_func compare_func;
608 } rcompactor;
609
610 struct {
611 size_t pooled_slots;
612 size_t step_slots;
613 } rincgc;
614
615#if GC_DEBUG_STRESS_TO_CLASS
616 VALUE stress_to_class;
617#endif
618
619 rb_darray(VALUE *) weak_references;
620 rb_postponed_job_handle_t finalize_deferred_pjob;
621
622 unsigned long live_ractor_cache_count;
624
625#ifndef HEAP_PAGE_ALIGN_LOG
626/* default tiny heap size: 64KiB */
627#define HEAP_PAGE_ALIGN_LOG 16
628#endif
629
630#if RACTOR_CHECK_MODE || GC_DEBUG
631struct rvalue_overhead {
632# if RACTOR_CHECK_MODE
633 uint32_t _ractor_belonging_id;
634# endif
635# if GC_DEBUG
636 const char *file;
637 int line;
638# endif
639};
640
641// Make sure that RVALUE_OVERHEAD aligns to sizeof(VALUE)
642# define RVALUE_OVERHEAD (sizeof(struct { \
643 union { \
644 struct rvalue_overhead overhead; \
645 VALUE value; \
646 }; \
647}))
648size_t rb_gc_impl_obj_slot_size(VALUE obj);
649# define GET_RVALUE_OVERHEAD(obj) ((struct rvalue_overhead *)((uintptr_t)obj + rb_gc_impl_obj_slot_size(obj)))
650#else
651# ifndef RVALUE_OVERHEAD
652# define RVALUE_OVERHEAD 0
653# endif
654#endif
655
656#define BASE_SLOT_SIZE (sizeof(struct RBasic) + sizeof(VALUE[RBIMPL_RVALUE_EMBED_LEN_MAX]) + RVALUE_OVERHEAD)
657
658#ifndef MAX
659# define MAX(a, b) (((a) > (b)) ? (a) : (b))
660#endif
661#ifndef MIN
662# define MIN(a, b) (((a) < (b)) ? (a) : (b))
663#endif
664#define roomof(x, y) (((x) + (y) - 1) / (y))
665#define CEILDIV(i, mod) roomof(i, mod)
666enum {
667 HEAP_PAGE_ALIGN = (1UL << HEAP_PAGE_ALIGN_LOG),
668 HEAP_PAGE_ALIGN_MASK = (~(~0UL << HEAP_PAGE_ALIGN_LOG)),
669 HEAP_PAGE_SIZE = HEAP_PAGE_ALIGN,
670 HEAP_PAGE_OBJ_LIMIT = (unsigned int)((HEAP_PAGE_SIZE - sizeof(struct heap_page_header)) / BASE_SLOT_SIZE),
671 HEAP_PAGE_BITMAP_LIMIT = CEILDIV(CEILDIV(HEAP_PAGE_SIZE, BASE_SLOT_SIZE), BITS_BITLENGTH),
672 HEAP_PAGE_BITMAP_SIZE = (BITS_SIZE * HEAP_PAGE_BITMAP_LIMIT),
673};
674#define HEAP_PAGE_ALIGN (1 << HEAP_PAGE_ALIGN_LOG)
675#define HEAP_PAGE_SIZE HEAP_PAGE_ALIGN
676
677#if !defined(INCREMENTAL_MARK_STEP_ALLOCATIONS)
678# define INCREMENTAL_MARK_STEP_ALLOCATIONS 500
679#endif
680
681#undef INIT_HEAP_PAGE_ALLOC_USE_MMAP
682/* Must define either HEAP_PAGE_ALLOC_USE_MMAP or
683 * INIT_HEAP_PAGE_ALLOC_USE_MMAP. */
684
685#ifndef HAVE_MMAP
686/* We can't use mmap of course, if it is not available. */
687static const bool HEAP_PAGE_ALLOC_USE_MMAP = false;
688
689#elif defined(__wasm__)
690/* wasmtime does not have proper support for mmap.
691 * See https://github.com/bytecodealliance/wasmtime/blob/main/docs/WASI-rationale.md#why-no-mmap-and-friends
692 */
693static const bool HEAP_PAGE_ALLOC_USE_MMAP = false;
694
695#elif HAVE_CONST_PAGE_SIZE
696/* If we have the PAGE_SIZE and it is a constant, then we can directly use it. */
697static const bool HEAP_PAGE_ALLOC_USE_MMAP = (PAGE_SIZE <= HEAP_PAGE_SIZE);
698
699#elif defined(PAGE_MAX_SIZE) && (PAGE_MAX_SIZE <= HEAP_PAGE_SIZE)
700/* If we can use the maximum page size. */
701static const bool HEAP_PAGE_ALLOC_USE_MMAP = true;
702
703#elif defined(PAGE_SIZE)
704/* If the PAGE_SIZE macro can be used dynamically. */
705# define INIT_HEAP_PAGE_ALLOC_USE_MMAP (PAGE_SIZE <= HEAP_PAGE_SIZE)
706
707#elif defined(HAVE_SYSCONF) && defined(_SC_PAGE_SIZE)
708/* If we can use sysconf to determine the page size. */
709# define INIT_HEAP_PAGE_ALLOC_USE_MMAP (sysconf(_SC_PAGE_SIZE) <= HEAP_PAGE_SIZE)
710
711#else
712/* Otherwise we can't determine the system page size, so don't use mmap. */
713static const bool HEAP_PAGE_ALLOC_USE_MMAP = false;
714#endif
715
716#ifdef INIT_HEAP_PAGE_ALLOC_USE_MMAP
717/* We can determine the system page size at runtime. */
718# define HEAP_PAGE_ALLOC_USE_MMAP (heap_page_alloc_use_mmap != false)
719
720static bool heap_page_alloc_use_mmap;
721#endif
722
723#define RVALUE_AGE_BIT_COUNT 2
724#define RVALUE_AGE_BIT_MASK (((bits_t)1 << RVALUE_AGE_BIT_COUNT) - 1)
725#define RVALUE_OLD_AGE 3
726
727struct free_slot {
728 VALUE flags; /* always 0 for freed obj */
729 struct free_slot *next;
730};
731
732struct heap_page {
733 unsigned short slot_size;
734 unsigned short total_slots;
735 unsigned short free_slots;
736 unsigned short final_slots;
737 unsigned short pinned_slots;
738 struct {
739 unsigned int before_sweep : 1;
740 unsigned int has_remembered_objects : 1;
741 unsigned int has_uncollectible_wb_unprotected_objects : 1;
742 } flags;
743
744 rb_heap_t *heap;
745
746 struct heap_page *free_next;
747 struct heap_page_body *body;
748 uintptr_t start;
749 struct free_slot *freelist;
750 struct ccan_list_node page_node;
751
752 bits_t wb_unprotected_bits[HEAP_PAGE_BITMAP_LIMIT];
753 /* the following three bitmaps are cleared at the beginning of full GC */
754 bits_t mark_bits[HEAP_PAGE_BITMAP_LIMIT];
755 bits_t uncollectible_bits[HEAP_PAGE_BITMAP_LIMIT];
756 bits_t marking_bits[HEAP_PAGE_BITMAP_LIMIT];
757
758 bits_t remembered_bits[HEAP_PAGE_BITMAP_LIMIT];
759
760 /* If set, the object is not movable */
761 bits_t pinned_bits[HEAP_PAGE_BITMAP_LIMIT];
762 bits_t age_bits[HEAP_PAGE_BITMAP_LIMIT * RVALUE_AGE_BIT_COUNT];
763};
764
765/*
766 * When asan is enabled, this will prohibit writing to the freelist until it is unlocked
767 */
768static void
769asan_lock_freelist(struct heap_page *page)
770{
771 asan_poison_memory_region(&page->freelist, sizeof(struct free_list *));
772}
773
774/*
775 * When asan is enabled, this will enable the ability to write to the freelist
776 */
777static void
778asan_unlock_freelist(struct heap_page *page)
779{
780 asan_unpoison_memory_region(&page->freelist, sizeof(struct free_list *), false);
781}
782
783static inline bool
784heap_page_in_global_empty_pages_pool(rb_objspace_t *objspace, struct heap_page *page)
785{
786 if (page->total_slots == 0) {
787 GC_ASSERT(page->start == 0);
788 GC_ASSERT(page->slot_size == 0);
789 GC_ASSERT(page->heap == NULL);
790 GC_ASSERT(page->free_slots == 0);
791 asan_unpoisoning_memory_region(&page->freelist, sizeof(&page->freelist)) {
792 GC_ASSERT(page->freelist == NULL);
793 }
794
795 return true;
796 }
797 else {
798 GC_ASSERT(page->start != 0);
799 GC_ASSERT(page->slot_size != 0);
800 GC_ASSERT(page->heap != NULL);
801
802 return false;
803 }
804}
805
806#define GET_PAGE_BODY(x) ((struct heap_page_body *)((bits_t)(x) & ~(HEAP_PAGE_ALIGN_MASK)))
807#define GET_PAGE_HEADER(x) (&GET_PAGE_BODY(x)->header)
808#define GET_HEAP_PAGE(x) (GET_PAGE_HEADER(x)->page)
809
810#define NUM_IN_PAGE(p) (((bits_t)(p) & HEAP_PAGE_ALIGN_MASK) / BASE_SLOT_SIZE)
811#define BITMAP_INDEX(p) (NUM_IN_PAGE(p) / BITS_BITLENGTH )
812#define BITMAP_OFFSET(p) (NUM_IN_PAGE(p) & (BITS_BITLENGTH-1))
813#define BITMAP_BIT(p) ((bits_t)1 << BITMAP_OFFSET(p))
814
815/* Bitmap Operations */
816#define MARKED_IN_BITMAP(bits, p) ((bits)[BITMAP_INDEX(p)] & BITMAP_BIT(p))
817#define MARK_IN_BITMAP(bits, p) ((bits)[BITMAP_INDEX(p)] = (bits)[BITMAP_INDEX(p)] | BITMAP_BIT(p))
818#define CLEAR_IN_BITMAP(bits, p) ((bits)[BITMAP_INDEX(p)] = (bits)[BITMAP_INDEX(p)] & ~BITMAP_BIT(p))
819
820/* getting bitmap */
821#define GET_HEAP_MARK_BITS(x) (&GET_HEAP_PAGE(x)->mark_bits[0])
822#define GET_HEAP_PINNED_BITS(x) (&GET_HEAP_PAGE(x)->pinned_bits[0])
823#define GET_HEAP_UNCOLLECTIBLE_BITS(x) (&GET_HEAP_PAGE(x)->uncollectible_bits[0])
824#define GET_HEAP_WB_UNPROTECTED_BITS(x) (&GET_HEAP_PAGE(x)->wb_unprotected_bits[0])
825#define GET_HEAP_MARKING_BITS(x) (&GET_HEAP_PAGE(x)->marking_bits[0])
826
827#define RVALUE_AGE_BITMAP_INDEX(n) (NUM_IN_PAGE(n) / (BITS_BITLENGTH / RVALUE_AGE_BIT_COUNT))
828#define RVALUE_AGE_BITMAP_OFFSET(n) ((NUM_IN_PAGE(n) % (BITS_BITLENGTH / RVALUE_AGE_BIT_COUNT)) * RVALUE_AGE_BIT_COUNT)
829
830static int
831RVALUE_AGE_GET(VALUE obj)
832{
833 bits_t *age_bits = GET_HEAP_PAGE(obj)->age_bits;
834 return (int)(age_bits[RVALUE_AGE_BITMAP_INDEX(obj)] >> RVALUE_AGE_BITMAP_OFFSET(obj)) & RVALUE_AGE_BIT_MASK;
835}
836
837static void
838RVALUE_AGE_SET(VALUE obj, int age)
839{
840 RUBY_ASSERT(age <= RVALUE_OLD_AGE);
841 bits_t *age_bits = GET_HEAP_PAGE(obj)->age_bits;
842 // clear the bits
843 age_bits[RVALUE_AGE_BITMAP_INDEX(obj)] &= ~(RVALUE_AGE_BIT_MASK << (RVALUE_AGE_BITMAP_OFFSET(obj)));
844 // shift the correct value in
845 age_bits[RVALUE_AGE_BITMAP_INDEX(obj)] |= ((bits_t)age << RVALUE_AGE_BITMAP_OFFSET(obj));
846 if (age == RVALUE_OLD_AGE) {
848 }
849 else {
851 }
852}
853
854#define malloc_limit objspace->malloc_params.limit
855#define malloc_increase objspace->malloc_params.increase
856#define malloc_allocated_size objspace->malloc_params.allocated_size
857#define heap_pages_lomem objspace->heap_pages.range[0]
858#define heap_pages_himem objspace->heap_pages.range[1]
859#define heap_pages_freeable_pages objspace->heap_pages.freeable_pages
860#define heap_pages_deferred_final objspace->heap_pages.deferred_final
861#define heaps objspace->heaps
862#define during_gc objspace->flags.during_gc
863#define finalizing objspace->atomic_flags.finalizing
864#define finalizer_table objspace->finalizer_table
865#define ruby_gc_stressful objspace->flags.gc_stressful
866#define ruby_gc_stress_mode objspace->gc_stress_mode
867#if GC_DEBUG_STRESS_TO_CLASS
868#define stress_to_class objspace->stress_to_class
869#define set_stress_to_class(c) (stress_to_class = (c))
870#else
871#define stress_to_class ((void)objspace, 0)
872#define set_stress_to_class(c) ((void)objspace, (c))
873#endif
874
875#if 0
876#define dont_gc_on() (fprintf(stderr, "dont_gc_on@%s:%d\n", __FILE__, __LINE__), objspace->flags.dont_gc = 1)
877#define dont_gc_off() (fprintf(stderr, "dont_gc_off@%s:%d\n", __FILE__, __LINE__), objspace->flags.dont_gc = 0)
878#define dont_gc_set(b) (fprintf(stderr, "dont_gc_set(%d)@%s:%d\n", __FILE__, __LINE__), objspace->flags.dont_gc = (int)(b))
879#define dont_gc_val() (objspace->flags.dont_gc)
880#else
881#define dont_gc_on() (objspace->flags.dont_gc = 1)
882#define dont_gc_off() (objspace->flags.dont_gc = 0)
883#define dont_gc_set(b) (objspace->flags.dont_gc = (int)(b))
884#define dont_gc_val() (objspace->flags.dont_gc)
885#endif
886
887#define gc_config_full_mark_set(b) (objspace->gc_config.full_mark = (int)(b))
888#define gc_config_full_mark_val (objspace->gc_config.full_mark)
889
890#ifndef DURING_GC_COULD_MALLOC_REGION_START
891# define DURING_GC_COULD_MALLOC_REGION_START() \
892 assert(rb_during_gc()); \
893 bool _prev_enabled = rb_gc_impl_gc_enabled_p(objspace); \
894 rb_gc_impl_gc_disable(objspace, false)
895#endif
896
897#ifndef DURING_GC_COULD_MALLOC_REGION_END
898# define DURING_GC_COULD_MALLOC_REGION_END() \
899 if (_prev_enabled) rb_gc_impl_gc_enable(objspace)
900#endif
901
902static inline enum gc_mode
903gc_mode_verify(enum gc_mode mode)
904{
905#if RGENGC_CHECK_MODE > 0
906 switch (mode) {
907 case gc_mode_none:
908 case gc_mode_marking:
909 case gc_mode_sweeping:
910 case gc_mode_compacting:
911 break;
912 default:
913 rb_bug("gc_mode_verify: unreachable (%d)", (int)mode);
914 }
915#endif
916 return mode;
917}
918
919static inline bool
920has_sweeping_pages(rb_objspace_t *objspace)
921{
922 for (int i = 0; i < HEAP_COUNT; i++) {
923 if ((&heaps[i])->sweeping_page) {
924 return TRUE;
925 }
926 }
927 return FALSE;
928}
929
930static inline size_t
931heap_eden_total_pages(rb_objspace_t *objspace)
932{
933 size_t count = 0;
934 for (int i = 0; i < HEAP_COUNT; i++) {
935 count += (&heaps[i])->total_pages;
936 }
937 return count;
938}
939
940static inline size_t
941total_allocated_objects(rb_objspace_t *objspace)
942{
943 size_t count = 0;
944 for (int i = 0; i < HEAP_COUNT; i++) {
945 rb_heap_t *heap = &heaps[i];
946 count += heap->total_allocated_objects;
947 }
948 return count;
949}
950
951static inline size_t
952total_freed_objects(rb_objspace_t *objspace)
953{
954 size_t count = 0;
955 for (int i = 0; i < HEAP_COUNT; i++) {
956 rb_heap_t *heap = &heaps[i];
957 count += heap->total_freed_objects;
958 }
959 return count;
960}
961
962static inline size_t
963total_final_slots_count(rb_objspace_t *objspace)
964{
965 size_t count = 0;
966 for (int i = 0; i < HEAP_COUNT; i++) {
967 rb_heap_t *heap = &heaps[i];
968 count += heap->final_slots_count;
969 }
970 return count;
971}
972
973#define gc_mode(objspace) gc_mode_verify((enum gc_mode)(objspace)->flags.mode)
974#define gc_mode_set(objspace, m) ((objspace)->flags.mode = (unsigned int)gc_mode_verify(m))
975#define gc_needs_major_flags objspace->rgengc.need_major_gc
976
977#define is_marking(objspace) (gc_mode(objspace) == gc_mode_marking)
978#define is_sweeping(objspace) (gc_mode(objspace) == gc_mode_sweeping)
979#define is_full_marking(objspace) ((objspace)->flags.during_minor_gc == FALSE)
980#define is_incremental_marking(objspace) ((objspace)->flags.during_incremental_marking != FALSE)
981#define will_be_incremental_marking(objspace) ((objspace)->rgengc.need_major_gc != GPR_FLAG_NONE)
982#define GC_INCREMENTAL_SWEEP_SLOT_COUNT 2048
983#define GC_INCREMENTAL_SWEEP_POOL_SLOT_COUNT 1024
984#define is_lazy_sweeping(objspace) (GC_ENABLE_LAZY_SWEEP && has_sweeping_pages(objspace))
985
986#if SIZEOF_LONG == SIZEOF_VOIDP
987# define obj_id_to_ref(objid) ((objid) ^ FIXNUM_FLAG) /* unset FIXNUM_FLAG */
988#elif SIZEOF_LONG_LONG == SIZEOF_VOIDP
989# define obj_id_to_ref(objid) (FIXNUM_P(objid) ? \
990 ((objid) ^ FIXNUM_FLAG) : (NUM2PTR(objid) << 1))
991#else
992# error not supported
993#endif
994
995struct RZombie {
996 VALUE flags;
997 VALUE next;
998 void (*dfree)(void *);
999 void *data;
1000};
1001
1002#define RZOMBIE(o) ((struct RZombie *)(o))
1003
1004static bool ruby_enable_autocompact = false;
1005#if RGENGC_CHECK_MODE
1006static gc_compact_compare_func ruby_autocompact_compare_func;
1007#endif
1008
1009static void init_mark_stack(mark_stack_t *stack);
1010static int garbage_collect(rb_objspace_t *, unsigned int reason);
1011
1012static int gc_start(rb_objspace_t *objspace, unsigned int reason);
1013static void gc_rest(rb_objspace_t *objspace);
1014
1015enum gc_enter_event {
1016 gc_enter_event_start,
1017 gc_enter_event_continue,
1018 gc_enter_event_rest,
1019 gc_enter_event_finalizer,
1020};
1021
1022static inline void gc_enter(rb_objspace_t *objspace, enum gc_enter_event event, unsigned int *lock_lev);
1023static inline void gc_exit(rb_objspace_t *objspace, enum gc_enter_event event, unsigned int *lock_lev);
1024static void gc_marking_enter(rb_objspace_t *objspace);
1025static void gc_marking_exit(rb_objspace_t *objspace);
1026static void gc_sweeping_enter(rb_objspace_t *objspace);
1027static void gc_sweeping_exit(rb_objspace_t *objspace);
1028static bool gc_marks_continue(rb_objspace_t *objspace, rb_heap_t *heap);
1029
1030static void gc_sweep(rb_objspace_t *objspace);
1031static void gc_sweep_finish_heap(rb_objspace_t *objspace, rb_heap_t *heap);
1032static void gc_sweep_continue(rb_objspace_t *objspace, rb_heap_t *heap);
1033
1034static inline void gc_mark(rb_objspace_t *objspace, VALUE ptr);
1035static inline void gc_pin(rb_objspace_t *objspace, VALUE ptr);
1036static inline void gc_mark_and_pin(rb_objspace_t *objspace, VALUE ptr);
1037
1038static int gc_mark_stacked_objects_incremental(rb_objspace_t *, size_t count);
1039NO_SANITIZE("memory", static inline bool is_pointer_to_heap(rb_objspace_t *objspace, const void *ptr));
1040
1041static void gc_verify_internal_consistency(void *objspace_ptr);
1042
1043static double getrusage_time(void);
1044static inline void gc_prof_setup_new_record(rb_objspace_t *objspace, unsigned int reason);
1045static inline void gc_prof_timer_start(rb_objspace_t *);
1046static inline void gc_prof_timer_stop(rb_objspace_t *);
1047static inline void gc_prof_mark_timer_start(rb_objspace_t *);
1048static inline void gc_prof_mark_timer_stop(rb_objspace_t *);
1049static inline void gc_prof_sweep_timer_start(rb_objspace_t *);
1050static inline void gc_prof_sweep_timer_stop(rb_objspace_t *);
1051static inline void gc_prof_set_malloc_info(rb_objspace_t *);
1052static inline void gc_prof_set_heap_info(rb_objspace_t *);
1053
1054#define gc_prof_record(objspace) (objspace)->profile.current_record
1055#define gc_prof_enabled(objspace) ((objspace)->profile.run && (objspace)->profile.current_record)
1056
1057#ifdef HAVE_VA_ARGS_MACRO
1058# define gc_report(level, objspace, ...) \
1059 if (!RGENGC_DEBUG_ENABLED(level)) {} else gc_report_body(level, objspace, __VA_ARGS__)
1060#else
1061# define gc_report if (!RGENGC_DEBUG_ENABLED(0)) {} else gc_report_body
1062#endif
1063PRINTF_ARGS(static void gc_report_body(int level, rb_objspace_t *objspace, const char *fmt, ...), 3, 4);
1064
1065static void gc_finalize_deferred(void *dmy);
1066
1067#if USE_TICK_T
1068
1069/* the following code is only for internal tuning. */
1070
1071/* Source code to use RDTSC is quoted and modified from
1072 * https://www.mcs.anl.gov/~kazutomo/rdtsc.html
1073 * written by Kazutomo Yoshii <kazutomo@mcs.anl.gov>
1074 */
1075
1076#if defined(__GNUC__) && defined(__i386__)
1077typedef unsigned long long tick_t;
1078#define PRItick "llu"
1079static inline tick_t
1080tick(void)
1081{
1082 unsigned long long int x;
1083 __asm__ __volatile__ ("rdtsc" : "=A" (x));
1084 return x;
1085}
1086
1087#elif defined(__GNUC__) && defined(__x86_64__)
1088typedef unsigned long long tick_t;
1089#define PRItick "llu"
1090
1091static __inline__ tick_t
1092tick(void)
1093{
1094 unsigned long hi, lo;
1095 __asm__ __volatile__ ("rdtsc" : "=a"(lo), "=d"(hi));
1096 return ((unsigned long long)lo)|( ((unsigned long long)hi)<<32);
1097}
1098
1099#elif defined(__powerpc64__) && (GCC_VERSION_SINCE(4,8,0) || defined(__clang__))
1100typedef unsigned long long tick_t;
1101#define PRItick "llu"
1102
1103static __inline__ tick_t
1104tick(void)
1105{
1106 unsigned long long val = __builtin_ppc_get_timebase();
1107 return val;
1108}
1109
1110#elif defined(__POWERPC__) && defined(__APPLE__)
1111/* Implementation for macOS PPC by @nobu
1112 * See: https://github.com/ruby/ruby/pull/5975#discussion_r890045558
1113 */
1114typedef unsigned long long tick_t;
1115#define PRItick "llu"
1116
1117static __inline__ tick_t
1118tick(void)
1119{
1120 unsigned long int upper, lower, tmp;
1121 # define mftbu(r) __asm__ volatile("mftbu %0" : "=r"(r))
1122 # define mftb(r) __asm__ volatile("mftb %0" : "=r"(r))
1123 do {
1124 mftbu(upper);
1125 mftb(lower);
1126 mftbu(tmp);
1127 } while (tmp != upper);
1128 return ((tick_t)upper << 32) | lower;
1129}
1130
1131#elif defined(__aarch64__) && defined(__GNUC__)
1132typedef unsigned long tick_t;
1133#define PRItick "lu"
1134
1135static __inline__ tick_t
1136tick(void)
1137{
1138 unsigned long val;
1139 __asm__ __volatile__ ("mrs %0, cntvct_el0" : "=r" (val));
1140 return val;
1141}
1142
1143
1144#elif defined(_WIN32) && defined(_MSC_VER)
1145#include <intrin.h>
1146typedef unsigned __int64 tick_t;
1147#define PRItick "llu"
1148
1149static inline tick_t
1150tick(void)
1151{
1152 return __rdtsc();
1153}
1154
1155#else /* use clock */
1156typedef clock_t tick_t;
1157#define PRItick "llu"
1158
1159static inline tick_t
1160tick(void)
1161{
1162 return clock();
1163}
1164#endif /* TSC */
1165#else /* USE_TICK_T */
1166#define MEASURE_LINE(expr) expr
1167#endif /* USE_TICK_T */
1168
1169static inline VALUE check_rvalue_consistency(rb_objspace_t *objspace, const VALUE obj);
1170
1171#define RVALUE_MARKED_BITMAP(obj) MARKED_IN_BITMAP(GET_HEAP_MARK_BITS(obj), (obj))
1172#define RVALUE_WB_UNPROTECTED_BITMAP(obj) MARKED_IN_BITMAP(GET_HEAP_WB_UNPROTECTED_BITS(obj), (obj))
1173#define RVALUE_MARKING_BITMAP(obj) MARKED_IN_BITMAP(GET_HEAP_MARKING_BITS(obj), (obj))
1174#define RVALUE_UNCOLLECTIBLE_BITMAP(obj) MARKED_IN_BITMAP(GET_HEAP_UNCOLLECTIBLE_BITS(obj), (obj))
1175#define RVALUE_PINNED_BITMAP(obj) MARKED_IN_BITMAP(GET_HEAP_PINNED_BITS(obj), (obj))
1176
1177static inline int
1178RVALUE_MARKED(rb_objspace_t *objspace, VALUE obj)
1179{
1180 check_rvalue_consistency(objspace, obj);
1181 return RVALUE_MARKED_BITMAP(obj) != 0;
1182}
1183
1184static inline int
1185RVALUE_PINNED(rb_objspace_t *objspace, VALUE obj)
1186{
1187 check_rvalue_consistency(objspace, obj);
1188 return RVALUE_PINNED_BITMAP(obj) != 0;
1189}
1190
1191static inline int
1192RVALUE_WB_UNPROTECTED(rb_objspace_t *objspace, VALUE obj)
1193{
1194 check_rvalue_consistency(objspace, obj);
1195 return RVALUE_WB_UNPROTECTED_BITMAP(obj) != 0;
1196}
1197
1198static inline int
1199RVALUE_MARKING(rb_objspace_t *objspace, VALUE obj)
1200{
1201 check_rvalue_consistency(objspace, obj);
1202 return RVALUE_MARKING_BITMAP(obj) != 0;
1203}
1204
1205static inline int
1206RVALUE_REMEMBERED(rb_objspace_t *objspace, VALUE obj)
1207{
1208 check_rvalue_consistency(objspace, obj);
1209 return MARKED_IN_BITMAP(GET_HEAP_PAGE(obj)->remembered_bits, obj) != 0;
1210}
1211
1212static inline int
1213RVALUE_UNCOLLECTIBLE(rb_objspace_t *objspace, VALUE obj)
1214{
1215 check_rvalue_consistency(objspace, obj);
1216 return RVALUE_UNCOLLECTIBLE_BITMAP(obj) != 0;
1217}
1218
1219#define RVALUE_PAGE_WB_UNPROTECTED(page, obj) MARKED_IN_BITMAP((page)->wb_unprotected_bits, (obj))
1220#define RVALUE_PAGE_UNCOLLECTIBLE(page, obj) MARKED_IN_BITMAP((page)->uncollectible_bits, (obj))
1221#define RVALUE_PAGE_MARKING(page, obj) MARKED_IN_BITMAP((page)->marking_bits, (obj))
1222
1223static int rgengc_remember(rb_objspace_t *objspace, VALUE obj);
1224static void rgengc_mark_and_rememberset_clear(rb_objspace_t *objspace, rb_heap_t *heap);
1225static void rgengc_rememberset_mark(rb_objspace_t *objspace, rb_heap_t *heap);
1226
1227static int
1228check_rvalue_consistency_force(rb_objspace_t *objspace, const VALUE obj, int terminate)
1229{
1230 int err = 0;
1231
1232 int lev = RB_GC_VM_LOCK_NO_BARRIER();
1233 {
1234 if (SPECIAL_CONST_P(obj)) {
1235 fprintf(stderr, "check_rvalue_consistency: %p is a special const.\n", (void *)obj);
1236 err++;
1237 }
1238 else if (!is_pointer_to_heap(objspace, (void *)obj)) {
1239 struct heap_page *empty_page = objspace->empty_pages;
1240 while (empty_page) {
1241 if ((uintptr_t)empty_page->body <= (uintptr_t)obj &&
1242 (uintptr_t)obj < (uintptr_t)empty_page->body + HEAP_PAGE_SIZE) {
1243 GC_ASSERT(heap_page_in_global_empty_pages_pool(objspace, empty_page));
1244 fprintf(stderr, "check_rvalue_consistency: %p is in an empty page (%p).\n",
1245 (void *)obj, (void *)empty_page);
1246 err++;
1247 goto skip;
1248 }
1249 }
1250 fprintf(stderr, "check_rvalue_consistency: %p is not a Ruby object.\n", (void *)obj);
1251 err++;
1252 skip:
1253 ;
1254 }
1255 else {
1256 const int wb_unprotected_bit = RVALUE_WB_UNPROTECTED_BITMAP(obj) != 0;
1257 const int uncollectible_bit = RVALUE_UNCOLLECTIBLE_BITMAP(obj) != 0;
1258 const int mark_bit = RVALUE_MARKED_BITMAP(obj) != 0;
1259 const int marking_bit = RVALUE_MARKING_BITMAP(obj) != 0;
1260 const int remembered_bit = MARKED_IN_BITMAP(GET_HEAP_PAGE(obj)->remembered_bits, obj) != 0;
1261 const int age = RVALUE_AGE_GET((VALUE)obj);
1262
1263 if (heap_page_in_global_empty_pages_pool(objspace, GET_HEAP_PAGE(obj))) {
1264 fprintf(stderr, "check_rvalue_consistency: %s is in tomb page.\n", rb_obj_info(obj));
1265 err++;
1266 }
1267 if (BUILTIN_TYPE(obj) == T_NONE) {
1268 fprintf(stderr, "check_rvalue_consistency: %s is T_NONE.\n", rb_obj_info(obj));
1269 err++;
1270 }
1271 if (BUILTIN_TYPE(obj) == T_ZOMBIE) {
1272 fprintf(stderr, "check_rvalue_consistency: %s is T_ZOMBIE.\n", rb_obj_info(obj));
1273 err++;
1274 }
1275
1276 if (BUILTIN_TYPE(obj) != T_DATA) {
1277 rb_obj_memsize_of((VALUE)obj);
1278 }
1279
1280 /* check generation
1281 *
1282 * OLD == age == 3 && old-bitmap && mark-bit (except incremental marking)
1283 */
1284 if (age > 0 && wb_unprotected_bit) {
1285 fprintf(stderr, "check_rvalue_consistency: %s is not WB protected, but age is %d > 0.\n", rb_obj_info(obj), age);
1286 err++;
1287 }
1288
1289 if (!is_marking(objspace) && uncollectible_bit && !mark_bit) {
1290 fprintf(stderr, "check_rvalue_consistency: %s is uncollectible, but is not marked while !gc.\n", rb_obj_info(obj));
1291 err++;
1292 }
1293
1294 if (!is_full_marking(objspace)) {
1295 if (uncollectible_bit && age != RVALUE_OLD_AGE && !wb_unprotected_bit) {
1296 fprintf(stderr, "check_rvalue_consistency: %s is uncollectible, but not old (age: %d) and not WB unprotected.\n",
1297 rb_obj_info(obj), age);
1298 err++;
1299 }
1300 if (remembered_bit && age != RVALUE_OLD_AGE) {
1301 fprintf(stderr, "check_rvalue_consistency: %s is remembered, but not old (age: %d).\n",
1302 rb_obj_info(obj), age);
1303 err++;
1304 }
1305 }
1306
1307 /*
1308 * check coloring
1309 *
1310 * marking:false marking:true
1311 * marked:false white *invalid*
1312 * marked:true black grey
1313 */
1314 if (is_incremental_marking(objspace) && marking_bit) {
1315 if (!is_marking(objspace) && !mark_bit) {
1316 fprintf(stderr, "check_rvalue_consistency: %s is marking, but not marked.\n", rb_obj_info(obj));
1317 err++;
1318 }
1319 }
1320 }
1321 }
1322 RB_GC_VM_UNLOCK_NO_BARRIER(lev);
1323
1324 if (err > 0 && terminate) {
1325 rb_bug("check_rvalue_consistency_force: there is %d errors.", err);
1326 }
1327 return err;
1328}
1329
1330#if RGENGC_CHECK_MODE == 0
1331static inline VALUE
1332check_rvalue_consistency(rb_objspace_t *objspace, const VALUE obj)
1333{
1334 return obj;
1335}
1336#else
1337static VALUE
1338check_rvalue_consistency(rb_objspace_t *objspace, const VALUE obj)
1339{
1340 check_rvalue_consistency_force(objspace, obj, TRUE);
1341 return obj;
1342}
1343#endif
1344
1345static inline bool
1346gc_object_moved_p(rb_objspace_t *objspace, VALUE obj)
1347{
1348 if (RB_SPECIAL_CONST_P(obj)) {
1349 return FALSE;
1350 }
1351 else {
1352 int ret;
1353 asan_unpoisoning_object(obj) {
1354 ret = BUILTIN_TYPE(obj) == T_MOVED;
1355 }
1356 return ret;
1357 }
1358}
1359
1360static inline int
1361RVALUE_OLD_P(rb_objspace_t *objspace, VALUE obj)
1362{
1363 GC_ASSERT(!RB_SPECIAL_CONST_P(obj));
1364 check_rvalue_consistency(objspace, obj);
1365 // Because this will only ever be called on GC controlled objects,
1366 // we can use the faster _RAW function here
1367 return RB_OBJ_PROMOTED_RAW(obj);
1368}
1369
1370static inline void
1371RVALUE_PAGE_OLD_UNCOLLECTIBLE_SET(rb_objspace_t *objspace, struct heap_page *page, VALUE obj)
1372{
1373 MARK_IN_BITMAP(&page->uncollectible_bits[0], obj);
1374 objspace->rgengc.old_objects++;
1375
1376#if RGENGC_PROFILE >= 2
1377 objspace->profile.total_promoted_count++;
1378 objspace->profile.promoted_types[BUILTIN_TYPE(obj)]++;
1379#endif
1380}
1381
1382static inline void
1383RVALUE_OLD_UNCOLLECTIBLE_SET(rb_objspace_t *objspace, VALUE obj)
1384{
1385 RB_DEBUG_COUNTER_INC(obj_promote);
1386 RVALUE_PAGE_OLD_UNCOLLECTIBLE_SET(objspace, GET_HEAP_PAGE(obj), obj);
1387}
1388
1389/* set age to age+1 */
1390static inline void
1391RVALUE_AGE_INC(rb_objspace_t *objspace, VALUE obj)
1392{
1393 int age = RVALUE_AGE_GET((VALUE)obj);
1394
1395 if (RGENGC_CHECK_MODE && age == RVALUE_OLD_AGE) {
1396 rb_bug("RVALUE_AGE_INC: can not increment age of OLD object %s.", rb_obj_info(obj));
1397 }
1398
1399 age++;
1400 RVALUE_AGE_SET(obj, age);
1401
1402 if (age == RVALUE_OLD_AGE) {
1403 RVALUE_OLD_UNCOLLECTIBLE_SET(objspace, obj);
1404 }
1405
1406 check_rvalue_consistency(objspace, obj);
1407}
1408
1409static inline void
1410RVALUE_AGE_SET_CANDIDATE(rb_objspace_t *objspace, VALUE obj)
1411{
1412 check_rvalue_consistency(objspace, obj);
1413 GC_ASSERT(!RVALUE_OLD_P(objspace, obj));
1414 RVALUE_AGE_SET(obj, RVALUE_OLD_AGE - 1);
1415 check_rvalue_consistency(objspace, obj);
1416}
1417
1418static inline void
1419RVALUE_AGE_RESET(VALUE obj)
1420{
1421 RVALUE_AGE_SET(obj, 0);
1422}
1423
1424static inline void
1425RVALUE_DEMOTE(rb_objspace_t *objspace, VALUE obj)
1426{
1427 check_rvalue_consistency(objspace, obj);
1428 GC_ASSERT(RVALUE_OLD_P(objspace, obj));
1429
1430 if (!is_incremental_marking(objspace) && RVALUE_REMEMBERED(objspace, obj)) {
1431 CLEAR_IN_BITMAP(GET_HEAP_PAGE(obj)->remembered_bits, obj);
1432 }
1433
1434 CLEAR_IN_BITMAP(GET_HEAP_UNCOLLECTIBLE_BITS(obj), obj);
1435 RVALUE_AGE_RESET(obj);
1436
1437 if (RVALUE_MARKED(objspace, obj)) {
1438 objspace->rgengc.old_objects--;
1439 }
1440
1441 check_rvalue_consistency(objspace, obj);
1442}
1443
1444static inline int
1445RVALUE_BLACK_P(rb_objspace_t *objspace, VALUE obj)
1446{
1447 return RVALUE_MARKED(objspace, obj) && !RVALUE_MARKING(objspace, obj);
1448}
1449
1450static inline int
1451RVALUE_WHITE_P(rb_objspace_t *objspace, VALUE obj)
1452{
1453 return !RVALUE_MARKED(objspace, obj);
1454}
1455
1456bool
1457rb_gc_impl_gc_enabled_p(void *objspace_ptr)
1458{
1459 rb_objspace_t *objspace = objspace_ptr;
1460 return !dont_gc_val();
1461}
1462
1463void
1464rb_gc_impl_gc_enable(void *objspace_ptr)
1465{
1466 rb_objspace_t *objspace = objspace_ptr;
1467
1468 dont_gc_off();
1469}
1470
1471void
1472rb_gc_impl_gc_disable(void *objspace_ptr, bool finish_current_gc)
1473{
1474 rb_objspace_t *objspace = objspace_ptr;
1475
1476 if (finish_current_gc) {
1477 gc_rest(objspace);
1478 }
1479
1480 dont_gc_on();
1481}
1482
1483/*
1484 --------------------------- ObjectSpace -----------------------------
1485*/
1486
1487static inline void *
1488calloc1(size_t n)
1489{
1490 return calloc(1, n);
1491}
1492
1493void
1494rb_gc_impl_set_event_hook(void *objspace_ptr, const rb_event_flag_t event)
1495{
1496 rb_objspace_t *objspace = objspace_ptr;
1497 objspace->hook_events = event & RUBY_INTERNAL_EVENT_OBJSPACE_MASK;
1498 objspace->flags.has_newobj_hook = !!(objspace->hook_events & RUBY_INTERNAL_EVENT_NEWOBJ);
1499}
1500
1501unsigned long long
1502rb_gc_impl_get_total_time(void *objspace_ptr)
1503{
1504 rb_objspace_t *objspace = objspace_ptr;
1505
1506 unsigned long long marking_time = objspace->profile.marking_time_ns;
1507 unsigned long long sweeping_time = objspace->profile.sweeping_time_ns;
1508
1509 return marking_time + sweeping_time;
1510}
1511
1512void
1513rb_gc_impl_set_measure_total_time(void *objspace_ptr, VALUE flag)
1514{
1515 rb_objspace_t *objspace = objspace_ptr;
1516
1517 objspace->flags.measure_gc = RTEST(flag) ? TRUE : FALSE;
1518}
1519
1520bool
1521rb_gc_impl_get_measure_total_time(void *objspace_ptr)
1522{
1523 rb_objspace_t *objspace = objspace_ptr;
1524
1525 return objspace->flags.measure_gc;
1526}
1527
1528static size_t
1529minimum_slots_for_heap(rb_objspace_t *objspace, rb_heap_t *heap)
1530{
1531 size_t heap_idx = heap - heaps;
1532 return gc_params.heap_init_slots[heap_idx];
1533}
1534
1535/* garbage objects will be collected soon. */
1536bool
1537rb_gc_impl_garbage_object_p(void *objspace_ptr, VALUE ptr)
1538{
1539 rb_objspace_t *objspace = objspace_ptr;
1540
1541 bool dead = false;
1542
1543 asan_unpoisoning_object(ptr) {
1544 switch (BUILTIN_TYPE(ptr)) {
1545 case T_NONE:
1546 case T_MOVED:
1547 case T_ZOMBIE:
1548 dead = true;
1549 break;
1550 default:
1551 break;
1552 }
1553 }
1554
1555 if (dead) return true;
1556 return is_lazy_sweeping(objspace) && GET_HEAP_PAGE(ptr)->flags.before_sweep &&
1557 !RVALUE_MARKED(objspace, ptr);
1558}
1559
1560static void free_stack_chunks(mark_stack_t *);
1561static void mark_stack_free_cache(mark_stack_t *);
1562static void heap_page_free(rb_objspace_t *objspace, struct heap_page *page);
1563
1564static inline void
1565heap_page_add_freeobj(rb_objspace_t *objspace, struct heap_page *page, VALUE obj)
1566{
1567 rb_asan_unpoison_object(obj, false);
1568
1569 asan_unlock_freelist(page);
1570
1571 struct free_slot *slot = (struct free_slot *)obj;
1572 slot->flags = 0;
1573 slot->next = page->freelist;
1574 page->freelist = slot;
1575 asan_lock_freelist(page);
1576
1577 RVALUE_AGE_RESET(obj);
1578
1579 if (RGENGC_CHECK_MODE &&
1580 /* obj should belong to page */
1581 !(page->start <= (uintptr_t)obj &&
1582 (uintptr_t)obj < ((uintptr_t)page->start + (page->total_slots * page->slot_size)) &&
1583 obj % BASE_SLOT_SIZE == 0)) {
1584 rb_bug("heap_page_add_freeobj: %p is not rvalue.", (void *)obj);
1585 }
1586
1587 rb_asan_poison_object(obj);
1588 gc_report(3, objspace, "heap_page_add_freeobj: add %p to freelist\n", (void *)obj);
1589}
1590
1591static void
1592heap_allocatable_slots_expand(rb_objspace_t *objspace,
1593 rb_heap_t *heap, size_t free_slots, size_t total_slots)
1594{
1595 double goal_ratio = gc_params.heap_free_slots_goal_ratio;
1596 size_t target_total_slots;
1597
1598 if (goal_ratio == 0.0) {
1599 target_total_slots = (size_t)(total_slots * gc_params.growth_factor);
1600 }
1601 else if (total_slots == 0) {
1602 target_total_slots = minimum_slots_for_heap(objspace, heap);
1603 }
1604 else {
1605 /* Find `f' where free_slots = f * total_slots * goal_ratio
1606 * => f = (total_slots - free_slots) / ((1 - goal_ratio) * total_slots)
1607 */
1608 double f = (double)(total_slots - free_slots) / ((1 - goal_ratio) * total_slots);
1609
1610 if (f > gc_params.growth_factor) f = gc_params.growth_factor;
1611 if (f < 1.0) f = 1.1;
1612
1613 target_total_slots = (size_t)(f * total_slots);
1614
1615 if (0) {
1616 fprintf(stderr,
1617 "free_slots(%8"PRIuSIZE")/total_slots(%8"PRIuSIZE")=%1.2f,"
1618 " G(%1.2f), f(%1.2f),"
1619 " total_slots(%8"PRIuSIZE") => target_total_slots(%8"PRIuSIZE")\n",
1620 free_slots, total_slots, free_slots/(double)total_slots,
1621 goal_ratio, f, total_slots, target_total_slots);
1622 }
1623 }
1624
1625 if (gc_params.growth_max_slots > 0) {
1626 size_t max_total_slots = (size_t)(total_slots + gc_params.growth_max_slots);
1627 if (target_total_slots > max_total_slots) target_total_slots = max_total_slots;
1628 }
1629
1630 size_t extend_slot_count = target_total_slots - total_slots;
1631 /* Extend by at least 1 page. */
1632 if (extend_slot_count == 0) extend_slot_count = 1;
1633
1634 objspace->heap_pages.allocatable_slots += extend_slot_count;
1635}
1636
1637static inline void
1638heap_add_freepage(rb_heap_t *heap, struct heap_page *page)
1639{
1640 asan_unlock_freelist(page);
1641 GC_ASSERT(page->free_slots != 0);
1642 GC_ASSERT(page->freelist != NULL);
1643
1644 page->free_next = heap->free_pages;
1645 heap->free_pages = page;
1646
1647 RUBY_DEBUG_LOG("page:%p freelist:%p", (void *)page, (void *)page->freelist);
1648
1649 asan_lock_freelist(page);
1650}
1651
1652static inline void
1653heap_add_poolpage(rb_objspace_t *objspace, rb_heap_t *heap, struct heap_page *page)
1654{
1655 asan_unlock_freelist(page);
1656 GC_ASSERT(page->free_slots != 0);
1657 GC_ASSERT(page->freelist != NULL);
1658
1659 page->free_next = heap->pooled_pages;
1660 heap->pooled_pages = page;
1661 objspace->rincgc.pooled_slots += page->free_slots;
1662
1663 asan_lock_freelist(page);
1664}
1665
1666static void
1667heap_unlink_page(rb_objspace_t *objspace, rb_heap_t *heap, struct heap_page *page)
1668{
1669 ccan_list_del(&page->page_node);
1670 heap->total_pages--;
1671 heap->total_slots -= page->total_slots;
1672}
1673
1674static void
1675gc_aligned_free(void *ptr, size_t size)
1676{
1677#if defined __MINGW32__
1678 __mingw_aligned_free(ptr);
1679#elif defined _WIN32
1680 _aligned_free(ptr);
1681#elif defined(HAVE_POSIX_MEMALIGN) || defined(HAVE_MEMALIGN)
1682 free(ptr);
1683#else
1684 free(((void**)ptr)[-1]);
1685#endif
1686}
1687
1688static void
1689heap_page_body_free(struct heap_page_body *page_body)
1690{
1691 GC_ASSERT((uintptr_t)page_body % HEAP_PAGE_ALIGN == 0);
1692
1693 if (HEAP_PAGE_ALLOC_USE_MMAP) {
1694#ifdef HAVE_MMAP
1695 GC_ASSERT(HEAP_PAGE_SIZE % sysconf(_SC_PAGE_SIZE) == 0);
1696 if (munmap(page_body, HEAP_PAGE_SIZE)) {
1697 rb_bug("heap_page_body_free: munmap failed");
1698 }
1699#endif
1700 }
1701 else {
1702 gc_aligned_free(page_body, HEAP_PAGE_SIZE);
1703 }
1704}
1705
1706static void
1707heap_page_free(rb_objspace_t *objspace, struct heap_page *page)
1708{
1709 objspace->heap_pages.freed_pages++;
1710 heap_page_body_free(page->body);
1711 free(page);
1712}
1713
1714static void
1715heap_pages_free_unused_pages(rb_objspace_t *objspace)
1716{
1717 if (objspace->empty_pages != NULL && heap_pages_freeable_pages > 0) {
1718 GC_ASSERT(objspace->empty_pages_count > 0);
1719 objspace->empty_pages = NULL;
1720 objspace->empty_pages_count = 0;
1721
1722 size_t i, j;
1723 for (i = j = 0; i < rb_darray_size(objspace->heap_pages.sorted); i++) {
1724 struct heap_page *page = rb_darray_get(objspace->heap_pages.sorted, i);
1725
1726 if (heap_page_in_global_empty_pages_pool(objspace, page) && heap_pages_freeable_pages > 0) {
1727 heap_page_free(objspace, page);
1728 heap_pages_freeable_pages--;
1729 }
1730 else {
1731 if (heap_page_in_global_empty_pages_pool(objspace, page)) {
1732 page->free_next = objspace->empty_pages;
1733 objspace->empty_pages = page;
1734 objspace->empty_pages_count++;
1735 }
1736
1737 if (i != j) {
1738 rb_darray_set(objspace->heap_pages.sorted, j, page);
1739 }
1740 j++;
1741 }
1742 }
1743
1744 rb_darray_pop(objspace->heap_pages.sorted, i - j);
1745 GC_ASSERT(rb_darray_size(objspace->heap_pages.sorted) == j);
1746
1747 struct heap_page *hipage = rb_darray_get(objspace->heap_pages.sorted, rb_darray_size(objspace->heap_pages.sorted) - 1);
1748 uintptr_t himem = (uintptr_t)hipage->body + HEAP_PAGE_SIZE;
1749 GC_ASSERT(himem <= heap_pages_himem);
1750 heap_pages_himem = himem;
1751
1752 struct heap_page *lopage = rb_darray_get(objspace->heap_pages.sorted, 0);
1753 uintptr_t lomem = (uintptr_t)lopage->body + sizeof(struct heap_page_header);
1754 GC_ASSERT(lomem >= heap_pages_lomem);
1755 heap_pages_lomem = lomem;
1756 }
1757}
1758
1759static void *
1760gc_aligned_malloc(size_t alignment, size_t size)
1761{
1762 /* alignment must be a power of 2 */
1763 GC_ASSERT(((alignment - 1) & alignment) == 0);
1764 GC_ASSERT(alignment % sizeof(void*) == 0);
1765
1766 void *res;
1767
1768#if defined __MINGW32__
1769 res = __mingw_aligned_malloc(size, alignment);
1770#elif defined _WIN32
1771 void *_aligned_malloc(size_t, size_t);
1772 res = _aligned_malloc(size, alignment);
1773#elif defined(HAVE_POSIX_MEMALIGN)
1774 if (posix_memalign(&res, alignment, size) != 0) {
1775 return NULL;
1776 }
1777#elif defined(HAVE_MEMALIGN)
1778 res = memalign(alignment, size);
1779#else
1780 char* aligned;
1781 res = malloc(alignment + size + sizeof(void*));
1782 aligned = (char*)res + alignment + sizeof(void*);
1783 aligned -= ((VALUE)aligned & (alignment - 1));
1784 ((void**)aligned)[-1] = res;
1785 res = (void*)aligned;
1786#endif
1787
1788 GC_ASSERT((uintptr_t)res % alignment == 0);
1789
1790 return res;
1791}
1792
1793static struct heap_page_body *
1794heap_page_body_allocate(void)
1795{
1796 struct heap_page_body *page_body;
1797
1798 if (HEAP_PAGE_ALLOC_USE_MMAP) {
1799#ifdef HAVE_MMAP
1800 GC_ASSERT(HEAP_PAGE_ALIGN % sysconf(_SC_PAGE_SIZE) == 0);
1801
1802 size_t mmap_size = HEAP_PAGE_ALIGN + HEAP_PAGE_SIZE;
1803 char *ptr = mmap(NULL, mmap_size,
1804 PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
1805 if (ptr == MAP_FAILED) {
1806 return NULL;
1807 }
1808
1809 // If we are building `default.c` as part of the ruby executable, we
1810 // may just call `ruby_annotate_mmap`. But if we are building
1811 // `default.c` as a shared library, we will not have access to private
1812 // symbols, and we have to either call prctl directly or make our own
1813 // wrapper.
1814#if defined(HAVE_SYS_PRCTL_H) && defined(PR_SET_VMA) && defined(PR_SET_VMA_ANON_NAME)
1815 prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME, ptr, mmap_size, "Ruby:GC:default:heap_page_body_allocate");
1816 errno = 0;
1817#endif
1818
1819 char *aligned = ptr + HEAP_PAGE_ALIGN;
1820 aligned -= ((VALUE)aligned & (HEAP_PAGE_ALIGN - 1));
1821 GC_ASSERT(aligned > ptr);
1822 GC_ASSERT(aligned <= ptr + HEAP_PAGE_ALIGN);
1823
1824 size_t start_out_of_range_size = aligned - ptr;
1825 GC_ASSERT(start_out_of_range_size % sysconf(_SC_PAGE_SIZE) == 0);
1826 if (start_out_of_range_size > 0) {
1827 if (munmap(ptr, start_out_of_range_size)) {
1828 rb_bug("heap_page_body_allocate: munmap failed for start");
1829 }
1830 }
1831
1832 size_t end_out_of_range_size = HEAP_PAGE_ALIGN - start_out_of_range_size;
1833 GC_ASSERT(end_out_of_range_size % sysconf(_SC_PAGE_SIZE) == 0);
1834 if (end_out_of_range_size > 0) {
1835 if (munmap(aligned + HEAP_PAGE_SIZE, end_out_of_range_size)) {
1836 rb_bug("heap_page_body_allocate: munmap failed for end");
1837 }
1838 }
1839
1840 page_body = (struct heap_page_body *)aligned;
1841#endif
1842 }
1843 else {
1844 page_body = gc_aligned_malloc(HEAP_PAGE_ALIGN, HEAP_PAGE_SIZE);
1845 }
1846
1847 GC_ASSERT((uintptr_t)page_body % HEAP_PAGE_ALIGN == 0);
1848
1849 return page_body;
1850}
1851
1852static struct heap_page *
1853heap_page_resurrect(rb_objspace_t *objspace)
1854{
1855 struct heap_page *page = NULL;
1856 if (objspace->empty_pages == NULL) {
1857 GC_ASSERT(objspace->empty_pages_count == 0);
1858 }
1859 else {
1860 GC_ASSERT(objspace->empty_pages_count > 0);
1861 objspace->empty_pages_count--;
1862 page = objspace->empty_pages;
1863 objspace->empty_pages = page->free_next;
1864 }
1865
1866 return page;
1867}
1868
1869static struct heap_page *
1870heap_page_allocate(rb_objspace_t *objspace)
1871{
1872 struct heap_page_body *page_body = heap_page_body_allocate();
1873 if (page_body == 0) {
1874 rb_memerror();
1875 }
1876
1877 struct heap_page *page = calloc1(sizeof(struct heap_page));
1878 if (page == 0) {
1879 heap_page_body_free(page_body);
1880 rb_memerror();
1881 }
1882
1883 uintptr_t start = (uintptr_t)page_body + sizeof(struct heap_page_header);
1884 uintptr_t end = (uintptr_t)page_body + HEAP_PAGE_SIZE;
1885
1886 size_t lo = 0;
1887 size_t hi = rb_darray_size(objspace->heap_pages.sorted);
1888 while (lo < hi) {
1889 struct heap_page *mid_page;
1890
1891 size_t mid = (lo + hi) / 2;
1892 mid_page = rb_darray_get(objspace->heap_pages.sorted, mid);
1893 if ((uintptr_t)mid_page->start < start) {
1894 lo = mid + 1;
1895 }
1896 else if ((uintptr_t)mid_page->start > start) {
1897 hi = mid;
1898 }
1899 else {
1900 rb_bug("same heap page is allocated: %p at %"PRIuVALUE, (void *)page_body, (VALUE)mid);
1901 }
1902 }
1903
1904 rb_darray_insert_without_gc(&objspace->heap_pages.sorted, hi, page);
1905
1906 if (heap_pages_lomem == 0 || heap_pages_lomem > start) heap_pages_lomem = start;
1907 if (heap_pages_himem < end) heap_pages_himem = end;
1908
1909 page->body = page_body;
1910 page_body->header.page = page;
1911
1912 objspace->heap_pages.allocated_pages++;
1913
1914 return page;
1915}
1916
1917static void
1918heap_add_page(rb_objspace_t *objspace, rb_heap_t *heap, struct heap_page *page)
1919{
1920 /* Adding to eden heap during incremental sweeping is forbidden */
1921 GC_ASSERT(!heap->sweeping_page);
1922 GC_ASSERT(heap_page_in_global_empty_pages_pool(objspace, page));
1923
1924 /* adjust obj_limit (object number available in this page) */
1925 uintptr_t start = (uintptr_t)page->body + sizeof(struct heap_page_header);
1926 if (start % BASE_SLOT_SIZE != 0) {
1927 int delta = BASE_SLOT_SIZE - (start % BASE_SLOT_SIZE);
1928 start = start + delta;
1929 GC_ASSERT(NUM_IN_PAGE(start) == 0 || NUM_IN_PAGE(start) == 1);
1930
1931 /* Find a num in page that is evenly divisible by `stride`.
1932 * This is to ensure that objects are aligned with bit planes.
1933 * In other words, ensure there are an even number of objects
1934 * per bit plane. */
1935 if (NUM_IN_PAGE(start) == 1) {
1936 start += heap->slot_size - BASE_SLOT_SIZE;
1937 }
1938
1939 GC_ASSERT(NUM_IN_PAGE(start) * BASE_SLOT_SIZE % heap->slot_size == 0);
1940 }
1941
1942 int slot_count = (int)((HEAP_PAGE_SIZE - (start - (uintptr_t)page->body))/heap->slot_size);
1943
1944 page->start = start;
1945 page->total_slots = slot_count;
1946 page->slot_size = heap->slot_size;
1947 page->heap = heap;
1948
1949 asan_unlock_freelist(page);
1950 page->freelist = NULL;
1951 asan_unpoison_memory_region(page->body, HEAP_PAGE_SIZE, false);
1952 for (VALUE p = (VALUE)start; p < start + (slot_count * heap->slot_size); p += heap->slot_size) {
1953 heap_page_add_freeobj(objspace, page, p);
1954 }
1955 asan_lock_freelist(page);
1956
1957 page->free_slots = slot_count;
1958
1959 heap->total_allocated_pages++;
1960
1961 ccan_list_add_tail(&heap->pages, &page->page_node);
1962 heap->total_pages++;
1963 heap->total_slots += page->total_slots;
1964}
1965
1966static int
1967heap_page_allocate_and_initialize(rb_objspace_t *objspace, rb_heap_t *heap)
1968{
1969 gc_report(1, objspace, "heap_page_allocate_and_initialize: rb_darray_size(objspace->heap_pages.sorted): %"PRIdSIZE", "
1970 "allocatable_slots: %"PRIdSIZE", heap->total_pages: %"PRIdSIZE"\n",
1971 rb_darray_size(objspace->heap_pages.sorted), objspace->heap_pages.allocatable_slots, heap->total_pages);
1972
1973 bool allocated = false;
1974 struct heap_page *page = heap_page_resurrect(objspace);
1975
1976 if (page == NULL && objspace->heap_pages.allocatable_slots > 0) {
1977 page = heap_page_allocate(objspace);
1978 allocated = true;
1979
1980 GC_ASSERT(page != NULL);
1981 }
1982
1983 if (page != NULL) {
1984 heap_add_page(objspace, heap, page);
1985 heap_add_freepage(heap, page);
1986
1987 if (allocated) {
1988 if (objspace->heap_pages.allocatable_slots > (size_t)page->total_slots) {
1989 objspace->heap_pages.allocatable_slots -= page->total_slots;
1990 }
1991 else {
1992 objspace->heap_pages.allocatable_slots = 0;
1993 }
1994 }
1995 }
1996
1997 return page != NULL;
1998}
1999
2000static void
2001heap_page_allocate_and_initialize_force(rb_objspace_t *objspace, rb_heap_t *heap)
2002{
2003 size_t prev_allocatable_slots = objspace->heap_pages.allocatable_slots;
2004 // Set allocatable slots to 1 to force a page to be created.
2005 objspace->heap_pages.allocatable_slots = 1;
2006 heap_page_allocate_and_initialize(objspace, heap);
2007 GC_ASSERT(heap->free_pages != NULL);
2008 objspace->heap_pages.allocatable_slots = prev_allocatable_slots;
2009}
2010
2011static void
2012gc_continue(rb_objspace_t *objspace, rb_heap_t *heap)
2013{
2014 unsigned int lock_lev;
2015 gc_enter(objspace, gc_enter_event_continue, &lock_lev);
2016
2017 /* Continue marking if in incremental marking. */
2018 if (is_incremental_marking(objspace)) {
2019 if (gc_marks_continue(objspace, heap)) {
2020 gc_sweep(objspace);
2021 }
2022 }
2023
2024 /* Continue sweeping if in lazy sweeping or the previous incremental
2025 * marking finished and did not yield a free page. */
2026 if (heap->free_pages == NULL && is_lazy_sweeping(objspace)) {
2027 gc_sweep_continue(objspace, heap);
2028 }
2029
2030 gc_exit(objspace, gc_enter_event_continue, &lock_lev);
2031}
2032
2033static void
2034heap_prepare(rb_objspace_t *objspace, rb_heap_t *heap)
2035{
2036 GC_ASSERT(heap->free_pages == NULL);
2037
2038 if (heap->total_slots < gc_params.heap_init_slots[heap - heaps] &&
2039 heap->sweeping_page == NULL) {
2040 heap_page_allocate_and_initialize_force(objspace, heap);
2041 GC_ASSERT(heap->free_pages != NULL);
2042 return;
2043 }
2044
2045 /* Continue incremental marking or lazy sweeping, if in any of those steps. */
2046 gc_continue(objspace, heap);
2047
2048 if (heap->free_pages == NULL) {
2049 heap_page_allocate_and_initialize(objspace, heap);
2050 }
2051
2052 /* If we still don't have a free page and not allowed to create a new page,
2053 * we should start a new GC cycle. */
2054 if (heap->free_pages == NULL) {
2055 GC_ASSERT(objspace->empty_pages_count == 0);
2056 GC_ASSERT(objspace->heap_pages.allocatable_slots == 0);
2057
2058 if (gc_start(objspace, GPR_FLAG_NEWOBJ) == FALSE) {
2059 rb_memerror();
2060 }
2061 else {
2062 if (objspace->heap_pages.allocatable_slots == 0 && !gc_config_full_mark_val) {
2063 heap_allocatable_slots_expand(objspace, heap,
2064 heap->freed_slots + heap->empty_slots,
2065 heap->total_slots);
2066 GC_ASSERT(objspace->heap_pages.allocatable_slots > 0);
2067 }
2068 /* Do steps of incremental marking or lazy sweeping if the GC run permits. */
2069 gc_continue(objspace, heap);
2070
2071 /* If we're not incremental marking (e.g. a minor GC) or finished
2072 * sweeping and still don't have a free page, then
2073 * gc_sweep_finish_heap should allow us to create a new page. */
2074 if (heap->free_pages == NULL && !heap_page_allocate_and_initialize(objspace, heap)) {
2075 if (gc_needs_major_flags == GPR_FLAG_NONE) {
2076 rb_bug("cannot create a new page after GC");
2077 }
2078 else { // Major GC is required, which will allow us to create new page
2079 if (gc_start(objspace, GPR_FLAG_NEWOBJ) == FALSE) {
2080 rb_memerror();
2081 }
2082 else {
2083 /* Do steps of incremental marking or lazy sweeping. */
2084 gc_continue(objspace, heap);
2085
2086 if (heap->free_pages == NULL &&
2087 !heap_page_allocate_and_initialize(objspace, heap)) {
2088 rb_bug("cannot create a new page after major GC");
2089 }
2090 }
2091 }
2092 }
2093 }
2094 }
2095
2096 GC_ASSERT(heap->free_pages != NULL);
2097}
2098
2099#if GC_DEBUG
2100static inline const char*
2101rb_gc_impl_source_location_cstr(int *ptr)
2102{
2103 /* We could directly refer `rb_source_location_cstr()` before, but not any
2104 * longer. We have to heavy lift using our debugging API. */
2105 if (! ptr) {
2106 return NULL;
2107 }
2108 else if (! (*ptr = rb_sourceline())) {
2109 return NULL;
2110 }
2111 else {
2112 return rb_sourcefile();
2113 }
2114}
2115#endif
2116
2117static inline VALUE
2118newobj_init(VALUE klass, VALUE flags, int wb_protected, rb_objspace_t *objspace, VALUE obj)
2119{
2120 GC_ASSERT(BUILTIN_TYPE(obj) == T_NONE);
2121 GC_ASSERT((flags & FL_WB_PROTECTED) == 0);
2122 RBASIC(obj)->flags = flags;
2123 *((VALUE *)&RBASIC(obj)->klass) = klass;
2124#if RBASIC_SHAPE_ID_FIELD
2125 RBASIC(obj)->shape_id = 0;
2126#endif
2127
2128 int t = flags & RUBY_T_MASK;
2129 if (t == T_CLASS || t == T_MODULE || t == T_ICLASS) {
2130 RVALUE_AGE_SET_CANDIDATE(objspace, obj);
2131 }
2132
2133#if RACTOR_CHECK_MODE
2134 void rb_ractor_setup_belonging(VALUE obj);
2135 rb_ractor_setup_belonging(obj);
2136#endif
2137
2138#if RGENGC_CHECK_MODE
2139 int lev = RB_GC_VM_LOCK_NO_BARRIER();
2140 {
2141 check_rvalue_consistency(objspace, obj);
2142
2143 GC_ASSERT(RVALUE_MARKED(objspace, obj) == FALSE);
2144 GC_ASSERT(RVALUE_MARKING(objspace, obj) == FALSE);
2145 GC_ASSERT(RVALUE_OLD_P(objspace, obj) == FALSE);
2146 GC_ASSERT(RVALUE_WB_UNPROTECTED(objspace, obj) == FALSE);
2147
2148 if (RVALUE_REMEMBERED(objspace, obj)) rb_bug("newobj: %s is remembered.", rb_obj_info(obj));
2149 }
2150 RB_GC_VM_UNLOCK_NO_BARRIER(lev);
2151#endif
2152
2153 if (RB_UNLIKELY(wb_protected == FALSE)) {
2154 MARK_IN_BITMAP(GET_HEAP_WB_UNPROTECTED_BITS(obj), obj);
2155 }
2156
2157#if RGENGC_PROFILE
2158 if (wb_protected) {
2159 objspace->profile.total_generated_normal_object_count++;
2160#if RGENGC_PROFILE >= 2
2161 objspace->profile.generated_normal_object_count_types[BUILTIN_TYPE(obj)]++;
2162#endif
2163 }
2164 else {
2165 objspace->profile.total_generated_shady_object_count++;
2166#if RGENGC_PROFILE >= 2
2167 objspace->profile.generated_shady_object_count_types[BUILTIN_TYPE(obj)]++;
2168#endif
2169 }
2170#endif
2171
2172#if GC_DEBUG
2173 GET_RVALUE_OVERHEAD(obj)->file = rb_gc_impl_source_location_cstr(&GET_RVALUE_OVERHEAD(obj)->line);
2174 GC_ASSERT(!SPECIAL_CONST_P(obj)); /* check alignment */
2175#endif
2176
2177 gc_report(5, objspace, "newobj: %s\n", rb_obj_info(obj));
2178
2179 // RUBY_DEBUG_LOG("obj:%p (%s)", (void *)obj, rb_obj_info(obj));
2180 return obj;
2181}
2182
2183size_t
2184rb_gc_impl_obj_slot_size(VALUE obj)
2185{
2186 return GET_HEAP_PAGE(obj)->slot_size - RVALUE_OVERHEAD;
2187}
2188
2189static inline size_t
2190heap_slot_size(unsigned char pool_id)
2191{
2192 GC_ASSERT(pool_id < HEAP_COUNT);
2193
2194 size_t slot_size = (1 << pool_id) * BASE_SLOT_SIZE;
2195
2196#if RGENGC_CHECK_MODE
2197 rb_objspace_t *objspace = rb_gc_get_objspace();
2198 GC_ASSERT(heaps[pool_id].slot_size == (short)slot_size);
2199#endif
2200
2201 slot_size -= RVALUE_OVERHEAD;
2202
2203 return slot_size;
2204}
2205
2206bool
2207rb_gc_impl_size_allocatable_p(size_t size)
2208{
2209 return size <= heap_slot_size(HEAP_COUNT - 1);
2210}
2211
2212static const size_t ALLOCATED_COUNT_STEP = 1024;
2213
2214static inline VALUE
2215ractor_cache_allocate_slot(rb_objspace_t *objspace, rb_ractor_newobj_cache_t *cache,
2216 size_t heap_idx)
2217{
2218 rb_ractor_newobj_heap_cache_t *heap_cache = &cache->heap_caches[heap_idx];
2219 struct free_slot *p = heap_cache->freelist;
2220
2221 if (RB_UNLIKELY(is_incremental_marking(objspace))) {
2222 // Not allowed to allocate without running an incremental marking step
2223 if (cache->incremental_mark_step_allocated_slots >= INCREMENTAL_MARK_STEP_ALLOCATIONS) {
2224 return Qfalse;
2225 }
2226
2227 if (p) {
2228 cache->incremental_mark_step_allocated_slots++;
2229 }
2230 }
2231
2232 if (RB_LIKELY(p)) {
2233 VALUE obj = (VALUE)p;
2234 rb_asan_unpoison_object(obj, true);
2235 heap_cache->freelist = p->next;
2236
2237 if (rb_gc_multi_ractor_p()) {
2238 heap_cache->allocated_objects_count++;
2239 rb_heap_t *heap = &heaps[heap_idx];
2240 if (heap_cache->allocated_objects_count >= ALLOCATED_COUNT_STEP) {
2241 RUBY_ATOMIC_SIZE_ADD(heap->total_allocated_objects, heap_cache->allocated_objects_count);
2242 heap_cache->allocated_objects_count = 0;
2243 }
2244 }
2245 else {
2246 rb_heap_t *heap = &heaps[heap_idx];
2247 heap->total_allocated_objects++;
2248 GC_ASSERT(heap->total_slots >=
2249 (heap->total_allocated_objects - heap->total_freed_objects - heap->final_slots_count));
2250 }
2251
2252#if RGENGC_CHECK_MODE
2253 GC_ASSERT(rb_gc_impl_obj_slot_size(obj) == heap_slot_size(heap_idx));
2254 // zero clear
2255 MEMZERO((char *)obj, char, heap_slot_size(heap_idx));
2256#endif
2257 return obj;
2258 }
2259 else {
2260 return Qfalse;
2261 }
2262}
2263
2264static struct heap_page *
2265heap_next_free_page(rb_objspace_t *objspace, rb_heap_t *heap)
2266{
2267 struct heap_page *page;
2268
2269 if (heap->free_pages == NULL) {
2270 heap_prepare(objspace, heap);
2271 }
2272
2273 page = heap->free_pages;
2274 heap->free_pages = page->free_next;
2275
2276 GC_ASSERT(page->free_slots != 0);
2277
2278 asan_unlock_freelist(page);
2279
2280 return page;
2281}
2282
2283static inline void
2284ractor_cache_set_page(rb_objspace_t *objspace, rb_ractor_newobj_cache_t *cache, size_t heap_idx,
2285 struct heap_page *page)
2286{
2287 gc_report(3, objspace, "ractor_set_cache: Using page %p\n", (void *)page->body);
2288
2289 rb_ractor_newobj_heap_cache_t *heap_cache = &cache->heap_caches[heap_idx];
2290
2291 GC_ASSERT(heap_cache->freelist == NULL);
2292 GC_ASSERT(page->free_slots != 0);
2293 GC_ASSERT(page->freelist != NULL);
2294
2295 heap_cache->using_page = page;
2296 heap_cache->freelist = page->freelist;
2297 page->free_slots = 0;
2298 page->freelist = NULL;
2299
2300 rb_asan_unpoison_object((VALUE)heap_cache->freelist, false);
2301 GC_ASSERT(RB_TYPE_P((VALUE)heap_cache->freelist, T_NONE));
2302 rb_asan_poison_object((VALUE)heap_cache->freelist);
2303}
2304
2305static inline size_t
2306heap_idx_for_size(size_t size)
2307{
2308 size += RVALUE_OVERHEAD;
2309
2310 size_t slot_count = CEILDIV(size, BASE_SLOT_SIZE);
2311
2312 /* heap_idx is ceil(log2(slot_count)) */
2313 size_t heap_idx = 64 - nlz_int64(slot_count - 1);
2314
2315 if (heap_idx >= HEAP_COUNT) {
2316 rb_bug("heap_idx_for_size: allocation size too large "
2317 "(size=%"PRIuSIZE"u, heap_idx=%"PRIuSIZE"u)", size, heap_idx);
2318 }
2319
2320#if RGENGC_CHECK_MODE
2321 rb_objspace_t *objspace = rb_gc_get_objspace();
2322 GC_ASSERT(size <= (size_t)heaps[heap_idx].slot_size);
2323 if (heap_idx > 0) GC_ASSERT(size > (size_t)heaps[heap_idx - 1].slot_size);
2324#endif
2325
2326 return heap_idx;
2327}
2328
2329size_t
2330rb_gc_impl_heap_id_for_size(void *objspace_ptr, size_t size)
2331{
2332 return heap_idx_for_size(size);
2333}
2334
2335
2336static size_t heap_sizes[HEAP_COUNT + 1] = { 0 };
2337
2338size_t *
2339rb_gc_impl_heap_sizes(void *objspace_ptr)
2340{
2341 if (heap_sizes[0] == 0) {
2342 for (unsigned char i = 0; i < HEAP_COUNT; i++) {
2343 heap_sizes[i] = heap_slot_size(i);
2344 }
2345 }
2346
2347 return heap_sizes;
2348}
2349
2350NOINLINE(static VALUE newobj_cache_miss(rb_objspace_t *objspace, rb_ractor_newobj_cache_t *cache, size_t heap_idx, bool vm_locked));
2351
2352static VALUE
2353newobj_cache_miss(rb_objspace_t *objspace, rb_ractor_newobj_cache_t *cache, size_t heap_idx, bool vm_locked)
2354{
2355 rb_heap_t *heap = &heaps[heap_idx];
2356 VALUE obj = Qfalse;
2357
2358 unsigned int lev = 0;
2359 bool unlock_vm = false;
2360
2361 if (!vm_locked) {
2362 lev = RB_GC_CR_LOCK();
2363 unlock_vm = true;
2364 }
2365
2366 {
2367 if (is_incremental_marking(objspace)) {
2368 gc_continue(objspace, heap);
2369 cache->incremental_mark_step_allocated_slots = 0;
2370
2371 // Retry allocation after resetting incremental_mark_step_allocated_slots
2372 obj = ractor_cache_allocate_slot(objspace, cache, heap_idx);
2373 }
2374
2375 if (obj == Qfalse) {
2376 // Get next free page (possibly running GC)
2377 struct heap_page *page = heap_next_free_page(objspace, heap);
2378 ractor_cache_set_page(objspace, cache, heap_idx, page);
2379
2380 // Retry allocation after moving to new page
2381 obj = ractor_cache_allocate_slot(objspace, cache, heap_idx);
2382 }
2383 }
2384
2385 if (unlock_vm) {
2386 RB_GC_CR_UNLOCK(lev);
2387 }
2388
2389 if (RB_UNLIKELY(obj == Qfalse)) {
2390 rb_memerror();
2391 }
2392 return obj;
2393}
2394
2395static VALUE
2396newobj_alloc(rb_objspace_t *objspace, rb_ractor_newobj_cache_t *cache, size_t heap_idx, bool vm_locked)
2397{
2398 VALUE obj = ractor_cache_allocate_slot(objspace, cache, heap_idx);
2399
2400 if (RB_UNLIKELY(obj == Qfalse)) {
2401 obj = newobj_cache_miss(objspace, cache, heap_idx, vm_locked);
2402 }
2403
2404 return obj;
2405}
2406
2407ALWAYS_INLINE(static VALUE newobj_slowpath(VALUE klass, VALUE flags, rb_objspace_t *objspace, rb_ractor_newobj_cache_t *cache, int wb_protected, size_t heap_idx));
2408
2409static inline VALUE
2410newobj_slowpath(VALUE klass, VALUE flags, rb_objspace_t *objspace, rb_ractor_newobj_cache_t *cache, int wb_protected, size_t heap_idx)
2411{
2412 VALUE obj;
2413 unsigned int lev;
2414
2415 lev = RB_GC_CR_LOCK();
2416 {
2417 if (RB_UNLIKELY(during_gc || ruby_gc_stressful)) {
2418 if (during_gc) {
2419 dont_gc_on();
2420 during_gc = 0;
2421 if (rb_memerror_reentered()) {
2422 rb_memerror();
2423 }
2424 rb_bug("object allocation during garbage collection phase");
2425 }
2426
2427 if (ruby_gc_stressful) {
2428 if (!garbage_collect(objspace, GPR_FLAG_NEWOBJ)) {
2429 rb_memerror();
2430 }
2431 }
2432 }
2433
2434 obj = newobj_alloc(objspace, cache, heap_idx, true);
2435 newobj_init(klass, flags, wb_protected, objspace, obj);
2436 }
2437 RB_GC_CR_UNLOCK(lev);
2438
2439 return obj;
2440}
2441
2442NOINLINE(static VALUE newobj_slowpath_wb_protected(VALUE klass, VALUE flags,
2443 rb_objspace_t *objspace, rb_ractor_newobj_cache_t *cache, size_t heap_idx));
2444NOINLINE(static VALUE newobj_slowpath_wb_unprotected(VALUE klass, VALUE flags,
2445 rb_objspace_t *objspace, rb_ractor_newobj_cache_t *cache, size_t heap_idx));
2446
2447static VALUE
2448newobj_slowpath_wb_protected(VALUE klass, VALUE flags, rb_objspace_t *objspace, rb_ractor_newobj_cache_t *cache, size_t heap_idx)
2449{
2450 return newobj_slowpath(klass, flags, objspace, cache, TRUE, heap_idx);
2451}
2452
2453static VALUE
2454newobj_slowpath_wb_unprotected(VALUE klass, VALUE flags, rb_objspace_t *objspace, rb_ractor_newobj_cache_t *cache, size_t heap_idx)
2455{
2456 return newobj_slowpath(klass, flags, objspace, cache, FALSE, heap_idx);
2457}
2458
2459VALUE
2460rb_gc_impl_new_obj(void *objspace_ptr, void *cache_ptr, VALUE klass, VALUE flags, bool wb_protected, size_t alloc_size)
2461{
2462 VALUE obj;
2463 rb_objspace_t *objspace = objspace_ptr;
2464
2465 RB_DEBUG_COUNTER_INC(obj_newobj);
2466 (void)RB_DEBUG_COUNTER_INC_IF(obj_newobj_wb_unprotected, !wb_protected);
2467
2468 if (RB_UNLIKELY(stress_to_class)) {
2469 if (rb_hash_lookup2(stress_to_class, klass, Qundef) != Qundef) {
2470 rb_memerror();
2471 }
2472 }
2473
2474 size_t heap_idx = heap_idx_for_size(alloc_size);
2475
2477
2478 if (!RB_UNLIKELY(during_gc || ruby_gc_stressful) &&
2479 wb_protected) {
2480 obj = newobj_alloc(objspace, cache, heap_idx, false);
2481 newobj_init(klass, flags, wb_protected, objspace, obj);
2482 }
2483 else {
2484 RB_DEBUG_COUNTER_INC(obj_newobj_slowpath);
2485
2486 obj = wb_protected ?
2487 newobj_slowpath_wb_protected(klass, flags, objspace, cache, heap_idx) :
2488 newobj_slowpath_wb_unprotected(klass, flags, objspace, cache, heap_idx);
2489 }
2490
2491 return obj;
2492}
2493
2494static int
2495ptr_in_page_body_p(const void *ptr, const void *memb)
2496{
2497 struct heap_page *page = *(struct heap_page **)memb;
2498 uintptr_t p_body = (uintptr_t)page->body;
2499
2500 if ((uintptr_t)ptr >= p_body) {
2501 return (uintptr_t)ptr < (p_body + HEAP_PAGE_SIZE) ? 0 : 1;
2502 }
2503 else {
2504 return -1;
2505 }
2506}
2507
2508PUREFUNC(static inline struct heap_page *heap_page_for_ptr(rb_objspace_t *objspace, uintptr_t ptr);)
2509static inline struct heap_page *
2510heap_page_for_ptr(rb_objspace_t *objspace, uintptr_t ptr)
2511{
2512 struct heap_page **res;
2513
2514 if (ptr < (uintptr_t)heap_pages_lomem ||
2515 ptr > (uintptr_t)heap_pages_himem) {
2516 return NULL;
2517 }
2518
2519 res = bsearch((void *)ptr, rb_darray_ref(objspace->heap_pages.sorted, 0),
2520 rb_darray_size(objspace->heap_pages.sorted), sizeof(struct heap_page *),
2521 ptr_in_page_body_p);
2522
2523 if (res) {
2524 return *res;
2525 }
2526 else {
2527 return NULL;
2528 }
2529}
2530
2531PUREFUNC(static inline bool is_pointer_to_heap(rb_objspace_t *objspace, const void *ptr);)
2532static inline bool
2533is_pointer_to_heap(rb_objspace_t *objspace, const void *ptr)
2534{
2535 register uintptr_t p = (uintptr_t)ptr;
2536 register struct heap_page *page;
2537
2538 RB_DEBUG_COUNTER_INC(gc_isptr_trial);
2539
2540 if (p < heap_pages_lomem || p > heap_pages_himem) return FALSE;
2541 RB_DEBUG_COUNTER_INC(gc_isptr_range);
2542
2543 if (p % BASE_SLOT_SIZE != 0) return FALSE;
2544 RB_DEBUG_COUNTER_INC(gc_isptr_align);
2545
2546 page = heap_page_for_ptr(objspace, (uintptr_t)ptr);
2547 if (page) {
2548 RB_DEBUG_COUNTER_INC(gc_isptr_maybe);
2549 if (heap_page_in_global_empty_pages_pool(objspace, page)) {
2550 return FALSE;
2551 }
2552 else {
2553 if (p < page->start) return FALSE;
2554 if (p >= page->start + (page->total_slots * page->slot_size)) return FALSE;
2555 if ((NUM_IN_PAGE(p) * BASE_SLOT_SIZE) % page->slot_size != 0) return FALSE;
2556
2557 return TRUE;
2558 }
2559 }
2560 return FALSE;
2561}
2562
2563bool
2564rb_gc_impl_pointer_to_heap_p(void *objspace_ptr, const void *ptr)
2565{
2566 return is_pointer_to_heap(objspace_ptr, ptr);
2567}
2568
2569#define ZOMBIE_OBJ_KEPT_FLAGS (FL_FINALIZE)
2570
2571void
2572rb_gc_impl_make_zombie(void *objspace_ptr, VALUE obj, void (*dfree)(void *), void *data)
2573{
2574 rb_objspace_t *objspace = objspace_ptr;
2575
2576 struct RZombie *zombie = RZOMBIE(obj);
2577 zombie->flags = T_ZOMBIE | (zombie->flags & ZOMBIE_OBJ_KEPT_FLAGS);
2578 zombie->dfree = dfree;
2579 zombie->data = data;
2580 VALUE prev, next = heap_pages_deferred_final;
2581 do {
2582 zombie->next = prev = next;
2583 next = RUBY_ATOMIC_VALUE_CAS(heap_pages_deferred_final, prev, obj);
2584 } while (next != prev);
2585
2586 struct heap_page *page = GET_HEAP_PAGE(obj);
2587 page->final_slots++;
2588 page->heap->final_slots_count++;
2589}
2590
2591typedef int each_obj_callback(void *, void *, size_t, void *);
2592typedef int each_page_callback(struct heap_page *, void *);
2593
2596 bool reenable_incremental;
2597
2598 each_obj_callback *each_obj_callback;
2599 each_page_callback *each_page_callback;
2600 void *data;
2601
2602 struct heap_page **pages[HEAP_COUNT];
2603 size_t pages_counts[HEAP_COUNT];
2604};
2605
2606static VALUE
2607objspace_each_objects_ensure(VALUE arg)
2608{
2609 struct each_obj_data *data = (struct each_obj_data *)arg;
2610 rb_objspace_t *objspace = data->objspace;
2611
2612 /* Reenable incremental GC */
2613 if (data->reenable_incremental) {
2614 objspace->flags.dont_incremental = FALSE;
2615 }
2616
2617 for (int i = 0; i < HEAP_COUNT; i++) {
2618 struct heap_page **pages = data->pages[i];
2619 free(pages);
2620 }
2621
2622 return Qnil;
2623}
2624
2625static VALUE
2626objspace_each_objects_try(VALUE arg)
2627{
2628 struct each_obj_data *data = (struct each_obj_data *)arg;
2629 rb_objspace_t *objspace = data->objspace;
2630
2631 /* Copy pages from all heaps to their respective buffers. */
2632 for (int i = 0; i < HEAP_COUNT; i++) {
2633 rb_heap_t *heap = &heaps[i];
2634 size_t size = heap->total_pages * sizeof(struct heap_page *);
2635
2636 struct heap_page **pages = malloc(size);
2637 if (!pages) rb_memerror();
2638
2639 /* Set up pages buffer by iterating over all pages in the current eden
2640 * heap. This will be a snapshot of the state of the heap before we
2641 * call the callback over each page that exists in this buffer. Thus it
2642 * is safe for the callback to allocate objects without possibly entering
2643 * an infinite loop. */
2644 struct heap_page *page = 0;
2645 size_t pages_count = 0;
2646 ccan_list_for_each(&heap->pages, page, page_node) {
2647 pages[pages_count] = page;
2648 pages_count++;
2649 }
2650 data->pages[i] = pages;
2651 data->pages_counts[i] = pages_count;
2652 GC_ASSERT(pages_count == heap->total_pages);
2653 }
2654
2655 for (int i = 0; i < HEAP_COUNT; i++) {
2656 rb_heap_t *heap = &heaps[i];
2657 size_t pages_count = data->pages_counts[i];
2658 struct heap_page **pages = data->pages[i];
2659
2660 struct heap_page *page = ccan_list_top(&heap->pages, struct heap_page, page_node);
2661 for (size_t i = 0; i < pages_count; i++) {
2662 /* If we have reached the end of the linked list then there are no
2663 * more pages, so break. */
2664 if (page == NULL) break;
2665
2666 /* If this page does not match the one in the buffer, then move to
2667 * the next page in the buffer. */
2668 if (pages[i] != page) continue;
2669
2670 uintptr_t pstart = (uintptr_t)page->start;
2671 uintptr_t pend = pstart + (page->total_slots * heap->slot_size);
2672
2673 if (data->each_obj_callback &&
2674 (*data->each_obj_callback)((void *)pstart, (void *)pend, heap->slot_size, data->data)) {
2675 break;
2676 }
2677 if (data->each_page_callback &&
2678 (*data->each_page_callback)(page, data->data)) {
2679 break;
2680 }
2681
2682 page = ccan_list_next(&heap->pages, page, page_node);
2683 }
2684 }
2685
2686 return Qnil;
2687}
2688
2689static void
2690objspace_each_exec(bool protected, struct each_obj_data *each_obj_data)
2691{
2692 /* Disable incremental GC */
2694 bool reenable_incremental = FALSE;
2695 if (protected) {
2696 reenable_incremental = !objspace->flags.dont_incremental;
2697
2698 gc_rest(objspace);
2699 objspace->flags.dont_incremental = TRUE;
2700 }
2701
2702 each_obj_data->reenable_incremental = reenable_incremental;
2703 memset(&each_obj_data->pages, 0, sizeof(each_obj_data->pages));
2704 memset(&each_obj_data->pages_counts, 0, sizeof(each_obj_data->pages_counts));
2705 rb_ensure(objspace_each_objects_try, (VALUE)each_obj_data,
2706 objspace_each_objects_ensure, (VALUE)each_obj_data);
2707}
2708
2709static void
2710objspace_each_objects(rb_objspace_t *objspace, each_obj_callback *callback, void *data, bool protected)
2711{
2712 struct each_obj_data each_obj_data = {
2713 .objspace = objspace,
2714 .each_obj_callback = callback,
2715 .each_page_callback = NULL,
2716 .data = data,
2717 };
2718 objspace_each_exec(protected, &each_obj_data);
2719}
2720
2721void
2722rb_gc_impl_each_objects(void *objspace_ptr, each_obj_callback *callback, void *data)
2723{
2724 objspace_each_objects(objspace_ptr, callback, data, TRUE);
2725}
2726
2727#if GC_CAN_COMPILE_COMPACTION
2728static void
2729objspace_each_pages(rb_objspace_t *objspace, each_page_callback *callback, void *data, bool protected)
2730{
2731 struct each_obj_data each_obj_data = {
2732 .objspace = objspace,
2733 .each_obj_callback = NULL,
2734 .each_page_callback = callback,
2735 .data = data,
2736 };
2737 objspace_each_exec(protected, &each_obj_data);
2738}
2739#endif
2740
2741VALUE
2742rb_gc_impl_define_finalizer(void *objspace_ptr, VALUE obj, VALUE block)
2743{
2744 rb_objspace_t *objspace = objspace_ptr;
2745 VALUE table;
2746 st_data_t data;
2747
2748 GC_ASSERT(!OBJ_FROZEN(obj));
2749
2750 RBASIC(obj)->flags |= FL_FINALIZE;
2751
2752 int lev = RB_GC_VM_LOCK();
2753
2754 if (st_lookup(finalizer_table, obj, &data)) {
2755 table = (VALUE)data;
2756
2757 /* avoid duplicate block, table is usually small */
2758 {
2759 long len = RARRAY_LEN(table);
2760 long i;
2761
2762 for (i = 0; i < len; i++) {
2763 VALUE recv = RARRAY_AREF(table, i);
2764 if (rb_equal(recv, block)) {
2765 RB_GC_VM_UNLOCK(lev);
2766 return recv;
2767 }
2768 }
2769 }
2770
2771 rb_ary_push(table, block);
2772 }
2773 else {
2774 table = rb_ary_new3(2, rb_obj_id(obj), block);
2775 rb_obj_hide(table);
2776 st_add_direct(finalizer_table, obj, table);
2777 }
2778
2779 RB_GC_VM_UNLOCK(lev);
2780
2781 return block;
2782}
2783
2784void
2785rb_gc_impl_undefine_finalizer(void *objspace_ptr, VALUE obj)
2786{
2787 rb_objspace_t *objspace = objspace_ptr;
2788
2789 GC_ASSERT(!OBJ_FROZEN(obj));
2790
2791 st_data_t data = obj;
2792
2793 int lev = RB_GC_VM_LOCK();
2794 st_delete(finalizer_table, &data, 0);
2795 RB_GC_VM_UNLOCK(lev);
2796
2797 FL_UNSET(obj, FL_FINALIZE);
2798}
2799
2800void
2801rb_gc_impl_copy_finalizer(void *objspace_ptr, VALUE dest, VALUE obj)
2802{
2803 rb_objspace_t *objspace = objspace_ptr;
2804 VALUE table;
2805 st_data_t data;
2806
2807 if (!FL_TEST(obj, FL_FINALIZE)) return;
2808
2809 int lev = RB_GC_VM_LOCK();
2810 if (RB_LIKELY(st_lookup(finalizer_table, obj, &data))) {
2811 table = rb_ary_dup((VALUE)data);
2812 RARRAY_ASET(table, 0, rb_obj_id(dest));
2813 st_insert(finalizer_table, dest, table);
2814 FL_SET(dest, FL_FINALIZE);
2815 }
2816 else {
2817 rb_bug("rb_gc_copy_finalizer: FL_FINALIZE set but not found in finalizer_table: %s", rb_obj_info(obj));
2818 }
2819 RB_GC_VM_UNLOCK(lev);
2820}
2821
2822static VALUE
2823get_final(long i, void *data)
2824{
2825 VALUE table = (VALUE)data;
2826
2827 return RARRAY_AREF(table, i + 1);
2828}
2829
2830static void
2831run_final(rb_objspace_t *objspace, VALUE zombie)
2832{
2833 if (RZOMBIE(zombie)->dfree) {
2834 RZOMBIE(zombie)->dfree(RZOMBIE(zombie)->data);
2835 }
2836
2837 st_data_t key = (st_data_t)zombie;
2838 if (FL_TEST_RAW(zombie, FL_FINALIZE)) {
2839 FL_UNSET(zombie, FL_FINALIZE);
2840 st_data_t table;
2841 if (st_delete(finalizer_table, &key, &table)) {
2842 rb_gc_run_obj_finalizer(RARRAY_AREF(table, 0), RARRAY_LEN(table) - 1, get_final, (void *)table);
2843 }
2844 else {
2845 rb_bug("FL_FINALIZE flag is set, but finalizers are not found");
2846 }
2847 }
2848 else {
2849 GC_ASSERT(!st_lookup(finalizer_table, key, NULL));
2850 }
2851}
2852
2853static void
2854finalize_list(rb_objspace_t *objspace, VALUE zombie)
2855{
2856 while (zombie) {
2857 VALUE next_zombie;
2858 struct heap_page *page;
2859 rb_asan_unpoison_object(zombie, false);
2860 next_zombie = RZOMBIE(zombie)->next;
2861 page = GET_HEAP_PAGE(zombie);
2862
2863 int lev = RB_GC_VM_LOCK();
2864
2865 run_final(objspace, zombie);
2866 {
2867 GC_ASSERT(BUILTIN_TYPE(zombie) == T_ZOMBIE);
2868 GC_ASSERT(page->heap->final_slots_count > 0);
2869 GC_ASSERT(page->final_slots > 0);
2870
2871 page->heap->final_slots_count--;
2872 page->final_slots--;
2873 page->free_slots++;
2874 heap_page_add_freeobj(objspace, page, zombie);
2875 page->heap->total_freed_objects++;
2876 }
2877 RB_GC_VM_UNLOCK(lev);
2878
2879 zombie = next_zombie;
2880 }
2881}
2882
2883static void
2884finalize_deferred_heap_pages(rb_objspace_t *objspace)
2885{
2886 VALUE zombie;
2887 while ((zombie = RUBY_ATOMIC_VALUE_EXCHANGE(heap_pages_deferred_final, 0)) != 0) {
2888 finalize_list(objspace, zombie);
2889 }
2890}
2891
2892static void
2893finalize_deferred(rb_objspace_t *objspace)
2894{
2895 rb_gc_set_pending_interrupt();
2896 finalize_deferred_heap_pages(objspace);
2897 rb_gc_unset_pending_interrupt();
2898}
2899
2900static void
2901gc_finalize_deferred(void *dmy)
2902{
2903 rb_objspace_t *objspace = dmy;
2904 if (RUBY_ATOMIC_EXCHANGE(finalizing, 1)) return;
2905
2906 finalize_deferred(objspace);
2907 RUBY_ATOMIC_SET(finalizing, 0);
2908}
2909
2910static void
2911gc_finalize_deferred_register(rb_objspace_t *objspace)
2912{
2913 /* will enqueue a call to gc_finalize_deferred */
2914 rb_postponed_job_trigger(objspace->finalize_deferred_pjob);
2915}
2916
2917static int pop_mark_stack(mark_stack_t *stack, VALUE *data);
2918
2919static void
2920gc_abort(void *objspace_ptr)
2921{
2922 rb_objspace_t *objspace = objspace_ptr;
2923
2924 if (is_incremental_marking(objspace)) {
2925 /* Remove all objects from the mark stack. */
2926 VALUE obj;
2927 while (pop_mark_stack(&objspace->mark_stack, &obj));
2928
2929 objspace->flags.during_incremental_marking = FALSE;
2930 }
2931
2932 if (is_lazy_sweeping(objspace)) {
2933 for (int i = 0; i < HEAP_COUNT; i++) {
2934 rb_heap_t *heap = &heaps[i];
2935
2936 heap->sweeping_page = NULL;
2937 struct heap_page *page = NULL;
2938
2939 ccan_list_for_each(&heap->pages, page, page_node) {
2940 page->flags.before_sweep = false;
2941 }
2942 }
2943 }
2944
2945 for (int i = 0; i < HEAP_COUNT; i++) {
2946 rb_heap_t *heap = &heaps[i];
2947 rgengc_mark_and_rememberset_clear(objspace, heap);
2948 }
2949
2950 gc_mode_set(objspace, gc_mode_none);
2951}
2952
2953void
2954rb_gc_impl_shutdown_free_objects(void *objspace_ptr)
2955{
2956 rb_objspace_t *objspace = objspace_ptr;
2957
2958 for (size_t i = 0; i < rb_darray_size(objspace->heap_pages.sorted); i++) {
2959 struct heap_page *page = rb_darray_get(objspace->heap_pages.sorted, i);
2960 short stride = page->slot_size;
2961
2962 uintptr_t p = (uintptr_t)page->start;
2963 uintptr_t pend = p + page->total_slots * stride;
2964 for (; p < pend; p += stride) {
2965 VALUE vp = (VALUE)p;
2966 asan_unpoisoning_object(vp) {
2967 if (RB_BUILTIN_TYPE(vp) != T_NONE) {
2968 rb_gc_obj_free_vm_weak_references(vp);
2969 if (rb_gc_obj_free(objspace, vp)) {
2970 RBASIC(vp)->flags = 0;
2971 }
2972 }
2973 }
2974 }
2975 }
2976}
2977
2978static int
2979rb_gc_impl_shutdown_call_finalizer_i(st_data_t key, st_data_t val, st_data_t _data)
2980{
2981 VALUE obj = (VALUE)key;
2982 VALUE table = (VALUE)val;
2983
2984 GC_ASSERT(RB_FL_TEST(obj, FL_FINALIZE));
2985 GC_ASSERT(RB_BUILTIN_TYPE(val) == T_ARRAY);
2986
2987 rb_gc_run_obj_finalizer(RARRAY_AREF(table, 0), RARRAY_LEN(table) - 1, get_final, (void *)table);
2988
2989 FL_UNSET(obj, FL_FINALIZE);
2990
2991 return ST_DELETE;
2992}
2993
2994void
2995rb_gc_impl_shutdown_call_finalizer(void *objspace_ptr)
2996{
2997 rb_objspace_t *objspace = objspace_ptr;
2998
2999#if RGENGC_CHECK_MODE >= 2
3000 gc_verify_internal_consistency(objspace);
3001#endif
3002
3003 /* prohibit incremental GC */
3004 objspace->flags.dont_incremental = 1;
3005
3006 if (RUBY_ATOMIC_EXCHANGE(finalizing, 1)) {
3007 /* Abort incremental marking and lazy sweeping to speed up shutdown. */
3008 gc_abort(objspace);
3009 dont_gc_on();
3010 return;
3011 }
3012
3013 while (finalizer_table->num_entries) {
3014 st_foreach(finalizer_table, rb_gc_impl_shutdown_call_finalizer_i, 0);
3015 }
3016
3017 /* run finalizers */
3018 finalize_deferred(objspace);
3019 GC_ASSERT(heap_pages_deferred_final == 0);
3020
3021 /* Abort incremental marking and lazy sweeping to speed up shutdown. */
3022 gc_abort(objspace);
3023
3024 /* prohibit GC because force T_DATA finalizers can break an object graph consistency */
3025 dont_gc_on();
3026
3027 /* running data/file finalizers are part of garbage collection */
3028 unsigned int lock_lev;
3029 gc_enter(objspace, gc_enter_event_finalizer, &lock_lev);
3030
3031 /* run data/file object's finalizers */
3032 for (size_t i = 0; i < rb_darray_size(objspace->heap_pages.sorted); i++) {
3033 struct heap_page *page = rb_darray_get(objspace->heap_pages.sorted, i);
3034 short stride = page->slot_size;
3035
3036 uintptr_t p = (uintptr_t)page->start;
3037 uintptr_t pend = p + page->total_slots * stride;
3038 for (; p < pend; p += stride) {
3039 VALUE vp = (VALUE)p;
3040 asan_unpoisoning_object(vp) {
3041 if (rb_gc_shutdown_call_finalizer_p(vp)) {
3042 rb_gc_obj_free_vm_weak_references(vp);
3043 if (rb_gc_obj_free(objspace, vp)) {
3044 RBASIC(vp)->flags = 0;
3045 }
3046 }
3047 }
3048 }
3049 }
3050
3051 gc_exit(objspace, gc_enter_event_finalizer, &lock_lev);
3052
3053 finalize_deferred_heap_pages(objspace);
3054
3055 st_free_table(finalizer_table);
3056 finalizer_table = 0;
3057 RUBY_ATOMIC_SET(finalizing, 0);
3058}
3059
3060void
3061rb_gc_impl_each_object(void *objspace_ptr, void (*func)(VALUE obj, void *data), void *data)
3062{
3063 rb_objspace_t *objspace = objspace_ptr;
3064
3065 for (size_t i = 0; i < rb_darray_size(objspace->heap_pages.sorted); i++) {
3066 struct heap_page *page = rb_darray_get(objspace->heap_pages.sorted, i);
3067 short stride = page->slot_size;
3068
3069 uintptr_t p = (uintptr_t)page->start;
3070 uintptr_t pend = p + page->total_slots * stride;
3071 for (; p < pend; p += stride) {
3072 VALUE obj = (VALUE)p;
3073
3074 asan_unpoisoning_object(obj) {
3075 func(obj, data);
3076 }
3077 }
3078 }
3079}
3080
3081/*
3082 ------------------------ Garbage Collection ------------------------
3083*/
3084
3085/* Sweeping */
3086
3087static size_t
3088objspace_available_slots(rb_objspace_t *objspace)
3089{
3090 size_t total_slots = 0;
3091 for (int i = 0; i < HEAP_COUNT; i++) {
3092 rb_heap_t *heap = &heaps[i];
3093 total_slots += heap->total_slots;
3094 }
3095 return total_slots;
3096}
3097
3098static size_t
3099objspace_live_slots(rb_objspace_t *objspace)
3100{
3101 return total_allocated_objects(objspace) - total_freed_objects(objspace) - total_final_slots_count(objspace);
3102}
3103
3104static size_t
3105objspace_free_slots(rb_objspace_t *objspace)
3106{
3107 return objspace_available_slots(objspace) - objspace_live_slots(objspace) - total_final_slots_count(objspace);
3108}
3109
3110static void
3111gc_setup_mark_bits(struct heap_page *page)
3112{
3113 /* copy oldgen bitmap to mark bitmap */
3114 memcpy(&page->mark_bits[0], &page->uncollectible_bits[0], HEAP_PAGE_BITMAP_SIZE);
3115}
3116
3117static int gc_is_moveable_obj(rb_objspace_t *objspace, VALUE obj);
3118static VALUE gc_move(rb_objspace_t *objspace, VALUE scan, VALUE free, size_t src_slot_size, size_t slot_size);
3119
3120#if defined(_WIN32)
3121enum {HEAP_PAGE_LOCK = PAGE_NOACCESS, HEAP_PAGE_UNLOCK = PAGE_READWRITE};
3122
3123static BOOL
3124protect_page_body(struct heap_page_body *body, DWORD protect)
3125{
3126 DWORD old_protect;
3127 return VirtualProtect(body, HEAP_PAGE_SIZE, protect, &old_protect) != 0;
3128}
3129#elif defined(__wasi__)
3130// wasi-libc's mprotect emulation does not support PROT_NONE
3131enum {HEAP_PAGE_LOCK, HEAP_PAGE_UNLOCK};
3132#define protect_page_body(body, protect) 1
3133#else
3134enum {HEAP_PAGE_LOCK = PROT_NONE, HEAP_PAGE_UNLOCK = PROT_READ | PROT_WRITE};
3135#define protect_page_body(body, protect) !mprotect((body), HEAP_PAGE_SIZE, (protect))
3136#endif
3137
3138static void
3139lock_page_body(rb_objspace_t *objspace, struct heap_page_body *body)
3140{
3141 if (!protect_page_body(body, HEAP_PAGE_LOCK)) {
3142 rb_bug("Couldn't protect page %p, errno: %s", (void *)body, strerror(errno));
3143 }
3144 else {
3145 gc_report(5, objspace, "Protecting page in move %p\n", (void *)body);
3146 }
3147}
3148
3149static void
3150unlock_page_body(rb_objspace_t *objspace, struct heap_page_body *body)
3151{
3152 if (!protect_page_body(body, HEAP_PAGE_UNLOCK)) {
3153 rb_bug("Couldn't unprotect page %p, errno: %s", (void *)body, strerror(errno));
3154 }
3155 else {
3156 gc_report(5, objspace, "Unprotecting page in move %p\n", (void *)body);
3157 }
3158}
3159
3160static bool
3161try_move(rb_objspace_t *objspace, rb_heap_t *heap, struct heap_page *free_page, VALUE src)
3162{
3163 GC_ASSERT(gc_is_moveable_obj(objspace, src));
3164
3165 struct heap_page *src_page = GET_HEAP_PAGE(src);
3166 if (!free_page) {
3167 return false;
3168 }
3169
3170 /* We should return true if either src is successfully moved, or src is
3171 * unmoveable. A false return will cause the sweeping cursor to be
3172 * incremented to the next page, and src will attempt to move again */
3173 GC_ASSERT(RVALUE_MARKED(objspace, src));
3174
3175 asan_unlock_freelist(free_page);
3176 VALUE dest = (VALUE)free_page->freelist;
3177 asan_lock_freelist(free_page);
3178 if (dest) {
3179 rb_asan_unpoison_object(dest, false);
3180 }
3181 else {
3182 /* if we can't get something from the freelist then the page must be
3183 * full */
3184 return false;
3185 }
3186 asan_unlock_freelist(free_page);
3187 free_page->freelist = ((struct free_slot *)dest)->next;
3188 asan_lock_freelist(free_page);
3189
3190 GC_ASSERT(RB_BUILTIN_TYPE(dest) == T_NONE);
3191
3192 if (src_page->slot_size > free_page->slot_size) {
3193 objspace->rcompactor.moved_down_count_table[BUILTIN_TYPE(src)]++;
3194 }
3195 else if (free_page->slot_size > src_page->slot_size) {
3196 objspace->rcompactor.moved_up_count_table[BUILTIN_TYPE(src)]++;
3197 }
3198 objspace->rcompactor.moved_count_table[BUILTIN_TYPE(src)]++;
3199 objspace->rcompactor.total_moved++;
3200
3201 gc_move(objspace, src, dest, src_page->slot_size, free_page->slot_size);
3202 gc_pin(objspace, src);
3203 free_page->free_slots--;
3204
3205 return true;
3206}
3207
3208static void
3209gc_unprotect_pages(rb_objspace_t *objspace, rb_heap_t *heap)
3210{
3211 struct heap_page *cursor = heap->compact_cursor;
3212
3213 while (cursor) {
3214 unlock_page_body(objspace, cursor->body);
3215 cursor = ccan_list_next(&heap->pages, cursor, page_node);
3216 }
3217}
3218
3219static void gc_update_references(rb_objspace_t *objspace);
3220#if GC_CAN_COMPILE_COMPACTION
3221static void invalidate_moved_page(rb_objspace_t *objspace, struct heap_page *page);
3222#endif
3223
3224#if defined(__MINGW32__) || defined(_WIN32)
3225# define GC_COMPACTION_SUPPORTED 1
3226#else
3227/* If not MinGW, Windows, or does not have mmap, we cannot use mprotect for
3228 * the read barrier, so we must disable compaction. */
3229# define GC_COMPACTION_SUPPORTED (GC_CAN_COMPILE_COMPACTION && HEAP_PAGE_ALLOC_USE_MMAP)
3230#endif
3231
3232#if GC_CAN_COMPILE_COMPACTION
3233static void
3234read_barrier_handler(uintptr_t address)
3235{
3236 rb_objspace_t *objspace = (rb_objspace_t *)rb_gc_get_objspace();
3237
3238 struct heap_page_body *page_body = GET_PAGE_BODY(address);
3239
3240 /* If the page_body is NULL, then mprotect cannot handle it and will crash
3241 * with "Cannot allocate memory". */
3242 if (page_body == NULL) {
3243 rb_bug("read_barrier_handler: segmentation fault at %p", (void *)address);
3244 }
3245
3246 int lev = RB_GC_VM_LOCK();
3247 {
3248 unlock_page_body(objspace, page_body);
3249
3250 objspace->profile.read_barrier_faults++;
3251
3252 invalidate_moved_page(objspace, GET_HEAP_PAGE(address));
3253 }
3254 RB_GC_VM_UNLOCK(lev);
3255}
3256#endif
3257
3258#if !GC_CAN_COMPILE_COMPACTION
3259static void
3260uninstall_handlers(void)
3261{
3262 /* no-op */
3263}
3264
3265static void
3266install_handlers(void)
3267{
3268 /* no-op */
3269}
3270#elif defined(_WIN32)
3271static LPTOP_LEVEL_EXCEPTION_FILTER old_handler;
3272typedef void (*signal_handler)(int);
3273static signal_handler old_sigsegv_handler;
3274
3275static LONG WINAPI
3276read_barrier_signal(EXCEPTION_POINTERS *info)
3277{
3278 /* EXCEPTION_ACCESS_VIOLATION is what's raised by access to protected pages */
3279 if (info->ExceptionRecord->ExceptionCode == EXCEPTION_ACCESS_VIOLATION) {
3280 /* > The second array element specifies the virtual address of the inaccessible data.
3281 * https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-exception_record
3282 *
3283 * Use this address to invalidate the page */
3284 read_barrier_handler((uintptr_t)info->ExceptionRecord->ExceptionInformation[1]);
3285 return EXCEPTION_CONTINUE_EXECUTION;
3286 }
3287 else {
3288 return EXCEPTION_CONTINUE_SEARCH;
3289 }
3290}
3291
3292static void
3293uninstall_handlers(void)
3294{
3295 signal(SIGSEGV, old_sigsegv_handler);
3296 SetUnhandledExceptionFilter(old_handler);
3297}
3298
3299static void
3300install_handlers(void)
3301{
3302 /* Remove SEGV handler so that the Unhandled Exception Filter handles it */
3303 old_sigsegv_handler = signal(SIGSEGV, NULL);
3304 /* Unhandled Exception Filter has access to the violation address similar
3305 * to si_addr from sigaction */
3306 old_handler = SetUnhandledExceptionFilter(read_barrier_signal);
3307}
3308#else
3309static struct sigaction old_sigbus_handler;
3310static struct sigaction old_sigsegv_handler;
3311
3312#ifdef HAVE_MACH_TASK_EXCEPTION_PORTS
3313static exception_mask_t old_exception_masks[32];
3314static mach_port_t old_exception_ports[32];
3315static exception_behavior_t old_exception_behaviors[32];
3316static thread_state_flavor_t old_exception_flavors[32];
3317static mach_msg_type_number_t old_exception_count;
3318
3319static void
3320disable_mach_bad_access_exc(void)
3321{
3322 old_exception_count = sizeof(old_exception_masks) / sizeof(old_exception_masks[0]);
3323 task_swap_exception_ports(
3324 mach_task_self(), EXC_MASK_BAD_ACCESS,
3325 MACH_PORT_NULL, EXCEPTION_DEFAULT, 0,
3326 old_exception_masks, &old_exception_count,
3327 old_exception_ports, old_exception_behaviors, old_exception_flavors
3328 );
3329}
3330
3331static void
3332restore_mach_bad_access_exc(void)
3333{
3334 for (mach_msg_type_number_t i = 0; i < old_exception_count; i++) {
3335 task_set_exception_ports(
3336 mach_task_self(),
3337 old_exception_masks[i], old_exception_ports[i],
3338 old_exception_behaviors[i], old_exception_flavors[i]
3339 );
3340 }
3341}
3342#endif
3343
3344static void
3345read_barrier_signal(int sig, siginfo_t *info, void *data)
3346{
3347 // setup SEGV/BUS handlers for errors
3348 struct sigaction prev_sigbus, prev_sigsegv;
3349 sigaction(SIGBUS, &old_sigbus_handler, &prev_sigbus);
3350 sigaction(SIGSEGV, &old_sigsegv_handler, &prev_sigsegv);
3351
3352 // enable SIGBUS/SEGV
3353 sigset_t set, prev_set;
3354 sigemptyset(&set);
3355 sigaddset(&set, SIGBUS);
3356 sigaddset(&set, SIGSEGV);
3357 sigprocmask(SIG_UNBLOCK, &set, &prev_set);
3358#ifdef HAVE_MACH_TASK_EXCEPTION_PORTS
3359 disable_mach_bad_access_exc();
3360#endif
3361 // run handler
3362 read_barrier_handler((uintptr_t)info->si_addr);
3363
3364 // reset SEGV/BUS handlers
3365#ifdef HAVE_MACH_TASK_EXCEPTION_PORTS
3366 restore_mach_bad_access_exc();
3367#endif
3368 sigaction(SIGBUS, &prev_sigbus, NULL);
3369 sigaction(SIGSEGV, &prev_sigsegv, NULL);
3370 sigprocmask(SIG_SETMASK, &prev_set, NULL);
3371}
3372
3373static void
3374uninstall_handlers(void)
3375{
3376#ifdef HAVE_MACH_TASK_EXCEPTION_PORTS
3377 restore_mach_bad_access_exc();
3378#endif
3379 sigaction(SIGBUS, &old_sigbus_handler, NULL);
3380 sigaction(SIGSEGV, &old_sigsegv_handler, NULL);
3381}
3382
3383static void
3384install_handlers(void)
3385{
3386 struct sigaction action;
3387 memset(&action, 0, sizeof(struct sigaction));
3388 sigemptyset(&action.sa_mask);
3389 action.sa_sigaction = read_barrier_signal;
3390 action.sa_flags = SA_SIGINFO | SA_ONSTACK;
3391
3392 sigaction(SIGBUS, &action, &old_sigbus_handler);
3393 sigaction(SIGSEGV, &action, &old_sigsegv_handler);
3394#ifdef HAVE_MACH_TASK_EXCEPTION_PORTS
3395 disable_mach_bad_access_exc();
3396#endif
3397}
3398#endif
3399
3400static void
3401gc_compact_finish(rb_objspace_t *objspace)
3402{
3403 for (int i = 0; i < HEAP_COUNT; i++) {
3404 rb_heap_t *heap = &heaps[i];
3405 gc_unprotect_pages(objspace, heap);
3406 }
3407
3408 uninstall_handlers();
3409
3410 gc_update_references(objspace);
3411 objspace->profile.compact_count++;
3412
3413 for (int i = 0; i < HEAP_COUNT; i++) {
3414 rb_heap_t *heap = &heaps[i];
3415 heap->compact_cursor = NULL;
3416 heap->free_pages = NULL;
3417 heap->compact_cursor_index = 0;
3418 }
3419
3420 if (gc_prof_enabled(objspace)) {
3421 gc_profile_record *record = gc_prof_record(objspace);
3422 record->moved_objects = objspace->rcompactor.total_moved - record->moved_objects;
3423 }
3424 objspace->flags.during_compacting = FALSE;
3425}
3426
3428 struct heap_page *page;
3429 int final_slots;
3430 int freed_slots;
3431 int empty_slots;
3432};
3433
3434static inline void
3435gc_sweep_plane(rb_objspace_t *objspace, rb_heap_t *heap, uintptr_t p, bits_t bitset, struct gc_sweep_context *ctx)
3436{
3437 struct heap_page *sweep_page = ctx->page;
3438 short slot_size = sweep_page->slot_size;
3439 short slot_bits = slot_size / BASE_SLOT_SIZE;
3440 GC_ASSERT(slot_bits > 0);
3441
3442 do {
3443 VALUE vp = (VALUE)p;
3444 GC_ASSERT(vp % BASE_SLOT_SIZE == 0);
3445
3446 rb_asan_unpoison_object(vp, false);
3447 if (bitset & 1) {
3448 switch (BUILTIN_TYPE(vp)) {
3449 default: /* majority case */
3450 gc_report(2, objspace, "page_sweep: free %p\n", (void *)p);
3451#if RGENGC_CHECK_MODE
3452 if (!is_full_marking(objspace)) {
3453 if (RVALUE_OLD_P(objspace, vp)) rb_bug("page_sweep: %p - old while minor GC.", (void *)p);
3454 if (RVALUE_REMEMBERED(objspace, vp)) rb_bug("page_sweep: %p - remembered.", (void *)p);
3455 }
3456#endif
3457
3458 if (RVALUE_WB_UNPROTECTED(objspace, vp)) CLEAR_IN_BITMAP(GET_HEAP_WB_UNPROTECTED_BITS(vp), vp);
3459
3460#if RGENGC_CHECK_MODE
3461#define CHECK(x) if (x(objspace, vp) != FALSE) rb_bug("obj_free: " #x "(%s) != FALSE", rb_obj_info(vp))
3462 CHECK(RVALUE_WB_UNPROTECTED);
3463 CHECK(RVALUE_MARKED);
3464 CHECK(RVALUE_MARKING);
3465 CHECK(RVALUE_UNCOLLECTIBLE);
3466#undef CHECK
3467#endif
3468
3469 rb_gc_event_hook(vp, RUBY_INTERNAL_EVENT_FREEOBJ);
3470
3471 rb_gc_obj_free_vm_weak_references(vp);
3472 if (rb_gc_obj_free(objspace, vp)) {
3473 // always add free slots back to the swept pages freelist,
3474 // so that if we're compacting, we can re-use the slots
3475 (void)VALGRIND_MAKE_MEM_UNDEFINED((void*)p, BASE_SLOT_SIZE);
3476 heap_page_add_freeobj(objspace, sweep_page, vp);
3477 gc_report(3, objspace, "page_sweep: %s is added to freelist\n", rb_obj_info(vp));
3478 ctx->freed_slots++;
3479 }
3480 else {
3481 ctx->final_slots++;
3482 }
3483 break;
3484
3485 case T_MOVED:
3486 if (objspace->flags.during_compacting) {
3487 /* The sweep cursor shouldn't have made it to any
3488 * T_MOVED slots while the compact flag is enabled.
3489 * The sweep cursor and compact cursor move in
3490 * opposite directions, and when they meet references will
3491 * get updated and "during_compacting" should get disabled */
3492 rb_bug("T_MOVED shouldn't be seen until compaction is finished");
3493 }
3494 gc_report(3, objspace, "page_sweep: %s is added to freelist\n", rb_obj_info(vp));
3495 ctx->empty_slots++;
3496 heap_page_add_freeobj(objspace, sweep_page, vp);
3497 break;
3498 case T_ZOMBIE:
3499 /* already counted */
3500 break;
3501 case T_NONE:
3502 ctx->empty_slots++; /* already freed */
3503 break;
3504 }
3505 }
3506 p += slot_size;
3507 bitset >>= slot_bits;
3508 } while (bitset);
3509}
3510
3511static inline void
3512gc_sweep_page(rb_objspace_t *objspace, rb_heap_t *heap, struct gc_sweep_context *ctx)
3513{
3514 struct heap_page *sweep_page = ctx->page;
3515 GC_ASSERT(sweep_page->heap == heap);
3516
3517 uintptr_t p;
3518 bits_t *bits, bitset;
3519
3520 gc_report(2, objspace, "page_sweep: start.\n");
3521
3522#if RGENGC_CHECK_MODE
3523 if (!objspace->flags.immediate_sweep) {
3524 GC_ASSERT(sweep_page->flags.before_sweep == TRUE);
3525 }
3526#endif
3527 sweep_page->flags.before_sweep = FALSE;
3528 sweep_page->free_slots = 0;
3529
3530 p = (uintptr_t)sweep_page->start;
3531 bits = sweep_page->mark_bits;
3532
3533 int page_rvalue_count = sweep_page->total_slots * (sweep_page->slot_size / BASE_SLOT_SIZE);
3534 int out_of_range_bits = (NUM_IN_PAGE(p) + page_rvalue_count) % BITS_BITLENGTH;
3535 if (out_of_range_bits != 0) { // sizeof(RVALUE) == 64
3536 bits[BITMAP_INDEX(p) + page_rvalue_count / BITS_BITLENGTH] |= ~(((bits_t)1 << out_of_range_bits) - 1);
3537 }
3538
3539 /* The last bitmap plane may not be used if the last plane does not
3540 * have enough space for the slot_size. In that case, the last plane must
3541 * be skipped since none of the bits will be set. */
3542 int bitmap_plane_count = CEILDIV(NUM_IN_PAGE(p) + page_rvalue_count, BITS_BITLENGTH);
3543 GC_ASSERT(bitmap_plane_count == HEAP_PAGE_BITMAP_LIMIT - 1 ||
3544 bitmap_plane_count == HEAP_PAGE_BITMAP_LIMIT);
3545
3546 // Skip out of range slots at the head of the page
3547 bitset = ~bits[0];
3548 bitset >>= NUM_IN_PAGE(p);
3549 if (bitset) {
3550 gc_sweep_plane(objspace, heap, p, bitset, ctx);
3551 }
3552 p += (BITS_BITLENGTH - NUM_IN_PAGE(p)) * BASE_SLOT_SIZE;
3553
3554 for (int i = 1; i < bitmap_plane_count; i++) {
3555 bitset = ~bits[i];
3556 if (bitset) {
3557 gc_sweep_plane(objspace, heap, p, bitset, ctx);
3558 }
3559 p += BITS_BITLENGTH * BASE_SLOT_SIZE;
3560 }
3561
3562 if (!heap->compact_cursor) {
3563 gc_setup_mark_bits(sweep_page);
3564 }
3565
3566#if GC_PROFILE_MORE_DETAIL
3567 if (gc_prof_enabled(objspace)) {
3568 gc_profile_record *record = gc_prof_record(objspace);
3569 record->removing_objects += ctx->final_slots + ctx->freed_slots;
3570 record->empty_objects += ctx->empty_slots;
3571 }
3572#endif
3573 if (0) fprintf(stderr, "gc_sweep_page(%"PRIdSIZE"): total_slots: %d, freed_slots: %d, empty_slots: %d, final_slots: %d\n",
3574 rb_gc_count(),
3575 sweep_page->total_slots,
3576 ctx->freed_slots, ctx->empty_slots, ctx->final_slots);
3577
3578 sweep_page->free_slots += ctx->freed_slots + ctx->empty_slots;
3579 sweep_page->heap->total_freed_objects += ctx->freed_slots;
3580
3581 if (heap_pages_deferred_final && !finalizing) {
3582 gc_finalize_deferred_register(objspace);
3583 }
3584
3585#if RGENGC_CHECK_MODE
3586 short freelist_len = 0;
3587 asan_unlock_freelist(sweep_page);
3588 struct free_slot *ptr = sweep_page->freelist;
3589 while (ptr) {
3590 freelist_len++;
3591 rb_asan_unpoison_object((VALUE)ptr, false);
3592 struct free_slot *next = ptr->next;
3593 rb_asan_poison_object((VALUE)ptr);
3594 ptr = next;
3595 }
3596 asan_lock_freelist(sweep_page);
3597 if (freelist_len != sweep_page->free_slots) {
3598 rb_bug("inconsistent freelist length: expected %d but was %d", sweep_page->free_slots, freelist_len);
3599 }
3600#endif
3601
3602 gc_report(2, objspace, "page_sweep: end.\n");
3603}
3604
3605static const char *
3606gc_mode_name(enum gc_mode mode)
3607{
3608 switch (mode) {
3609 case gc_mode_none: return "none";
3610 case gc_mode_marking: return "marking";
3611 case gc_mode_sweeping: return "sweeping";
3612 case gc_mode_compacting: return "compacting";
3613 default: rb_bug("gc_mode_name: unknown mode: %d", (int)mode);
3614 }
3615}
3616
3617static void
3618gc_mode_transition(rb_objspace_t *objspace, enum gc_mode mode)
3619{
3620#if RGENGC_CHECK_MODE
3621 enum gc_mode prev_mode = gc_mode(objspace);
3622 switch (prev_mode) {
3623 case gc_mode_none: GC_ASSERT(mode == gc_mode_marking); break;
3624 case gc_mode_marking: GC_ASSERT(mode == gc_mode_sweeping); break;
3625 case gc_mode_sweeping: GC_ASSERT(mode == gc_mode_none || mode == gc_mode_compacting); break;
3626 case gc_mode_compacting: GC_ASSERT(mode == gc_mode_none); break;
3627 }
3628#endif
3629 if (0) fprintf(stderr, "gc_mode_transition: %s->%s\n", gc_mode_name(gc_mode(objspace)), gc_mode_name(mode));
3630 gc_mode_set(objspace, mode);
3631}
3632
3633static void
3634heap_page_freelist_append(struct heap_page *page, struct free_slot *freelist)
3635{
3636 if (freelist) {
3637 asan_unlock_freelist(page);
3638 if (page->freelist) {
3639 struct free_slot *p = page->freelist;
3640 rb_asan_unpoison_object((VALUE)p, false);
3641 while (p->next) {
3642 struct free_slot *prev = p;
3643 p = p->next;
3644 rb_asan_poison_object((VALUE)prev);
3645 rb_asan_unpoison_object((VALUE)p, false);
3646 }
3647 p->next = freelist;
3648 rb_asan_poison_object((VALUE)p);
3649 }
3650 else {
3651 page->freelist = freelist;
3652 }
3653 asan_lock_freelist(page);
3654 }
3655}
3656
3657static void
3658gc_sweep_start_heap(rb_objspace_t *objspace, rb_heap_t *heap)
3659{
3660 heap->sweeping_page = ccan_list_top(&heap->pages, struct heap_page, page_node);
3661 heap->free_pages = NULL;
3662 heap->pooled_pages = NULL;
3663 if (!objspace->flags.immediate_sweep) {
3664 struct heap_page *page = NULL;
3665
3666 ccan_list_for_each(&heap->pages, page, page_node) {
3667 page->flags.before_sweep = TRUE;
3668 }
3669 }
3670}
3671
3672#if defined(__GNUC__) && __GNUC__ == 4 && __GNUC_MINOR__ == 4
3673__attribute__((noinline))
3674#endif
3675
3676#if GC_CAN_COMPILE_COMPACTION
3677static void gc_sort_heap_by_compare_func(rb_objspace_t *objspace, gc_compact_compare_func compare_func);
3678static int compare_pinned_slots(const void *left, const void *right, void *d);
3679#endif
3680
3681static void
3682gc_ractor_newobj_cache_clear(void *c, void *data)
3683{
3684 rb_objspace_t *objspace = rb_gc_get_objspace();
3685 rb_ractor_newobj_cache_t *newobj_cache = c;
3686
3687 newobj_cache->incremental_mark_step_allocated_slots = 0;
3688
3689 for (size_t heap_idx = 0; heap_idx < HEAP_COUNT; heap_idx++) {
3690
3691 rb_ractor_newobj_heap_cache_t *cache = &newobj_cache->heap_caches[heap_idx];
3692
3693 rb_heap_t *heap = &heaps[heap_idx];
3694 RUBY_ATOMIC_SIZE_ADD(heap->total_allocated_objects, cache->allocated_objects_count);
3695 cache->allocated_objects_count = 0;
3696
3697 struct heap_page *page = cache->using_page;
3698 struct free_slot *freelist = cache->freelist;
3699 RUBY_DEBUG_LOG("ractor using_page:%p freelist:%p", (void *)page, (void *)freelist);
3700
3701 heap_page_freelist_append(page, freelist);
3702
3703 cache->using_page = NULL;
3704 cache->freelist = NULL;
3705 }
3706}
3707
3708static void
3709gc_sweep_start(rb_objspace_t *objspace)
3710{
3711 gc_mode_transition(objspace, gc_mode_sweeping);
3712 objspace->rincgc.pooled_slots = 0;
3713
3714#if GC_CAN_COMPILE_COMPACTION
3715 if (objspace->flags.during_compacting) {
3716 gc_sort_heap_by_compare_func(
3717 objspace,
3718 objspace->rcompactor.compare_func ? objspace->rcompactor.compare_func : compare_pinned_slots
3719 );
3720 }
3721#endif
3722
3723 for (int i = 0; i < HEAP_COUNT; i++) {
3724 rb_heap_t *heap = &heaps[i];
3725 gc_sweep_start_heap(objspace, heap);
3726
3727 /* We should call gc_sweep_finish_heap for size pools with no pages. */
3728 if (heap->sweeping_page == NULL) {
3729 GC_ASSERT(heap->total_pages == 0);
3730 GC_ASSERT(heap->total_slots == 0);
3731 gc_sweep_finish_heap(objspace, heap);
3732 }
3733 }
3734
3735 rb_gc_ractor_newobj_cache_foreach(gc_ractor_newobj_cache_clear, NULL);
3736}
3737
3738static void
3739gc_sweep_finish_heap(rb_objspace_t *objspace, rb_heap_t *heap)
3740{
3741 size_t total_slots = heap->total_slots;
3742 size_t swept_slots = heap->freed_slots + heap->empty_slots;
3743
3744 size_t init_slots = gc_params.heap_init_slots[heap - heaps];
3745 size_t min_free_slots = (size_t)(MAX(total_slots, init_slots) * gc_params.heap_free_slots_min_ratio);
3746
3747 if (swept_slots < min_free_slots &&
3748 /* The heap is a growth heap if it freed more slots than had empty slots. */
3749 ((heap->empty_slots == 0 && total_slots > 0) || heap->freed_slots > heap->empty_slots)) {
3750 /* If we don't have enough slots and we have pages on the tomb heap, move
3751 * pages from the tomb heap to the eden heap. This may prevent page
3752 * creation thrashing (frequently allocating and deallocting pages) and
3753 * GC thrashing (running GC more frequently than required). */
3754 struct heap_page *resurrected_page;
3755 while (swept_slots < min_free_slots &&
3756 (resurrected_page = heap_page_resurrect(objspace))) {
3757 heap_add_page(objspace, heap, resurrected_page);
3758 heap_add_freepage(heap, resurrected_page);
3759
3760 swept_slots += resurrected_page->free_slots;
3761 }
3762
3763 if (swept_slots < min_free_slots) {
3764 /* Grow this heap if we are in a major GC or if we haven't run at least
3765 * RVALUE_OLD_AGE minor GC since the last major GC. */
3766 if (is_full_marking(objspace) ||
3767 objspace->profile.count - objspace->rgengc.last_major_gc < RVALUE_OLD_AGE) {
3768 if (objspace->heap_pages.allocatable_slots < min_free_slots) {
3769 heap_allocatable_slots_expand(objspace, heap, swept_slots, heap->total_slots);
3770 }
3771 }
3772 else {
3773 gc_needs_major_flags |= GPR_FLAG_MAJOR_BY_NOFREE;
3774 heap->force_major_gc_count++;
3775 }
3776 }
3777 }
3778}
3779
3780static void
3781gc_sweep_finish(rb_objspace_t *objspace)
3782{
3783 gc_report(1, objspace, "gc_sweep_finish\n");
3784
3785 gc_prof_set_heap_info(objspace);
3786 heap_pages_free_unused_pages(objspace);
3787
3788 for (int i = 0; i < HEAP_COUNT; i++) {
3789 rb_heap_t *heap = &heaps[i];
3790
3791 heap->freed_slots = 0;
3792 heap->empty_slots = 0;
3793
3794 if (!will_be_incremental_marking(objspace)) {
3795 struct heap_page *end_page = heap->free_pages;
3796 if (end_page) {
3797 while (end_page->free_next) end_page = end_page->free_next;
3798 end_page->free_next = heap->pooled_pages;
3799 }
3800 else {
3801 heap->free_pages = heap->pooled_pages;
3802 }
3803 heap->pooled_pages = NULL;
3804 objspace->rincgc.pooled_slots = 0;
3805 }
3806 }
3807
3808 rb_gc_event_hook(0, RUBY_INTERNAL_EVENT_GC_END_SWEEP);
3809 gc_mode_transition(objspace, gc_mode_none);
3810
3811#if RGENGC_CHECK_MODE >= 2
3812 gc_verify_internal_consistency(objspace);
3813#endif
3814}
3815
3816static int
3817gc_sweep_step(rb_objspace_t *objspace, rb_heap_t *heap)
3818{
3819 struct heap_page *sweep_page = heap->sweeping_page;
3820 int swept_slots = 0;
3821 int pooled_slots = 0;
3822
3823 if (sweep_page == NULL) return FALSE;
3824
3825#if GC_ENABLE_LAZY_SWEEP
3826 gc_prof_sweep_timer_start(objspace);
3827#endif
3828
3829 do {
3830 RUBY_DEBUG_LOG("sweep_page:%p", (void *)sweep_page);
3831
3832 struct gc_sweep_context ctx = {
3833 .page = sweep_page,
3834 .final_slots = 0,
3835 .freed_slots = 0,
3836 .empty_slots = 0,
3837 };
3838 gc_sweep_page(objspace, heap, &ctx);
3839 int free_slots = ctx.freed_slots + ctx.empty_slots;
3840
3841 heap->sweeping_page = ccan_list_next(&heap->pages, sweep_page, page_node);
3842
3843 if (free_slots == sweep_page->total_slots) {
3844 /* There are no living objects, so move this page to the global empty pages. */
3845 heap_unlink_page(objspace, heap, sweep_page);
3846
3847 sweep_page->start = 0;
3848 sweep_page->total_slots = 0;
3849 sweep_page->slot_size = 0;
3850 sweep_page->heap = NULL;
3851 sweep_page->free_slots = 0;
3852
3853 asan_unlock_freelist(sweep_page);
3854 sweep_page->freelist = NULL;
3855 asan_lock_freelist(sweep_page);
3856
3857 asan_poison_memory_region(sweep_page->body, HEAP_PAGE_SIZE);
3858
3859 objspace->empty_pages_count++;
3860 sweep_page->free_next = objspace->empty_pages;
3861 objspace->empty_pages = sweep_page;
3862 }
3863 else if (free_slots > 0) {
3864 heap->freed_slots += ctx.freed_slots;
3865 heap->empty_slots += ctx.empty_slots;
3866
3867 if (pooled_slots < GC_INCREMENTAL_SWEEP_POOL_SLOT_COUNT) {
3868 heap_add_poolpage(objspace, heap, sweep_page);
3869 pooled_slots += free_slots;
3870 }
3871 else {
3872 heap_add_freepage(heap, sweep_page);
3873 swept_slots += free_slots;
3874 if (swept_slots > GC_INCREMENTAL_SWEEP_SLOT_COUNT) {
3875 break;
3876 }
3877 }
3878 }
3879 else {
3880 sweep_page->free_next = NULL;
3881 }
3882 } while ((sweep_page = heap->sweeping_page));
3883
3884 if (!heap->sweeping_page) {
3885 gc_sweep_finish_heap(objspace, heap);
3886
3887 if (!has_sweeping_pages(objspace)) {
3888 gc_sweep_finish(objspace);
3889 }
3890 }
3891
3892#if GC_ENABLE_LAZY_SWEEP
3893 gc_prof_sweep_timer_stop(objspace);
3894#endif
3895
3896 return heap->free_pages != NULL;
3897}
3898
3899static void
3900gc_sweep_rest(rb_objspace_t *objspace)
3901{
3902 for (int i = 0; i < HEAP_COUNT; i++) {
3903 rb_heap_t *heap = &heaps[i];
3904
3905 while (heap->sweeping_page) {
3906 gc_sweep_step(objspace, heap);
3907 }
3908 }
3909}
3910
3911static void
3912gc_sweep_continue(rb_objspace_t *objspace, rb_heap_t *sweep_heap)
3913{
3914 GC_ASSERT(dont_gc_val() == FALSE || objspace->profile.latest_gc_info & GPR_FLAG_METHOD);
3915 if (!GC_ENABLE_LAZY_SWEEP) return;
3916
3917 gc_sweeping_enter(objspace);
3918
3919 for (int i = 0; i < HEAP_COUNT; i++) {
3920 rb_heap_t *heap = &heaps[i];
3921 if (gc_sweep_step(objspace, heap)) {
3922 GC_ASSERT(heap->free_pages != NULL);
3923 }
3924 else if (heap == sweep_heap) {
3925 if (objspace->empty_pages_count > 0 || objspace->heap_pages.allocatable_slots > 0) {
3926 /* [Bug #21548]
3927 *
3928 * If this heap is the heap we want to sweep, but we weren't able
3929 * to free any slots, but we also either have empty pages or could
3930 * allocate new pages, then we want to preemptively claim a page
3931 * because it's possible that sweeping another heap will call
3932 * gc_sweep_finish_heap, which may use up all of the
3933 * empty/allocatable pages. If other heaps are not finished sweeping
3934 * then we do not finish this GC and we will end up triggering a new
3935 * GC cycle during this GC phase. */
3936 heap_page_allocate_and_initialize(objspace, heap);
3937
3938 GC_ASSERT(heap->free_pages != NULL);
3939 }
3940 else {
3941 /* Not allowed to create a new page so finish sweeping. */
3942 gc_sweep_rest(objspace);
3943 GC_ASSERT(gc_mode(objspace) == gc_mode_none);
3944 break;
3945 }
3946 }
3947 }
3948
3949 gc_sweeping_exit(objspace);
3950}
3951
3952VALUE
3953rb_gc_impl_location(void *objspace_ptr, VALUE value)
3954{
3955 VALUE destination;
3956
3957 asan_unpoisoning_object(value) {
3958 if (BUILTIN_TYPE(value) == T_MOVED) {
3959 destination = (VALUE)RMOVED(value)->destination;
3960 GC_ASSERT(BUILTIN_TYPE(destination) != T_NONE);
3961 }
3962 else {
3963 destination = value;
3964 }
3965 }
3966
3967 return destination;
3968}
3969
3970#if GC_CAN_COMPILE_COMPACTION
3971static void
3972invalidate_moved_plane(rb_objspace_t *objspace, struct heap_page *page, uintptr_t p, bits_t bitset)
3973{
3974 if (bitset) {
3975 do {
3976 if (bitset & 1) {
3977 VALUE forwarding_object = (VALUE)p;
3978 VALUE object;
3979
3980 if (BUILTIN_TYPE(forwarding_object) == T_MOVED) {
3981 GC_ASSERT(RVALUE_PINNED(objspace, forwarding_object));
3982 GC_ASSERT(!RVALUE_MARKED(objspace, forwarding_object));
3983
3984 CLEAR_IN_BITMAP(GET_HEAP_PINNED_BITS(forwarding_object), forwarding_object);
3985
3986 object = rb_gc_impl_location(objspace, forwarding_object);
3987
3988 uint32_t original_shape_id = 0;
3989 if (RB_TYPE_P(object, T_OBJECT)) {
3990 original_shape_id = RMOVED(forwarding_object)->original_shape_id;
3991 }
3992
3993 gc_move(objspace, object, forwarding_object, GET_HEAP_PAGE(object)->slot_size, page->slot_size);
3994 /* forwarding_object is now our actual object, and "object"
3995 * is the free slot for the original page */
3996
3997 if (original_shape_id) {
3998 rb_gc_set_shape(forwarding_object, original_shape_id);
3999 }
4000
4001 struct heap_page *orig_page = GET_HEAP_PAGE(object);
4002 orig_page->free_slots++;
4003 heap_page_add_freeobj(objspace, orig_page, object);
4004
4005 GC_ASSERT(RVALUE_MARKED(objspace, forwarding_object));
4006 GC_ASSERT(BUILTIN_TYPE(forwarding_object) != T_MOVED);
4007 GC_ASSERT(BUILTIN_TYPE(forwarding_object) != T_NONE);
4008 }
4009 }
4010 p += BASE_SLOT_SIZE;
4011 bitset >>= 1;
4012 } while (bitset);
4013 }
4014}
4015
4016static void
4017invalidate_moved_page(rb_objspace_t *objspace, struct heap_page *page)
4018{
4019 int i;
4020 bits_t *mark_bits, *pin_bits;
4021 bits_t bitset;
4022
4023 mark_bits = page->mark_bits;
4024 pin_bits = page->pinned_bits;
4025
4026 uintptr_t p = page->start;
4027
4028 // Skip out of range slots at the head of the page
4029 bitset = pin_bits[0] & ~mark_bits[0];
4030 bitset >>= NUM_IN_PAGE(p);
4031 invalidate_moved_plane(objspace, page, p, bitset);
4032 p += (BITS_BITLENGTH - NUM_IN_PAGE(p)) * BASE_SLOT_SIZE;
4033
4034 for (i=1; i < HEAP_PAGE_BITMAP_LIMIT; i++) {
4035 /* Moved objects are pinned but never marked. We reuse the pin bits
4036 * to indicate there is a moved object in this slot. */
4037 bitset = pin_bits[i] & ~mark_bits[i];
4038
4039 invalidate_moved_plane(objspace, page, p, bitset);
4040 p += BITS_BITLENGTH * BASE_SLOT_SIZE;
4041 }
4042}
4043#endif
4044
4045static void
4046gc_compact_start(rb_objspace_t *objspace)
4047{
4048 struct heap_page *page = NULL;
4049 gc_mode_transition(objspace, gc_mode_compacting);
4050
4051 for (int i = 0; i < HEAP_COUNT; i++) {
4052 rb_heap_t *heap = &heaps[i];
4053 ccan_list_for_each(&heap->pages, page, page_node) {
4054 page->flags.before_sweep = TRUE;
4055 }
4056
4057 heap->compact_cursor = ccan_list_tail(&heap->pages, struct heap_page, page_node);
4058 heap->compact_cursor_index = 0;
4059 }
4060
4061 if (gc_prof_enabled(objspace)) {
4062 gc_profile_record *record = gc_prof_record(objspace);
4063 record->moved_objects = objspace->rcompactor.total_moved;
4064 }
4065
4066 memset(objspace->rcompactor.considered_count_table, 0, T_MASK * sizeof(size_t));
4067 memset(objspace->rcompactor.moved_count_table, 0, T_MASK * sizeof(size_t));
4068 memset(objspace->rcompactor.moved_up_count_table, 0, T_MASK * sizeof(size_t));
4069 memset(objspace->rcompactor.moved_down_count_table, 0, T_MASK * sizeof(size_t));
4070
4071 /* Set up read barrier for pages containing MOVED objects */
4072 install_handlers();
4073}
4074
4075static void gc_sweep_compact(rb_objspace_t *objspace);
4076
4077static void
4078gc_sweep(rb_objspace_t *objspace)
4079{
4080 gc_sweeping_enter(objspace);
4081
4082 const unsigned int immediate_sweep = objspace->flags.immediate_sweep;
4083
4084 gc_report(1, objspace, "gc_sweep: immediate: %d\n", immediate_sweep);
4085
4086 gc_sweep_start(objspace);
4087 if (objspace->flags.during_compacting) {
4088 gc_sweep_compact(objspace);
4089 }
4090
4091 if (immediate_sweep) {
4092#if !GC_ENABLE_LAZY_SWEEP
4093 gc_prof_sweep_timer_start(objspace);
4094#endif
4095 gc_sweep_rest(objspace);
4096#if !GC_ENABLE_LAZY_SWEEP
4097 gc_prof_sweep_timer_stop(objspace);
4098#endif
4099 }
4100 else {
4101
4102 /* Sweep every size pool. */
4103 for (int i = 0; i < HEAP_COUNT; i++) {
4104 rb_heap_t *heap = &heaps[i];
4105 gc_sweep_step(objspace, heap);
4106 }
4107 }
4108
4109 gc_sweeping_exit(objspace);
4110}
4111
4112/* Marking - Marking stack */
4113
4114static stack_chunk_t *
4115stack_chunk_alloc(void)
4116{
4117 stack_chunk_t *res;
4118
4119 res = malloc(sizeof(stack_chunk_t));
4120 if (!res)
4121 rb_memerror();
4122
4123 return res;
4124}
4125
4126static inline int
4127is_mark_stack_empty(mark_stack_t *stack)
4128{
4129 return stack->chunk == NULL;
4130}
4131
4132static size_t
4133mark_stack_size(mark_stack_t *stack)
4134{
4135 size_t size = stack->index;
4136 stack_chunk_t *chunk = stack->chunk ? stack->chunk->next : NULL;
4137
4138 while (chunk) {
4139 size += stack->limit;
4140 chunk = chunk->next;
4141 }
4142 return size;
4143}
4144
4145static void
4146add_stack_chunk_cache(mark_stack_t *stack, stack_chunk_t *chunk)
4147{
4148 chunk->next = stack->cache;
4149 stack->cache = chunk;
4150 stack->cache_size++;
4151}
4152
4153static void
4154shrink_stack_chunk_cache(mark_stack_t *stack)
4155{
4156 stack_chunk_t *chunk;
4157
4158 if (stack->unused_cache_size > (stack->cache_size/2)) {
4159 chunk = stack->cache;
4160 stack->cache = stack->cache->next;
4161 stack->cache_size--;
4162 free(chunk);
4163 }
4164 stack->unused_cache_size = stack->cache_size;
4165}
4166
4167static void
4168push_mark_stack_chunk(mark_stack_t *stack)
4169{
4170 stack_chunk_t *next;
4171
4172 GC_ASSERT(stack->index == stack->limit);
4173
4174 if (stack->cache_size > 0) {
4175 next = stack->cache;
4176 stack->cache = stack->cache->next;
4177 stack->cache_size--;
4178 if (stack->unused_cache_size > stack->cache_size)
4179 stack->unused_cache_size = stack->cache_size;
4180 }
4181 else {
4182 next = stack_chunk_alloc();
4183 }
4184 next->next = stack->chunk;
4185 stack->chunk = next;
4186 stack->index = 0;
4187}
4188
4189static void
4190pop_mark_stack_chunk(mark_stack_t *stack)
4191{
4192 stack_chunk_t *prev;
4193
4194 prev = stack->chunk->next;
4195 GC_ASSERT(stack->index == 0);
4196 add_stack_chunk_cache(stack, stack->chunk);
4197 stack->chunk = prev;
4198 stack->index = stack->limit;
4199}
4200
4201static void
4202mark_stack_chunk_list_free(stack_chunk_t *chunk)
4203{
4204 stack_chunk_t *next = NULL;
4205
4206 while (chunk != NULL) {
4207 next = chunk->next;
4208 free(chunk);
4209 chunk = next;
4210 }
4211}
4212
4213static void
4214free_stack_chunks(mark_stack_t *stack)
4215{
4216 mark_stack_chunk_list_free(stack->chunk);
4217}
4218
4219static void
4220mark_stack_free_cache(mark_stack_t *stack)
4221{
4222 mark_stack_chunk_list_free(stack->cache);
4223 stack->cache_size = 0;
4224 stack->unused_cache_size = 0;
4225}
4226
4227static void
4228push_mark_stack(mark_stack_t *stack, VALUE obj)
4229{
4230 switch (BUILTIN_TYPE(obj)) {
4231 case T_OBJECT:
4232 case T_CLASS:
4233 case T_MODULE:
4234 case T_FLOAT:
4235 case T_STRING:
4236 case T_REGEXP:
4237 case T_ARRAY:
4238 case T_HASH:
4239 case T_STRUCT:
4240 case T_BIGNUM:
4241 case T_FILE:
4242 case T_DATA:
4243 case T_MATCH:
4244 case T_COMPLEX:
4245 case T_RATIONAL:
4246 case T_TRUE:
4247 case T_FALSE:
4248 case T_SYMBOL:
4249 case T_IMEMO:
4250 case T_ICLASS:
4251 if (stack->index == stack->limit) {
4252 push_mark_stack_chunk(stack);
4253 }
4254 stack->chunk->data[stack->index++] = obj;
4255 return;
4256
4257 case T_NONE:
4258 case T_NIL:
4259 case T_FIXNUM:
4260 case T_MOVED:
4261 case T_ZOMBIE:
4262 case T_UNDEF:
4263 case T_MASK:
4264 rb_bug("push_mark_stack() called for broken object");
4265 break;
4266
4267 case T_NODE:
4268 rb_bug("push_mark_stack: unexpected T_NODE object");
4269 break;
4270 }
4271
4272 rb_bug("rb_gc_mark(): unknown data type 0x%x(%p) %s",
4273 BUILTIN_TYPE(obj), (void *)obj,
4274 is_pointer_to_heap((rb_objspace_t *)rb_gc_get_objspace(), (void *)obj) ? "corrupted object" : "non object");
4275}
4276
4277static int
4278pop_mark_stack(mark_stack_t *stack, VALUE *data)
4279{
4280 if (is_mark_stack_empty(stack)) {
4281 return FALSE;
4282 }
4283 if (stack->index == 1) {
4284 *data = stack->chunk->data[--stack->index];
4285 pop_mark_stack_chunk(stack);
4286 }
4287 else {
4288 *data = stack->chunk->data[--stack->index];
4289 }
4290 return TRUE;
4291}
4292
4293static void
4294init_mark_stack(mark_stack_t *stack)
4295{
4296 int i;
4297
4298 MEMZERO(stack, mark_stack_t, 1);
4299 stack->index = stack->limit = STACK_CHUNK_SIZE;
4300
4301 for (i=0; i < 4; i++) {
4302 add_stack_chunk_cache(stack, stack_chunk_alloc());
4303 }
4304 stack->unused_cache_size = stack->cache_size;
4305}
4306
4307/* Marking */
4308
4309static void
4310rgengc_check_relation(rb_objspace_t *objspace, VALUE obj)
4311{
4312 const VALUE old_parent = objspace->rgengc.parent_object;
4313
4314 if (old_parent) { /* parent object is old */
4315 if (RVALUE_WB_UNPROTECTED(objspace, obj) || !RVALUE_OLD_P(objspace, obj)) {
4316 rgengc_remember(objspace, old_parent);
4317 }
4318 }
4319
4320 GC_ASSERT(old_parent == objspace->rgengc.parent_object);
4321}
4322
4323static inline int
4324gc_mark_set(rb_objspace_t *objspace, VALUE obj)
4325{
4326 if (RVALUE_MARKED(objspace, obj)) return 0;
4327 MARK_IN_BITMAP(GET_HEAP_MARK_BITS(obj), obj);
4328 return 1;
4329}
4330
4331static void
4332gc_aging(rb_objspace_t *objspace, VALUE obj)
4333{
4334 /* Disable aging if Major GC's are disabled. This will prevent longish lived
4335 * objects filling up the heap at the expense of marking many more objects.
4336 *
4337 * We should always pre-warm our process when disabling majors, by running
4338 * GC manually several times so that most objects likely to become oldgen
4339 * are already oldgen.
4340 */
4341 if(!gc_config_full_mark_val)
4342 return;
4343
4344 struct heap_page *page = GET_HEAP_PAGE(obj);
4345
4346 GC_ASSERT(RVALUE_MARKING(objspace, obj) == FALSE);
4347 check_rvalue_consistency(objspace, obj);
4348
4349 if (!RVALUE_PAGE_WB_UNPROTECTED(page, obj)) {
4350 if (!RVALUE_OLD_P(objspace, obj)) {
4351 gc_report(3, objspace, "gc_aging: YOUNG: %s\n", rb_obj_info(obj));
4352 RVALUE_AGE_INC(objspace, obj);
4353 }
4354 else if (is_full_marking(objspace)) {
4355 GC_ASSERT(RVALUE_PAGE_UNCOLLECTIBLE(page, obj) == FALSE);
4356 RVALUE_PAGE_OLD_UNCOLLECTIBLE_SET(objspace, page, obj);
4357 }
4358 }
4359 check_rvalue_consistency(objspace, obj);
4360
4361 objspace->marked_slots++;
4362}
4363
4364static void
4365gc_grey(rb_objspace_t *objspace, VALUE obj)
4366{
4367#if RGENGC_CHECK_MODE
4368 if (RVALUE_MARKED(objspace, obj) == FALSE) rb_bug("gc_grey: %s is not marked.", rb_obj_info(obj));
4369 if (RVALUE_MARKING(objspace, obj) == TRUE) rb_bug("gc_grey: %s is marking/remembered.", rb_obj_info(obj));
4370#endif
4371
4372 if (is_incremental_marking(objspace)) {
4373 MARK_IN_BITMAP(GET_HEAP_MARKING_BITS(obj), obj);
4374 }
4375
4376 push_mark_stack(&objspace->mark_stack, obj);
4377}
4378
4379static inline void
4380gc_mark_check_t_none(rb_objspace_t *objspace, VALUE obj)
4381{
4382 if (RB_UNLIKELY(RB_TYPE_P(obj, T_NONE))) {
4383 enum {info_size = 256};
4384 char obj_info_buf[info_size];
4385 rb_raw_obj_info(obj_info_buf, info_size, obj);
4386
4387 char parent_obj_info_buf[info_size];
4388 if (objspace->rgengc.parent_object == Qfalse) {
4389 strlcpy(parent_obj_info_buf, "(none)", info_size);
4390 }
4391 else {
4392 rb_raw_obj_info(parent_obj_info_buf, info_size, objspace->rgengc.parent_object);
4393 }
4394
4395 rb_bug("try to mark T_NONE object (obj: %s, parent: %s)", obj_info_buf, parent_obj_info_buf);
4396 }
4397}
4398
4399static void
4400gc_mark(rb_objspace_t *objspace, VALUE obj)
4401{
4402 GC_ASSERT(during_gc);
4403
4404 rgengc_check_relation(objspace, obj);
4405 if (!gc_mark_set(objspace, obj)) return; /* already marked */
4406
4407 if (0) { // for debug GC marking miss
4408 if (objspace->rgengc.parent_object) {
4409 RUBY_DEBUG_LOG("%p (%s) parent:%p (%s)",
4410 (void *)obj, obj_type_name(obj),
4411 (void *)objspace->rgengc.parent_object, obj_type_name(objspace->rgengc.parent_object));
4412 }
4413 else {
4414 RUBY_DEBUG_LOG("%p (%s)", (void *)obj, obj_type_name(obj));
4415 }
4416 }
4417
4418 gc_mark_check_t_none(objspace, obj);
4419
4420 gc_aging(objspace, obj);
4421 gc_grey(objspace, obj);
4422}
4423
4424static inline void
4425gc_pin(rb_objspace_t *objspace, VALUE obj)
4426{
4427 GC_ASSERT(!SPECIAL_CONST_P(obj));
4428 if (RB_UNLIKELY(objspace->flags.during_compacting)) {
4429 if (RB_LIKELY(during_gc)) {
4430 if (!RVALUE_PINNED(objspace, obj)) {
4431 GC_ASSERT(GET_HEAP_PAGE(obj)->pinned_slots <= GET_HEAP_PAGE(obj)->total_slots);
4432 GET_HEAP_PAGE(obj)->pinned_slots++;
4433 MARK_IN_BITMAP(GET_HEAP_PINNED_BITS(obj), obj);
4434 }
4435 }
4436 }
4437}
4438
4439static inline void
4440gc_mark_and_pin(rb_objspace_t *objspace, VALUE obj)
4441{
4442 gc_pin(objspace, obj);
4443 gc_mark(objspace, obj);
4444}
4445
4446void
4447rb_gc_impl_mark_and_move(void *objspace_ptr, VALUE *ptr)
4448{
4449 rb_objspace_t *objspace = objspace_ptr;
4450
4451 if (RB_UNLIKELY(objspace->flags.during_reference_updating)) {
4452 GC_ASSERT(objspace->flags.during_compacting);
4453 GC_ASSERT(during_gc);
4454
4455 VALUE destination = rb_gc_impl_location(objspace, *ptr);
4456 if (destination != *ptr) {
4457 *ptr = destination;
4458 }
4459 }
4460 else {
4461 gc_mark(objspace, *ptr);
4462 }
4463}
4464
4465void
4466rb_gc_impl_mark(void *objspace_ptr, VALUE obj)
4467{
4468 rb_objspace_t *objspace = objspace_ptr;
4469
4470 gc_mark(objspace, obj);
4471}
4472
4473void
4474rb_gc_impl_mark_and_pin(void *objspace_ptr, VALUE obj)
4475{
4476 rb_objspace_t *objspace = objspace_ptr;
4477
4478 gc_mark_and_pin(objspace, obj);
4479}
4480
4481void
4482rb_gc_impl_mark_maybe(void *objspace_ptr, VALUE obj)
4483{
4484 rb_objspace_t *objspace = objspace_ptr;
4485
4486 (void)VALGRIND_MAKE_MEM_DEFINED(&obj, sizeof(obj));
4487
4488 if (is_pointer_to_heap(objspace, (void *)obj)) {
4489 asan_unpoisoning_object(obj) {
4490 /* Garbage can live on the stack, so do not mark or pin */
4491 switch (BUILTIN_TYPE(obj)) {
4492 case T_ZOMBIE:
4493 case T_NONE:
4494 break;
4495 default:
4496 gc_mark_and_pin(objspace, obj);
4497 break;
4498 }
4499 }
4500 }
4501}
4502
4503void
4504rb_gc_impl_mark_weak(void *objspace_ptr, VALUE *ptr)
4505{
4506 rb_objspace_t *objspace = objspace_ptr;
4507
4508 GC_ASSERT(objspace->rgengc.parent_object == 0 || FL_TEST(objspace->rgengc.parent_object, FL_WB_PROTECTED));
4509
4510 VALUE obj = *ptr;
4511
4512 gc_mark_check_t_none(objspace, obj);
4513
4514 /* If we are in a minor GC and the other object is old, then obj should
4515 * already be marked and cannot be reclaimed in this GC cycle so we don't
4516 * need to add it to the weak references list. */
4517 if (!is_full_marking(objspace) && RVALUE_OLD_P(objspace, obj)) {
4518 GC_ASSERT(RVALUE_MARKED(objspace, obj));
4519 GC_ASSERT(!objspace->flags.during_compacting);
4520
4521 return;
4522 }
4523
4524 rgengc_check_relation(objspace, obj);
4525
4526 rb_darray_append_without_gc(&objspace->weak_references, ptr);
4527
4528 objspace->profile.weak_references_count++;
4529}
4530
4531void
4532rb_gc_impl_remove_weak(void *objspace_ptr, VALUE parent_obj, VALUE *ptr)
4533{
4534 rb_objspace_t *objspace = objspace_ptr;
4535
4536 /* If we're not incremental marking, then the state of the objects can't
4537 * change so we don't need to do anything. */
4538 if (!is_incremental_marking(objspace)) return;
4539 /* If parent_obj has not been marked, then ptr has not yet been marked
4540 * weak, so we don't need to do anything. */
4541 if (!RVALUE_MARKED(objspace, parent_obj)) return;
4542
4543 VALUE **ptr_ptr;
4544 rb_darray_foreach(objspace->weak_references, i, ptr_ptr) {
4545 if (*ptr_ptr == ptr) {
4546 *ptr_ptr = NULL;
4547 break;
4548 }
4549 }
4550}
4551
4552static int
4553pin_value(st_data_t key, st_data_t value, st_data_t data)
4554{
4555 rb_gc_impl_mark_and_pin((void *)data, (VALUE)value);
4556
4557 return ST_CONTINUE;
4558}
4559
4560static void
4561mark_roots(rb_objspace_t *objspace, const char **categoryp)
4562{
4563#define MARK_CHECKPOINT(category) do { \
4564 if (categoryp) *categoryp = category; \
4565} while (0)
4566
4567 MARK_CHECKPOINT("objspace");
4568 objspace->rgengc.parent_object = Qfalse;
4569
4570 if (finalizer_table != NULL) {
4571 st_foreach(finalizer_table, pin_value, (st_data_t)objspace);
4572 }
4573
4574 if (stress_to_class) rb_gc_mark(stress_to_class);
4575
4576 rb_gc_save_machine_context();
4577 rb_gc_mark_roots(objspace, categoryp);
4578}
4579
4580static inline void
4581gc_mark_set_parent(rb_objspace_t *objspace, VALUE obj)
4582{
4583 if (RVALUE_OLD_P(objspace, obj)) {
4584 objspace->rgengc.parent_object = obj;
4585 }
4586 else {
4587 objspace->rgengc.parent_object = Qfalse;
4588 }
4589}
4590
4591static void
4592gc_mark_children(rb_objspace_t *objspace, VALUE obj)
4593{
4594 gc_mark_set_parent(objspace, obj);
4595 rb_gc_mark_children(objspace, obj);
4596}
4597
4602static inline int
4603gc_mark_stacked_objects(rb_objspace_t *objspace, int incremental, size_t count)
4604{
4605 mark_stack_t *mstack = &objspace->mark_stack;
4606 VALUE obj;
4607 size_t marked_slots_at_the_beginning = objspace->marked_slots;
4608 size_t popped_count = 0;
4609
4610 while (pop_mark_stack(mstack, &obj)) {
4611 if (obj == Qundef) continue; /* skip */
4612
4613 if (RGENGC_CHECK_MODE && !RVALUE_MARKED(objspace, obj)) {
4614 rb_bug("gc_mark_stacked_objects: %s is not marked.", rb_obj_info(obj));
4615 }
4616 gc_mark_children(objspace, obj);
4617
4618 if (incremental) {
4619 if (RGENGC_CHECK_MODE && !RVALUE_MARKING(objspace, obj)) {
4620 rb_bug("gc_mark_stacked_objects: incremental, but marking bit is 0");
4621 }
4622 CLEAR_IN_BITMAP(GET_HEAP_MARKING_BITS(obj), obj);
4623 popped_count++;
4624
4625 if (popped_count + (objspace->marked_slots - marked_slots_at_the_beginning) > count) {
4626 break;
4627 }
4628 }
4629 else {
4630 /* just ignore marking bits */
4631 }
4632 }
4633
4634 if (RGENGC_CHECK_MODE >= 3) gc_verify_internal_consistency(objspace);
4635
4636 if (is_mark_stack_empty(mstack)) {
4637 shrink_stack_chunk_cache(mstack);
4638 return TRUE;
4639 }
4640 else {
4641 return FALSE;
4642 }
4643}
4644
4645static int
4646gc_mark_stacked_objects_incremental(rb_objspace_t *objspace, size_t count)
4647{
4648 return gc_mark_stacked_objects(objspace, TRUE, count);
4649}
4650
4651static int
4652gc_mark_stacked_objects_all(rb_objspace_t *objspace)
4653{
4654 return gc_mark_stacked_objects(objspace, FALSE, 0);
4655}
4656
4657#if RGENGC_CHECK_MODE >= 4
4658
4659#define MAKE_ROOTSIG(obj) (((VALUE)(obj) << 1) | 0x01)
4660#define IS_ROOTSIG(obj) ((VALUE)(obj) & 0x01)
4661#define GET_ROOTSIG(obj) ((const char *)((VALUE)(obj) >> 1))
4662
4663struct reflist {
4664 VALUE *list;
4665 int pos;
4666 int size;
4667};
4668
4669static struct reflist *
4670reflist_create(VALUE obj)
4671{
4672 struct reflist *refs = xmalloc(sizeof(struct reflist));
4673 refs->size = 1;
4674 refs->list = ALLOC_N(VALUE, refs->size);
4675 refs->list[0] = obj;
4676 refs->pos = 1;
4677 return refs;
4678}
4679
4680static void
4681reflist_destruct(struct reflist *refs)
4682{
4683 xfree(refs->list);
4684 xfree(refs);
4685}
4686
4687static void
4688reflist_add(struct reflist *refs, VALUE obj)
4689{
4690 if (refs->pos == refs->size) {
4691 refs->size *= 2;
4692 SIZED_REALLOC_N(refs->list, VALUE, refs->size, refs->size/2);
4693 }
4694
4695 refs->list[refs->pos++] = obj;
4696}
4697
4698static void
4699reflist_dump(struct reflist *refs)
4700{
4701 int i;
4702 for (i=0; i<refs->pos; i++) {
4703 VALUE obj = refs->list[i];
4704 if (IS_ROOTSIG(obj)) { /* root */
4705 fprintf(stderr, "<root@%s>", GET_ROOTSIG(obj));
4706 }
4707 else {
4708 fprintf(stderr, "<%s>", rb_obj_info(obj));
4709 }
4710 if (i+1 < refs->pos) fprintf(stderr, ", ");
4711 }
4712}
4713
4714static int
4715reflist_referred_from_machine_context(struct reflist *refs)
4716{
4717 int i;
4718 for (i=0; i<refs->pos; i++) {
4719 VALUE obj = refs->list[i];
4720 if (IS_ROOTSIG(obj) && strcmp(GET_ROOTSIG(obj), "machine_context") == 0) return 1;
4721 }
4722 return 0;
4723}
4724
4725struct allrefs {
4727 /* a -> obj1
4728 * b -> obj1
4729 * c -> obj1
4730 * c -> obj2
4731 * d -> obj3
4732 * #=> {obj1 => [a, b, c], obj2 => [c, d]}
4733 */
4734 struct st_table *references;
4735 const char *category;
4736 VALUE root_obj;
4738};
4739
4740static int
4741allrefs_add(struct allrefs *data, VALUE obj)
4742{
4743 struct reflist *refs;
4744 st_data_t r;
4745
4746 if (st_lookup(data->references, obj, &r)) {
4747 refs = (struct reflist *)r;
4748 reflist_add(refs, data->root_obj);
4749 return 0;
4750 }
4751 else {
4752 refs = reflist_create(data->root_obj);
4753 st_insert(data->references, obj, (st_data_t)refs);
4754 return 1;
4755 }
4756}
4757
4758static void
4759allrefs_i(VALUE obj, void *ptr)
4760{
4761 struct allrefs *data = (struct allrefs *)ptr;
4762
4763 if (allrefs_add(data, obj)) {
4764 push_mark_stack(&data->mark_stack, obj);
4765 }
4766}
4767
4768static void
4769allrefs_roots_i(VALUE obj, void *ptr)
4770{
4771 struct allrefs *data = (struct allrefs *)ptr;
4772 if (strlen(data->category) == 0) rb_bug("!!!");
4773 data->root_obj = MAKE_ROOTSIG(data->category);
4774
4775 if (allrefs_add(data, obj)) {
4776 push_mark_stack(&data->mark_stack, obj);
4777 }
4778}
4779#define PUSH_MARK_FUNC_DATA(v) do { \
4780 struct gc_mark_func_data_struct *prev_mark_func_data = GET_VM()->gc.mark_func_data; \
4781 GET_VM()->gc.mark_func_data = (v);
4782
4783#define POP_MARK_FUNC_DATA() GET_VM()->gc.mark_func_data = prev_mark_func_data;} while (0)
4784
4785static st_table *
4786objspace_allrefs(rb_objspace_t *objspace)
4787{
4788 struct allrefs data;
4789 struct gc_mark_func_data_struct mfd;
4790 VALUE obj;
4791 int prev_dont_gc = dont_gc_val();
4792 dont_gc_on();
4793
4794 data.objspace = objspace;
4795 data.references = st_init_numtable();
4796 init_mark_stack(&data.mark_stack);
4797
4798 mfd.mark_func = allrefs_roots_i;
4799 mfd.data = &data;
4800
4801 /* traverse root objects */
4802 PUSH_MARK_FUNC_DATA(&mfd);
4803 GET_VM()->gc.mark_func_data = &mfd;
4804 mark_roots(objspace, &data.category);
4805 POP_MARK_FUNC_DATA();
4806
4807 /* traverse rest objects reachable from root objects */
4808 while (pop_mark_stack(&data.mark_stack, &obj)) {
4809 rb_objspace_reachable_objects_from(data.root_obj = obj, allrefs_i, &data);
4810 }
4811 free_stack_chunks(&data.mark_stack);
4812
4813 dont_gc_set(prev_dont_gc);
4814 return data.references;
4815}
4816
4817static int
4818objspace_allrefs_destruct_i(st_data_t key, st_data_t value, st_data_t ptr)
4819{
4820 struct reflist *refs = (struct reflist *)value;
4821 reflist_destruct(refs);
4822 return ST_CONTINUE;
4823}
4824
4825static void
4826objspace_allrefs_destruct(struct st_table *refs)
4827{
4828 st_foreach(refs, objspace_allrefs_destruct_i, 0);
4829 st_free_table(refs);
4830}
4831
4832#if RGENGC_CHECK_MODE >= 5
4833static int
4834allrefs_dump_i(st_data_t k, st_data_t v, st_data_t ptr)
4835{
4836 VALUE obj = (VALUE)k;
4837 struct reflist *refs = (struct reflist *)v;
4838 fprintf(stderr, "[allrefs_dump_i] %s <- ", rb_obj_info(obj));
4839 reflist_dump(refs);
4840 fprintf(stderr, "\n");
4841 return ST_CONTINUE;
4842}
4843
4844static void
4845allrefs_dump(rb_objspace_t *objspace)
4846{
4847 VALUE size = objspace->rgengc.allrefs_table->num_entries;
4848 fprintf(stderr, "[all refs] (size: %"PRIuVALUE")\n", size);
4849 st_foreach(objspace->rgengc.allrefs_table, allrefs_dump_i, 0);
4850}
4851#endif
4852
4853static int
4854gc_check_after_marks_i(st_data_t k, st_data_t v, st_data_t ptr)
4855{
4856 VALUE obj = k;
4857 struct reflist *refs = (struct reflist *)v;
4859
4860 /* object should be marked or oldgen */
4861 if (!RVALUE_MARKED(objspace, obj)) {
4862 fprintf(stderr, "gc_check_after_marks_i: %s is not marked and not oldgen.\n", rb_obj_info(obj));
4863 fprintf(stderr, "gc_check_after_marks_i: %p is referred from ", (void *)obj);
4864 reflist_dump(refs);
4865
4866 if (reflist_referred_from_machine_context(refs)) {
4867 fprintf(stderr, " (marked from machine stack).\n");
4868 /* marked from machine context can be false positive */
4869 }
4870 else {
4871 objspace->rgengc.error_count++;
4872 fprintf(stderr, "\n");
4873 }
4874 }
4875 return ST_CONTINUE;
4876}
4877
4878static void
4879gc_marks_check(rb_objspace_t *objspace, st_foreach_callback_func *checker_func, const char *checker_name)
4880{
4881 size_t saved_malloc_increase = objspace->malloc_params.increase;
4882#if RGENGC_ESTIMATE_OLDMALLOC
4883 size_t saved_oldmalloc_increase = objspace->rgengc.oldmalloc_increase;
4884#endif
4885 VALUE already_disabled = rb_objspace_gc_disable(objspace);
4886
4887 objspace->rgengc.allrefs_table = objspace_allrefs(objspace);
4888
4889 if (checker_func) {
4890 st_foreach(objspace->rgengc.allrefs_table, checker_func, (st_data_t)objspace);
4891 }
4892
4893 if (objspace->rgengc.error_count > 0) {
4894#if RGENGC_CHECK_MODE >= 5
4895 allrefs_dump(objspace);
4896#endif
4897 if (checker_name) rb_bug("%s: GC has problem.", checker_name);
4898 }
4899
4900 objspace_allrefs_destruct(objspace->rgengc.allrefs_table);
4901 objspace->rgengc.allrefs_table = 0;
4902
4903 if (already_disabled == Qfalse) rb_objspace_gc_enable(objspace);
4904 objspace->malloc_params.increase = saved_malloc_increase;
4905#if RGENGC_ESTIMATE_OLDMALLOC
4906 objspace->rgengc.oldmalloc_increase = saved_oldmalloc_increase;
4907#endif
4908}
4909#endif /* RGENGC_CHECK_MODE >= 4 */
4910
4913 int err_count;
4914 size_t live_object_count;
4915 size_t zombie_object_count;
4916
4917 VALUE parent;
4918 size_t old_object_count;
4919 size_t remembered_shady_count;
4920};
4921
4922static void
4923check_generation_i(const VALUE child, void *ptr)
4924{
4926 const VALUE parent = data->parent;
4927
4928 if (RGENGC_CHECK_MODE) GC_ASSERT(RVALUE_OLD_P(data->objspace, parent));
4929
4930 if (!RVALUE_OLD_P(data->objspace, child)) {
4931 if (!RVALUE_REMEMBERED(data->objspace, parent) &&
4932 !RVALUE_REMEMBERED(data->objspace, child) &&
4933 !RVALUE_UNCOLLECTIBLE(data->objspace, child)) {
4934 fprintf(stderr, "verify_internal_consistency_reachable_i: WB miss (O->Y) %s -> %s\n", rb_obj_info(parent), rb_obj_info(child));
4935 data->err_count++;
4936 }
4937 }
4938}
4939
4940static void
4941check_color_i(const VALUE child, void *ptr)
4942{
4944 const VALUE parent = data->parent;
4945
4946 if (!RVALUE_WB_UNPROTECTED(data->objspace, parent) && RVALUE_WHITE_P(data->objspace, child)) {
4947 fprintf(stderr, "verify_internal_consistency_reachable_i: WB miss (B->W) - %s -> %s\n",
4948 rb_obj_info(parent), rb_obj_info(child));
4949 data->err_count++;
4950 }
4951}
4952
4953static void
4954check_children_i(const VALUE child, void *ptr)
4955{
4957 if (check_rvalue_consistency_force(data->objspace, child, FALSE) != 0) {
4958 fprintf(stderr, "check_children_i: %s has error (referenced from %s)",
4959 rb_obj_info(child), rb_obj_info(data->parent));
4960
4961 data->err_count++;
4962 }
4963}
4964
4965static int
4966verify_internal_consistency_i(void *page_start, void *page_end, size_t stride,
4968{
4969 VALUE obj;
4970 rb_objspace_t *objspace = data->objspace;
4971
4972 for (obj = (VALUE)page_start; obj != (VALUE)page_end; obj += stride) {
4973 asan_unpoisoning_object(obj) {
4974 if (!rb_gc_impl_garbage_object_p(objspace, obj)) {
4975 /* count objects */
4976 data->live_object_count++;
4977 data->parent = obj;
4978
4979 /* Normally, we don't expect T_MOVED objects to be in the heap.
4980 * But they can stay alive on the stack, */
4981 if (!gc_object_moved_p(objspace, obj)) {
4982 /* moved slots don't have children */
4983 rb_objspace_reachable_objects_from(obj, check_children_i, (void *)data);
4984 }
4985
4986 /* check health of children */
4987 if (RVALUE_OLD_P(objspace, obj)) data->old_object_count++;
4988 if (RVALUE_WB_UNPROTECTED(objspace, obj) && RVALUE_UNCOLLECTIBLE(objspace, obj)) data->remembered_shady_count++;
4989
4990 if (!is_marking(objspace) && RVALUE_OLD_P(objspace, obj)) {
4991 /* reachable objects from an oldgen object should be old or (young with remember) */
4992 data->parent = obj;
4993 rb_objspace_reachable_objects_from(obj, check_generation_i, (void *)data);
4994 }
4995
4996 if (is_incremental_marking(objspace)) {
4997 if (RVALUE_BLACK_P(objspace, obj)) {
4998 /* reachable objects from black objects should be black or grey objects */
4999 data->parent = obj;
5000 rb_objspace_reachable_objects_from(obj, check_color_i, (void *)data);
5001 }
5002 }
5003 }
5004 else {
5005 if (BUILTIN_TYPE(obj) == T_ZOMBIE) {
5006 data->zombie_object_count++;
5007
5008 if ((RBASIC(obj)->flags & ~ZOMBIE_OBJ_KEPT_FLAGS) != T_ZOMBIE) {
5009 fprintf(stderr, "verify_internal_consistency_i: T_ZOMBIE has extra flags set: %s\n",
5010 rb_obj_info(obj));
5011 data->err_count++;
5012 }
5013
5014 if (!!FL_TEST(obj, FL_FINALIZE) != !!st_is_member(finalizer_table, obj)) {
5015 fprintf(stderr, "verify_internal_consistency_i: FL_FINALIZE %s but %s finalizer_table: %s\n",
5016 FL_TEST(obj, FL_FINALIZE) ? "set" : "not set", st_is_member(finalizer_table, obj) ? "in" : "not in",
5017 rb_obj_info(obj));
5018 data->err_count++;
5019 }
5020 }
5021 }
5022 }
5023 }
5024
5025 return 0;
5026}
5027
5028static int
5029gc_verify_heap_page(rb_objspace_t *objspace, struct heap_page *page, VALUE obj)
5030{
5031 unsigned int has_remembered_shady = FALSE;
5032 unsigned int has_remembered_old = FALSE;
5033 int remembered_old_objects = 0;
5034 int free_objects = 0;
5035 int zombie_objects = 0;
5036
5037 short slot_size = page->slot_size;
5038 uintptr_t start = (uintptr_t)page->start;
5039 uintptr_t end = start + page->total_slots * slot_size;
5040
5041 for (uintptr_t ptr = start; ptr < end; ptr += slot_size) {
5042 VALUE val = (VALUE)ptr;
5043 asan_unpoisoning_object(val) {
5044 enum ruby_value_type type = BUILTIN_TYPE(val);
5045
5046 if (type == T_NONE) free_objects++;
5047 if (type == T_ZOMBIE) zombie_objects++;
5048 if (RVALUE_PAGE_UNCOLLECTIBLE(page, val) && RVALUE_PAGE_WB_UNPROTECTED(page, val)) {
5049 has_remembered_shady = TRUE;
5050 }
5051 if (RVALUE_PAGE_MARKING(page, val)) {
5052 has_remembered_old = TRUE;
5053 remembered_old_objects++;
5054 }
5055 }
5056 }
5057
5058 if (!is_incremental_marking(objspace) &&
5059 page->flags.has_remembered_objects == FALSE && has_remembered_old == TRUE) {
5060
5061 for (uintptr_t ptr = start; ptr < end; ptr += slot_size) {
5062 VALUE val = (VALUE)ptr;
5063 if (RVALUE_PAGE_MARKING(page, val)) {
5064 fprintf(stderr, "marking -> %s\n", rb_obj_info(val));
5065 }
5066 }
5067 rb_bug("page %p's has_remembered_objects should be false, but there are remembered old objects (%d). %s",
5068 (void *)page, remembered_old_objects, obj ? rb_obj_info(obj) : "");
5069 }
5070
5071 if (page->flags.has_uncollectible_wb_unprotected_objects == FALSE && has_remembered_shady == TRUE) {
5072 rb_bug("page %p's has_remembered_shady should be false, but there are remembered shady objects. %s",
5073 (void *)page, obj ? rb_obj_info(obj) : "");
5074 }
5075
5076 if (0) {
5077 /* free_slots may not equal to free_objects */
5078 if (page->free_slots != free_objects) {
5079 rb_bug("page %p's free_slots should be %d, but %d", (void *)page, page->free_slots, free_objects);
5080 }
5081 }
5082 if (page->final_slots != zombie_objects) {
5083 rb_bug("page %p's final_slots should be %d, but %d", (void *)page, page->final_slots, zombie_objects);
5084 }
5085
5086 return remembered_old_objects;
5087}
5088
5089static int
5090gc_verify_heap_pages_(rb_objspace_t *objspace, struct ccan_list_head *head)
5091{
5092 int remembered_old_objects = 0;
5093 struct heap_page *page = 0;
5094
5095 ccan_list_for_each(head, page, page_node) {
5096 asan_unlock_freelist(page);
5097 struct free_slot *p = page->freelist;
5098 while (p) {
5099 VALUE vp = (VALUE)p;
5100 VALUE prev = vp;
5101 rb_asan_unpoison_object(vp, false);
5102 if (BUILTIN_TYPE(vp) != T_NONE) {
5103 fprintf(stderr, "freelist slot expected to be T_NONE but was: %s\n", rb_obj_info(vp));
5104 }
5105 p = p->next;
5106 rb_asan_poison_object(prev);
5107 }
5108 asan_lock_freelist(page);
5109
5110 if (page->flags.has_remembered_objects == FALSE) {
5111 remembered_old_objects += gc_verify_heap_page(objspace, page, Qfalse);
5112 }
5113 }
5114
5115 return remembered_old_objects;
5116}
5117
5118static int
5119gc_verify_heap_pages(rb_objspace_t *objspace)
5120{
5121 int remembered_old_objects = 0;
5122 for (int i = 0; i < HEAP_COUNT; i++) {
5123 remembered_old_objects += gc_verify_heap_pages_(objspace, &((&heaps[i])->pages));
5124 }
5125 return remembered_old_objects;
5126}
5127
5128static void
5129gc_verify_internal_consistency_(rb_objspace_t *objspace)
5130{
5131 struct verify_internal_consistency_struct data = {0};
5132
5133 data.objspace = objspace;
5134 gc_report(5, objspace, "gc_verify_internal_consistency: start\n");
5135
5136 /* check relations */
5137 for (size_t i = 0; i < rb_darray_size(objspace->heap_pages.sorted); i++) {
5138 struct heap_page *page = rb_darray_get(objspace->heap_pages.sorted, i);
5139 short slot_size = page->slot_size;
5140
5141 uintptr_t start = (uintptr_t)page->start;
5142 uintptr_t end = start + page->total_slots * slot_size;
5143
5144 verify_internal_consistency_i((void *)start, (void *)end, slot_size, &data);
5145 }
5146
5147 if (data.err_count != 0) {
5148#if RGENGC_CHECK_MODE >= 5
5149 objspace->rgengc.error_count = data.err_count;
5150 gc_marks_check(objspace, NULL, NULL);
5151 allrefs_dump(objspace);
5152#endif
5153 rb_bug("gc_verify_internal_consistency: found internal inconsistency.");
5154 }
5155
5156 /* check heap_page status */
5157 gc_verify_heap_pages(objspace);
5158
5159 /* check counters */
5160
5161 if (!is_lazy_sweeping(objspace) &&
5162 !finalizing &&
5163 !rb_gc_multi_ractor_p()) {
5164 if (objspace_live_slots(objspace) != data.live_object_count) {
5165 fprintf(stderr, "heap_pages_final_slots: %"PRIdSIZE", total_freed_objects: %"PRIdSIZE"\n",
5166 total_final_slots_count(objspace), total_freed_objects(objspace));
5167 rb_bug("inconsistent live slot number: expect %"PRIuSIZE", but %"PRIuSIZE".",
5168 objspace_live_slots(objspace), data.live_object_count);
5169 }
5170 }
5171
5172 if (!is_marking(objspace)) {
5173 if (objspace->rgengc.old_objects != data.old_object_count) {
5174 rb_bug("inconsistent old slot number: expect %"PRIuSIZE", but %"PRIuSIZE".",
5175 objspace->rgengc.old_objects, data.old_object_count);
5176 }
5177 if (objspace->rgengc.uncollectible_wb_unprotected_objects != data.remembered_shady_count) {
5178 rb_bug("inconsistent number of wb unprotected objects: expect %"PRIuSIZE", but %"PRIuSIZE".",
5179 objspace->rgengc.uncollectible_wb_unprotected_objects, data.remembered_shady_count);
5180 }
5181 }
5182
5183 if (!finalizing) {
5184 size_t list_count = 0;
5185
5186 {
5187 VALUE z = heap_pages_deferred_final;
5188 while (z) {
5189 list_count++;
5190 z = RZOMBIE(z)->next;
5191 }
5192 }
5193
5194 if (total_final_slots_count(objspace) != data.zombie_object_count ||
5195 total_final_slots_count(objspace) != list_count) {
5196
5197 rb_bug("inconsistent finalizing object count:\n"
5198 " expect %"PRIuSIZE"\n"
5199 " but %"PRIuSIZE" zombies\n"
5200 " heap_pages_deferred_final list has %"PRIuSIZE" items.",
5201 total_final_slots_count(objspace),
5202 data.zombie_object_count,
5203 list_count);
5204 }
5205 }
5206
5207 gc_report(5, objspace, "gc_verify_internal_consistency: OK\n");
5208}
5209
5210static void
5211gc_verify_internal_consistency(void *objspace_ptr)
5212{
5213 rb_objspace_t *objspace = objspace_ptr;
5214
5215 unsigned int lev = RB_GC_VM_LOCK();
5216 {
5217 rb_gc_vm_barrier(); // stop other ractors
5218
5219 unsigned int prev_during_gc = during_gc;
5220 during_gc = FALSE; // stop gc here
5221 {
5222 gc_verify_internal_consistency_(objspace);
5223 }
5224 during_gc = prev_during_gc;
5225 }
5226 RB_GC_VM_UNLOCK(lev);
5227}
5228
5229static void
5230heap_move_pooled_pages_to_free_pages(rb_heap_t *heap)
5231{
5232 if (heap->pooled_pages) {
5233 if (heap->free_pages) {
5234 struct heap_page *free_pages_tail = heap->free_pages;
5235 while (free_pages_tail->free_next) {
5236 free_pages_tail = free_pages_tail->free_next;
5237 }
5238 free_pages_tail->free_next = heap->pooled_pages;
5239 }
5240 else {
5241 heap->free_pages = heap->pooled_pages;
5242 }
5243
5244 heap->pooled_pages = NULL;
5245 }
5246}
5247
5248static int
5249gc_remember_unprotected(rb_objspace_t *objspace, VALUE obj)
5250{
5251 struct heap_page *page = GET_HEAP_PAGE(obj);
5252 bits_t *uncollectible_bits = &page->uncollectible_bits[0];
5253
5254 if (!MARKED_IN_BITMAP(uncollectible_bits, obj)) {
5255 page->flags.has_uncollectible_wb_unprotected_objects = TRUE;
5256 MARK_IN_BITMAP(uncollectible_bits, obj);
5257 objspace->rgengc.uncollectible_wb_unprotected_objects++;
5258
5259#if RGENGC_PROFILE > 0
5260 objspace->profile.total_remembered_shady_object_count++;
5261#if RGENGC_PROFILE >= 2
5262 objspace->profile.remembered_shady_object_count_types[BUILTIN_TYPE(obj)]++;
5263#endif
5264#endif
5265 return TRUE;
5266 }
5267 else {
5268 return FALSE;
5269 }
5270}
5271
5272static inline void
5273gc_marks_wb_unprotected_objects_plane(rb_objspace_t *objspace, uintptr_t p, bits_t bits)
5274{
5275 if (bits) {
5276 do {
5277 if (bits & 1) {
5278 gc_report(2, objspace, "gc_marks_wb_unprotected_objects: marked shady: %s\n", rb_obj_info((VALUE)p));
5279 GC_ASSERT(RVALUE_WB_UNPROTECTED(objspace, (VALUE)p));
5280 GC_ASSERT(RVALUE_MARKED(objspace, (VALUE)p));
5281 gc_mark_children(objspace, (VALUE)p);
5282 }
5283 p += BASE_SLOT_SIZE;
5284 bits >>= 1;
5285 } while (bits);
5286 }
5287}
5288
5289static void
5290gc_marks_wb_unprotected_objects(rb_objspace_t *objspace, rb_heap_t *heap)
5291{
5292 struct heap_page *page = 0;
5293
5294 ccan_list_for_each(&heap->pages, page, page_node) {
5295 bits_t *mark_bits = page->mark_bits;
5296 bits_t *wbun_bits = page->wb_unprotected_bits;
5297 uintptr_t p = page->start;
5298 size_t j;
5299
5300 bits_t bits = mark_bits[0] & wbun_bits[0];
5301 bits >>= NUM_IN_PAGE(p);
5302 gc_marks_wb_unprotected_objects_plane(objspace, p, bits);
5303 p += (BITS_BITLENGTH - NUM_IN_PAGE(p)) * BASE_SLOT_SIZE;
5304
5305 for (j=1; j<HEAP_PAGE_BITMAP_LIMIT; j++) {
5306 bits_t bits = mark_bits[j] & wbun_bits[j];
5307
5308 gc_marks_wb_unprotected_objects_plane(objspace, p, bits);
5309 p += BITS_BITLENGTH * BASE_SLOT_SIZE;
5310 }
5311 }
5312
5313 gc_mark_stacked_objects_all(objspace);
5314}
5315
5316static void
5317gc_update_weak_references(rb_objspace_t *objspace)
5318{
5319 size_t retained_weak_references_count = 0;
5320 VALUE **ptr_ptr;
5321 rb_darray_foreach(objspace->weak_references, i, ptr_ptr) {
5322 if (!*ptr_ptr) continue;
5323
5324 VALUE obj = **ptr_ptr;
5325
5326 if (RB_SPECIAL_CONST_P(obj)) continue;
5327
5328 if (!RVALUE_MARKED(objspace, obj)) {
5329 **ptr_ptr = Qundef;
5330 }
5331 else {
5332 retained_weak_references_count++;
5333 }
5334 }
5335
5336 objspace->profile.retained_weak_references_count = retained_weak_references_count;
5337
5338 rb_darray_clear(objspace->weak_references);
5339 rb_darray_resize_capa_without_gc(&objspace->weak_references, retained_weak_references_count);
5340}
5341
5342static void
5343gc_marks_finish(rb_objspace_t *objspace)
5344{
5345 /* finish incremental GC */
5346 if (is_incremental_marking(objspace)) {
5347 if (RGENGC_CHECK_MODE && is_mark_stack_empty(&objspace->mark_stack) == 0) {
5348 rb_bug("gc_marks_finish: mark stack is not empty (%"PRIdSIZE").",
5349 mark_stack_size(&objspace->mark_stack));
5350 }
5351
5352 mark_roots(objspace, NULL);
5353 while (gc_mark_stacked_objects_incremental(objspace, INT_MAX) == false);
5354
5355#if RGENGC_CHECK_MODE >= 2
5356 if (gc_verify_heap_pages(objspace) != 0) {
5357 rb_bug("gc_marks_finish (incremental): there are remembered old objects.");
5358 }
5359#endif
5360
5361 objspace->flags.during_incremental_marking = FALSE;
5362 /* check children of all marked wb-unprotected objects */
5363 for (int i = 0; i < HEAP_COUNT; i++) {
5364 gc_marks_wb_unprotected_objects(objspace, &heaps[i]);
5365 }
5366 }
5367
5368 gc_update_weak_references(objspace);
5369
5370#if RGENGC_CHECK_MODE >= 2
5371 gc_verify_internal_consistency(objspace);
5372#endif
5373
5374#if RGENGC_CHECK_MODE >= 4
5375 during_gc = FALSE;
5376 gc_marks_check(objspace, gc_check_after_marks_i, "after_marks");
5377 during_gc = TRUE;
5378#endif
5379
5380 {
5381 const unsigned long r_mul = objspace->live_ractor_cache_count > 8 ? 8 : objspace->live_ractor_cache_count; // upto 8
5382
5383 size_t total_slots = objspace_available_slots(objspace);
5384 size_t sweep_slots = total_slots - objspace->marked_slots; /* will be swept slots */
5385 size_t max_free_slots = (size_t)(total_slots * gc_params.heap_free_slots_max_ratio);
5386 size_t min_free_slots = (size_t)(total_slots * gc_params.heap_free_slots_min_ratio);
5387 if (min_free_slots < gc_params.heap_free_slots * r_mul) {
5388 min_free_slots = gc_params.heap_free_slots * r_mul;
5389 }
5390
5391 int full_marking = is_full_marking(objspace);
5392
5393 GC_ASSERT(objspace_available_slots(objspace) >= objspace->marked_slots);
5394
5395 /* Setup freeable slots. */
5396 size_t total_init_slots = 0;
5397 for (int i = 0; i < HEAP_COUNT; i++) {
5398 total_init_slots += gc_params.heap_init_slots[i] * r_mul;
5399 }
5400
5401 if (max_free_slots < total_init_slots) {
5402 max_free_slots = total_init_slots;
5403 }
5404
5405 if (sweep_slots > max_free_slots) {
5406 heap_pages_freeable_pages = (sweep_slots - max_free_slots) / HEAP_PAGE_OBJ_LIMIT;
5407 }
5408 else {
5409 heap_pages_freeable_pages = 0;
5410 }
5411
5412 if (objspace->heap_pages.allocatable_slots == 0 && sweep_slots < min_free_slots) {
5413 if (!full_marking) {
5414 if (objspace->profile.count - objspace->rgengc.last_major_gc < RVALUE_OLD_AGE) {
5415 full_marking = TRUE;
5416 }
5417 else {
5418 gc_report(1, objspace, "gc_marks_finish: next is full GC!!)\n");
5419 gc_needs_major_flags |= GPR_FLAG_MAJOR_BY_NOFREE;
5420 }
5421 }
5422
5423 if (full_marking) {
5424 heap_allocatable_slots_expand(objspace, NULL, sweep_slots, total_slots);
5425 }
5426 }
5427
5428 if (full_marking) {
5429 /* See the comment about RUBY_GC_HEAP_OLDOBJECT_LIMIT_FACTOR */
5430 const double r = gc_params.oldobject_limit_factor;
5431 objspace->rgengc.uncollectible_wb_unprotected_objects_limit = MAX(
5432 (size_t)(objspace->rgengc.uncollectible_wb_unprotected_objects * r),
5433 (size_t)(objspace->rgengc.old_objects * gc_params.uncollectible_wb_unprotected_objects_limit_ratio)
5434 );
5435 objspace->rgengc.old_objects_limit = (size_t)(objspace->rgengc.old_objects * r);
5436 }
5437
5438 if (objspace->rgengc.uncollectible_wb_unprotected_objects > objspace->rgengc.uncollectible_wb_unprotected_objects_limit) {
5439 gc_needs_major_flags |= GPR_FLAG_MAJOR_BY_SHADY;
5440 }
5441 if (objspace->rgengc.old_objects > objspace->rgengc.old_objects_limit) {
5442 gc_needs_major_flags |= GPR_FLAG_MAJOR_BY_OLDGEN;
5443 }
5444
5445 gc_report(1, objspace, "gc_marks_finish (marks %"PRIdSIZE" objects, "
5446 "old %"PRIdSIZE" objects, total %"PRIdSIZE" slots, "
5447 "sweep %"PRIdSIZE" slots, allocatable %"PRIdSIZE" slots, next GC: %s)\n",
5448 objspace->marked_slots, objspace->rgengc.old_objects, objspace_available_slots(objspace), sweep_slots, objspace->heap_pages.allocatable_slots,
5449 gc_needs_major_flags ? "major" : "minor");
5450 }
5451
5452 // TODO: refactor so we don't need to call this
5453 rb_ractor_finish_marking();
5454
5455 rb_gc_event_hook(0, RUBY_INTERNAL_EVENT_GC_END_MARK);
5456}
5457
5458static bool
5459gc_compact_heap_cursors_met_p(rb_heap_t *heap)
5460{
5461 return heap->sweeping_page == heap->compact_cursor;
5462}
5463
5464
5465static rb_heap_t *
5466gc_compact_destination_pool(rb_objspace_t *objspace, rb_heap_t *src_pool, VALUE obj)
5467{
5468 size_t obj_size = rb_gc_obj_optimal_size(obj);
5469 if (obj_size == 0) {
5470 return src_pool;
5471 }
5472
5473 size_t idx = 0;
5474 if (rb_gc_impl_size_allocatable_p(obj_size)) {
5475 idx = heap_idx_for_size(obj_size);
5476 }
5477
5478 return &heaps[idx];
5479}
5480
5481static bool
5482gc_compact_move(rb_objspace_t *objspace, rb_heap_t *heap, VALUE src)
5483{
5484 GC_ASSERT(BUILTIN_TYPE(src) != T_MOVED);
5485 GC_ASSERT(gc_is_moveable_obj(objspace, src));
5486
5487 rb_heap_t *dest_pool = gc_compact_destination_pool(objspace, heap, src);
5488 uint32_t orig_shape = 0;
5489 uint32_t new_shape = 0;
5490
5491 if (gc_compact_heap_cursors_met_p(dest_pool)) {
5492 return dest_pool != heap;
5493 }
5494
5495 if (RB_TYPE_P(src, T_OBJECT)) {
5496 orig_shape = rb_gc_get_shape(src);
5497
5498 if (dest_pool != heap) {
5499 new_shape = rb_gc_rebuild_shape(src, dest_pool - heaps);
5500
5501 if (new_shape == 0) {
5502 dest_pool = heap;
5503 }
5504 }
5505 }
5506
5507 while (!try_move(objspace, dest_pool, dest_pool->free_pages, src)) {
5508 struct gc_sweep_context ctx = {
5509 .page = dest_pool->sweeping_page,
5510 .final_slots = 0,
5511 .freed_slots = 0,
5512 .empty_slots = 0,
5513 };
5514
5515 /* The page of src could be partially compacted, so it may contain
5516 * T_MOVED. Sweeping a page may read objects on this page, so we
5517 * need to lock the page. */
5518 lock_page_body(objspace, GET_PAGE_BODY(src));
5519 gc_sweep_page(objspace, dest_pool, &ctx);
5520 unlock_page_body(objspace, GET_PAGE_BODY(src));
5521
5522 if (dest_pool->sweeping_page->free_slots > 0) {
5523 heap_add_freepage(dest_pool, dest_pool->sweeping_page);
5524 }
5525
5526 dest_pool->sweeping_page = ccan_list_next(&dest_pool->pages, dest_pool->sweeping_page, page_node);
5527 if (gc_compact_heap_cursors_met_p(dest_pool)) {
5528 return dest_pool != heap;
5529 }
5530 }
5531
5532 if (orig_shape != 0) {
5533 if (new_shape != 0) {
5534 VALUE dest = rb_gc_impl_location(objspace, src);
5535 rb_gc_set_shape(dest, new_shape);
5536 }
5537 RMOVED(src)->original_shape_id = orig_shape;
5538 }
5539
5540 return true;
5541}
5542
5543static bool
5544gc_compact_plane(rb_objspace_t *objspace, rb_heap_t *heap, uintptr_t p, bits_t bitset, struct heap_page *page)
5545{
5546 short slot_size = page->slot_size;
5547 short slot_bits = slot_size / BASE_SLOT_SIZE;
5548 GC_ASSERT(slot_bits > 0);
5549
5550 do {
5551 VALUE vp = (VALUE)p;
5552 GC_ASSERT(vp % BASE_SLOT_SIZE == 0);
5553
5554 if (bitset & 1) {
5555 objspace->rcompactor.considered_count_table[BUILTIN_TYPE(vp)]++;
5556
5557 if (gc_is_moveable_obj(objspace, vp)) {
5558 if (!gc_compact_move(objspace, heap, vp)) {
5559 //the cursors met. bubble up
5560 return false;
5561 }
5562 }
5563 }
5564 p += slot_size;
5565 bitset >>= slot_bits;
5566 } while (bitset);
5567
5568 return true;
5569}
5570
5571// Iterate up all the objects in page, moving them to where they want to go
5572static bool
5573gc_compact_page(rb_objspace_t *objspace, rb_heap_t *heap, struct heap_page *page)
5574{
5575 GC_ASSERT(page == heap->compact_cursor);
5576
5577 bits_t *mark_bits, *pin_bits;
5578 bits_t bitset;
5579 uintptr_t p = page->start;
5580
5581 mark_bits = page->mark_bits;
5582 pin_bits = page->pinned_bits;
5583
5584 // objects that can be moved are marked and not pinned
5585 bitset = (mark_bits[0] & ~pin_bits[0]);
5586 bitset >>= NUM_IN_PAGE(p);
5587 if (bitset) {
5588 if (!gc_compact_plane(objspace, heap, (uintptr_t)p, bitset, page))
5589 return false;
5590 }
5591 p += (BITS_BITLENGTH - NUM_IN_PAGE(p)) * BASE_SLOT_SIZE;
5592
5593 for (int j = 1; j < HEAP_PAGE_BITMAP_LIMIT; j++) {
5594 bitset = (mark_bits[j] & ~pin_bits[j]);
5595 if (bitset) {
5596 if (!gc_compact_plane(objspace, heap, (uintptr_t)p, bitset, page))
5597 return false;
5598 }
5599 p += BITS_BITLENGTH * BASE_SLOT_SIZE;
5600 }
5601
5602 return true;
5603}
5604
5605static bool
5606gc_compact_all_compacted_p(rb_objspace_t *objspace)
5607{
5608 for (int i = 0; i < HEAP_COUNT; i++) {
5609 rb_heap_t *heap = &heaps[i];
5610
5611 if (heap->total_pages > 0 &&
5612 !gc_compact_heap_cursors_met_p(heap)) {
5613 return false;
5614 }
5615 }
5616
5617 return true;
5618}
5619
5620static void
5621gc_sweep_compact(rb_objspace_t *objspace)
5622{
5623 gc_compact_start(objspace);
5624#if RGENGC_CHECK_MODE >= 2
5625 gc_verify_internal_consistency(objspace);
5626#endif
5627
5628 while (!gc_compact_all_compacted_p(objspace)) {
5629 for (int i = 0; i < HEAP_COUNT; i++) {
5630 rb_heap_t *heap = &heaps[i];
5631
5632 if (gc_compact_heap_cursors_met_p(heap)) {
5633 continue;
5634 }
5635
5636 struct heap_page *start_page = heap->compact_cursor;
5637
5638 if (!gc_compact_page(objspace, heap, start_page)) {
5639 lock_page_body(objspace, start_page->body);
5640
5641 continue;
5642 }
5643
5644 // If we get here, we've finished moving all objects on the compact_cursor page
5645 // So we can lock it and move the cursor on to the next one.
5646 lock_page_body(objspace, start_page->body);
5647 heap->compact_cursor = ccan_list_prev(&heap->pages, heap->compact_cursor, page_node);
5648 }
5649 }
5650
5651 gc_compact_finish(objspace);
5652
5653#if RGENGC_CHECK_MODE >= 2
5654 gc_verify_internal_consistency(objspace);
5655#endif
5656}
5657
5658static void
5659gc_marks_rest(rb_objspace_t *objspace)
5660{
5661 gc_report(1, objspace, "gc_marks_rest\n");
5662
5663 for (int i = 0; i < HEAP_COUNT; i++) {
5664 (&heaps[i])->pooled_pages = NULL;
5665 }
5666
5667 if (is_incremental_marking(objspace)) {
5668 while (gc_mark_stacked_objects_incremental(objspace, INT_MAX) == FALSE);
5669 }
5670 else {
5671 gc_mark_stacked_objects_all(objspace);
5672 }
5673
5674 gc_marks_finish(objspace);
5675}
5676
5677static bool
5678gc_marks_step(rb_objspace_t *objspace, size_t slots)
5679{
5680 bool marking_finished = false;
5681
5682 GC_ASSERT(is_marking(objspace));
5683 if (gc_mark_stacked_objects_incremental(objspace, slots)) {
5684 gc_marks_finish(objspace);
5685
5686 marking_finished = true;
5687 }
5688
5689 return marking_finished;
5690}
5691
5692static bool
5693gc_marks_continue(rb_objspace_t *objspace, rb_heap_t *heap)
5694{
5695 GC_ASSERT(dont_gc_val() == FALSE || objspace->profile.latest_gc_info & GPR_FLAG_METHOD);
5696 bool marking_finished = true;
5697
5698 gc_marking_enter(objspace);
5699
5700 if (heap->free_pages) {
5701 gc_report(2, objspace, "gc_marks_continue: has pooled pages");
5702
5703 marking_finished = gc_marks_step(objspace, objspace->rincgc.step_slots);
5704 }
5705 else {
5706 gc_report(2, objspace, "gc_marks_continue: no more pooled pages (stack depth: %"PRIdSIZE").\n",
5707 mark_stack_size(&objspace->mark_stack));
5708 heap->force_incremental_marking_finish_count++;
5709 gc_marks_rest(objspace);
5710 }
5711
5712 gc_marking_exit(objspace);
5713
5714 return marking_finished;
5715}
5716
5717static void
5718gc_marks_start(rb_objspace_t *objspace, int full_mark)
5719{
5720 /* start marking */
5721 gc_report(1, objspace, "gc_marks_start: (%s)\n", full_mark ? "full" : "minor");
5722 gc_mode_transition(objspace, gc_mode_marking);
5723
5724 if (full_mark) {
5725 size_t incremental_marking_steps = (objspace->rincgc.pooled_slots / INCREMENTAL_MARK_STEP_ALLOCATIONS) + 1;
5726 objspace->rincgc.step_slots = (objspace->marked_slots * 2) / incremental_marking_steps;
5727
5728 if (0) fprintf(stderr, "objspace->marked_slots: %"PRIdSIZE", "
5729 "objspace->rincgc.pooled_page_num: %"PRIdSIZE", "
5730 "objspace->rincgc.step_slots: %"PRIdSIZE", \n",
5731 objspace->marked_slots, objspace->rincgc.pooled_slots, objspace->rincgc.step_slots);
5732 objspace->flags.during_minor_gc = FALSE;
5733 if (ruby_enable_autocompact) {
5734 objspace->flags.during_compacting |= TRUE;
5735 }
5736 objspace->profile.major_gc_count++;
5737 objspace->rgengc.uncollectible_wb_unprotected_objects = 0;
5738 objspace->rgengc.old_objects = 0;
5739 objspace->rgengc.last_major_gc = objspace->profile.count;
5740 objspace->marked_slots = 0;
5741
5742 for (int i = 0; i < HEAP_COUNT; i++) {
5743 rb_heap_t *heap = &heaps[i];
5744 rgengc_mark_and_rememberset_clear(objspace, heap);
5745 heap_move_pooled_pages_to_free_pages(heap);
5746
5747 if (objspace->flags.during_compacting) {
5748 struct heap_page *page = NULL;
5749
5750 ccan_list_for_each(&heap->pages, page, page_node) {
5751 page->pinned_slots = 0;
5752 }
5753 }
5754 }
5755 }
5756 else {
5757 objspace->flags.during_minor_gc = TRUE;
5758 objspace->marked_slots =
5759 objspace->rgengc.old_objects + objspace->rgengc.uncollectible_wb_unprotected_objects; /* uncollectible objects are marked already */
5760 objspace->profile.minor_gc_count++;
5761
5762 for (int i = 0; i < HEAP_COUNT; i++) {
5763 rgengc_rememberset_mark(objspace, &heaps[i]);
5764 }
5765 }
5766
5767 mark_roots(objspace, NULL);
5768
5769 gc_report(1, objspace, "gc_marks_start: (%s) end, stack in %"PRIdSIZE"\n",
5770 full_mark ? "full" : "minor", mark_stack_size(&objspace->mark_stack));
5771}
5772
5773static bool
5774gc_marks(rb_objspace_t *objspace, int full_mark)
5775{
5776 gc_prof_mark_timer_start(objspace);
5777 gc_marking_enter(objspace);
5778
5779 bool marking_finished = false;
5780
5781 /* setup marking */
5782
5783 gc_marks_start(objspace, full_mark);
5784 if (!is_incremental_marking(objspace)) {
5785 gc_marks_rest(objspace);
5786 marking_finished = true;
5787 }
5788
5789#if RGENGC_PROFILE > 0
5790 if (gc_prof_record(objspace)) {
5791 gc_profile_record *record = gc_prof_record(objspace);
5792 record->old_objects = objspace->rgengc.old_objects;
5793 }
5794#endif
5795
5796 gc_marking_exit(objspace);
5797 gc_prof_mark_timer_stop(objspace);
5798
5799 return marking_finished;
5800}
5801
5802/* RGENGC */
5803
5804static void
5805gc_report_body(int level, rb_objspace_t *objspace, const char *fmt, ...)
5806{
5807 if (level <= RGENGC_DEBUG) {
5808 char buf[1024];
5809 FILE *out = stderr;
5810 va_list args;
5811 const char *status = " ";
5812
5813 if (during_gc) {
5814 status = is_full_marking(objspace) ? "+" : "-";
5815 }
5816 else {
5817 if (is_lazy_sweeping(objspace)) {
5818 status = "S";
5819 }
5820 if (is_incremental_marking(objspace)) {
5821 status = "M";
5822 }
5823 }
5824
5825 va_start(args, fmt);
5826 vsnprintf(buf, 1024, fmt, args);
5827 va_end(args);
5828
5829 fprintf(out, "%s|", status);
5830 fputs(buf, out);
5831 }
5832}
5833
5834/* bit operations */
5835
5836static int
5837rgengc_remembersetbits_set(rb_objspace_t *objspace, VALUE obj)
5838{
5839 struct heap_page *page = GET_HEAP_PAGE(obj);
5840 bits_t *bits = &page->remembered_bits[0];
5841
5842 if (MARKED_IN_BITMAP(bits, obj)) {
5843 return FALSE;
5844 }
5845 else {
5846 page->flags.has_remembered_objects = TRUE;
5847 MARK_IN_BITMAP(bits, obj);
5848 return TRUE;
5849 }
5850}
5851
5852/* wb, etc */
5853
5854/* return FALSE if already remembered */
5855static int
5856rgengc_remember(rb_objspace_t *objspace, VALUE obj)
5857{
5858 gc_report(6, objspace, "rgengc_remember: %s %s\n", rb_obj_info(obj),
5859 RVALUE_REMEMBERED(objspace, obj) ? "was already remembered" : "is remembered now");
5860
5861 check_rvalue_consistency(objspace, obj);
5862
5863 if (RGENGC_CHECK_MODE) {
5864 if (RVALUE_WB_UNPROTECTED(objspace, obj)) rb_bug("rgengc_remember: %s is not wb protected.", rb_obj_info(obj));
5865 }
5866
5867#if RGENGC_PROFILE > 0
5868 if (!RVALUE_REMEMBERED(objspace, obj)) {
5869 if (RVALUE_WB_UNPROTECTED(objspace, obj) == 0) {
5870 objspace->profile.total_remembered_normal_object_count++;
5871#if RGENGC_PROFILE >= 2
5872 objspace->profile.remembered_normal_object_count_types[BUILTIN_TYPE(obj)]++;
5873#endif
5874 }
5875 }
5876#endif /* RGENGC_PROFILE > 0 */
5877
5878 return rgengc_remembersetbits_set(objspace, obj);
5879}
5880
5881#ifndef PROFILE_REMEMBERSET_MARK
5882#define PROFILE_REMEMBERSET_MARK 0
5883#endif
5884
5885static inline void
5886rgengc_rememberset_mark_plane(rb_objspace_t *objspace, uintptr_t p, bits_t bitset)
5887{
5888 if (bitset) {
5889 do {
5890 if (bitset & 1) {
5891 VALUE obj = (VALUE)p;
5892 gc_report(2, objspace, "rgengc_rememberset_mark: mark %s\n", rb_obj_info(obj));
5893 GC_ASSERT(RVALUE_UNCOLLECTIBLE(objspace, obj));
5894 GC_ASSERT(RVALUE_OLD_P(objspace, obj) || RVALUE_WB_UNPROTECTED(objspace, obj));
5895
5896 gc_mark_children(objspace, obj);
5897 }
5898 p += BASE_SLOT_SIZE;
5899 bitset >>= 1;
5900 } while (bitset);
5901 }
5902}
5903
5904static void
5905rgengc_rememberset_mark(rb_objspace_t *objspace, rb_heap_t *heap)
5906{
5907 size_t j;
5908 struct heap_page *page = 0;
5909#if PROFILE_REMEMBERSET_MARK
5910 int has_old = 0, has_shady = 0, has_both = 0, skip = 0;
5911#endif
5912 gc_report(1, objspace, "rgengc_rememberset_mark: start\n");
5913
5914 ccan_list_for_each(&heap->pages, page, page_node) {
5915 if (page->flags.has_remembered_objects | page->flags.has_uncollectible_wb_unprotected_objects) {
5916 uintptr_t p = page->start;
5917 bits_t bitset, bits[HEAP_PAGE_BITMAP_LIMIT];
5918 bits_t *remembered_bits = page->remembered_bits;
5919 bits_t *uncollectible_bits = page->uncollectible_bits;
5920 bits_t *wb_unprotected_bits = page->wb_unprotected_bits;
5921#if PROFILE_REMEMBERSET_MARK
5922 if (page->flags.has_remembered_objects && page->flags.has_uncollectible_wb_unprotected_objects) has_both++;
5923 else if (page->flags.has_remembered_objects) has_old++;
5924 else if (page->flags.has_uncollectible_wb_unprotected_objects) has_shady++;
5925#endif
5926 for (j=0; j<HEAP_PAGE_BITMAP_LIMIT; j++) {
5927 bits[j] = remembered_bits[j] | (uncollectible_bits[j] & wb_unprotected_bits[j]);
5928 remembered_bits[j] = 0;
5929 }
5930 page->flags.has_remembered_objects = FALSE;
5931
5932 bitset = bits[0];
5933 bitset >>= NUM_IN_PAGE(p);
5934 rgengc_rememberset_mark_plane(objspace, p, bitset);
5935 p += (BITS_BITLENGTH - NUM_IN_PAGE(p)) * BASE_SLOT_SIZE;
5936
5937 for (j=1; j < HEAP_PAGE_BITMAP_LIMIT; j++) {
5938 bitset = bits[j];
5939 rgengc_rememberset_mark_plane(objspace, p, bitset);
5940 p += BITS_BITLENGTH * BASE_SLOT_SIZE;
5941 }
5942 }
5943#if PROFILE_REMEMBERSET_MARK
5944 else {
5945 skip++;
5946 }
5947#endif
5948 }
5949
5950#if PROFILE_REMEMBERSET_MARK
5951 fprintf(stderr, "%d\t%d\t%d\t%d\n", has_both, has_old, has_shady, skip);
5952#endif
5953 gc_report(1, objspace, "rgengc_rememberset_mark: finished\n");
5954}
5955
5956static void
5957rgengc_mark_and_rememberset_clear(rb_objspace_t *objspace, rb_heap_t *heap)
5958{
5959 struct heap_page *page = 0;
5960
5961 ccan_list_for_each(&heap->pages, page, page_node) {
5962 memset(&page->mark_bits[0], 0, HEAP_PAGE_BITMAP_SIZE);
5963 memset(&page->uncollectible_bits[0], 0, HEAP_PAGE_BITMAP_SIZE);
5964 memset(&page->marking_bits[0], 0, HEAP_PAGE_BITMAP_SIZE);
5965 memset(&page->remembered_bits[0], 0, HEAP_PAGE_BITMAP_SIZE);
5966 memset(&page->pinned_bits[0], 0, HEAP_PAGE_BITMAP_SIZE);
5967 page->flags.has_uncollectible_wb_unprotected_objects = FALSE;
5968 page->flags.has_remembered_objects = FALSE;
5969 }
5970}
5971
5972/* RGENGC: APIs */
5973
5974NOINLINE(static void gc_writebarrier_generational(VALUE a, VALUE b, rb_objspace_t *objspace));
5975
5976static void
5977gc_writebarrier_generational(VALUE a, VALUE b, rb_objspace_t *objspace)
5978{
5979 if (RGENGC_CHECK_MODE) {
5980 if (!RVALUE_OLD_P(objspace, a)) rb_bug("gc_writebarrier_generational: %s is not an old object.", rb_obj_info(a));
5981 if ( RVALUE_OLD_P(objspace, b)) rb_bug("gc_writebarrier_generational: %s is an old object.", rb_obj_info(b));
5982 if (is_incremental_marking(objspace)) rb_bug("gc_writebarrier_generational: called while incremental marking: %s -> %s", rb_obj_info(a), rb_obj_info(b));
5983 }
5984
5985 /* mark `a' and remember (default behavior) */
5986 if (!RVALUE_REMEMBERED(objspace, a)) {
5987 int lev = RB_GC_VM_LOCK_NO_BARRIER();
5988 {
5989 rgengc_remember(objspace, a);
5990 }
5991 RB_GC_VM_UNLOCK_NO_BARRIER(lev);
5992
5993 gc_report(1, objspace, "gc_writebarrier_generational: %s (remembered) -> %s\n", rb_obj_info(a), rb_obj_info(b));
5994 }
5995
5996 check_rvalue_consistency(objspace, a);
5997 check_rvalue_consistency(objspace, b);
5998}
5999
6000static void
6001gc_mark_from(rb_objspace_t *objspace, VALUE obj, VALUE parent)
6002{
6003 gc_mark_set_parent(objspace, parent);
6004 rgengc_check_relation(objspace, obj);
6005 if (gc_mark_set(objspace, obj) == FALSE) return;
6006 gc_aging(objspace, obj);
6007 gc_grey(objspace, obj);
6008}
6009
6010NOINLINE(static void gc_writebarrier_incremental(VALUE a, VALUE b, rb_objspace_t *objspace));
6011
6012static void
6013gc_writebarrier_incremental(VALUE a, VALUE b, rb_objspace_t *objspace)
6014{
6015 gc_report(2, objspace, "gc_writebarrier_incremental: [LG] %p -> %s\n", (void *)a, rb_obj_info(b));
6016
6017 if (RVALUE_BLACK_P(objspace, a)) {
6018 if (RVALUE_WHITE_P(objspace, b)) {
6019 if (!RVALUE_WB_UNPROTECTED(objspace, a)) {
6020 gc_report(2, objspace, "gc_writebarrier_incremental: [IN] %p -> %s\n", (void *)a, rb_obj_info(b));
6021 gc_mark_from(objspace, b, a);
6022 }
6023 }
6024 else if (RVALUE_OLD_P(objspace, a) && !RVALUE_OLD_P(objspace, b)) {
6025 rgengc_remember(objspace, a);
6026 }
6027
6028 if (RB_UNLIKELY(objspace->flags.during_compacting)) {
6029 MARK_IN_BITMAP(GET_HEAP_PINNED_BITS(b), b);
6030 }
6031 }
6032}
6033
6034void
6035rb_gc_impl_writebarrier(void *objspace_ptr, VALUE a, VALUE b)
6036{
6037 rb_objspace_t *objspace = objspace_ptr;
6038
6039 if (RGENGC_CHECK_MODE) {
6040 if (SPECIAL_CONST_P(a)) rb_bug("rb_gc_writebarrier: a is special const: %"PRIxVALUE, a);
6041 }
6042
6043 if (SPECIAL_CONST_P(b)) return;
6044
6045 GC_ASSERT(RB_BUILTIN_TYPE(a) != T_NONE);
6046 GC_ASSERT(RB_BUILTIN_TYPE(a) != T_MOVED);
6047 GC_ASSERT(RB_BUILTIN_TYPE(a) != T_ZOMBIE);
6048 GC_ASSERT(RB_BUILTIN_TYPE(b) != T_NONE);
6049 GC_ASSERT(RB_BUILTIN_TYPE(b) != T_MOVED);
6050 GC_ASSERT(RB_BUILTIN_TYPE(b) != T_ZOMBIE);
6051
6052 retry:
6053 if (!is_incremental_marking(objspace)) {
6054 if (!RVALUE_OLD_P(objspace, a) || RVALUE_OLD_P(objspace, b)) {
6055 // do nothing
6056 }
6057 else {
6058 gc_writebarrier_generational(a, b, objspace);
6059 }
6060 }
6061 else {
6062 bool retry = false;
6063 /* slow path */
6064 int lev = RB_GC_VM_LOCK_NO_BARRIER();
6065 {
6066 if (is_incremental_marking(objspace)) {
6067 gc_writebarrier_incremental(a, b, objspace);
6068 }
6069 else {
6070 retry = true;
6071 }
6072 }
6073 RB_GC_VM_UNLOCK_NO_BARRIER(lev);
6074
6075 if (retry) goto retry;
6076 }
6077 return;
6078}
6079
6080void
6081rb_gc_impl_writebarrier_unprotect(void *objspace_ptr, VALUE obj)
6082{
6083 rb_objspace_t *objspace = objspace_ptr;
6084
6085 if (RVALUE_WB_UNPROTECTED(objspace, obj)) {
6086 return;
6087 }
6088 else {
6089 gc_report(2, objspace, "rb_gc_writebarrier_unprotect: %s %s\n", rb_obj_info(obj),
6090 RVALUE_REMEMBERED(objspace, obj) ? " (already remembered)" : "");
6091
6092 unsigned int lev = RB_GC_VM_LOCK_NO_BARRIER();
6093 {
6094 if (RVALUE_OLD_P(objspace, obj)) {
6095 gc_report(1, objspace, "rb_gc_writebarrier_unprotect: %s\n", rb_obj_info(obj));
6096 RVALUE_DEMOTE(objspace, obj);
6097 gc_mark_set(objspace, obj);
6098 gc_remember_unprotected(objspace, obj);
6099
6100#if RGENGC_PROFILE
6101 objspace->profile.total_shade_operation_count++;
6102#if RGENGC_PROFILE >= 2
6103 objspace->profile.shade_operation_count_types[BUILTIN_TYPE(obj)]++;
6104#endif /* RGENGC_PROFILE >= 2 */
6105#endif /* RGENGC_PROFILE */
6106 }
6107 else {
6108 RVALUE_AGE_RESET(obj);
6109 }
6110
6111 RB_DEBUG_COUNTER_INC(obj_wb_unprotect);
6112 MARK_IN_BITMAP(GET_HEAP_WB_UNPROTECTED_BITS(obj), obj);
6113 }
6114 RB_GC_VM_UNLOCK_NO_BARRIER(lev);
6115 }
6116}
6117
6118void
6119rb_gc_impl_copy_attributes(void *objspace_ptr, VALUE dest, VALUE obj)
6120{
6121 rb_objspace_t *objspace = objspace_ptr;
6122
6123 if (RVALUE_WB_UNPROTECTED(objspace, obj)) {
6124 rb_gc_impl_writebarrier_unprotect(objspace, dest);
6125 }
6126 rb_gc_impl_copy_finalizer(objspace, dest, obj);
6127}
6128
6129const char *
6130rb_gc_impl_active_gc_name(void)
6131{
6132 return "default";
6133}
6134
6135void
6136rb_gc_impl_writebarrier_remember(void *objspace_ptr, VALUE obj)
6137{
6138 rb_objspace_t *objspace = objspace_ptr;
6139
6140 gc_report(1, objspace, "rb_gc_writebarrier_remember: %s\n", rb_obj_info(obj));
6141
6142 if (is_incremental_marking(objspace) || RVALUE_OLD_P(objspace, obj)) {
6143 int lev = RB_GC_VM_LOCK_NO_BARRIER();
6144 {
6145 if (is_incremental_marking(objspace)) {
6146 if (RVALUE_BLACK_P(objspace, obj)) {
6147 gc_grey(objspace, obj);
6148 }
6149 }
6150 else if (RVALUE_OLD_P(objspace, obj)) {
6151 rgengc_remember(objspace, obj);
6152 }
6153 }
6154 RB_GC_VM_UNLOCK_NO_BARRIER(lev);
6155 }
6156}
6157
6159 // Must be ID only
6160 ID ID_wb_protected, ID_age, ID_old, ID_uncollectible, ID_marking,
6161 ID_marked, ID_pinned, ID_object_id, ID_shareable;
6162};
6163
6164#define RB_GC_OBJECT_METADATA_ENTRY_COUNT (sizeof(struct rb_gc_object_metadata_names) / sizeof(ID))
6165static struct rb_gc_object_metadata_entry object_metadata_entries[RB_GC_OBJECT_METADATA_ENTRY_COUNT + 1];
6166
6168rb_gc_impl_object_metadata(void *objspace_ptr, VALUE obj)
6169{
6170 rb_objspace_t *objspace = objspace_ptr;
6171 size_t n = 0;
6172 static struct rb_gc_object_metadata_names names;
6173
6174 if (!names.ID_marked) {
6175#define I(s) names.ID_##s = rb_intern(#s)
6176 I(wb_protected);
6177 I(age);
6178 I(old);
6179 I(uncollectible);
6180 I(marking);
6181 I(marked);
6182 I(pinned);
6183 I(object_id);
6184 I(shareable);
6185#undef I
6186 }
6187
6188#define SET_ENTRY(na, v) do { \
6189 GC_ASSERT(n <= RB_GC_OBJECT_METADATA_ENTRY_COUNT); \
6190 object_metadata_entries[n].name = names.ID_##na; \
6191 object_metadata_entries[n].val = v; \
6192 n++; \
6193} while (0)
6194
6195 if (!RVALUE_WB_UNPROTECTED(objspace, obj)) SET_ENTRY(wb_protected, Qtrue);
6196 SET_ENTRY(age, INT2FIX(RVALUE_AGE_GET(obj)));
6197 if (RVALUE_OLD_P(objspace, obj)) SET_ENTRY(old, Qtrue);
6198 if (RVALUE_UNCOLLECTIBLE(objspace, obj)) SET_ENTRY(uncollectible, Qtrue);
6199 if (RVALUE_MARKING(objspace, obj)) SET_ENTRY(marking, Qtrue);
6200 if (RVALUE_MARKED(objspace, obj)) SET_ENTRY(marked, Qtrue);
6201 if (RVALUE_PINNED(objspace, obj)) SET_ENTRY(pinned, Qtrue);
6202 if (rb_obj_id_p(obj)) SET_ENTRY(object_id, rb_obj_id(obj));
6203 if (FL_TEST(obj, FL_SHAREABLE)) SET_ENTRY(shareable, Qtrue);
6204
6205 object_metadata_entries[n].name = 0;
6206 object_metadata_entries[n].val = 0;
6207#undef SET_ENTRY
6208
6209 return object_metadata_entries;
6210}
6211
6212void *
6213rb_gc_impl_ractor_cache_alloc(void *objspace_ptr, void *ractor)
6214{
6215 rb_objspace_t *objspace = objspace_ptr;
6216
6217 objspace->live_ractor_cache_count++;
6218
6219 return calloc1(sizeof(rb_ractor_newobj_cache_t));
6220}
6221
6222void
6223rb_gc_impl_ractor_cache_free(void *objspace_ptr, void *cache)
6224{
6225 rb_objspace_t *objspace = objspace_ptr;
6226
6227 objspace->live_ractor_cache_count--;
6228 gc_ractor_newobj_cache_clear(cache, NULL);
6229 free(cache);
6230}
6231
6232static void
6233heap_ready_to_gc(rb_objspace_t *objspace, rb_heap_t *heap)
6234{
6235 if (!heap->free_pages) {
6236 if (!heap_page_allocate_and_initialize(objspace, heap)) {
6237 objspace->heap_pages.allocatable_slots = 1;
6238 heap_page_allocate_and_initialize(objspace, heap);
6239 }
6240 }
6241}
6242
6243static int
6244ready_to_gc(rb_objspace_t *objspace)
6245{
6246 if (dont_gc_val() || during_gc) {
6247 for (int i = 0; i < HEAP_COUNT; i++) {
6248 rb_heap_t *heap = &heaps[i];
6249 heap_ready_to_gc(objspace, heap);
6250 }
6251 return FALSE;
6252 }
6253 else {
6254 return TRUE;
6255 }
6256}
6257
6258static void
6259gc_reset_malloc_info(rb_objspace_t *objspace, bool full_mark)
6260{
6261 gc_prof_set_malloc_info(objspace);
6262 {
6263 size_t inc = RUBY_ATOMIC_SIZE_EXCHANGE(malloc_increase, 0);
6264 size_t old_limit = malloc_limit;
6265
6266 if (inc > malloc_limit) {
6267 malloc_limit = (size_t)(inc * gc_params.malloc_limit_growth_factor);
6268 if (malloc_limit > gc_params.malloc_limit_max) {
6269 malloc_limit = gc_params.malloc_limit_max;
6270 }
6271 }
6272 else {
6273 malloc_limit = (size_t)(malloc_limit * 0.98); /* magic number */
6274 if (malloc_limit < gc_params.malloc_limit_min) {
6275 malloc_limit = gc_params.malloc_limit_min;
6276 }
6277 }
6278
6279 if (0) {
6280 if (old_limit != malloc_limit) {
6281 fprintf(stderr, "[%"PRIuSIZE"] malloc_limit: %"PRIuSIZE" -> %"PRIuSIZE"\n",
6282 rb_gc_count(), old_limit, malloc_limit);
6283 }
6284 else {
6285 fprintf(stderr, "[%"PRIuSIZE"] malloc_limit: not changed (%"PRIuSIZE")\n",
6286 rb_gc_count(), malloc_limit);
6287 }
6288 }
6289 }
6290
6291 /* reset oldmalloc info */
6292#if RGENGC_ESTIMATE_OLDMALLOC
6293 if (!full_mark) {
6294 if (objspace->rgengc.oldmalloc_increase > objspace->rgengc.oldmalloc_increase_limit) {
6295 gc_needs_major_flags |= GPR_FLAG_MAJOR_BY_OLDMALLOC;
6296 objspace->rgengc.oldmalloc_increase_limit =
6297 (size_t)(objspace->rgengc.oldmalloc_increase_limit * gc_params.oldmalloc_limit_growth_factor);
6298
6299 if (objspace->rgengc.oldmalloc_increase_limit > gc_params.oldmalloc_limit_max) {
6300 objspace->rgengc.oldmalloc_increase_limit = gc_params.oldmalloc_limit_max;
6301 }
6302 }
6303
6304 if (0) fprintf(stderr, "%"PRIdSIZE"\t%d\t%"PRIuSIZE"\t%"PRIuSIZE"\t%"PRIdSIZE"\n",
6305 rb_gc_count(),
6306 gc_needs_major_flags,
6307 objspace->rgengc.oldmalloc_increase,
6308 objspace->rgengc.oldmalloc_increase_limit,
6309 gc_params.oldmalloc_limit_max);
6310 }
6311 else {
6312 /* major GC */
6313 objspace->rgengc.oldmalloc_increase = 0;
6314
6315 if ((objspace->profile.latest_gc_info & GPR_FLAG_MAJOR_BY_OLDMALLOC) == 0) {
6316 objspace->rgengc.oldmalloc_increase_limit =
6317 (size_t)(objspace->rgengc.oldmalloc_increase_limit / ((gc_params.oldmalloc_limit_growth_factor - 1)/10 + 1));
6318 if (objspace->rgengc.oldmalloc_increase_limit < gc_params.oldmalloc_limit_min) {
6319 objspace->rgengc.oldmalloc_increase_limit = gc_params.oldmalloc_limit_min;
6320 }
6321 }
6322 }
6323#endif
6324}
6325
6326static int
6327garbage_collect(rb_objspace_t *objspace, unsigned int reason)
6328{
6329 int ret;
6330
6331 int lev = RB_GC_VM_LOCK();
6332 {
6333#if GC_PROFILE_MORE_DETAIL
6334 objspace->profile.prepare_time = getrusage_time();
6335#endif
6336
6337 gc_rest(objspace);
6338
6339#if GC_PROFILE_MORE_DETAIL
6340 objspace->profile.prepare_time = getrusage_time() - objspace->profile.prepare_time;
6341#endif
6342
6343 ret = gc_start(objspace, reason);
6344 }
6345 RB_GC_VM_UNLOCK(lev);
6346
6347 return ret;
6348}
6349
6350static int
6351gc_start(rb_objspace_t *objspace, unsigned int reason)
6352{
6353 unsigned int do_full_mark = !!(reason & GPR_FLAG_FULL_MARK);
6354
6355 if (!rb_darray_size(objspace->heap_pages.sorted)) return TRUE; /* heap is not ready */
6356 if (!(reason & GPR_FLAG_METHOD) && !ready_to_gc(objspace)) return TRUE; /* GC is not allowed */
6357
6358 GC_ASSERT(gc_mode(objspace) == gc_mode_none, "gc_mode is %s\n", gc_mode_name(gc_mode(objspace)));
6359 GC_ASSERT(!is_lazy_sweeping(objspace));
6360 GC_ASSERT(!is_incremental_marking(objspace));
6361
6362 unsigned int lock_lev;
6363 gc_enter(objspace, gc_enter_event_start, &lock_lev);
6364
6365 /* reason may be clobbered, later, so keep set immediate_sweep here */
6366 objspace->flags.immediate_sweep = !!(reason & GPR_FLAG_IMMEDIATE_SWEEP);
6367
6368#if RGENGC_CHECK_MODE >= 2
6369 gc_verify_internal_consistency(objspace);
6370#endif
6371
6372 if (ruby_gc_stressful) {
6373 int flag = FIXNUM_P(ruby_gc_stress_mode) ? FIX2INT(ruby_gc_stress_mode) : 0;
6374
6375 if ((flag & (1 << gc_stress_no_major)) == 0) {
6376 do_full_mark = TRUE;
6377 }
6378
6379 objspace->flags.immediate_sweep = !(flag & (1<<gc_stress_no_immediate_sweep));
6380 }
6381
6382 if (gc_needs_major_flags) {
6383 reason |= gc_needs_major_flags;
6384 do_full_mark = TRUE;
6385 }
6386
6387 /* if major gc has been disabled, never do a full mark */
6388 if (!gc_config_full_mark_val) {
6389 do_full_mark = FALSE;
6390 }
6391 gc_needs_major_flags = GPR_FLAG_NONE;
6392
6393 if (do_full_mark && (reason & GPR_FLAG_MAJOR_MASK) == 0) {
6394 reason |= GPR_FLAG_MAJOR_BY_FORCE; /* GC by CAPI, METHOD, and so on. */
6395 }
6396
6397 if (objspace->flags.dont_incremental ||
6398 reason & GPR_FLAG_IMMEDIATE_MARK ||
6399 ruby_gc_stressful) {
6400 objspace->flags.during_incremental_marking = FALSE;
6401 }
6402 else {
6403 objspace->flags.during_incremental_marking = do_full_mark;
6404 }
6405
6406 /* Explicitly enable compaction (GC.compact) */
6407 if (do_full_mark && ruby_enable_autocompact) {
6408 objspace->flags.during_compacting = TRUE;
6409#if RGENGC_CHECK_MODE
6410 objspace->rcompactor.compare_func = ruby_autocompact_compare_func;
6411#endif
6412 }
6413 else {
6414 objspace->flags.during_compacting = !!(reason & GPR_FLAG_COMPACT);
6415 }
6416
6417 if (!GC_ENABLE_LAZY_SWEEP || objspace->flags.dont_incremental) {
6418 objspace->flags.immediate_sweep = TRUE;
6419 }
6420
6421 if (objspace->flags.immediate_sweep) reason |= GPR_FLAG_IMMEDIATE_SWEEP;
6422
6423 gc_report(1, objspace, "gc_start(reason: %x) => %u, %d, %d\n",
6424 reason,
6425 do_full_mark, !is_incremental_marking(objspace), objspace->flags.immediate_sweep);
6426
6427 RB_DEBUG_COUNTER_INC(gc_count);
6428
6429 if (reason & GPR_FLAG_MAJOR_MASK) {
6430 (void)RB_DEBUG_COUNTER_INC_IF(gc_major_nofree, reason & GPR_FLAG_MAJOR_BY_NOFREE);
6431 (void)RB_DEBUG_COUNTER_INC_IF(gc_major_oldgen, reason & GPR_FLAG_MAJOR_BY_OLDGEN);
6432 (void)RB_DEBUG_COUNTER_INC_IF(gc_major_shady, reason & GPR_FLAG_MAJOR_BY_SHADY);
6433 (void)RB_DEBUG_COUNTER_INC_IF(gc_major_force, reason & GPR_FLAG_MAJOR_BY_FORCE);
6434#if RGENGC_ESTIMATE_OLDMALLOC
6435 (void)RB_DEBUG_COUNTER_INC_IF(gc_major_oldmalloc, reason & GPR_FLAG_MAJOR_BY_OLDMALLOC);
6436#endif
6437 }
6438 else {
6439 (void)RB_DEBUG_COUNTER_INC_IF(gc_minor_newobj, reason & GPR_FLAG_NEWOBJ);
6440 (void)RB_DEBUG_COUNTER_INC_IF(gc_minor_malloc, reason & GPR_FLAG_MALLOC);
6441 (void)RB_DEBUG_COUNTER_INC_IF(gc_minor_method, reason & GPR_FLAG_METHOD);
6442 (void)RB_DEBUG_COUNTER_INC_IF(gc_minor_capi, reason & GPR_FLAG_CAPI);
6443 (void)RB_DEBUG_COUNTER_INC_IF(gc_minor_stress, reason & GPR_FLAG_STRESS);
6444 }
6445
6446 objspace->profile.count++;
6447 objspace->profile.latest_gc_info = reason;
6448 objspace->profile.total_allocated_objects_at_gc_start = total_allocated_objects(objspace);
6449 objspace->profile.heap_used_at_gc_start = rb_darray_size(objspace->heap_pages.sorted);
6450 objspace->profile.weak_references_count = 0;
6451 objspace->profile.retained_weak_references_count = 0;
6452 gc_prof_setup_new_record(objspace, reason);
6453 gc_reset_malloc_info(objspace, do_full_mark);
6454
6455 rb_gc_event_hook(0, RUBY_INTERNAL_EVENT_GC_START);
6456
6457 GC_ASSERT(during_gc);
6458
6459 gc_prof_timer_start(objspace);
6460 {
6461 if (gc_marks(objspace, do_full_mark)) {
6462 gc_sweep(objspace);
6463 }
6464 }
6465 gc_prof_timer_stop(objspace);
6466
6467 gc_exit(objspace, gc_enter_event_start, &lock_lev);
6468 return TRUE;
6469}
6470
6471static void
6472gc_rest(rb_objspace_t *objspace)
6473{
6474 if (is_incremental_marking(objspace) || is_lazy_sweeping(objspace)) {
6475 unsigned int lock_lev;
6476 gc_enter(objspace, gc_enter_event_rest, &lock_lev);
6477
6478 if (RGENGC_CHECK_MODE >= 2) gc_verify_internal_consistency(objspace);
6479
6480 if (is_incremental_marking(objspace)) {
6481 gc_marking_enter(objspace);
6482 gc_marks_rest(objspace);
6483 gc_marking_exit(objspace);
6484
6485 gc_sweep(objspace);
6486 }
6487
6488 if (is_lazy_sweeping(objspace)) {
6489 gc_sweeping_enter(objspace);
6490 gc_sweep_rest(objspace);
6491 gc_sweeping_exit(objspace);
6492 }
6493
6494 gc_exit(objspace, gc_enter_event_rest, &lock_lev);
6495 }
6496}
6497
6500 unsigned int reason;
6501};
6502
6503static void
6504gc_current_status_fill(rb_objspace_t *objspace, char *buff)
6505{
6506 int i = 0;
6507 if (is_marking(objspace)) {
6508 buff[i++] = 'M';
6509 if (is_full_marking(objspace)) buff[i++] = 'F';
6510 if (is_incremental_marking(objspace)) buff[i++] = 'I';
6511 }
6512 else if (is_sweeping(objspace)) {
6513 buff[i++] = 'S';
6514 if (is_lazy_sweeping(objspace)) buff[i++] = 'L';
6515 }
6516 else {
6517 buff[i++] = 'N';
6518 }
6519 buff[i] = '\0';
6520}
6521
6522static const char *
6523gc_current_status(rb_objspace_t *objspace)
6524{
6525 static char buff[0x10];
6526 gc_current_status_fill(objspace, buff);
6527 return buff;
6528}
6529
6530#if PRINT_ENTER_EXIT_TICK
6531
6532static tick_t last_exit_tick;
6533static tick_t enter_tick;
6534static int enter_count = 0;
6535static char last_gc_status[0x10];
6536
6537static inline void
6538gc_record(rb_objspace_t *objspace, int direction, const char *event)
6539{
6540 if (direction == 0) { /* enter */
6541 enter_count++;
6542 enter_tick = tick();
6543 gc_current_status_fill(objspace, last_gc_status);
6544 }
6545 else { /* exit */
6546 tick_t exit_tick = tick();
6547 char current_gc_status[0x10];
6548 gc_current_status_fill(objspace, current_gc_status);
6549#if 1
6550 /* [last mutator time] [gc time] [event] */
6551 fprintf(stderr, "%"PRItick"\t%"PRItick"\t%s\t[%s->%s|%c]\n",
6552 enter_tick - last_exit_tick,
6553 exit_tick - enter_tick,
6554 event,
6555 last_gc_status, current_gc_status,
6556 (objspace->profile.latest_gc_info & GPR_FLAG_MAJOR_MASK) ? '+' : '-');
6557 last_exit_tick = exit_tick;
6558#else
6559 /* [enter_tick] [gc time] [event] */
6560 fprintf(stderr, "%"PRItick"\t%"PRItick"\t%s\t[%s->%s|%c]\n",
6561 enter_tick,
6562 exit_tick - enter_tick,
6563 event,
6564 last_gc_status, current_gc_status,
6565 (objspace->profile.latest_gc_info & GPR_FLAG_MAJOR_MASK) ? '+' : '-');
6566#endif
6567 }
6568}
6569#else /* PRINT_ENTER_EXIT_TICK */
6570static inline void
6571gc_record(rb_objspace_t *objspace, int direction, const char *event)
6572{
6573 /* null */
6574}
6575#endif /* PRINT_ENTER_EXIT_TICK */
6576
6577static const char *
6578gc_enter_event_cstr(enum gc_enter_event event)
6579{
6580 switch (event) {
6581 case gc_enter_event_start: return "start";
6582 case gc_enter_event_continue: return "continue";
6583 case gc_enter_event_rest: return "rest";
6584 case gc_enter_event_finalizer: return "finalizer";
6585 }
6586 return NULL;
6587}
6588
6589static void
6590gc_enter_count(enum gc_enter_event event)
6591{
6592 switch (event) {
6593 case gc_enter_event_start: RB_DEBUG_COUNTER_INC(gc_enter_start); break;
6594 case gc_enter_event_continue: RB_DEBUG_COUNTER_INC(gc_enter_continue); break;
6595 case gc_enter_event_rest: RB_DEBUG_COUNTER_INC(gc_enter_rest); break;
6596 case gc_enter_event_finalizer: RB_DEBUG_COUNTER_INC(gc_enter_finalizer); break;
6597 }
6598}
6599
6600static bool current_process_time(struct timespec *ts);
6601
6602static void
6603gc_clock_start(struct timespec *ts)
6604{
6605 if (!current_process_time(ts)) {
6606 ts->tv_sec = 0;
6607 ts->tv_nsec = 0;
6608 }
6609}
6610
6611static unsigned long long
6612gc_clock_end(struct timespec *ts)
6613{
6614 struct timespec end_time;
6615
6616 if ((ts->tv_sec > 0 || ts->tv_nsec > 0) &&
6617 current_process_time(&end_time) &&
6618 end_time.tv_sec >= ts->tv_sec) {
6619 return (unsigned long long)(end_time.tv_sec - ts->tv_sec) * (1000 * 1000 * 1000) +
6620 (end_time.tv_nsec - ts->tv_nsec);
6621 }
6622
6623 return 0;
6624}
6625
6626static inline void
6627gc_enter(rb_objspace_t *objspace, enum gc_enter_event event, unsigned int *lock_lev)
6628{
6629 *lock_lev = RB_GC_VM_LOCK();
6630
6631 switch (event) {
6632 case gc_enter_event_rest:
6633 if (!is_marking(objspace)) break;
6634 // fall through
6635 case gc_enter_event_start:
6636 case gc_enter_event_continue:
6637 // stop other ractors
6638 rb_gc_vm_barrier();
6639 break;
6640 default:
6641 break;
6642 }
6643
6644 gc_enter_count(event);
6645 if (RB_UNLIKELY(during_gc != 0)) rb_bug("during_gc != 0");
6646 if (RGENGC_CHECK_MODE >= 3) gc_verify_internal_consistency(objspace);
6647
6648 during_gc = TRUE;
6649 RUBY_DEBUG_LOG("%s (%s)",gc_enter_event_cstr(event), gc_current_status(objspace));
6650 gc_report(1, objspace, "gc_enter: %s [%s]\n", gc_enter_event_cstr(event), gc_current_status(objspace));
6651 gc_record(objspace, 0, gc_enter_event_cstr(event));
6652
6653 rb_gc_event_hook(0, RUBY_INTERNAL_EVENT_GC_ENTER);
6654}
6655
6656static inline void
6657gc_exit(rb_objspace_t *objspace, enum gc_enter_event event, unsigned int *lock_lev)
6658{
6659 GC_ASSERT(during_gc != 0);
6660
6661 rb_gc_event_hook(0, RUBY_INTERNAL_EVENT_GC_EXIT);
6662
6663 gc_record(objspace, 1, gc_enter_event_cstr(event));
6664 RUBY_DEBUG_LOG("%s (%s)", gc_enter_event_cstr(event), gc_current_status(objspace));
6665 gc_report(1, objspace, "gc_exit: %s [%s]\n", gc_enter_event_cstr(event), gc_current_status(objspace));
6666 during_gc = FALSE;
6667
6668 RB_GC_VM_UNLOCK(*lock_lev);
6669}
6670
6671#ifndef MEASURE_GC
6672#define MEASURE_GC (objspace->flags.measure_gc)
6673#endif
6674
6675static void
6676gc_marking_enter(rb_objspace_t *objspace)
6677{
6678 GC_ASSERT(during_gc != 0);
6679
6680 if (MEASURE_GC) {
6681 gc_clock_start(&objspace->profile.marking_start_time);
6682 }
6683}
6684
6685static void
6686gc_marking_exit(rb_objspace_t *objspace)
6687{
6688 GC_ASSERT(during_gc != 0);
6689
6690 if (MEASURE_GC) {
6691 objspace->profile.marking_time_ns += gc_clock_end(&objspace->profile.marking_start_time);
6692 }
6693}
6694
6695static void
6696gc_sweeping_enter(rb_objspace_t *objspace)
6697{
6698 GC_ASSERT(during_gc != 0);
6699
6700 if (MEASURE_GC) {
6701 gc_clock_start(&objspace->profile.sweeping_start_time);
6702 }
6703}
6704
6705static void
6706gc_sweeping_exit(rb_objspace_t *objspace)
6707{
6708 GC_ASSERT(during_gc != 0);
6709
6710 if (MEASURE_GC) {
6711 objspace->profile.sweeping_time_ns += gc_clock_end(&objspace->profile.sweeping_start_time);
6712 }
6713}
6714
6715static void *
6716gc_with_gvl(void *ptr)
6717{
6718 struct objspace_and_reason *oar = (struct objspace_and_reason *)ptr;
6719 return (void *)(VALUE)garbage_collect(oar->objspace, oar->reason);
6720}
6721
6722int ruby_thread_has_gvl_p(void);
6723
6724static int
6725garbage_collect_with_gvl(rb_objspace_t *objspace, unsigned int reason)
6726{
6727 if (dont_gc_val()) {
6728 return TRUE;
6729 }
6730 else if (!ruby_native_thread_p()) {
6731 return TRUE;
6732 }
6733 else if (!ruby_thread_has_gvl_p()) {
6734 void *ret;
6735 struct objspace_and_reason oar;
6736 oar.objspace = objspace;
6737 oar.reason = reason;
6738 ret = rb_thread_call_with_gvl(gc_with_gvl, (void *)&oar);
6739
6740 return !!ret;
6741 }
6742 else {
6743 return garbage_collect(objspace, reason);
6744 }
6745}
6746
6747static int
6748gc_set_candidate_object_i(void *vstart, void *vend, size_t stride, void *data)
6749{
6751
6752 VALUE v = (VALUE)vstart;
6753 for (; v != (VALUE)vend; v += stride) {
6754 asan_unpoisoning_object(v) {
6755 switch (BUILTIN_TYPE(v)) {
6756 case T_NONE:
6757 case T_ZOMBIE:
6758 break;
6759 default:
6760 rb_gc_prepare_heap_process_object(v);
6761 if (!RVALUE_OLD_P(objspace, v) && !RVALUE_WB_UNPROTECTED(objspace, v)) {
6762 RVALUE_AGE_SET_CANDIDATE(objspace, v);
6763 }
6764 }
6765 }
6766 }
6767
6768 return 0;
6769}
6770
6771void
6772rb_gc_impl_start(void *objspace_ptr, bool full_mark, bool immediate_mark, bool immediate_sweep, bool compact)
6773{
6774 rb_objspace_t *objspace = objspace_ptr;
6775 unsigned int reason = (GPR_FLAG_FULL_MARK |
6776 GPR_FLAG_IMMEDIATE_MARK |
6777 GPR_FLAG_IMMEDIATE_SWEEP |
6778 GPR_FLAG_METHOD);
6779
6780 int full_marking_p = gc_config_full_mark_val;
6781 gc_config_full_mark_set(TRUE);
6782
6783 /* For now, compact implies full mark / sweep, so ignore other flags */
6784 if (compact) {
6785 GC_ASSERT(GC_COMPACTION_SUPPORTED);
6786
6787 reason |= GPR_FLAG_COMPACT;
6788 }
6789 else {
6790 if (!full_mark) reason &= ~GPR_FLAG_FULL_MARK;
6791 if (!immediate_mark) reason &= ~GPR_FLAG_IMMEDIATE_MARK;
6792 if (!immediate_sweep) reason &= ~GPR_FLAG_IMMEDIATE_SWEEP;
6793 }
6794
6795 garbage_collect(objspace, reason);
6796 gc_finalize_deferred(objspace);
6797
6798 gc_config_full_mark_set(full_marking_p);
6799}
6800
6801void
6802rb_gc_impl_prepare_heap(void *objspace_ptr)
6803{
6804 rb_objspace_t *objspace = objspace_ptr;
6805
6806 size_t orig_total_slots = objspace_available_slots(objspace);
6807 size_t orig_allocatable_slots = objspace->heap_pages.allocatable_slots;
6808
6809 rb_gc_impl_each_objects(objspace, gc_set_candidate_object_i, objspace_ptr);
6810
6811 double orig_max_free_slots = gc_params.heap_free_slots_max_ratio;
6812 /* Ensure that all empty pages are moved onto empty_pages. */
6813 gc_params.heap_free_slots_max_ratio = 0.0;
6814 rb_gc_impl_start(objspace, true, true, true, true);
6815 gc_params.heap_free_slots_max_ratio = orig_max_free_slots;
6816
6817 objspace->heap_pages.allocatable_slots = 0;
6818 heap_pages_freeable_pages = objspace->empty_pages_count;
6819 heap_pages_free_unused_pages(objspace_ptr);
6820 GC_ASSERT(heap_pages_freeable_pages == 0);
6821 GC_ASSERT(objspace->empty_pages_count == 0);
6822 objspace->heap_pages.allocatable_slots = orig_allocatable_slots;
6823
6824 size_t total_slots = objspace_available_slots(objspace);
6825 if (orig_total_slots > total_slots) {
6826 objspace->heap_pages.allocatable_slots += orig_total_slots - total_slots;
6827 }
6828
6829#if defined(HAVE_MALLOC_TRIM) && !defined(RUBY_ALTERNATIVE_MALLOC_HEADER)
6830 malloc_trim(0);
6831#endif
6832}
6833
6834static int
6835gc_is_moveable_obj(rb_objspace_t *objspace, VALUE obj)
6836{
6837 GC_ASSERT(!SPECIAL_CONST_P(obj));
6838
6839 switch (BUILTIN_TYPE(obj)) {
6840 case T_NONE:
6841 case T_MOVED:
6842 case T_ZOMBIE:
6843 return FALSE;
6844 case T_SYMBOL:
6845 // TODO: restore original behavior
6846 // if (RSYMBOL(obj)->id & ~ID_SCOPE_MASK) {
6847 // return FALSE;
6848 // }
6849 return false;
6850 /* fall through */
6851 case T_STRING:
6852 case T_OBJECT:
6853 case T_FLOAT:
6854 case T_IMEMO:
6855 case T_ARRAY:
6856 case T_BIGNUM:
6857 case T_ICLASS:
6858 case T_MODULE:
6859 case T_REGEXP:
6860 case T_DATA:
6861 case T_MATCH:
6862 case T_STRUCT:
6863 case T_HASH:
6864 case T_FILE:
6865 case T_COMPLEX:
6866 case T_RATIONAL:
6867 case T_NODE:
6868 case T_CLASS:
6869 if (FL_TEST_RAW(obj, FL_FINALIZE)) {
6870 /* The finalizer table is a numtable. It looks up objects by address.
6871 * We can't mark the keys in the finalizer table because that would
6872 * prevent the objects from being collected. This check prevents
6873 * objects that are keys in the finalizer table from being moved
6874 * without directly pinning them. */
6875 GC_ASSERT(st_is_member(finalizer_table, obj));
6876
6877 return FALSE;
6878 }
6879 GC_ASSERT(RVALUE_MARKED(objspace, obj));
6880 GC_ASSERT(!RVALUE_PINNED(objspace, obj));
6881
6882 return TRUE;
6883
6884 default:
6885 rb_bug("gc_is_moveable_obj: unreachable (%d)", (int)BUILTIN_TYPE(obj));
6886 break;
6887 }
6888
6889 return FALSE;
6890}
6891
6892void rb_mv_generic_ivar(VALUE src, VALUE dst);
6893
6894static VALUE
6895gc_move(rb_objspace_t *objspace, VALUE src, VALUE dest, size_t src_slot_size, size_t slot_size)
6896{
6897 int marked;
6898 int wb_unprotected;
6899 int uncollectible;
6900 int age;
6901
6902 gc_report(4, objspace, "Moving object: %p -> %p\n", (void *)src, (void *)dest);
6903
6904 GC_ASSERT(BUILTIN_TYPE(src) != T_NONE);
6905 GC_ASSERT(!MARKED_IN_BITMAP(GET_HEAP_MARK_BITS(dest), dest));
6906
6907 GC_ASSERT(!RVALUE_MARKING(objspace, src));
6908
6909 /* Save off bits for current object. */
6910 marked = RVALUE_MARKED(objspace, src);
6911 wb_unprotected = RVALUE_WB_UNPROTECTED(objspace, src);
6912 uncollectible = RVALUE_UNCOLLECTIBLE(objspace, src);
6913 bool remembered = RVALUE_REMEMBERED(objspace, src);
6914 age = RVALUE_AGE_GET(src);
6915
6916 /* Clear bits for eventual T_MOVED */
6917 CLEAR_IN_BITMAP(GET_HEAP_MARK_BITS(src), src);
6918 CLEAR_IN_BITMAP(GET_HEAP_WB_UNPROTECTED_BITS(src), src);
6919 CLEAR_IN_BITMAP(GET_HEAP_UNCOLLECTIBLE_BITS(src), src);
6920 CLEAR_IN_BITMAP(GET_HEAP_PAGE(src)->remembered_bits, src);
6921
6922 /* Move the object */
6923 memcpy((void *)dest, (void *)src, MIN(src_slot_size, slot_size));
6924
6925 if (RVALUE_OVERHEAD > 0) {
6926 void *dest_overhead = (void *)(((uintptr_t)dest) + slot_size - RVALUE_OVERHEAD);
6927 void *src_overhead = (void *)(((uintptr_t)src) + src_slot_size - RVALUE_OVERHEAD);
6928
6929 memcpy(dest_overhead, src_overhead, RVALUE_OVERHEAD);
6930 }
6931
6932 memset((void *)src, 0, src_slot_size);
6933 RVALUE_AGE_RESET(src);
6934
6935 /* Set bits for object in new location */
6936 if (remembered) {
6937 MARK_IN_BITMAP(GET_HEAP_PAGE(dest)->remembered_bits, dest);
6938 }
6939 else {
6940 CLEAR_IN_BITMAP(GET_HEAP_PAGE(dest)->remembered_bits, dest);
6941 }
6942
6943 if (marked) {
6944 MARK_IN_BITMAP(GET_HEAP_MARK_BITS(dest), dest);
6945 }
6946 else {
6947 CLEAR_IN_BITMAP(GET_HEAP_MARK_BITS(dest), dest);
6948 }
6949
6950 if (wb_unprotected) {
6951 MARK_IN_BITMAP(GET_HEAP_WB_UNPROTECTED_BITS(dest), dest);
6952 }
6953 else {
6954 CLEAR_IN_BITMAP(GET_HEAP_WB_UNPROTECTED_BITS(dest), dest);
6955 }
6956
6957 if (uncollectible) {
6958 MARK_IN_BITMAP(GET_HEAP_UNCOLLECTIBLE_BITS(dest), dest);
6959 }
6960 else {
6961 CLEAR_IN_BITMAP(GET_HEAP_UNCOLLECTIBLE_BITS(dest), dest);
6962 }
6963
6964 RVALUE_AGE_SET(dest, age);
6965 /* Assign forwarding address */
6966 RMOVED(src)->flags = T_MOVED;
6967 RMOVED(src)->dummy = Qundef;
6968 RMOVED(src)->destination = dest;
6969 GC_ASSERT(BUILTIN_TYPE(dest) != T_NONE);
6970
6971 GET_HEAP_PAGE(src)->heap->total_freed_objects++;
6972 GET_HEAP_PAGE(dest)->heap->total_allocated_objects++;
6973
6974 return src;
6975}
6976
6977#if GC_CAN_COMPILE_COMPACTION
6978static int
6979compare_pinned_slots(const void *left, const void *right, void *dummy)
6980{
6981 struct heap_page *left_page;
6982 struct heap_page *right_page;
6983
6984 left_page = *(struct heap_page * const *)left;
6985 right_page = *(struct heap_page * const *)right;
6986
6987 return left_page->pinned_slots - right_page->pinned_slots;
6988}
6989
6990static int
6991compare_free_slots(const void *left, const void *right, void *dummy)
6992{
6993 struct heap_page *left_page;
6994 struct heap_page *right_page;
6995
6996 left_page = *(struct heap_page * const *)left;
6997 right_page = *(struct heap_page * const *)right;
6998
6999 return left_page->free_slots - right_page->free_slots;
7000}
7001
7002static void
7003gc_sort_heap_by_compare_func(rb_objspace_t *objspace, gc_compact_compare_func compare_func)
7004{
7005 for (int j = 0; j < HEAP_COUNT; j++) {
7006 rb_heap_t *heap = &heaps[j];
7007
7008 size_t total_pages = heap->total_pages;
7009 size_t size = rb_size_mul_or_raise(total_pages, sizeof(struct heap_page *), rb_eRuntimeError);
7010 struct heap_page *page = 0, **page_list = malloc(size);
7011 size_t i = 0;
7012
7013 heap->free_pages = NULL;
7014 ccan_list_for_each(&heap->pages, page, page_node) {
7015 page_list[i++] = page;
7016 GC_ASSERT(page);
7017 }
7018
7019 GC_ASSERT((size_t)i == total_pages);
7020
7021 /* Sort the heap so "filled pages" are first. `heap_add_page` adds to the
7022 * head of the list, so empty pages will end up at the start of the heap */
7023 ruby_qsort(page_list, total_pages, sizeof(struct heap_page *), compare_func, NULL);
7024
7025 /* Reset the eden heap */
7026 ccan_list_head_init(&heap->pages);
7027
7028 for (i = 0; i < total_pages; i++) {
7029 ccan_list_add(&heap->pages, &page_list[i]->page_node);
7030 if (page_list[i]->free_slots != 0) {
7031 heap_add_freepage(heap, page_list[i]);
7032 }
7033 }
7034
7035 free(page_list);
7036 }
7037}
7038#endif
7039
7040bool
7041rb_gc_impl_object_moved_p(void *objspace_ptr, VALUE obj)
7042{
7043 return gc_object_moved_p(objspace_ptr, obj);
7044}
7045
7046static int
7047gc_ref_update(void *vstart, void *vend, size_t stride, rb_objspace_t *objspace, struct heap_page *page)
7048{
7049 VALUE v = (VALUE)vstart;
7050
7051 page->flags.has_uncollectible_wb_unprotected_objects = FALSE;
7052 page->flags.has_remembered_objects = FALSE;
7053
7054 /* For each object on the page */
7055 for (; v != (VALUE)vend; v += stride) {
7056 asan_unpoisoning_object(v) {
7057 switch (BUILTIN_TYPE(v)) {
7058 case T_NONE:
7059 case T_MOVED:
7060 case T_ZOMBIE:
7061 break;
7062 default:
7063 if (RVALUE_WB_UNPROTECTED(objspace, v)) {
7064 page->flags.has_uncollectible_wb_unprotected_objects = TRUE;
7065 }
7066 if (RVALUE_REMEMBERED(objspace, v)) {
7067 page->flags.has_remembered_objects = TRUE;
7068 }
7069 if (page->flags.before_sweep) {
7070 if (RVALUE_MARKED(objspace, v)) {
7071 rb_gc_update_object_references(objspace, v);
7072 }
7073 }
7074 else {
7075 rb_gc_update_object_references(objspace, v);
7076 }
7077 }
7078 }
7079 }
7080
7081 return 0;
7082}
7083
7084static int
7085gc_update_references_weak_table_i(VALUE obj, void *data)
7086{
7087 int ret;
7088 asan_unpoisoning_object(obj) {
7089 ret = BUILTIN_TYPE(obj) == T_MOVED ? ST_REPLACE : ST_CONTINUE;
7090 }
7091 return ret;
7092}
7093
7094static int
7095gc_update_references_weak_table_replace_i(VALUE *obj, void *data)
7096{
7097 *obj = rb_gc_location(*obj);
7098
7099 return ST_CONTINUE;
7100}
7101
7102static void
7103gc_update_references(rb_objspace_t *objspace)
7104{
7105 objspace->flags.during_reference_updating = true;
7106
7107 rb_gc_before_updating_jit_code();
7108
7109 struct heap_page *page = NULL;
7110
7111 for (int i = 0; i < HEAP_COUNT; i++) {
7112 bool should_set_mark_bits = TRUE;
7113 rb_heap_t *heap = &heaps[i];
7114
7115 ccan_list_for_each(&heap->pages, page, page_node) {
7116 uintptr_t start = (uintptr_t)page->start;
7117 uintptr_t end = start + (page->total_slots * heap->slot_size);
7118
7119 gc_ref_update((void *)start, (void *)end, heap->slot_size, objspace, page);
7120 if (page == heap->sweeping_page) {
7121 should_set_mark_bits = FALSE;
7122 }
7123 if (should_set_mark_bits) {
7124 gc_setup_mark_bits(page);
7125 }
7126 }
7127 }
7128
7129 gc_update_table_refs(finalizer_table);
7130
7131 rb_gc_update_vm_references((void *)objspace);
7132
7133 for (int table = 0; table < RB_GC_VM_WEAK_TABLE_COUNT; table++) {
7134 rb_gc_vm_weak_table_foreach(
7135 gc_update_references_weak_table_i,
7136 gc_update_references_weak_table_replace_i,
7137 NULL,
7138 false,
7139 table
7140 );
7141 }
7142
7143 rb_gc_after_updating_jit_code();
7144
7145 objspace->flags.during_reference_updating = false;
7146}
7147
7148#if GC_CAN_COMPILE_COMPACTION
7149static void
7150root_obj_check_moved_i(const char *category, VALUE obj, void *data)
7151{
7152 rb_objspace_t *objspace = data;
7153
7154 if (gc_object_moved_p(objspace, obj)) {
7155 rb_bug("ROOT %s points to MOVED: %p -> %s", category, (void *)obj, rb_obj_info(rb_gc_impl_location(objspace, obj)));
7156 }
7157}
7158
7159static void
7160reachable_object_check_moved_i(VALUE ref, void *data)
7161{
7162 VALUE parent = (VALUE)data;
7163 if (gc_object_moved_p(rb_gc_get_objspace(), ref)) {
7164 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)));
7165 }
7166}
7167
7168static int
7169heap_check_moved_i(void *vstart, void *vend, size_t stride, void *data)
7170{
7171 rb_objspace_t *objspace = data;
7172
7173 VALUE v = (VALUE)vstart;
7174 for (; v != (VALUE)vend; v += stride) {
7175 if (gc_object_moved_p(objspace, v)) {
7176 /* Moved object still on the heap, something may have a reference. */
7177 }
7178 else {
7179 asan_unpoisoning_object(v) {
7180 switch (BUILTIN_TYPE(v)) {
7181 case T_NONE:
7182 case T_ZOMBIE:
7183 break;
7184 default:
7185 if (!rb_gc_impl_garbage_object_p(objspace, v)) {
7186 rb_objspace_reachable_objects_from(v, reachable_object_check_moved_i, (void *)v);
7187 }
7188 }
7189 }
7190 }
7191 }
7192
7193 return 0;
7194}
7195#endif
7196
7197bool
7198rb_gc_impl_during_gc_p(void *objspace_ptr)
7199{
7200 rb_objspace_t *objspace = objspace_ptr;
7201
7202 return during_gc;
7203}
7204
7205#if RGENGC_PROFILE >= 2
7206
7207static const char*
7208type_name(int type, VALUE obj)
7209{
7210 switch ((enum ruby_value_type)type) {
7211 case RUBY_T_NONE: return "T_NONE";
7212 case RUBY_T_OBJECT: return "T_OBJECT";
7213 case RUBY_T_CLASS: return "T_CLASS";
7214 case RUBY_T_MODULE: return "T_MODULE";
7215 case RUBY_T_FLOAT: return "T_FLOAT";
7216 case RUBY_T_STRING: return "T_STRING";
7217 case RUBY_T_REGEXP: return "T_REGEXP";
7218 case RUBY_T_ARRAY: return "T_ARRAY";
7219 case RUBY_T_HASH: return "T_HASH";
7220 case RUBY_T_STRUCT: return "T_STRUCT";
7221 case RUBY_T_BIGNUM: return "T_BIGNUM";
7222 case RUBY_T_FILE: return "T_FILE";
7223 case RUBY_T_DATA: return "T_DATA";
7224 case RUBY_T_MATCH: return "T_MATCH";
7225 case RUBY_T_COMPLEX: return "T_COMPLEX";
7226 case RUBY_T_RATIONAL: return "T_RATIONAL";
7227 case RUBY_T_NIL: return "T_NIL";
7228 case RUBY_T_TRUE: return "T_TRUE";
7229 case RUBY_T_FALSE: return "T_FALSE";
7230 case RUBY_T_SYMBOL: return "T_SYMBOL";
7231 case RUBY_T_FIXNUM: return "T_FIXNUM";
7232 case RUBY_T_UNDEF: return "T_UNDEF";
7233 case RUBY_T_IMEMO: return "T_IMEMO";
7234 case RUBY_T_NODE: return "T_NODE";
7235 case RUBY_T_ICLASS: return "T_ICLASS";
7236 case RUBY_T_ZOMBIE: return "T_ZOMBIE";
7237 case RUBY_T_MOVED: return "T_MOVED";
7238 default: return "unknown";
7239 }
7240}
7241
7242static void
7243gc_count_add_each_types(VALUE hash, const char *name, const size_t *types)
7244{
7245 VALUE result = rb_hash_new_with_size(T_MASK);
7246 int i;
7247 for (i=0; i<T_MASK; i++) {
7248 const char *type = type_name(i, 0);
7249 rb_hash_aset(result, ID2SYM(rb_intern(type)), SIZET2NUM(types[i]));
7250 }
7251 rb_hash_aset(hash, ID2SYM(rb_intern(name)), result);
7252}
7253#endif
7254
7255size_t
7256rb_gc_impl_gc_count(void *objspace_ptr)
7257{
7258 rb_objspace_t *objspace = objspace_ptr;
7259
7260 return objspace->profile.count;
7261}
7262
7263static VALUE
7264gc_info_decode(rb_objspace_t *objspace, const VALUE hash_or_key, const unsigned int orig_flags)
7265{
7266 static VALUE sym_major_by = Qnil, sym_gc_by, sym_immediate_sweep, sym_have_finalizer, sym_state, sym_need_major_by;
7267 static VALUE sym_nofree, sym_oldgen, sym_shady, sym_force, sym_stress;
7268#if RGENGC_ESTIMATE_OLDMALLOC
7269 static VALUE sym_oldmalloc;
7270#endif
7271 static VALUE sym_newobj, sym_malloc, sym_method, sym_capi;
7272 static VALUE sym_none, sym_marking, sym_sweeping;
7273 static VALUE sym_weak_references_count, sym_retained_weak_references_count;
7274 VALUE hash = Qnil, key = Qnil;
7275 VALUE major_by, need_major_by;
7276 unsigned int flags = orig_flags ? orig_flags : objspace->profile.latest_gc_info;
7277
7278 if (SYMBOL_P(hash_or_key)) {
7279 key = hash_or_key;
7280 }
7281 else if (RB_TYPE_P(hash_or_key, T_HASH)) {
7282 hash = hash_or_key;
7283 }
7284 else {
7285 rb_bug("gc_info_decode: non-hash or symbol given");
7286 }
7287
7288 if (NIL_P(sym_major_by)) {
7289#define S(s) sym_##s = ID2SYM(rb_intern_const(#s))
7290 S(major_by);
7291 S(gc_by);
7292 S(immediate_sweep);
7293 S(have_finalizer);
7294 S(state);
7295 S(need_major_by);
7296
7297 S(stress);
7298 S(nofree);
7299 S(oldgen);
7300 S(shady);
7301 S(force);
7302#if RGENGC_ESTIMATE_OLDMALLOC
7303 S(oldmalloc);
7304#endif
7305 S(newobj);
7306 S(malloc);
7307 S(method);
7308 S(capi);
7309
7310 S(none);
7311 S(marking);
7312 S(sweeping);
7313
7314 S(weak_references_count);
7315 S(retained_weak_references_count);
7316#undef S
7317 }
7318
7319#define SET(name, attr) \
7320 if (key == sym_##name) \
7321 return (attr); \
7322 else if (hash != Qnil) \
7323 rb_hash_aset(hash, sym_##name, (attr));
7324
7325 major_by =
7326 (flags & GPR_FLAG_MAJOR_BY_NOFREE) ? sym_nofree :
7327 (flags & GPR_FLAG_MAJOR_BY_OLDGEN) ? sym_oldgen :
7328 (flags & GPR_FLAG_MAJOR_BY_SHADY) ? sym_shady :
7329 (flags & GPR_FLAG_MAJOR_BY_FORCE) ? sym_force :
7330#if RGENGC_ESTIMATE_OLDMALLOC
7331 (flags & GPR_FLAG_MAJOR_BY_OLDMALLOC) ? sym_oldmalloc :
7332#endif
7333 Qnil;
7334 SET(major_by, major_by);
7335
7336 if (orig_flags == 0) { /* set need_major_by only if flags not set explicitly */
7337 unsigned int need_major_flags = gc_needs_major_flags;
7338 need_major_by =
7339 (need_major_flags & GPR_FLAG_MAJOR_BY_NOFREE) ? sym_nofree :
7340 (need_major_flags & GPR_FLAG_MAJOR_BY_OLDGEN) ? sym_oldgen :
7341 (need_major_flags & GPR_FLAG_MAJOR_BY_SHADY) ? sym_shady :
7342 (need_major_flags & GPR_FLAG_MAJOR_BY_FORCE) ? sym_force :
7343#if RGENGC_ESTIMATE_OLDMALLOC
7344 (need_major_flags & GPR_FLAG_MAJOR_BY_OLDMALLOC) ? sym_oldmalloc :
7345#endif
7346 Qnil;
7347 SET(need_major_by, need_major_by);
7348 }
7349
7350 SET(gc_by,
7351 (flags & GPR_FLAG_NEWOBJ) ? sym_newobj :
7352 (flags & GPR_FLAG_MALLOC) ? sym_malloc :
7353 (flags & GPR_FLAG_METHOD) ? sym_method :
7354 (flags & GPR_FLAG_CAPI) ? sym_capi :
7355 (flags & GPR_FLAG_STRESS) ? sym_stress :
7356 Qnil
7357 );
7358
7359 SET(have_finalizer, (flags & GPR_FLAG_HAVE_FINALIZE) ? Qtrue : Qfalse);
7360 SET(immediate_sweep, (flags & GPR_FLAG_IMMEDIATE_SWEEP) ? Qtrue : Qfalse);
7361
7362 if (orig_flags == 0) {
7363 SET(state, gc_mode(objspace) == gc_mode_none ? sym_none :
7364 gc_mode(objspace) == gc_mode_marking ? sym_marking : sym_sweeping);
7365 }
7366
7367 SET(weak_references_count, LONG2FIX(objspace->profile.weak_references_count));
7368 SET(retained_weak_references_count, LONG2FIX(objspace->profile.retained_weak_references_count));
7369#undef SET
7370
7371 if (!NIL_P(key)) {
7372 // Matched key should return above
7373 return Qundef;
7374 }
7375
7376 return hash;
7377}
7378
7379VALUE
7380rb_gc_impl_latest_gc_info(void *objspace_ptr, VALUE key)
7381{
7382 rb_objspace_t *objspace = objspace_ptr;
7383
7384 return gc_info_decode(objspace, key, 0);
7385}
7386
7387
7388enum gc_stat_sym {
7389 gc_stat_sym_count,
7390 gc_stat_sym_time,
7391 gc_stat_sym_marking_time,
7392 gc_stat_sym_sweeping_time,
7393 gc_stat_sym_heap_allocated_pages,
7394 gc_stat_sym_heap_empty_pages,
7395 gc_stat_sym_heap_allocatable_slots,
7396 gc_stat_sym_heap_available_slots,
7397 gc_stat_sym_heap_live_slots,
7398 gc_stat_sym_heap_free_slots,
7399 gc_stat_sym_heap_final_slots,
7400 gc_stat_sym_heap_marked_slots,
7401 gc_stat_sym_heap_eden_pages,
7402 gc_stat_sym_total_allocated_pages,
7403 gc_stat_sym_total_freed_pages,
7404 gc_stat_sym_total_allocated_objects,
7405 gc_stat_sym_total_freed_objects,
7406 gc_stat_sym_malloc_increase_bytes,
7407 gc_stat_sym_malloc_increase_bytes_limit,
7408 gc_stat_sym_minor_gc_count,
7409 gc_stat_sym_major_gc_count,
7410 gc_stat_sym_compact_count,
7411 gc_stat_sym_read_barrier_faults,
7412 gc_stat_sym_total_moved_objects,
7413 gc_stat_sym_remembered_wb_unprotected_objects,
7414 gc_stat_sym_remembered_wb_unprotected_objects_limit,
7415 gc_stat_sym_old_objects,
7416 gc_stat_sym_old_objects_limit,
7417#if RGENGC_ESTIMATE_OLDMALLOC
7418 gc_stat_sym_oldmalloc_increase_bytes,
7419 gc_stat_sym_oldmalloc_increase_bytes_limit,
7420#endif
7421 gc_stat_sym_weak_references_count,
7422#if RGENGC_PROFILE
7423 gc_stat_sym_total_generated_normal_object_count,
7424 gc_stat_sym_total_generated_shady_object_count,
7425 gc_stat_sym_total_shade_operation_count,
7426 gc_stat_sym_total_promoted_count,
7427 gc_stat_sym_total_remembered_normal_object_count,
7428 gc_stat_sym_total_remembered_shady_object_count,
7429#endif
7430 gc_stat_sym_last
7431};
7432
7433static VALUE gc_stat_symbols[gc_stat_sym_last];
7434
7435static void
7436setup_gc_stat_symbols(void)
7437{
7438 if (gc_stat_symbols[0] == 0) {
7439#define S(s) gc_stat_symbols[gc_stat_sym_##s] = ID2SYM(rb_intern_const(#s))
7440 S(count);
7441 S(time);
7442 S(marking_time),
7443 S(sweeping_time),
7444 S(heap_allocated_pages);
7445 S(heap_empty_pages);
7446 S(heap_allocatable_slots);
7447 S(heap_available_slots);
7448 S(heap_live_slots);
7449 S(heap_free_slots);
7450 S(heap_final_slots);
7451 S(heap_marked_slots);
7452 S(heap_eden_pages);
7453 S(total_allocated_pages);
7454 S(total_freed_pages);
7455 S(total_allocated_objects);
7456 S(total_freed_objects);
7457 S(malloc_increase_bytes);
7458 S(malloc_increase_bytes_limit);
7459 S(minor_gc_count);
7460 S(major_gc_count);
7461 S(compact_count);
7462 S(read_barrier_faults);
7463 S(total_moved_objects);
7464 S(remembered_wb_unprotected_objects);
7465 S(remembered_wb_unprotected_objects_limit);
7466 S(old_objects);
7467 S(old_objects_limit);
7468#if RGENGC_ESTIMATE_OLDMALLOC
7469 S(oldmalloc_increase_bytes);
7470 S(oldmalloc_increase_bytes_limit);
7471#endif
7472 S(weak_references_count);
7473#if RGENGC_PROFILE
7474 S(total_generated_normal_object_count);
7475 S(total_generated_shady_object_count);
7476 S(total_shade_operation_count);
7477 S(total_promoted_count);
7478 S(total_remembered_normal_object_count);
7479 S(total_remembered_shady_object_count);
7480#endif /* RGENGC_PROFILE */
7481#undef S
7482 }
7483}
7484
7485static uint64_t
7486ns_to_ms(uint64_t ns)
7487{
7488 return ns / (1000 * 1000);
7489}
7490
7491VALUE
7492rb_gc_impl_stat(void *objspace_ptr, VALUE hash_or_sym)
7493{
7494 rb_objspace_t *objspace = objspace_ptr;
7495 VALUE hash = Qnil, key = Qnil;
7496
7497 setup_gc_stat_symbols();
7498
7499 if (RB_TYPE_P(hash_or_sym, T_HASH)) {
7500 hash = hash_or_sym;
7501 }
7502 else if (SYMBOL_P(hash_or_sym)) {
7503 key = hash_or_sym;
7504 }
7505 else {
7506 rb_bug("non-hash or symbol given");
7507 }
7508
7509#define SET(name, attr) \
7510 if (key == gc_stat_symbols[gc_stat_sym_##name]) \
7511 return SIZET2NUM(attr); \
7512 else if (hash != Qnil) \
7513 rb_hash_aset(hash, gc_stat_symbols[gc_stat_sym_##name], SIZET2NUM(attr));
7514
7515 SET(count, objspace->profile.count);
7516 SET(time, (size_t)ns_to_ms(objspace->profile.marking_time_ns + objspace->profile.sweeping_time_ns)); // TODO: UINT64T2NUM
7517 SET(marking_time, (size_t)ns_to_ms(objspace->profile.marking_time_ns));
7518 SET(sweeping_time, (size_t)ns_to_ms(objspace->profile.sweeping_time_ns));
7519
7520 /* implementation dependent counters */
7521 SET(heap_allocated_pages, rb_darray_size(objspace->heap_pages.sorted));
7522 SET(heap_empty_pages, objspace->empty_pages_count)
7523 SET(heap_allocatable_slots, objspace->heap_pages.allocatable_slots);
7524 SET(heap_available_slots, objspace_available_slots(objspace));
7525 SET(heap_live_slots, objspace_live_slots(objspace));
7526 SET(heap_free_slots, objspace_free_slots(objspace));
7527 SET(heap_final_slots, total_final_slots_count(objspace));
7528 SET(heap_marked_slots, objspace->marked_slots);
7529 SET(heap_eden_pages, heap_eden_total_pages(objspace));
7530 SET(total_allocated_pages, objspace->heap_pages.allocated_pages);
7531 SET(total_freed_pages, objspace->heap_pages.freed_pages);
7532 SET(total_allocated_objects, total_allocated_objects(objspace));
7533 SET(total_freed_objects, total_freed_objects(objspace));
7534 SET(malloc_increase_bytes, malloc_increase);
7535 SET(malloc_increase_bytes_limit, malloc_limit);
7536 SET(minor_gc_count, objspace->profile.minor_gc_count);
7537 SET(major_gc_count, objspace->profile.major_gc_count);
7538 SET(compact_count, objspace->profile.compact_count);
7539 SET(read_barrier_faults, objspace->profile.read_barrier_faults);
7540 SET(total_moved_objects, objspace->rcompactor.total_moved);
7541 SET(remembered_wb_unprotected_objects, objspace->rgengc.uncollectible_wb_unprotected_objects);
7542 SET(remembered_wb_unprotected_objects_limit, objspace->rgengc.uncollectible_wb_unprotected_objects_limit);
7543 SET(old_objects, objspace->rgengc.old_objects);
7544 SET(old_objects_limit, objspace->rgengc.old_objects_limit);
7545#if RGENGC_ESTIMATE_OLDMALLOC
7546 SET(oldmalloc_increase_bytes, objspace->rgengc.oldmalloc_increase);
7547 SET(oldmalloc_increase_bytes_limit, objspace->rgengc.oldmalloc_increase_limit);
7548#endif
7549
7550#if RGENGC_PROFILE
7551 SET(total_generated_normal_object_count, objspace->profile.total_generated_normal_object_count);
7552 SET(total_generated_shady_object_count, objspace->profile.total_generated_shady_object_count);
7553 SET(total_shade_operation_count, objspace->profile.total_shade_operation_count);
7554 SET(total_promoted_count, objspace->profile.total_promoted_count);
7555 SET(total_remembered_normal_object_count, objspace->profile.total_remembered_normal_object_count);
7556 SET(total_remembered_shady_object_count, objspace->profile.total_remembered_shady_object_count);
7557#endif /* RGENGC_PROFILE */
7558#undef SET
7559
7560 if (!NIL_P(key)) {
7561 // Matched key should return above
7562 return Qundef;
7563 }
7564
7565#if defined(RGENGC_PROFILE) && RGENGC_PROFILE >= 2
7566 if (hash != Qnil) {
7567 gc_count_add_each_types(hash, "generated_normal_object_count_types", objspace->profile.generated_normal_object_count_types);
7568 gc_count_add_each_types(hash, "generated_shady_object_count_types", objspace->profile.generated_shady_object_count_types);
7569 gc_count_add_each_types(hash, "shade_operation_count_types", objspace->profile.shade_operation_count_types);
7570 gc_count_add_each_types(hash, "promoted_types", objspace->profile.promoted_types);
7571 gc_count_add_each_types(hash, "remembered_normal_object_count_types", objspace->profile.remembered_normal_object_count_types);
7572 gc_count_add_each_types(hash, "remembered_shady_object_count_types", objspace->profile.remembered_shady_object_count_types);
7573 }
7574#endif
7575
7576 return hash;
7577}
7578
7579enum gc_stat_heap_sym {
7580 gc_stat_heap_sym_slot_size,
7581 gc_stat_heap_sym_heap_eden_pages,
7582 gc_stat_heap_sym_heap_eden_slots,
7583 gc_stat_heap_sym_total_allocated_pages,
7584 gc_stat_heap_sym_force_major_gc_count,
7585 gc_stat_heap_sym_force_incremental_marking_finish_count,
7586 gc_stat_heap_sym_total_allocated_objects,
7587 gc_stat_heap_sym_total_freed_objects,
7588 gc_stat_heap_sym_last
7589};
7590
7591static VALUE gc_stat_heap_symbols[gc_stat_heap_sym_last];
7592
7593static void
7594setup_gc_stat_heap_symbols(void)
7595{
7596 if (gc_stat_heap_symbols[0] == 0) {
7597#define S(s) gc_stat_heap_symbols[gc_stat_heap_sym_##s] = ID2SYM(rb_intern_const(#s))
7598 S(slot_size);
7599 S(heap_eden_pages);
7600 S(heap_eden_slots);
7601 S(total_allocated_pages);
7602 S(force_major_gc_count);
7603 S(force_incremental_marking_finish_count);
7604 S(total_allocated_objects);
7605 S(total_freed_objects);
7606#undef S
7607 }
7608}
7609
7610static VALUE
7611stat_one_heap(rb_heap_t *heap, VALUE hash, VALUE key)
7612{
7613#define SET(name, attr) \
7614 if (key == gc_stat_heap_symbols[gc_stat_heap_sym_##name]) \
7615 return SIZET2NUM(attr); \
7616 else if (hash != Qnil) \
7617 rb_hash_aset(hash, gc_stat_heap_symbols[gc_stat_heap_sym_##name], SIZET2NUM(attr));
7618
7619 SET(slot_size, heap->slot_size);
7620 SET(heap_eden_pages, heap->total_pages);
7621 SET(heap_eden_slots, heap->total_slots);
7622 SET(total_allocated_pages, heap->total_allocated_pages);
7623 SET(force_major_gc_count, heap->force_major_gc_count);
7624 SET(force_incremental_marking_finish_count, heap->force_incremental_marking_finish_count);
7625 SET(total_allocated_objects, heap->total_allocated_objects);
7626 SET(total_freed_objects, heap->total_freed_objects);
7627#undef SET
7628
7629 if (!NIL_P(key)) {
7630 // Matched key should return above
7631 return Qundef;
7632 }
7633
7634 return hash;
7635}
7636
7637VALUE
7638rb_gc_impl_stat_heap(void *objspace_ptr, VALUE heap_name, VALUE hash_or_sym)
7639{
7640 rb_objspace_t *objspace = objspace_ptr;
7641
7642 setup_gc_stat_heap_symbols();
7643
7644 if (NIL_P(heap_name)) {
7645 if (!RB_TYPE_P(hash_or_sym, T_HASH)) {
7646 rb_bug("non-hash given");
7647 }
7648
7649 for (int i = 0; i < HEAP_COUNT; i++) {
7650 VALUE hash = rb_hash_aref(hash_or_sym, INT2FIX(i));
7651 if (NIL_P(hash)) {
7652 hash = rb_hash_new();
7653 rb_hash_aset(hash_or_sym, INT2FIX(i), hash);
7654 }
7655
7656 stat_one_heap(&heaps[i], hash, Qnil);
7657 }
7658 }
7659 else if (FIXNUM_P(heap_name)) {
7660 int heap_idx = FIX2INT(heap_name);
7661
7662 if (heap_idx < 0 || heap_idx >= HEAP_COUNT) {
7663 rb_raise(rb_eArgError, "size pool index out of range");
7664 }
7665
7666 if (SYMBOL_P(hash_or_sym)) {
7667 return stat_one_heap(&heaps[heap_idx], Qnil, hash_or_sym);
7668 }
7669 else if (RB_TYPE_P(hash_or_sym, T_HASH)) {
7670 return stat_one_heap(&heaps[heap_idx], hash_or_sym, Qnil);
7671 }
7672 else {
7673 rb_bug("non-hash or symbol given");
7674 }
7675 }
7676 else {
7677 rb_bug("heap_name must be nil or an Integer");
7678 }
7679
7680 return hash_or_sym;
7681}
7682
7683/* I could include internal.h for this, but doing so undefines some Array macros
7684 * necessary for initialising objects, and I don't want to include all the array
7685 * headers to get them back
7686 * TODO: Investigate why RARRAY_AREF gets undefined in internal.h
7687 */
7688#ifndef RBOOL
7689#define RBOOL(v) (v ? Qtrue : Qfalse)
7690#endif
7691
7692VALUE
7693rb_gc_impl_config_get(void *objspace_ptr)
7694{
7695#define sym(name) ID2SYM(rb_intern_const(name))
7696 rb_objspace_t *objspace = objspace_ptr;
7697 VALUE hash = rb_hash_new();
7698
7699 rb_hash_aset(hash, sym("rgengc_allow_full_mark"), RBOOL(gc_config_full_mark_val));
7700
7701 return hash;
7702}
7703
7704static int
7705gc_config_set_key(VALUE key, VALUE value, VALUE data)
7706{
7708 if (rb_sym2id(key) == rb_intern("rgengc_allow_full_mark")) {
7709 gc_rest(objspace);
7710 gc_config_full_mark_set(RTEST(value));
7711 }
7712 return ST_CONTINUE;
7713}
7714
7715void
7716rb_gc_impl_config_set(void *objspace_ptr, VALUE hash)
7717{
7718 rb_objspace_t *objspace = objspace_ptr;
7719
7720 if (!RB_TYPE_P(hash, T_HASH)) {
7721 rb_raise(rb_eArgError, "expected keyword arguments");
7722 }
7723
7724 rb_hash_foreach(hash, gc_config_set_key, (st_data_t)objspace);
7725}
7726
7727VALUE
7728rb_gc_impl_stress_get(void *objspace_ptr)
7729{
7730 rb_objspace_t *objspace = objspace_ptr;
7731 return ruby_gc_stress_mode;
7732}
7733
7734void
7735rb_gc_impl_stress_set(void *objspace_ptr, VALUE flag)
7736{
7737 rb_objspace_t *objspace = objspace_ptr;
7738
7739 objspace->flags.gc_stressful = RTEST(flag);
7740 objspace->gc_stress_mode = flag;
7741}
7742
7743static int
7744get_envparam_size(const char *name, size_t *default_value, size_t lower_bound)
7745{
7746 const char *ptr = getenv(name);
7747 ssize_t val;
7748
7749 if (ptr != NULL && *ptr) {
7750 size_t unit = 0;
7751 char *end;
7752#if SIZEOF_SIZE_T == SIZEOF_LONG_LONG
7753 val = strtoll(ptr, &end, 0);
7754#else
7755 val = strtol(ptr, &end, 0);
7756#endif
7757 switch (*end) {
7758 case 'k': case 'K':
7759 unit = 1024;
7760 ++end;
7761 break;
7762 case 'm': case 'M':
7763 unit = 1024*1024;
7764 ++end;
7765 break;
7766 case 'g': case 'G':
7767 unit = 1024*1024*1024;
7768 ++end;
7769 break;
7770 }
7771 while (*end && isspace((unsigned char)*end)) end++;
7772 if (*end) {
7773 if (RTEST(ruby_verbose)) fprintf(stderr, "invalid string for %s: %s\n", name, ptr);
7774 return 0;
7775 }
7776 if (unit > 0) {
7777 if (val < -(ssize_t)(SIZE_MAX / 2 / unit) || (ssize_t)(SIZE_MAX / 2 / unit) < val) {
7778 if (RTEST(ruby_verbose)) fprintf(stderr, "%s=%s is ignored because it overflows\n", name, ptr);
7779 return 0;
7780 }
7781 val *= unit;
7782 }
7783 if (val > 0 && (size_t)val > lower_bound) {
7784 if (RTEST(ruby_verbose)) {
7785 fprintf(stderr, "%s=%"PRIdSIZE" (default value: %"PRIuSIZE")\n", name, val, *default_value);
7786 }
7787 *default_value = (size_t)val;
7788 return 1;
7789 }
7790 else {
7791 if (RTEST(ruby_verbose)) {
7792 fprintf(stderr, "%s=%"PRIdSIZE" (default value: %"PRIuSIZE") is ignored because it must be greater than %"PRIuSIZE".\n",
7793 name, val, *default_value, lower_bound);
7794 }
7795 return 0;
7796 }
7797 }
7798 return 0;
7799}
7800
7801static int
7802get_envparam_double(const char *name, double *default_value, double lower_bound, double upper_bound, int accept_zero)
7803{
7804 const char *ptr = getenv(name);
7805 double val;
7806
7807 if (ptr != NULL && *ptr) {
7808 char *end;
7809 val = strtod(ptr, &end);
7810 if (!*ptr || *end) {
7811 if (RTEST(ruby_verbose)) fprintf(stderr, "invalid string for %s: %s\n", name, ptr);
7812 return 0;
7813 }
7814
7815 if (accept_zero && val == 0.0) {
7816 goto accept;
7817 }
7818 else if (val <= lower_bound) {
7819 if (RTEST(ruby_verbose)) {
7820 fprintf(stderr, "%s=%f (default value: %f) is ignored because it must be greater than %f.\n",
7821 name, val, *default_value, lower_bound);
7822 }
7823 }
7824 else if (upper_bound != 0.0 && /* ignore upper_bound if it is 0.0 */
7825 val > upper_bound) {
7826 if (RTEST(ruby_verbose)) {
7827 fprintf(stderr, "%s=%f (default value: %f) is ignored because it must be lower than %f.\n",
7828 name, val, *default_value, upper_bound);
7829 }
7830 }
7831 else {
7832 goto accept;
7833 }
7834 }
7835 return 0;
7836
7837 accept:
7838 if (RTEST(ruby_verbose)) fprintf(stderr, "%s=%f (default value: %f)\n", name, val, *default_value);
7839 *default_value = val;
7840 return 1;
7841}
7842
7843/*
7844 * GC tuning environment variables
7845 *
7846 * * RUBY_GC_HEAP_FREE_SLOTS
7847 * - Prepare at least this amount of slots after GC.
7848 * - Allocate slots if there are not enough slots.
7849 * * RUBY_GC_HEAP_GROWTH_FACTOR (new from 2.1)
7850 * - Allocate slots by this factor.
7851 * - (next slots number) = (current slots number) * (this factor)
7852 * * RUBY_GC_HEAP_GROWTH_MAX_SLOTS (new from 2.1)
7853 * - Allocation rate is limited to this number of slots.
7854 * * RUBY_GC_HEAP_FREE_SLOTS_MIN_RATIO (new from 2.4)
7855 * - Allocate additional pages when the number of free slots is
7856 * lower than the value (total_slots * (this ratio)).
7857 * * RUBY_GC_HEAP_FREE_SLOTS_GOAL_RATIO (new from 2.4)
7858 * - Allocate slots to satisfy this formula:
7859 * free_slots = total_slots * goal_ratio
7860 * - In other words, prepare (total_slots * goal_ratio) free slots.
7861 * - if this value is 0.0, then use RUBY_GC_HEAP_GROWTH_FACTOR directly.
7862 * * RUBY_GC_HEAP_FREE_SLOTS_MAX_RATIO (new from 2.4)
7863 * - Allow to free pages when the number of free slots is
7864 * greater than the value (total_slots * (this ratio)).
7865 * * RUBY_GC_HEAP_OLDOBJECT_LIMIT_FACTOR (new from 2.1.1)
7866 * - Do full GC when the number of old objects is more than R * N
7867 * where R is this factor and
7868 * N is the number of old objects just after last full GC.
7869 *
7870 * * obsolete
7871 * * RUBY_FREE_MIN -> RUBY_GC_HEAP_FREE_SLOTS (from 2.1)
7872 * * RUBY_HEAP_MIN_SLOTS -> RUBY_GC_HEAP_INIT_SLOTS (from 2.1)
7873 *
7874 * * RUBY_GC_MALLOC_LIMIT
7875 * * RUBY_GC_MALLOC_LIMIT_MAX (new from 2.1)
7876 * * RUBY_GC_MALLOC_LIMIT_GROWTH_FACTOR (new from 2.1)
7877 *
7878 * * RUBY_GC_OLDMALLOC_LIMIT (new from 2.1)
7879 * * RUBY_GC_OLDMALLOC_LIMIT_MAX (new from 2.1)
7880 * * RUBY_GC_OLDMALLOC_LIMIT_GROWTH_FACTOR (new from 2.1)
7881 */
7882
7883void
7884rb_gc_impl_set_params(void *objspace_ptr)
7885{
7886 rb_objspace_t *objspace = objspace_ptr;
7887 /* RUBY_GC_HEAP_FREE_SLOTS */
7888 if (get_envparam_size("RUBY_GC_HEAP_FREE_SLOTS", &gc_params.heap_free_slots, 0)) {
7889 /* ok */
7890 }
7891
7892 for (int i = 0; i < HEAP_COUNT; i++) {
7893 char env_key[sizeof("RUBY_GC_HEAP_" "_INIT_SLOTS") + DECIMAL_SIZE_OF_BITS(sizeof(int) * CHAR_BIT)];
7894 snprintf(env_key, sizeof(env_key), "RUBY_GC_HEAP_%d_INIT_SLOTS", i);
7895
7896 get_envparam_size(env_key, &gc_params.heap_init_slots[i], 0);
7897 }
7898
7899 get_envparam_double("RUBY_GC_HEAP_GROWTH_FACTOR", &gc_params.growth_factor, 1.0, 0.0, FALSE);
7900 get_envparam_size ("RUBY_GC_HEAP_GROWTH_MAX_SLOTS", &gc_params.growth_max_slots, 0);
7901 get_envparam_double("RUBY_GC_HEAP_FREE_SLOTS_MIN_RATIO", &gc_params.heap_free_slots_min_ratio,
7902 0.0, 1.0, FALSE);
7903 get_envparam_double("RUBY_GC_HEAP_FREE_SLOTS_MAX_RATIO", &gc_params.heap_free_slots_max_ratio,
7904 gc_params.heap_free_slots_min_ratio, 1.0, FALSE);
7905 get_envparam_double("RUBY_GC_HEAP_FREE_SLOTS_GOAL_RATIO", &gc_params.heap_free_slots_goal_ratio,
7906 gc_params.heap_free_slots_min_ratio, gc_params.heap_free_slots_max_ratio, TRUE);
7907 get_envparam_double("RUBY_GC_HEAP_OLDOBJECT_LIMIT_FACTOR", &gc_params.oldobject_limit_factor, 0.0, 0.0, TRUE);
7908 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);
7909
7910 if (get_envparam_size("RUBY_GC_MALLOC_LIMIT", &gc_params.malloc_limit_min, 0)) {
7911 malloc_limit = gc_params.malloc_limit_min;
7912 }
7913 get_envparam_size ("RUBY_GC_MALLOC_LIMIT_MAX", &gc_params.malloc_limit_max, 0);
7914 if (!gc_params.malloc_limit_max) { /* ignore max-check if 0 */
7915 gc_params.malloc_limit_max = SIZE_MAX;
7916 }
7917 get_envparam_double("RUBY_GC_MALLOC_LIMIT_GROWTH_FACTOR", &gc_params.malloc_limit_growth_factor, 1.0, 0.0, FALSE);
7918
7919#if RGENGC_ESTIMATE_OLDMALLOC
7920 if (get_envparam_size("RUBY_GC_OLDMALLOC_LIMIT", &gc_params.oldmalloc_limit_min, 0)) {
7921 objspace->rgengc.oldmalloc_increase_limit = gc_params.oldmalloc_limit_min;
7922 }
7923 get_envparam_size ("RUBY_GC_OLDMALLOC_LIMIT_MAX", &gc_params.oldmalloc_limit_max, 0);
7924 get_envparam_double("RUBY_GC_OLDMALLOC_LIMIT_GROWTH_FACTOR", &gc_params.oldmalloc_limit_growth_factor, 1.0, 0.0, FALSE);
7925#endif
7926}
7927
7928static inline size_t
7929objspace_malloc_size(rb_objspace_t *objspace, void *ptr, size_t hint)
7930{
7931#ifdef HAVE_MALLOC_USABLE_SIZE
7932 if (!hint) {
7933 hint = malloc_usable_size(ptr);
7934 }
7935#endif
7936 return hint;
7937}
7938
7939enum memop_type {
7940 MEMOP_TYPE_MALLOC = 0,
7941 MEMOP_TYPE_FREE,
7942 MEMOP_TYPE_REALLOC
7943};
7944
7945static inline void
7946atomic_sub_nounderflow(size_t *var, size_t sub)
7947{
7948 if (sub == 0) return;
7949
7950 while (1) {
7951 size_t val = *var;
7952 if (val < sub) sub = val;
7953 if (RUBY_ATOMIC_SIZE_CAS(*var, val, val-sub) == val) break;
7954 }
7955}
7956
7957#define gc_stress_full_mark_after_malloc_p() \
7958 (FIXNUM_P(ruby_gc_stress_mode) && (FIX2LONG(ruby_gc_stress_mode) & (1<<gc_stress_full_mark_after_malloc)))
7959
7960static void
7961objspace_malloc_gc_stress(rb_objspace_t *objspace)
7962{
7963 if (ruby_gc_stressful && ruby_native_thread_p()) {
7964 unsigned int reason = (GPR_FLAG_IMMEDIATE_MARK | GPR_FLAG_IMMEDIATE_SWEEP |
7965 GPR_FLAG_STRESS | GPR_FLAG_MALLOC);
7966
7967 if (gc_stress_full_mark_after_malloc_p()) {
7968 reason |= GPR_FLAG_FULL_MARK;
7969 }
7970 garbage_collect_with_gvl(objspace, reason);
7971 }
7972}
7973
7974static inline bool
7975objspace_malloc_increase_report(rb_objspace_t *objspace, void *mem, size_t new_size, size_t old_size, enum memop_type type, bool gc_allowed)
7976{
7977 if (0) fprintf(stderr, "increase - ptr: %p, type: %s, new_size: %"PRIdSIZE", old_size: %"PRIdSIZE"\n",
7978 mem,
7979 type == MEMOP_TYPE_MALLOC ? "malloc" :
7980 type == MEMOP_TYPE_FREE ? "free " :
7981 type == MEMOP_TYPE_REALLOC ? "realloc": "error",
7982 new_size, old_size);
7983 return false;
7984}
7985
7986static bool
7987objspace_malloc_increase_body(rb_objspace_t *objspace, void *mem, size_t new_size, size_t old_size, enum memop_type type, bool gc_allowed)
7988{
7989 if (new_size > old_size) {
7990 RUBY_ATOMIC_SIZE_ADD(malloc_increase, new_size - old_size);
7991#if RGENGC_ESTIMATE_OLDMALLOC
7992 RUBY_ATOMIC_SIZE_ADD(objspace->rgengc.oldmalloc_increase, new_size - old_size);
7993#endif
7994 }
7995 else {
7996 atomic_sub_nounderflow(&malloc_increase, old_size - new_size);
7997#if RGENGC_ESTIMATE_OLDMALLOC
7998 atomic_sub_nounderflow(&objspace->rgengc.oldmalloc_increase, old_size - new_size);
7999#endif
8000 }
8001
8002 if (type == MEMOP_TYPE_MALLOC && gc_allowed) {
8003 retry:
8004 if (malloc_increase > malloc_limit && ruby_native_thread_p() && !dont_gc_val()) {
8005 if (ruby_thread_has_gvl_p() && is_lazy_sweeping(objspace)) {
8006 gc_rest(objspace); /* gc_rest can reduce malloc_increase */
8007 goto retry;
8008 }
8009 garbage_collect_with_gvl(objspace, GPR_FLAG_MALLOC);
8010 }
8011 }
8012
8013#if MALLOC_ALLOCATED_SIZE
8014 if (new_size >= old_size) {
8015 RUBY_ATOMIC_SIZE_ADD(objspace->malloc_params.allocated_size, new_size - old_size);
8016 }
8017 else {
8018 size_t dec_size = old_size - new_size;
8019
8020#if MALLOC_ALLOCATED_SIZE_CHECK
8021 size_t allocated_size = objspace->malloc_params.allocated_size;
8022 if (allocated_size < dec_size) {
8023 rb_bug("objspace_malloc_increase: underflow malloc_params.allocated_size.");
8024 }
8025#endif
8026 atomic_sub_nounderflow(&objspace->malloc_params.allocated_size, dec_size);
8027 }
8028
8029 switch (type) {
8030 case MEMOP_TYPE_MALLOC:
8031 RUBY_ATOMIC_SIZE_INC(objspace->malloc_params.allocations);
8032 break;
8033 case MEMOP_TYPE_FREE:
8034 {
8035 size_t allocations = objspace->malloc_params.allocations;
8036 if (allocations > 0) {
8037 atomic_sub_nounderflow(&objspace->malloc_params.allocations, 1);
8038 }
8039#if MALLOC_ALLOCATED_SIZE_CHECK
8040 else {
8041 GC_ASSERT(objspace->malloc_params.allocations > 0);
8042 }
8043#endif
8044 }
8045 break;
8046 case MEMOP_TYPE_REALLOC: /* ignore */ break;
8047 }
8048#endif
8049 return true;
8050}
8051
8052#define objspace_malloc_increase(...) \
8053 for (bool malloc_increase_done = objspace_malloc_increase_report(__VA_ARGS__); \
8054 !malloc_increase_done; \
8055 malloc_increase_done = objspace_malloc_increase_body(__VA_ARGS__))
8056
8057struct malloc_obj_info { /* 4 words */
8058 size_t size;
8059};
8060
8061static inline size_t
8062objspace_malloc_prepare(rb_objspace_t *objspace, size_t size)
8063{
8064 if (size == 0) size = 1;
8065
8066#if CALC_EXACT_MALLOC_SIZE
8067 size += sizeof(struct malloc_obj_info);
8068#endif
8069
8070 return size;
8071}
8072
8073static bool
8074malloc_during_gc_p(rb_objspace_t *objspace)
8075{
8076 /* malloc is not allowed during GC when we're not using multiple ractors
8077 * (since ractors can run while another thread is sweeping) and when we
8078 * have the GVL (since if we don't have the GVL, we'll try to acquire the
8079 * GVL which will block and ensure the other thread finishes GC). */
8080 return during_gc && !dont_gc_val() && !rb_gc_multi_ractor_p() && ruby_thread_has_gvl_p();
8081}
8082
8083static inline void *
8084objspace_malloc_fixup(rb_objspace_t *objspace, void *mem, size_t size, bool gc_allowed)
8085{
8086 size = objspace_malloc_size(objspace, mem, size);
8087 objspace_malloc_increase(objspace, mem, size, 0, MEMOP_TYPE_MALLOC, gc_allowed) {}
8088
8089#if CALC_EXACT_MALLOC_SIZE
8090 {
8091 struct malloc_obj_info *info = mem;
8092 info->size = size;
8093 mem = info + 1;
8094 }
8095#endif
8096
8097 return mem;
8098}
8099
8100#if defined(__GNUC__) && RUBY_DEBUG
8101#define RB_BUG_INSTEAD_OF_RB_MEMERROR 1
8102#endif
8103
8104#ifndef RB_BUG_INSTEAD_OF_RB_MEMERROR
8105# define RB_BUG_INSTEAD_OF_RB_MEMERROR 0
8106#endif
8107
8108#define GC_MEMERROR(...) \
8109 ((RB_BUG_INSTEAD_OF_RB_MEMERROR+0) ? rb_bug("" __VA_ARGS__) : (void)0)
8110
8111#define TRY_WITH_GC(siz, expr) do { \
8112 const gc_profile_record_flag gpr = \
8113 GPR_FLAG_FULL_MARK | \
8114 GPR_FLAG_IMMEDIATE_MARK | \
8115 GPR_FLAG_IMMEDIATE_SWEEP | \
8116 GPR_FLAG_MALLOC; \
8117 objspace_malloc_gc_stress(objspace); \
8118 \
8119 if (RB_LIKELY((expr))) { \
8120 /* Success on 1st try */ \
8121 } \
8122 else if (gc_allowed && !garbage_collect_with_gvl(objspace, gpr)) { \
8123 /* @shyouhei thinks this doesn't happen */ \
8124 GC_MEMERROR("TRY_WITH_GC: could not GC"); \
8125 } \
8126 else if ((expr)) { \
8127 /* Success on 2nd try */ \
8128 } \
8129 else { \
8130 GC_MEMERROR("TRY_WITH_GC: could not allocate:" \
8131 "%"PRIdSIZE" bytes for %s", \
8132 siz, # expr); \
8133 } \
8134 } while (0)
8135
8136static void
8137check_malloc_not_in_gc(rb_objspace_t *objspace, const char *msg)
8138{
8139 if (RB_UNLIKELY(malloc_during_gc_p(objspace))) {
8140 dont_gc_on();
8141 during_gc = false;
8142 rb_bug("Cannot %s during GC", msg);
8143 }
8144}
8145
8146void
8147rb_gc_impl_free(void *objspace_ptr, void *ptr, size_t old_size)
8148{
8149 rb_objspace_t *objspace = objspace_ptr;
8150
8151 if (!ptr) {
8152 /*
8153 * ISO/IEC 9899 says "If ptr is a null pointer, no action occurs" since
8154 * its first version. We would better follow.
8155 */
8156 return;
8157 }
8158#if CALC_EXACT_MALLOC_SIZE
8159 struct malloc_obj_info *info = (struct malloc_obj_info *)ptr - 1;
8160 ptr = info;
8161 old_size = info->size;
8162#endif
8163 old_size = objspace_malloc_size(objspace, ptr, old_size);
8164
8165 objspace_malloc_increase(objspace, ptr, 0, old_size, MEMOP_TYPE_FREE, true) {
8166 free(ptr);
8167 ptr = NULL;
8168 RB_DEBUG_COUNTER_INC(heap_xfree);
8169 }
8170}
8171
8172void *
8173rb_gc_impl_malloc(void *objspace_ptr, size_t size, bool gc_allowed)
8174{
8175 rb_objspace_t *objspace = objspace_ptr;
8176 check_malloc_not_in_gc(objspace, "malloc");
8177
8178 void *mem;
8179
8180 size = objspace_malloc_prepare(objspace, size);
8181 TRY_WITH_GC(size, mem = malloc(size));
8182 RB_DEBUG_COUNTER_INC(heap_xmalloc);
8183 if (!mem) return mem;
8184 return objspace_malloc_fixup(objspace, mem, size, gc_allowed);
8185}
8186
8187void *
8188rb_gc_impl_calloc(void *objspace_ptr, size_t size, bool gc_allowed)
8189{
8190 rb_objspace_t *objspace = objspace_ptr;
8191
8192 if (RB_UNLIKELY(malloc_during_gc_p(objspace))) {
8193 rb_warn("calloc during GC detected, this could cause crashes if it triggers another GC");
8194#if RGENGC_CHECK_MODE || RUBY_DEBUG
8195 rb_bug("Cannot calloc during GC");
8196#endif
8197 }
8198
8199 void *mem;
8200
8201 size = objspace_malloc_prepare(objspace, size);
8202 TRY_WITH_GC(size, mem = calloc1(size));
8203 if (!mem) return mem;
8204 return objspace_malloc_fixup(objspace, mem, size, gc_allowed);
8205}
8206
8207void *
8208rb_gc_impl_realloc(void *objspace_ptr, void *ptr, size_t new_size, size_t old_size, bool gc_allowed)
8209{
8210 rb_objspace_t *objspace = objspace_ptr;
8211
8212 check_malloc_not_in_gc(objspace, "realloc");
8213
8214 void *mem;
8215
8216 if (!ptr) return rb_gc_impl_malloc(objspace, new_size, gc_allowed);
8217
8218 /*
8219 * The behavior of realloc(ptr, 0) is implementation defined.
8220 * Therefore we don't use realloc(ptr, 0) for portability reason.
8221 * see http://www.open-std.org/jtc1/sc22/wg14/www/docs/dr_400.htm
8222 */
8223 if (new_size == 0) {
8224 if ((mem = rb_gc_impl_malloc(objspace, 0, gc_allowed)) != NULL) {
8225 /*
8226 * - OpenBSD's malloc(3) man page says that when 0 is passed, it
8227 * returns a non-NULL pointer to an access-protected memory page.
8228 * The returned pointer cannot be read / written at all, but
8229 * still be a valid argument of free().
8230 *
8231 * https://man.openbsd.org/malloc.3
8232 *
8233 * - Linux's malloc(3) man page says that it _might_ perhaps return
8234 * a non-NULL pointer when its argument is 0. That return value
8235 * is safe (and is expected) to be passed to free().
8236 *
8237 * https://man7.org/linux/man-pages/man3/malloc.3.html
8238 *
8239 * - As I read the implementation jemalloc's malloc() returns fully
8240 * normal 16 bytes memory region when its argument is 0.
8241 *
8242 * - As I read the implementation musl libc's malloc() returns
8243 * fully normal 32 bytes memory region when its argument is 0.
8244 *
8245 * - Other malloc implementations can also return non-NULL.
8246 */
8247 rb_gc_impl_free(objspace, ptr, old_size);
8248 return mem;
8249 }
8250 else {
8251 /*
8252 * It is dangerous to return NULL here, because that could lead to
8253 * RCE. Fallback to 1 byte instead of zero.
8254 *
8255 * https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2019-11932
8256 */
8257 new_size = 1;
8258 }
8259 }
8260
8261#if CALC_EXACT_MALLOC_SIZE
8262 {
8263 struct malloc_obj_info *info = (struct malloc_obj_info *)ptr - 1;
8264 new_size += sizeof(struct malloc_obj_info);
8265 ptr = info;
8266 old_size = info->size;
8267 }
8268#endif
8269
8270 old_size = objspace_malloc_size(objspace, ptr, old_size);
8271 TRY_WITH_GC(new_size, mem = RB_GNUC_EXTENSION_BLOCK(realloc(ptr, new_size)));
8272 if (!mem) return mem;
8273 new_size = objspace_malloc_size(objspace, mem, new_size);
8274
8275#if CALC_EXACT_MALLOC_SIZE
8276 {
8277 struct malloc_obj_info *info = mem;
8278 info->size = new_size;
8279 mem = info + 1;
8280 }
8281#endif
8282
8283 objspace_malloc_increase(objspace, mem, new_size, old_size, MEMOP_TYPE_REALLOC, gc_allowed);
8284
8285 RB_DEBUG_COUNTER_INC(heap_xrealloc);
8286 return mem;
8287}
8288
8289void
8290rb_gc_impl_adjust_memory_usage(void *objspace_ptr, ssize_t diff)
8291{
8292 rb_objspace_t *objspace = objspace_ptr;
8293
8294 if (diff > 0) {
8295 objspace_malloc_increase(objspace, 0, diff, 0, MEMOP_TYPE_REALLOC, true);
8296 }
8297 else if (diff < 0) {
8298 objspace_malloc_increase(objspace, 0, 0, -diff, MEMOP_TYPE_REALLOC, true);
8299 }
8300}
8301
8302// TODO: move GC profiler stuff back into gc.c
8303/*
8304 ------------------------------ GC profiler ------------------------------
8305*/
8306
8307#define GC_PROFILE_RECORD_DEFAULT_SIZE 100
8308
8309static bool
8310current_process_time(struct timespec *ts)
8311{
8312#if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_PROCESS_CPUTIME_ID)
8313 {
8314 static int try_clock_gettime = 1;
8315 if (try_clock_gettime && clock_gettime(CLOCK_PROCESS_CPUTIME_ID, ts) == 0) {
8316 return true;
8317 }
8318 else {
8319 try_clock_gettime = 0;
8320 }
8321 }
8322#endif
8323
8324#ifdef RUSAGE_SELF
8325 {
8326 struct rusage usage;
8327 struct timeval time;
8328 if (getrusage(RUSAGE_SELF, &usage) == 0) {
8329 time = usage.ru_utime;
8330 ts->tv_sec = time.tv_sec;
8331 ts->tv_nsec = (int32_t)time.tv_usec * 1000;
8332 return true;
8333 }
8334 }
8335#endif
8336
8337#ifdef _WIN32
8338 {
8339 FILETIME creation_time, exit_time, kernel_time, user_time;
8340 ULARGE_INTEGER ui;
8341
8342 if (GetProcessTimes(GetCurrentProcess(),
8343 &creation_time, &exit_time, &kernel_time, &user_time) != 0) {
8344 memcpy(&ui, &user_time, sizeof(FILETIME));
8345#define PER100NSEC (uint64_t)(1000 * 1000 * 10)
8346 ts->tv_nsec = (long)(ui.QuadPart % PER100NSEC);
8347 ts->tv_sec = (time_t)(ui.QuadPart / PER100NSEC);
8348 return true;
8349 }
8350 }
8351#endif
8352
8353 return false;
8354}
8355
8356static double
8357getrusage_time(void)
8358{
8359 struct timespec ts;
8360 if (current_process_time(&ts)) {
8361 return ts.tv_sec + ts.tv_nsec * 1e-9;
8362 }
8363 else {
8364 return 0.0;
8365 }
8366}
8367
8368
8369static inline void
8370gc_prof_setup_new_record(rb_objspace_t *objspace, unsigned int reason)
8371{
8372 if (objspace->profile.run) {
8373 size_t index = objspace->profile.next_index;
8374 gc_profile_record *record;
8375
8376 /* create new record */
8377 objspace->profile.next_index++;
8378
8379 if (!objspace->profile.records) {
8380 objspace->profile.size = GC_PROFILE_RECORD_DEFAULT_SIZE;
8381 objspace->profile.records = malloc(xmalloc2_size(sizeof(gc_profile_record), objspace->profile.size));
8382 }
8383 if (index >= objspace->profile.size) {
8384 void *ptr;
8385 objspace->profile.size += 1000;
8386 ptr = realloc(objspace->profile.records, xmalloc2_size(sizeof(gc_profile_record), objspace->profile.size));
8387 if (!ptr) rb_memerror();
8388 objspace->profile.records = ptr;
8389 }
8390 if (!objspace->profile.records) {
8391 rb_bug("gc_profile malloc or realloc miss");
8392 }
8393 record = objspace->profile.current_record = &objspace->profile.records[objspace->profile.next_index - 1];
8394 MEMZERO(record, gc_profile_record, 1);
8395
8396 /* setup before-GC parameter */
8397 record->flags = reason | (ruby_gc_stressful ? GPR_FLAG_STRESS : 0);
8398#if MALLOC_ALLOCATED_SIZE
8399 record->allocated_size = malloc_allocated_size;
8400#endif
8401#if GC_PROFILE_MORE_DETAIL && GC_PROFILE_DETAIL_MEMORY
8402#ifdef RUSAGE_SELF
8403 {
8404 struct rusage usage;
8405 if (getrusage(RUSAGE_SELF, &usage) == 0) {
8406 record->maxrss = usage.ru_maxrss;
8407 record->minflt = usage.ru_minflt;
8408 record->majflt = usage.ru_majflt;
8409 }
8410 }
8411#endif
8412#endif
8413 }
8414}
8415
8416static inline void
8417gc_prof_timer_start(rb_objspace_t *objspace)
8418{
8419 if (gc_prof_enabled(objspace)) {
8420 gc_profile_record *record = gc_prof_record(objspace);
8421#if GC_PROFILE_MORE_DETAIL
8422 record->prepare_time = objspace->profile.prepare_time;
8423#endif
8424 record->gc_time = 0;
8425 record->gc_invoke_time = getrusage_time();
8426 }
8427}
8428
8429static double
8430elapsed_time_from(double time)
8431{
8432 double now = getrusage_time();
8433 if (now > time) {
8434 return now - time;
8435 }
8436 else {
8437 return 0;
8438 }
8439}
8440
8441static inline void
8442gc_prof_timer_stop(rb_objspace_t *objspace)
8443{
8444 if (gc_prof_enabled(objspace)) {
8445 gc_profile_record *record = gc_prof_record(objspace);
8446 record->gc_time = elapsed_time_from(record->gc_invoke_time);
8447 record->gc_invoke_time -= objspace->profile.invoke_time;
8448 }
8449}
8450
8451#ifdef BUILDING_MODULAR_GC
8452# define RUBY_DTRACE_GC_HOOK(name)
8453#else
8454# define RUBY_DTRACE_GC_HOOK(name) \
8455 do {if (RUBY_DTRACE_GC_##name##_ENABLED()) RUBY_DTRACE_GC_##name();} while (0)
8456#endif
8457
8458static inline void
8459gc_prof_mark_timer_start(rb_objspace_t *objspace)
8460{
8461 RUBY_DTRACE_GC_HOOK(MARK_BEGIN);
8462#if GC_PROFILE_MORE_DETAIL
8463 if (gc_prof_enabled(objspace)) {
8464 gc_prof_record(objspace)->gc_mark_time = getrusage_time();
8465 }
8466#endif
8467}
8468
8469static inline void
8470gc_prof_mark_timer_stop(rb_objspace_t *objspace)
8471{
8472 RUBY_DTRACE_GC_HOOK(MARK_END);
8473#if GC_PROFILE_MORE_DETAIL
8474 if (gc_prof_enabled(objspace)) {
8475 gc_profile_record *record = gc_prof_record(objspace);
8476 record->gc_mark_time = elapsed_time_from(record->gc_mark_time);
8477 }
8478#endif
8479}
8480
8481static inline void
8482gc_prof_sweep_timer_start(rb_objspace_t *objspace)
8483{
8484 RUBY_DTRACE_GC_HOOK(SWEEP_BEGIN);
8485 if (gc_prof_enabled(objspace)) {
8486 gc_profile_record *record = gc_prof_record(objspace);
8487
8488 if (record->gc_time > 0 || GC_PROFILE_MORE_DETAIL) {
8489 objspace->profile.gc_sweep_start_time = getrusage_time();
8490 }
8491 }
8492}
8493
8494static inline void
8495gc_prof_sweep_timer_stop(rb_objspace_t *objspace)
8496{
8497 RUBY_DTRACE_GC_HOOK(SWEEP_END);
8498
8499 if (gc_prof_enabled(objspace)) {
8500 double sweep_time;
8501 gc_profile_record *record = gc_prof_record(objspace);
8502
8503 if (record->gc_time > 0) {
8504 sweep_time = elapsed_time_from(objspace->profile.gc_sweep_start_time);
8505 /* need to accumulate GC time for lazy sweep after gc() */
8506 record->gc_time += sweep_time;
8507 }
8508 else if (GC_PROFILE_MORE_DETAIL) {
8509 sweep_time = elapsed_time_from(objspace->profile.gc_sweep_start_time);
8510 }
8511
8512#if GC_PROFILE_MORE_DETAIL
8513 record->gc_sweep_time += sweep_time;
8514 if (heap_pages_deferred_final) record->flags |= GPR_FLAG_HAVE_FINALIZE;
8515#endif
8516 if (heap_pages_deferred_final) objspace->profile.latest_gc_info |= GPR_FLAG_HAVE_FINALIZE;
8517 }
8518}
8519
8520static inline void
8521gc_prof_set_malloc_info(rb_objspace_t *objspace)
8522{
8523#if GC_PROFILE_MORE_DETAIL
8524 if (gc_prof_enabled(objspace)) {
8525 gc_profile_record *record = gc_prof_record(objspace);
8526 record->allocate_increase = malloc_increase;
8527 record->allocate_limit = malloc_limit;
8528 }
8529#endif
8530}
8531
8532static inline void
8533gc_prof_set_heap_info(rb_objspace_t *objspace)
8534{
8535 if (gc_prof_enabled(objspace)) {
8536 gc_profile_record *record = gc_prof_record(objspace);
8537 size_t live = objspace->profile.total_allocated_objects_at_gc_start - total_freed_objects(objspace);
8538 size_t total = objspace->profile.heap_used_at_gc_start * HEAP_PAGE_OBJ_LIMIT;
8539
8540#if GC_PROFILE_MORE_DETAIL
8541 record->heap_use_pages = objspace->profile.heap_used_at_gc_start;
8542 record->heap_live_objects = live;
8543 record->heap_free_objects = total - live;
8544#endif
8545
8546 record->heap_total_objects = total;
8547 record->heap_use_size = live * BASE_SLOT_SIZE;
8548 record->heap_total_size = total * BASE_SLOT_SIZE;
8549 }
8550}
8551
8552/*
8553 * call-seq:
8554 * GC::Profiler.clear -> nil
8555 *
8556 * Clears the \GC profiler data.
8557 *
8558 */
8559
8560static VALUE
8561gc_profile_clear(VALUE _)
8562{
8563 rb_objspace_t *objspace = rb_gc_get_objspace();
8564 void *p = objspace->profile.records;
8565 objspace->profile.records = NULL;
8566 objspace->profile.size = 0;
8567 objspace->profile.next_index = 0;
8568 objspace->profile.current_record = 0;
8569 free(p);
8570 return Qnil;
8571}
8572
8573/*
8574 * call-seq:
8575 * GC::Profiler.raw_data -> [Hash, ...]
8576 *
8577 * Returns an Array of individual raw profile data Hashes ordered
8578 * from earliest to latest by +:GC_INVOKE_TIME+.
8579 *
8580 * For example:
8581 *
8582 * [
8583 * {
8584 * :GC_TIME=>1.3000000000000858e-05,
8585 * :GC_INVOKE_TIME=>0.010634999999999999,
8586 * :HEAP_USE_SIZE=>289640,
8587 * :HEAP_TOTAL_SIZE=>588960,
8588 * :HEAP_TOTAL_OBJECTS=>14724,
8589 * :GC_IS_MARKED=>false
8590 * },
8591 * # ...
8592 * ]
8593 *
8594 * The keys mean:
8595 *
8596 * +:GC_TIME+::
8597 * Time elapsed in seconds for this GC run
8598 * +:GC_INVOKE_TIME+::
8599 * Time elapsed in seconds from startup to when the GC was invoked
8600 * +:HEAP_USE_SIZE+::
8601 * Total bytes of heap used
8602 * +:HEAP_TOTAL_SIZE+::
8603 * Total size of heap in bytes
8604 * +:HEAP_TOTAL_OBJECTS+::
8605 * Total number of objects
8606 * +:GC_IS_MARKED+::
8607 * Returns +true+ if the GC is in mark phase
8608 *
8609 * If ruby was built with +GC_PROFILE_MORE_DETAIL+, you will also have access
8610 * to the following hash keys:
8611 *
8612 * +:GC_MARK_TIME+::
8613 * +:GC_SWEEP_TIME+::
8614 * +:ALLOCATE_INCREASE+::
8615 * +:ALLOCATE_LIMIT+::
8616 * +:HEAP_USE_PAGES+::
8617 * +:HEAP_LIVE_OBJECTS+::
8618 * +:HEAP_FREE_OBJECTS+::
8619 * +:HAVE_FINALIZE+::
8620 *
8621 */
8622
8623static VALUE
8624gc_profile_record_get(VALUE _)
8625{
8626 VALUE prof;
8627 VALUE gc_profile = rb_ary_new();
8628 size_t i;
8629 rb_objspace_t *objspace = rb_gc_get_objspace();
8630
8631 if (!objspace->profile.run) {
8632 return Qnil;
8633 }
8634
8635 for (i =0; i < objspace->profile.next_index; i++) {
8636 gc_profile_record *record = &objspace->profile.records[i];
8637
8638 prof = rb_hash_new();
8639 rb_hash_aset(prof, ID2SYM(rb_intern("GC_FLAGS")), gc_info_decode(objspace, rb_hash_new(), record->flags));
8640 rb_hash_aset(prof, ID2SYM(rb_intern("GC_TIME")), DBL2NUM(record->gc_time));
8641 rb_hash_aset(prof, ID2SYM(rb_intern("GC_INVOKE_TIME")), DBL2NUM(record->gc_invoke_time));
8642 rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_USE_SIZE")), SIZET2NUM(record->heap_use_size));
8643 rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_TOTAL_SIZE")), SIZET2NUM(record->heap_total_size));
8644 rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_TOTAL_OBJECTS")), SIZET2NUM(record->heap_total_objects));
8645 rb_hash_aset(prof, ID2SYM(rb_intern("MOVED_OBJECTS")), SIZET2NUM(record->moved_objects));
8646 rb_hash_aset(prof, ID2SYM(rb_intern("GC_IS_MARKED")), Qtrue);
8647#if GC_PROFILE_MORE_DETAIL
8648 rb_hash_aset(prof, ID2SYM(rb_intern("GC_MARK_TIME")), DBL2NUM(record->gc_mark_time));
8649 rb_hash_aset(prof, ID2SYM(rb_intern("GC_SWEEP_TIME")), DBL2NUM(record->gc_sweep_time));
8650 rb_hash_aset(prof, ID2SYM(rb_intern("ALLOCATE_INCREASE")), SIZET2NUM(record->allocate_increase));
8651 rb_hash_aset(prof, ID2SYM(rb_intern("ALLOCATE_LIMIT")), SIZET2NUM(record->allocate_limit));
8652 rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_USE_PAGES")), SIZET2NUM(record->heap_use_pages));
8653 rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_LIVE_OBJECTS")), SIZET2NUM(record->heap_live_objects));
8654 rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_FREE_OBJECTS")), SIZET2NUM(record->heap_free_objects));
8655
8656 rb_hash_aset(prof, ID2SYM(rb_intern("REMOVING_OBJECTS")), SIZET2NUM(record->removing_objects));
8657 rb_hash_aset(prof, ID2SYM(rb_intern("EMPTY_OBJECTS")), SIZET2NUM(record->empty_objects));
8658
8659 rb_hash_aset(prof, ID2SYM(rb_intern("HAVE_FINALIZE")), (record->flags & GPR_FLAG_HAVE_FINALIZE) ? Qtrue : Qfalse);
8660#endif
8661
8662#if RGENGC_PROFILE > 0
8663 rb_hash_aset(prof, ID2SYM(rb_intern("OLD_OBJECTS")), SIZET2NUM(record->old_objects));
8664 rb_hash_aset(prof, ID2SYM(rb_intern("REMEMBERED_NORMAL_OBJECTS")), SIZET2NUM(record->remembered_normal_objects));
8665 rb_hash_aset(prof, ID2SYM(rb_intern("REMEMBERED_SHADY_OBJECTS")), SIZET2NUM(record->remembered_shady_objects));
8666#endif
8667 rb_ary_push(gc_profile, prof);
8668 }
8669
8670 return gc_profile;
8671}
8672
8673#if GC_PROFILE_MORE_DETAIL
8674#define MAJOR_REASON_MAX 0x10
8675
8676static char *
8677gc_profile_dump_major_reason(unsigned int flags, char *buff)
8678{
8679 unsigned int reason = flags & GPR_FLAG_MAJOR_MASK;
8680 int i = 0;
8681
8682 if (reason == GPR_FLAG_NONE) {
8683 buff[0] = '-';
8684 buff[1] = 0;
8685 }
8686 else {
8687#define C(x, s) \
8688 if (reason & GPR_FLAG_MAJOR_BY_##x) { \
8689 buff[i++] = #x[0]; \
8690 if (i >= MAJOR_REASON_MAX) rb_bug("gc_profile_dump_major_reason: overflow"); \
8691 buff[i] = 0; \
8692 }
8693 C(NOFREE, N);
8694 C(OLDGEN, O);
8695 C(SHADY, S);
8696#if RGENGC_ESTIMATE_OLDMALLOC
8697 C(OLDMALLOC, M);
8698#endif
8699#undef C
8700 }
8701 return buff;
8702}
8703#endif
8704
8705
8706
8707static void
8708gc_profile_dump_on(VALUE out, VALUE (*append)(VALUE, VALUE))
8709{
8710 rb_objspace_t *objspace = rb_gc_get_objspace();
8711 size_t count = objspace->profile.next_index;
8712#ifdef MAJOR_REASON_MAX
8713 char reason_str[MAJOR_REASON_MAX];
8714#endif
8715
8716 if (objspace->profile.run && count /* > 1 */) {
8717 size_t i;
8718 const gc_profile_record *record;
8719
8720 append(out, rb_sprintf("GC %"PRIuSIZE" invokes.\n", objspace->profile.count));
8721 append(out, rb_str_new_cstr("Index Invoke Time(sec) Use Size(byte) Total Size(byte) Total Object GC Time(ms)\n"));
8722
8723 for (i = 0; i < count; i++) {
8724 record = &objspace->profile.records[i];
8725 append(out, rb_sprintf("%5"PRIuSIZE" %19.3f %20"PRIuSIZE" %20"PRIuSIZE" %20"PRIuSIZE" %30.20f\n",
8726 i+1, record->gc_invoke_time, record->heap_use_size,
8727 record->heap_total_size, record->heap_total_objects, record->gc_time*1000));
8728 }
8729
8730#if GC_PROFILE_MORE_DETAIL
8731 const char *str = "\n\n" \
8732 "More detail.\n" \
8733 "Prepare Time = Previously GC's rest sweep time\n"
8734 "Index Flags Allocate Inc. Allocate Limit"
8735#if CALC_EXACT_MALLOC_SIZE
8736 " Allocated Size"
8737#endif
8738 " Use Page Mark Time(ms) Sweep Time(ms) Prepare Time(ms) LivingObj FreeObj RemovedObj EmptyObj"
8739#if RGENGC_PROFILE
8740 " OldgenObj RemNormObj RemShadObj"
8741#endif
8742#if GC_PROFILE_DETAIL_MEMORY
8743 " MaxRSS(KB) MinorFLT MajorFLT"
8744#endif
8745 "\n";
8746 append(out, rb_str_new_cstr(str));
8747
8748 for (i = 0; i < count; i++) {
8749 record = &objspace->profile.records[i];
8750 append(out, rb_sprintf("%5"PRIuSIZE" %4s/%c/%6s%c %13"PRIuSIZE" %15"PRIuSIZE
8751#if CALC_EXACT_MALLOC_SIZE
8752 " %15"PRIuSIZE
8753#endif
8754 " %9"PRIuSIZE" %17.12f %17.12f %17.12f %10"PRIuSIZE" %10"PRIuSIZE" %10"PRIuSIZE" %10"PRIuSIZE
8755#if RGENGC_PROFILE
8756 "%10"PRIuSIZE" %10"PRIuSIZE" %10"PRIuSIZE
8757#endif
8758#if GC_PROFILE_DETAIL_MEMORY
8759 "%11ld %8ld %8ld"
8760#endif
8761
8762 "\n",
8763 i+1,
8764 gc_profile_dump_major_reason(record->flags, reason_str),
8765 (record->flags & GPR_FLAG_HAVE_FINALIZE) ? 'F' : '.',
8766 (record->flags & GPR_FLAG_NEWOBJ) ? "NEWOBJ" :
8767 (record->flags & GPR_FLAG_MALLOC) ? "MALLOC" :
8768 (record->flags & GPR_FLAG_METHOD) ? "METHOD" :
8769 (record->flags & GPR_FLAG_CAPI) ? "CAPI__" : "??????",
8770 (record->flags & GPR_FLAG_STRESS) ? '!' : ' ',
8771 record->allocate_increase, record->allocate_limit,
8772#if CALC_EXACT_MALLOC_SIZE
8773 record->allocated_size,
8774#endif
8775 record->heap_use_pages,
8776 record->gc_mark_time*1000,
8777 record->gc_sweep_time*1000,
8778 record->prepare_time*1000,
8779
8780 record->heap_live_objects,
8781 record->heap_free_objects,
8782 record->removing_objects,
8783 record->empty_objects
8784#if RGENGC_PROFILE
8785 ,
8786 record->old_objects,
8787 record->remembered_normal_objects,
8788 record->remembered_shady_objects
8789#endif
8790#if GC_PROFILE_DETAIL_MEMORY
8791 ,
8792 record->maxrss / 1024,
8793 record->minflt,
8794 record->majflt
8795#endif
8796
8797 ));
8798 }
8799#endif
8800 }
8801}
8802
8803/*
8804 * call-seq:
8805 * GC::Profiler.result -> String
8806 *
8807 * Returns a profile data report such as:
8808 *
8809 * GC 1 invokes.
8810 * Index Invoke Time(sec) Use Size(byte) Total Size(byte) Total Object GC time(ms)
8811 * 1 0.012 159240 212940 10647 0.00000000000001530000
8812 */
8813
8814static VALUE
8815gc_profile_result(VALUE _)
8816{
8817 VALUE str = rb_str_buf_new(0);
8818 gc_profile_dump_on(str, rb_str_buf_append);
8819 return str;
8820}
8821
8822/*
8823 * call-seq:
8824 * GC::Profiler.report
8825 * GC::Profiler.report(io)
8826 *
8827 * Writes the GC::Profiler.result to <tt>$stdout</tt> or the given IO object.
8828 *
8829 */
8830
8831static VALUE
8832gc_profile_report(int argc, VALUE *argv, VALUE self)
8833{
8834 VALUE out;
8835
8836 out = (!rb_check_arity(argc, 0, 1) ? rb_stdout : argv[0]);
8837 gc_profile_dump_on(out, rb_io_write);
8838
8839 return Qnil;
8840}
8841
8842/*
8843 * call-seq:
8844 * GC::Profiler.total_time -> float
8845 *
8846 * The total time used for garbage collection in seconds
8847 */
8848
8849static VALUE
8850gc_profile_total_time(VALUE self)
8851{
8852 double time = 0;
8853 rb_objspace_t *objspace = rb_gc_get_objspace();
8854
8855 if (objspace->profile.run && objspace->profile.next_index > 0) {
8856 size_t i;
8857 size_t count = objspace->profile.next_index;
8858
8859 for (i = 0; i < count; i++) {
8860 time += objspace->profile.records[i].gc_time;
8861 }
8862 }
8863 return DBL2NUM(time);
8864}
8865
8866/*
8867 * call-seq:
8868 * GC::Profiler.enabled? -> true or false
8869 *
8870 * The current status of \GC profile mode.
8871 */
8872
8873static VALUE
8874gc_profile_enable_get(VALUE self)
8875{
8876 rb_objspace_t *objspace = rb_gc_get_objspace();
8877 return objspace->profile.run ? Qtrue : Qfalse;
8878}
8879
8880/*
8881 * call-seq:
8882 * GC::Profiler.enable -> nil
8883 *
8884 * Starts the \GC profiler.
8885 *
8886 */
8887
8888static VALUE
8889gc_profile_enable(VALUE _)
8890{
8891 rb_objspace_t *objspace = rb_gc_get_objspace();
8892 objspace->profile.run = TRUE;
8893 objspace->profile.current_record = 0;
8894 return Qnil;
8895}
8896
8897/*
8898 * call-seq:
8899 * GC::Profiler.disable -> nil
8900 *
8901 * Stops the \GC profiler.
8902 *
8903 */
8904
8905static VALUE
8906gc_profile_disable(VALUE _)
8907{
8908 rb_objspace_t *objspace = rb_gc_get_objspace();
8909
8910 objspace->profile.run = FALSE;
8911 objspace->profile.current_record = 0;
8912 return Qnil;
8913}
8914
8915/*
8916 * call-seq:
8917 * GC.verify_internal_consistency -> nil
8918 *
8919 * Verify internal consistency.
8920 *
8921 * This method is implementation specific.
8922 * Now this method checks generational consistency
8923 * if RGenGC is supported.
8924 */
8925static VALUE
8926gc_verify_internal_consistency_m(VALUE dummy)
8927{
8928 gc_verify_internal_consistency(rb_gc_get_objspace());
8929 return Qnil;
8930}
8931
8932#if GC_CAN_COMPILE_COMPACTION
8933/*
8934 * call-seq:
8935 * GC.auto_compact = flag
8936 *
8937 * Updates automatic compaction mode.
8938 *
8939 * When enabled, the compactor will execute on every major collection.
8940 *
8941 * Enabling compaction will degrade performance on major collections.
8942 */
8943static VALUE
8944gc_set_auto_compact(VALUE _, VALUE v)
8945{
8946 GC_ASSERT(GC_COMPACTION_SUPPORTED);
8947
8948 ruby_enable_autocompact = RTEST(v);
8949
8950#if RGENGC_CHECK_MODE
8951 ruby_autocompact_compare_func = NULL;
8952
8953 if (SYMBOL_P(v)) {
8954 ID id = RB_SYM2ID(v);
8955 if (id == rb_intern("empty")) {
8956 ruby_autocompact_compare_func = compare_free_slots;
8957 }
8958 }
8959#endif
8960
8961 return v;
8962}
8963#else
8964# define gc_set_auto_compact rb_f_notimplement
8965#endif
8966
8967#if GC_CAN_COMPILE_COMPACTION
8968/*
8969 * call-seq:
8970 * GC.auto_compact -> true or false
8971 *
8972 * Returns whether or not automatic compaction has been enabled.
8973 */
8974static VALUE
8975gc_get_auto_compact(VALUE _)
8976{
8977 return ruby_enable_autocompact ? Qtrue : Qfalse;
8978}
8979#else
8980# define gc_get_auto_compact rb_f_notimplement
8981#endif
8982
8983#if GC_CAN_COMPILE_COMPACTION
8984/*
8985 * call-seq:
8986 * GC.latest_compact_info -> hash
8987 *
8988 * Returns information about object moved in the most recent \GC compaction.
8989 *
8990 * The returned +hash+ contains the following keys:
8991 *
8992 * [considered]
8993 * Hash containing the type of the object as the key and the number of
8994 * objects of that type that were considered for movement.
8995 * [moved]
8996 * Hash containing the type of the object as the key and the number of
8997 * objects of that type that were actually moved.
8998 * [moved_up]
8999 * Hash containing the type of the object as the key and the number of
9000 * objects of that type that were increased in size.
9001 * [moved_down]
9002 * Hash containing the type of the object as the key and the number of
9003 * objects of that type that were decreased in size.
9004 *
9005 * Some objects can't be moved (due to pinning) so these numbers can be used to
9006 * calculate compaction efficiency.
9007 */
9008static VALUE
9009gc_compact_stats(VALUE self)
9010{
9011 rb_objspace_t *objspace = rb_gc_get_objspace();
9012 VALUE h = rb_hash_new();
9013 VALUE considered = rb_hash_new();
9014 VALUE moved = rb_hash_new();
9015 VALUE moved_up = rb_hash_new();
9016 VALUE moved_down = rb_hash_new();
9017
9018 for (size_t i = 0; i < T_MASK; i++) {
9019 if (objspace->rcompactor.considered_count_table[i]) {
9020 rb_hash_aset(considered, type_sym(i), SIZET2NUM(objspace->rcompactor.considered_count_table[i]));
9021 }
9022
9023 if (objspace->rcompactor.moved_count_table[i]) {
9024 rb_hash_aset(moved, type_sym(i), SIZET2NUM(objspace->rcompactor.moved_count_table[i]));
9025 }
9026
9027 if (objspace->rcompactor.moved_up_count_table[i]) {
9028 rb_hash_aset(moved_up, type_sym(i), SIZET2NUM(objspace->rcompactor.moved_up_count_table[i]));
9029 }
9030
9031 if (objspace->rcompactor.moved_down_count_table[i]) {
9032 rb_hash_aset(moved_down, type_sym(i), SIZET2NUM(objspace->rcompactor.moved_down_count_table[i]));
9033 }
9034 }
9035
9036 rb_hash_aset(h, ID2SYM(rb_intern("considered")), considered);
9037 rb_hash_aset(h, ID2SYM(rb_intern("moved")), moved);
9038 rb_hash_aset(h, ID2SYM(rb_intern("moved_up")), moved_up);
9039 rb_hash_aset(h, ID2SYM(rb_intern("moved_down")), moved_down);
9040
9041 return h;
9042}
9043#else
9044# define gc_compact_stats rb_f_notimplement
9045#endif
9046
9047#if GC_CAN_COMPILE_COMPACTION
9048/*
9049 * call-seq:
9050 * GC.compact -> hash
9051 *
9052 * This function compacts objects together in Ruby's heap. It eliminates
9053 * unused space (or fragmentation) in the heap by moving objects in to that
9054 * unused space.
9055 *
9056 * The returned +hash+ contains statistics about the objects that were moved;
9057 * see GC.latest_compact_info.
9058 *
9059 * This method is only expected to work on CRuby.
9060 *
9061 * To test whether \GC compaction is supported, use the idiom:
9062 *
9063 * GC.respond_to?(:compact)
9064 */
9065static VALUE
9066gc_compact(VALUE self)
9067{
9068 rb_objspace_t *objspace = rb_gc_get_objspace();
9069 int full_marking_p = gc_config_full_mark_val;
9070 gc_config_full_mark_set(TRUE);
9071
9072 /* Run GC with compaction enabled */
9073 rb_gc_impl_start(rb_gc_get_objspace(), true, true, true, true);
9074 gc_config_full_mark_set(full_marking_p);
9075
9076 return gc_compact_stats(self);
9077}
9078#else
9079# define gc_compact rb_f_notimplement
9080#endif
9081
9082#if GC_CAN_COMPILE_COMPACTION
9083struct desired_compaction_pages_i_data {
9085 size_t required_slots[HEAP_COUNT];
9086};
9087
9088static int
9089desired_compaction_pages_i(struct heap_page *page, void *data)
9090{
9091 struct desired_compaction_pages_i_data *tdata = data;
9092 rb_objspace_t *objspace = tdata->objspace;
9093 VALUE vstart = (VALUE)page->start;
9094 VALUE vend = vstart + (VALUE)(page->total_slots * page->heap->slot_size);
9095
9096
9097 for (VALUE v = vstart; v != vend; v += page->heap->slot_size) {
9098 asan_unpoisoning_object(v) {
9099 /* skip T_NONEs; they won't be moved */
9100 if (BUILTIN_TYPE(v) != T_NONE) {
9101 rb_heap_t *dest_pool = gc_compact_destination_pool(objspace, page->heap, v);
9102 size_t dest_pool_idx = dest_pool - heaps;
9103 tdata->required_slots[dest_pool_idx]++;
9104 }
9105 }
9106 }
9107
9108 return 0;
9109}
9110
9111/* call-seq:
9112 * GC.verify_compaction_references(toward: nil, double_heap: false) -> hash
9113 *
9114 * Verify compaction reference consistency.
9115 *
9116 * This method is implementation specific. During compaction, objects that
9117 * were moved are replaced with T_MOVED objects. No object should have a
9118 * reference to a T_MOVED object after compaction.
9119 *
9120 * This function expands the heap to ensure room to move all objects,
9121 * compacts the heap to make sure everything moves, updates all references,
9122 * then performs a full \GC. If any object contains a reference to a T_MOVED
9123 * object, that object should be pushed on the mark stack, and will
9124 * make a SEGV.
9125 */
9126static VALUE
9127gc_verify_compaction_references(int argc, VALUE* argv, VALUE self)
9128{
9129 static ID keywords[3] = {0};
9130 if (!keywords[0]) {
9131 keywords[0] = rb_intern("toward");
9132 keywords[1] = rb_intern("double_heap");
9133 keywords[2] = rb_intern("expand_heap");
9134 }
9135
9136 VALUE options;
9137 rb_scan_args_kw(rb_keyword_given_p(), argc, argv, ":", &options);
9138
9139 VALUE arguments[3] = { Qnil, Qfalse, Qfalse };
9140 int kwarg_count = rb_get_kwargs(options, keywords, 0, 3, arguments);
9141 bool toward_empty = kwarg_count > 0 && SYMBOL_P(arguments[0]) && SYM2ID(arguments[0]) == rb_intern("empty");
9142 bool expand_heap = (kwarg_count > 1 && RTEST(arguments[1])) || (kwarg_count > 2 && RTEST(arguments[2]));
9143
9144 rb_objspace_t *objspace = rb_gc_get_objspace();
9145
9146 /* Clear the heap. */
9147 rb_gc_impl_start(objspace, true, true, true, false);
9148
9149 unsigned int lev = RB_GC_VM_LOCK();
9150 {
9151 gc_rest(objspace);
9152
9153 /* if both double_heap and expand_heap are set, expand_heap takes precedence */
9154 if (expand_heap) {
9155 struct desired_compaction_pages_i_data desired_compaction = {
9156 .objspace = objspace,
9157 .required_slots = {0},
9158 };
9159 /* Work out how many objects want to be in each size pool, taking account of moves */
9160 objspace_each_pages(objspace, desired_compaction_pages_i, &desired_compaction, TRUE);
9161
9162 /* Find out which pool has the most pages */
9163 size_t max_existing_pages = 0;
9164 for (int i = 0; i < HEAP_COUNT; i++) {
9165 rb_heap_t *heap = &heaps[i];
9166 max_existing_pages = MAX(max_existing_pages, heap->total_pages);
9167 }
9168
9169 /* Add pages to each size pool so that compaction is guaranteed to move every object */
9170 for (int i = 0; i < HEAP_COUNT; i++) {
9171 rb_heap_t *heap = &heaps[i];
9172
9173 size_t pages_to_add = 0;
9174 /*
9175 * Step 1: Make sure every pool has the same number of pages, by adding empty pages
9176 * to smaller pools. This is required to make sure the compact cursor can advance
9177 * through all of the pools in `gc_sweep_compact` without hitting the "sweep &
9178 * compact cursors met" condition on some pools before fully compacting others
9179 */
9180 pages_to_add += max_existing_pages - heap->total_pages;
9181 /*
9182 * Step 2: Now add additional free pages to each size pool sufficient to hold all objects
9183 * that want to be in that size pool, whether moved into it or moved within it
9184 */
9185 objspace->heap_pages.allocatable_slots = desired_compaction.required_slots[i];
9186 while (objspace->heap_pages.allocatable_slots > 0) {
9187 heap_page_allocate_and_initialize(objspace, heap);
9188 }
9189 /*
9190 * Step 3: Add two more pages so that the compact & sweep cursors will meet _after_ all objects
9191 * have been moved, and not on the last iteration of the `gc_sweep_compact` loop
9192 */
9193 pages_to_add += 2;
9194
9195 for (; pages_to_add > 0; pages_to_add--) {
9196 heap_page_allocate_and_initialize_force(objspace, heap);
9197 }
9198 }
9199 }
9200
9201 if (toward_empty) {
9202 objspace->rcompactor.compare_func = compare_free_slots;
9203 }
9204 }
9205 RB_GC_VM_UNLOCK(lev);
9206
9207 rb_gc_impl_start(rb_gc_get_objspace(), true, true, true, true);
9208
9209 rb_objspace_reachable_objects_from_root(root_obj_check_moved_i, objspace);
9210 objspace_each_objects(objspace, heap_check_moved_i, objspace, TRUE);
9211
9212 objspace->rcompactor.compare_func = NULL;
9213
9214 return gc_compact_stats(self);
9215}
9216#else
9217# define gc_verify_compaction_references rb_f_notimplement
9218#endif
9219
9220void
9221rb_gc_impl_objspace_free(void *objspace_ptr)
9222{
9223 rb_objspace_t *objspace = objspace_ptr;
9224
9225 if (is_lazy_sweeping(objspace))
9226 rb_bug("lazy sweeping underway when freeing object space");
9227
9228 free(objspace->profile.records);
9229 objspace->profile.records = NULL;
9230
9231 for (size_t i = 0; i < rb_darray_size(objspace->heap_pages.sorted); i++) {
9232 heap_page_free(objspace, rb_darray_get(objspace->heap_pages.sorted, i));
9233 }
9234 rb_darray_free_without_gc(objspace->heap_pages.sorted);
9235 heap_pages_lomem = 0;
9236 heap_pages_himem = 0;
9237
9238 for (int i = 0; i < HEAP_COUNT; i++) {
9239 rb_heap_t *heap = &heaps[i];
9240 heap->total_pages = 0;
9241 heap->total_slots = 0;
9242 }
9243
9244 free_stack_chunks(&objspace->mark_stack);
9245 mark_stack_free_cache(&objspace->mark_stack);
9246
9247 rb_darray_free_without_gc(objspace->weak_references);
9248
9249 free(objspace);
9250}
9251
9252#if MALLOC_ALLOCATED_SIZE
9253/*
9254 * call-seq:
9255 * GC.malloc_allocated_size -> Integer
9256 *
9257 * Returns the size of memory allocated by malloc().
9258 *
9259 * Only available if ruby was built with +CALC_EXACT_MALLOC_SIZE+.
9260 */
9261
9262static VALUE
9263gc_malloc_allocated_size(VALUE self)
9264{
9265 rb_objspace_t *objspace = (rb_objspace_t *)rb_gc_get_objspace();
9266 return ULL2NUM(objspace->malloc_params.allocated_size);
9267}
9268
9269/*
9270 * call-seq:
9271 * GC.malloc_allocations -> Integer
9272 *
9273 * Returns the number of malloc() allocations.
9274 *
9275 * Only available if ruby was built with +CALC_EXACT_MALLOC_SIZE+.
9276 */
9277
9278static VALUE
9279gc_malloc_allocations(VALUE self)
9280{
9281 rb_objspace_t *objspace = (rb_objspace_t *)rb_gc_get_objspace();
9282 return ULL2NUM(objspace->malloc_params.allocations);
9283}
9284#endif
9285
9286void rb_gc_impl_before_fork(void *objspace_ptr) { /* no-op */ }
9287void rb_gc_impl_after_fork(void *objspace_ptr, rb_pid_t pid) {
9288 if (pid == 0) { /* child process */
9289 rb_gc_ractor_newobj_cache_foreach(gc_ractor_newobj_cache_clear, NULL);
9290 }
9291}
9292
9293VALUE rb_ident_hash_new_with_size(st_index_t size);
9294
9295/*
9296 * call-seq:
9297 * GC.add_stress_to_class(class[, ...])
9298 *
9299 * Raises NoMemoryError when allocating an instance of the given classes.
9300 *
9301 */
9302static VALUE
9303rb_gcdebug_add_stress_to_class(int argc, VALUE *argv, VALUE self)
9304{
9305 rb_objspace_t *objspace = rb_gc_get_objspace();
9306
9307 if (!stress_to_class) {
9308 set_stress_to_class(rb_ident_hash_new_with_size(argc));
9309 }
9310
9311 for (int i = 0; i < argc; i++) {
9312 VALUE klass = argv[i];
9313 rb_hash_aset(stress_to_class, klass, Qtrue);
9314 }
9315
9316 return self;
9317}
9318
9319/*
9320 * call-seq:
9321 * GC.remove_stress_to_class(class[, ...])
9322 *
9323 * No longer raises NoMemoryError when allocating an instance of the
9324 * given classes.
9325 *
9326 */
9327static VALUE
9328rb_gcdebug_remove_stress_to_class(int argc, VALUE *argv, VALUE self)
9329{
9330 rb_objspace_t *objspace = rb_gc_get_objspace();
9331
9332 if (stress_to_class) {
9333 for (int i = 0; i < argc; ++i) {
9334 rb_hash_delete(stress_to_class, argv[i]);
9335 }
9336
9337 if (rb_hash_size(stress_to_class) == 0) {
9338 stress_to_class = 0;
9339 }
9340 }
9341
9342 return Qnil;
9343}
9344
9345void *
9346rb_gc_impl_objspace_alloc(void)
9347{
9348 rb_objspace_t *objspace = calloc1(sizeof(rb_objspace_t));
9349
9350 return objspace;
9351}
9352
9353void
9354rb_gc_impl_objspace_init(void *objspace_ptr)
9355{
9356 rb_objspace_t *objspace = objspace_ptr;
9357
9358 gc_config_full_mark_set(TRUE);
9359
9360 objspace->flags.measure_gc = true;
9361 malloc_limit = gc_params.malloc_limit_min;
9362 objspace->finalize_deferred_pjob = rb_postponed_job_preregister(0, gc_finalize_deferred, objspace);
9363 if (objspace->finalize_deferred_pjob == POSTPONED_JOB_HANDLE_INVALID) {
9364 rb_bug("Could not preregister postponed job for GC");
9365 }
9366
9367 for (int i = 0; i < HEAP_COUNT; i++) {
9368 rb_heap_t *heap = &heaps[i];
9369
9370 heap->slot_size = (1 << i) * BASE_SLOT_SIZE;
9371
9372 ccan_list_head_init(&heap->pages);
9373 }
9374
9375 rb_darray_make_without_gc(&objspace->heap_pages.sorted, 0);
9376 rb_darray_make_without_gc(&objspace->weak_references, 0);
9377
9378 // TODO: debug why on Windows Ruby crashes on boot when GC is on.
9379#ifdef _WIN32
9380 dont_gc_on();
9381#endif
9382
9383#if defined(INIT_HEAP_PAGE_ALLOC_USE_MMAP)
9384 /* Need to determine if we can use mmap at runtime. */
9385 heap_page_alloc_use_mmap = INIT_HEAP_PAGE_ALLOC_USE_MMAP;
9386#endif
9387#if RGENGC_ESTIMATE_OLDMALLOC
9388 objspace->rgengc.oldmalloc_increase_limit = gc_params.oldmalloc_limit_min;
9389#endif
9390 /* Set size pools allocatable pages. */
9391 for (int i = 0; i < HEAP_COUNT; i++) {
9392 /* Set the default value of heap_init_slots. */
9393 gc_params.heap_init_slots[i] = GC_HEAP_INIT_SLOTS;
9394 }
9395
9396 init_mark_stack(&objspace->mark_stack);
9397
9398 objspace->profile.invoke_time = getrusage_time();
9399 finalizer_table = st_init_numtable();
9400}
9401
9402void
9403rb_gc_impl_init(void)
9404{
9405 VALUE gc_constants = rb_hash_new();
9406 rb_hash_aset(gc_constants, ID2SYM(rb_intern("DEBUG")), GC_DEBUG ? Qtrue : Qfalse);
9407 rb_hash_aset(gc_constants, ID2SYM(rb_intern("BASE_SLOT_SIZE")), SIZET2NUM(BASE_SLOT_SIZE - RVALUE_OVERHEAD));
9408 rb_hash_aset(gc_constants, ID2SYM(rb_intern("RBASIC_SIZE")), SIZET2NUM(sizeof(struct RBasic)));
9409 rb_hash_aset(gc_constants, ID2SYM(rb_intern("RVALUE_OVERHEAD")), SIZET2NUM(RVALUE_OVERHEAD));
9410 rb_hash_aset(gc_constants, ID2SYM(rb_intern("HEAP_PAGE_OBJ_LIMIT")), SIZET2NUM(HEAP_PAGE_OBJ_LIMIT));
9411 rb_hash_aset(gc_constants, ID2SYM(rb_intern("HEAP_PAGE_BITMAP_SIZE")), SIZET2NUM(HEAP_PAGE_BITMAP_SIZE));
9412 rb_hash_aset(gc_constants, ID2SYM(rb_intern("HEAP_PAGE_SIZE")), SIZET2NUM(HEAP_PAGE_SIZE));
9413 rb_hash_aset(gc_constants, ID2SYM(rb_intern("HEAP_COUNT")), LONG2FIX(HEAP_COUNT));
9414 rb_hash_aset(gc_constants, ID2SYM(rb_intern("RVARGC_MAX_ALLOCATE_SIZE")), LONG2FIX(heap_slot_size(HEAP_COUNT - 1)));
9415 rb_hash_aset(gc_constants, ID2SYM(rb_intern("RVALUE_OLD_AGE")), LONG2FIX(RVALUE_OLD_AGE));
9416 if (RB_BUG_INSTEAD_OF_RB_MEMERROR+0) {
9417 rb_hash_aset(gc_constants, ID2SYM(rb_intern("RB_BUG_INSTEAD_OF_RB_MEMERROR")), Qtrue);
9418 }
9419 OBJ_FREEZE(gc_constants);
9420 /* Internal constants in the garbage collector. */
9421 rb_define_const(rb_mGC, "INTERNAL_CONSTANTS", gc_constants);
9422
9423 if (GC_COMPACTION_SUPPORTED) {
9424 rb_define_singleton_method(rb_mGC, "compact", gc_compact, 0);
9425 rb_define_singleton_method(rb_mGC, "auto_compact", gc_get_auto_compact, 0);
9426 rb_define_singleton_method(rb_mGC, "auto_compact=", gc_set_auto_compact, 1);
9427 rb_define_singleton_method(rb_mGC, "latest_compact_info", gc_compact_stats, 0);
9428 rb_define_singleton_method(rb_mGC, "verify_compaction_references", gc_verify_compaction_references, -1);
9429 }
9430 else {
9434 rb_define_singleton_method(rb_mGC, "latest_compact_info", rb_f_notimplement, 0);
9435 rb_define_singleton_method(rb_mGC, "verify_compaction_references", rb_f_notimplement, -1);
9436 }
9437
9438 if (GC_DEBUG_STRESS_TO_CLASS) {
9439 rb_define_singleton_method(rb_mGC, "add_stress_to_class", rb_gcdebug_add_stress_to_class, -1);
9440 rb_define_singleton_method(rb_mGC, "remove_stress_to_class", rb_gcdebug_remove_stress_to_class, -1);
9441 }
9442
9443 /* internal methods */
9444 rb_define_singleton_method(rb_mGC, "verify_internal_consistency", gc_verify_internal_consistency_m, 0);
9445
9446#if MALLOC_ALLOCATED_SIZE
9447 rb_define_singleton_method(rb_mGC, "malloc_allocated_size", gc_malloc_allocated_size, 0);
9448 rb_define_singleton_method(rb_mGC, "malloc_allocations", gc_malloc_allocations, 0);
9449#endif
9450
9451 VALUE rb_mProfiler = rb_define_module_under(rb_mGC, "Profiler");
9452 rb_define_singleton_method(rb_mProfiler, "enabled?", gc_profile_enable_get, 0);
9453 rb_define_singleton_method(rb_mProfiler, "enable", gc_profile_enable, 0);
9454 rb_define_singleton_method(rb_mProfiler, "raw_data", gc_profile_record_get, 0);
9455 rb_define_singleton_method(rb_mProfiler, "disable", gc_profile_disable, 0);
9456 rb_define_singleton_method(rb_mProfiler, "clear", gc_profile_clear, 0);
9457 rb_define_singleton_method(rb_mProfiler, "result", gc_profile_result, 0);
9458 rb_define_singleton_method(rb_mProfiler, "report", gc_profile_report, -1);
9459 rb_define_singleton_method(rb_mProfiler, "total_time", gc_profile_total_time, 0);
9460
9461 {
9462 VALUE opts;
9463 /* \GC build options */
9464 rb_define_const(rb_mGC, "OPTS", opts = rb_ary_new());
9465#define OPT(o) if (o) rb_ary_push(opts, rb_interned_str(#o, sizeof(#o) - 1))
9466 OPT(GC_DEBUG);
9467 OPT(USE_RGENGC);
9468 OPT(RGENGC_DEBUG);
9469 OPT(RGENGC_CHECK_MODE);
9470 OPT(RGENGC_PROFILE);
9471 OPT(RGENGC_ESTIMATE_OLDMALLOC);
9472 OPT(GC_PROFILE_MORE_DETAIL);
9473 OPT(GC_ENABLE_LAZY_SWEEP);
9474 OPT(CALC_EXACT_MALLOC_SIZE);
9475 OPT(MALLOC_ALLOCATED_SIZE);
9476 OPT(MALLOC_ALLOCATED_SIZE_CHECK);
9477 OPT(GC_PROFILE_DETAIL_MEMORY);
9478 OPT(GC_COMPACTION_SUPPORTED);
9479#undef OPT
9480 OBJ_FREEZE(opts);
9481 }
9482}
#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:1787
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:1753
#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
#define RUBY_INTERNAL_EVENT_NEWOBJ
Object allocated.
Definition event.h:93
static VALUE RB_FL_TEST(VALUE obj, VALUE flags)
Tests if the given flag(s) are set or not.
Definition fl_type.h:489
static void RB_FL_SET_RAW(VALUE obj, VALUE flags)
This is an implementation detail of RB_FL_SET().
Definition fl_type.h:600
static void RB_FL_UNSET_RAW(VALUE obj, VALUE flags)
This is an implementation detail of RB_FL_UNSET().
Definition fl_type.h:660
@ RUBY_FL_PROMOTED
Ruby objects are "generational".
Definition fl_type.h:217
VALUE rb_define_module_under(VALUE outer, const char *name)
Defines a module under the namespace of outer.
Definition class.c:1624
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:3150
int rb_keyword_given_p(void)
Determines if the current method is given a keyword argument.
Definition eval.c:1049
int rb_get_kwargs(VALUE keyword_hash, const ID *table, int required, int optional, VALUE *values)
Keyword argument deconstructor.
Definition class.c:2926
#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:136
#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:134
#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:63
#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:131
#define FL_SET
Old name of RB_FL_SET.
Definition fl_type.h:128
#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:130
#define FL_UNSET
Old name of RB_FL_UNSET.
Definition fl_type.h:132
#define FIXNUM_P
Old name of RB_FIXNUM_P.
#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:475
VALUE rb_eRuntimeError
RuntimeError exception.
Definition error.c:1428
void rb_warn(const char *fmt,...)
Identical to rb_warning(), except it reports unless $VERBOSE is nil.
Definition error.c:466
VALUE rb_obj_hide(VALUE obj)
Make the object invisible from Ruby code.
Definition object.c:100
VALUE rb_mGC
GC module.
Definition gc.c:422
VALUE rb_equal(VALUE lhs, VALUE rhs)
This function is an optimised version of calling #==.
Definition object.c:177
VALUE rb_stdout
STDOUT constant.
Definition io.c:201
#define RB_GNUC_EXTENSION_BLOCK(x)
This is expanded to the passed token for non-GCC compilers.
Definition defines.h:91
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:706
#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:3738
VALUE rb_str_buf_new(long capa)
Allocates a "string buffer".
Definition string.c:1693
#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:1513
const char * rb_sourcefile(void)
Resembles __FILE__.
Definition vm.c:1916
VALUE rb_f_notimplement(int argc, const VALUE *argv, VALUE obj, VALUE marker)
Raises rb_eNotImpError.
Definition vm_method.c:788
int rb_sourceline(void)
Resembles __LINE__.
Definition vm.c:1930
#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:943
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:2037
#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 DECIMAL_SIZE_OF_BITS(n)
an approximation of ceil(n * log10(2)), up to 1,048,576 (1<<20) without overflow within 32-bit calcul...
Definition util.h:39
#define MEMZERO(p, type, n)
Handy macro to erase a region of memory.
Definition memory.h:360
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:51
static void RARRAY_ASET(VALUE ary, long i, VALUE v)
Assigns an object in an array.
Definition rarray.h:386
#define RARRAY_AREF(a, i)
Definition rarray.h:403
#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:5759
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:15
Definition st.h:79
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