Ruby 3.5.0dev (2025-08-27 revision 61d26c35bf8c744b4c59a44536bc58a6c4653ab6)
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 struct RBasic basic;
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
2099static inline VALUE
2100newobj_fill(VALUE obj, VALUE v1, VALUE v2, VALUE v3)
2101{
2102 VALUE *p = (VALUE *)(obj + sizeof(struct RBasic));
2103 p[0] = v1;
2104 p[1] = v2;
2105 p[2] = v3;
2106 return obj;
2107}
2108
2109#if GC_DEBUG
2110static inline const char*
2111rb_gc_impl_source_location_cstr(int *ptr)
2112{
2113 /* We could directly refer `rb_source_location_cstr()` before, but not any
2114 * longer. We have to heavy lift using our debugging API. */
2115 if (! ptr) {
2116 return NULL;
2117 }
2118 else if (! (*ptr = rb_sourceline())) {
2119 return NULL;
2120 }
2121 else {
2122 return rb_sourcefile();
2123 }
2124}
2125#endif
2126
2127static inline VALUE
2128newobj_init(VALUE klass, VALUE flags, int wb_protected, rb_objspace_t *objspace, VALUE obj)
2129{
2130 GC_ASSERT(BUILTIN_TYPE(obj) == T_NONE);
2131 GC_ASSERT((flags & FL_WB_PROTECTED) == 0);
2132 RBASIC(obj)->flags = flags;
2133 *((VALUE *)&RBASIC(obj)->klass) = klass;
2134#if RBASIC_SHAPE_ID_FIELD
2135 RBASIC(obj)->shape_id = 0;
2136#endif
2137
2138 int t = flags & RUBY_T_MASK;
2139 if (t == T_CLASS || t == T_MODULE || t == T_ICLASS) {
2140 RVALUE_AGE_SET_CANDIDATE(objspace, obj);
2141 }
2142
2143#if RACTOR_CHECK_MODE
2144 void rb_ractor_setup_belonging(VALUE obj);
2145 rb_ractor_setup_belonging(obj);
2146#endif
2147
2148#if RGENGC_CHECK_MODE
2149 newobj_fill(obj, 0, 0, 0);
2150
2151 int lev = RB_GC_VM_LOCK_NO_BARRIER();
2152 {
2153 check_rvalue_consistency(objspace, obj);
2154
2155 GC_ASSERT(RVALUE_MARKED(objspace, obj) == FALSE);
2156 GC_ASSERT(RVALUE_MARKING(objspace, obj) == FALSE);
2157 GC_ASSERT(RVALUE_OLD_P(objspace, obj) == FALSE);
2158 GC_ASSERT(RVALUE_WB_UNPROTECTED(objspace, obj) == FALSE);
2159
2160 if (RVALUE_REMEMBERED(objspace, obj)) rb_bug("newobj: %s is remembered.", rb_obj_info(obj));
2161 }
2162 RB_GC_VM_UNLOCK_NO_BARRIER(lev);
2163#endif
2164
2165 if (RB_UNLIKELY(wb_protected == FALSE)) {
2166 MARK_IN_BITMAP(GET_HEAP_WB_UNPROTECTED_BITS(obj), obj);
2167 }
2168
2169#if RGENGC_PROFILE
2170 if (wb_protected) {
2171 objspace->profile.total_generated_normal_object_count++;
2172#if RGENGC_PROFILE >= 2
2173 objspace->profile.generated_normal_object_count_types[BUILTIN_TYPE(obj)]++;
2174#endif
2175 }
2176 else {
2177 objspace->profile.total_generated_shady_object_count++;
2178#if RGENGC_PROFILE >= 2
2179 objspace->profile.generated_shady_object_count_types[BUILTIN_TYPE(obj)]++;
2180#endif
2181 }
2182#endif
2183
2184#if GC_DEBUG
2185 GET_RVALUE_OVERHEAD(obj)->file = rb_gc_impl_source_location_cstr(&GET_RVALUE_OVERHEAD(obj)->line);
2186 GC_ASSERT(!SPECIAL_CONST_P(obj)); /* check alignment */
2187#endif
2188
2189 gc_report(5, objspace, "newobj: %s\n", rb_obj_info(obj));
2190
2191 // RUBY_DEBUG_LOG("obj:%p (%s)", (void *)obj, rb_obj_info(obj));
2192 return obj;
2193}
2194
2195size_t
2196rb_gc_impl_obj_slot_size(VALUE obj)
2197{
2198 return GET_HEAP_PAGE(obj)->slot_size - RVALUE_OVERHEAD;
2199}
2200
2201static inline size_t
2202heap_slot_size(unsigned char pool_id)
2203{
2204 GC_ASSERT(pool_id < HEAP_COUNT);
2205
2206 size_t slot_size = (1 << pool_id) * BASE_SLOT_SIZE;
2207
2208#if RGENGC_CHECK_MODE
2209 rb_objspace_t *objspace = rb_gc_get_objspace();
2210 GC_ASSERT(heaps[pool_id].slot_size == (short)slot_size);
2211#endif
2212
2213 slot_size -= RVALUE_OVERHEAD;
2214
2215 return slot_size;
2216}
2217
2218bool
2219rb_gc_impl_size_allocatable_p(size_t size)
2220{
2221 return size <= heap_slot_size(HEAP_COUNT - 1);
2222}
2223
2224static const size_t ALLOCATED_COUNT_STEP = 1024;
2225
2226static inline VALUE
2227ractor_cache_allocate_slot(rb_objspace_t *objspace, rb_ractor_newobj_cache_t *cache,
2228 size_t heap_idx)
2229{
2230 rb_ractor_newobj_heap_cache_t *heap_cache = &cache->heap_caches[heap_idx];
2231 struct free_slot *p = heap_cache->freelist;
2232
2233 if (RB_UNLIKELY(is_incremental_marking(objspace))) {
2234 // Not allowed to allocate without running an incremental marking step
2235 if (cache->incremental_mark_step_allocated_slots >= INCREMENTAL_MARK_STEP_ALLOCATIONS) {
2236 return Qfalse;
2237 }
2238
2239 if (p) {
2240 cache->incremental_mark_step_allocated_slots++;
2241 }
2242 }
2243
2244 if (RB_LIKELY(p)) {
2245 VALUE obj = (VALUE)p;
2246 rb_asan_unpoison_object(obj, true);
2247 heap_cache->freelist = p->next;
2248
2249 if (rb_gc_multi_ractor_p()) {
2250 heap_cache->allocated_objects_count++;
2251 rb_heap_t *heap = &heaps[heap_idx];
2252 if (heap_cache->allocated_objects_count >= ALLOCATED_COUNT_STEP) {
2253 RUBY_ATOMIC_SIZE_ADD(heap->total_allocated_objects, heap_cache->allocated_objects_count);
2254 heap_cache->allocated_objects_count = 0;
2255 }
2256 }
2257 else {
2258 rb_heap_t *heap = &heaps[heap_idx];
2259 heap->total_allocated_objects++;
2260 GC_ASSERT(heap->total_slots >=
2261 (heap->total_allocated_objects - heap->total_freed_objects - heap->final_slots_count));
2262 }
2263
2264#if RGENGC_CHECK_MODE
2265 GC_ASSERT(rb_gc_impl_obj_slot_size(obj) == heap_slot_size(heap_idx));
2266 // zero clear
2267 MEMZERO((char *)obj, char, heap_slot_size(heap_idx));
2268#endif
2269 return obj;
2270 }
2271 else {
2272 return Qfalse;
2273 }
2274}
2275
2276static struct heap_page *
2277heap_next_free_page(rb_objspace_t *objspace, rb_heap_t *heap)
2278{
2279 struct heap_page *page;
2280
2281 if (heap->free_pages == NULL) {
2282 heap_prepare(objspace, heap);
2283 }
2284
2285 page = heap->free_pages;
2286 heap->free_pages = page->free_next;
2287
2288 GC_ASSERT(page->free_slots != 0);
2289
2290 asan_unlock_freelist(page);
2291
2292 return page;
2293}
2294
2295static inline void
2296ractor_cache_set_page(rb_objspace_t *objspace, rb_ractor_newobj_cache_t *cache, size_t heap_idx,
2297 struct heap_page *page)
2298{
2299 gc_report(3, objspace, "ractor_set_cache: Using page %p\n", (void *)page->body);
2300
2301 rb_ractor_newobj_heap_cache_t *heap_cache = &cache->heap_caches[heap_idx];
2302
2303 GC_ASSERT(heap_cache->freelist == NULL);
2304 GC_ASSERT(page->free_slots != 0);
2305 GC_ASSERT(page->freelist != NULL);
2306
2307 heap_cache->using_page = page;
2308 heap_cache->freelist = page->freelist;
2309 page->free_slots = 0;
2310 page->freelist = NULL;
2311
2312 rb_asan_unpoison_object((VALUE)heap_cache->freelist, false);
2313 GC_ASSERT(RB_TYPE_P((VALUE)heap_cache->freelist, T_NONE));
2314 rb_asan_poison_object((VALUE)heap_cache->freelist);
2315}
2316
2317static inline size_t
2318heap_idx_for_size(size_t size)
2319{
2320 size += RVALUE_OVERHEAD;
2321
2322 size_t slot_count = CEILDIV(size, BASE_SLOT_SIZE);
2323
2324 /* heap_idx is ceil(log2(slot_count)) */
2325 size_t heap_idx = 64 - nlz_int64(slot_count - 1);
2326
2327 if (heap_idx >= HEAP_COUNT) {
2328 rb_bug("heap_idx_for_size: allocation size too large "
2329 "(size=%"PRIuSIZE"u, heap_idx=%"PRIuSIZE"u)", size, heap_idx);
2330 }
2331
2332#if RGENGC_CHECK_MODE
2333 rb_objspace_t *objspace = rb_gc_get_objspace();
2334 GC_ASSERT(size <= (size_t)heaps[heap_idx].slot_size);
2335 if (heap_idx > 0) GC_ASSERT(size > (size_t)heaps[heap_idx - 1].slot_size);
2336#endif
2337
2338 return heap_idx;
2339}
2340
2341size_t
2342rb_gc_impl_heap_id_for_size(void *objspace_ptr, size_t size)
2343{
2344 return heap_idx_for_size(size);
2345}
2346
2347
2348static size_t heap_sizes[HEAP_COUNT + 1] = { 0 };
2349
2350size_t *
2351rb_gc_impl_heap_sizes(void *objspace_ptr)
2352{
2353 if (heap_sizes[0] == 0) {
2354 for (unsigned char i = 0; i < HEAP_COUNT; i++) {
2355 heap_sizes[i] = heap_slot_size(i);
2356 }
2357 }
2358
2359 return heap_sizes;
2360}
2361
2362NOINLINE(static VALUE newobj_cache_miss(rb_objspace_t *objspace, rb_ractor_newobj_cache_t *cache, size_t heap_idx, bool vm_locked));
2363
2364static VALUE
2365newobj_cache_miss(rb_objspace_t *objspace, rb_ractor_newobj_cache_t *cache, size_t heap_idx, bool vm_locked)
2366{
2367 rb_heap_t *heap = &heaps[heap_idx];
2368 VALUE obj = Qfalse;
2369
2370 unsigned int lev = 0;
2371 bool unlock_vm = false;
2372
2373 if (!vm_locked) {
2374 lev = RB_GC_CR_LOCK();
2375 unlock_vm = true;
2376 }
2377
2378 {
2379 if (is_incremental_marking(objspace)) {
2380 gc_continue(objspace, heap);
2381 cache->incremental_mark_step_allocated_slots = 0;
2382
2383 // Retry allocation after resetting incremental_mark_step_allocated_slots
2384 obj = ractor_cache_allocate_slot(objspace, cache, heap_idx);
2385 }
2386
2387 if (obj == Qfalse) {
2388 // Get next free page (possibly running GC)
2389 struct heap_page *page = heap_next_free_page(objspace, heap);
2390 ractor_cache_set_page(objspace, cache, heap_idx, page);
2391
2392 // Retry allocation after moving to new page
2393 obj = ractor_cache_allocate_slot(objspace, cache, heap_idx);
2394 }
2395 }
2396
2397 if (unlock_vm) {
2398 RB_GC_CR_UNLOCK(lev);
2399 }
2400
2401 if (RB_UNLIKELY(obj == Qfalse)) {
2402 rb_memerror();
2403 }
2404 return obj;
2405}
2406
2407static VALUE
2408newobj_alloc(rb_objspace_t *objspace, rb_ractor_newobj_cache_t *cache, size_t heap_idx, bool vm_locked)
2409{
2410 VALUE obj = ractor_cache_allocate_slot(objspace, cache, heap_idx);
2411
2412 if (RB_UNLIKELY(obj == Qfalse)) {
2413 obj = newobj_cache_miss(objspace, cache, heap_idx, vm_locked);
2414 }
2415
2416 return obj;
2417}
2418
2419ALWAYS_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));
2420
2421static inline VALUE
2422newobj_slowpath(VALUE klass, VALUE flags, rb_objspace_t *objspace, rb_ractor_newobj_cache_t *cache, int wb_protected, size_t heap_idx)
2423{
2424 VALUE obj;
2425 unsigned int lev;
2426
2427 lev = RB_GC_CR_LOCK();
2428 {
2429 if (RB_UNLIKELY(during_gc || ruby_gc_stressful)) {
2430 if (during_gc) {
2431 dont_gc_on();
2432 during_gc = 0;
2433 if (rb_memerror_reentered()) {
2434 rb_memerror();
2435 }
2436 rb_bug("object allocation during garbage collection phase");
2437 }
2438
2439 if (ruby_gc_stressful) {
2440 if (!garbage_collect(objspace, GPR_FLAG_NEWOBJ)) {
2441 rb_memerror();
2442 }
2443 }
2444 }
2445
2446 obj = newobj_alloc(objspace, cache, heap_idx, true);
2447 newobj_init(klass, flags, wb_protected, objspace, obj);
2448 }
2449 RB_GC_CR_UNLOCK(lev);
2450
2451 return obj;
2452}
2453
2454NOINLINE(static VALUE newobj_slowpath_wb_protected(VALUE klass, VALUE flags,
2455 rb_objspace_t *objspace, rb_ractor_newobj_cache_t *cache, size_t heap_idx));
2456NOINLINE(static VALUE newobj_slowpath_wb_unprotected(VALUE klass, VALUE flags,
2457 rb_objspace_t *objspace, rb_ractor_newobj_cache_t *cache, size_t heap_idx));
2458
2459static VALUE
2460newobj_slowpath_wb_protected(VALUE klass, VALUE flags, rb_objspace_t *objspace, rb_ractor_newobj_cache_t *cache, size_t heap_idx)
2461{
2462 return newobj_slowpath(klass, flags, objspace, cache, TRUE, heap_idx);
2463}
2464
2465static VALUE
2466newobj_slowpath_wb_unprotected(VALUE klass, VALUE flags, rb_objspace_t *objspace, rb_ractor_newobj_cache_t *cache, size_t heap_idx)
2467{
2468 return newobj_slowpath(klass, flags, objspace, cache, FALSE, heap_idx);
2469}
2470
2471VALUE
2472rb_gc_impl_new_obj(void *objspace_ptr, void *cache_ptr, VALUE klass, VALUE flags, VALUE v1, VALUE v2, VALUE v3, bool wb_protected, size_t alloc_size)
2473{
2474 VALUE obj;
2475 rb_objspace_t *objspace = objspace_ptr;
2476
2477 RB_DEBUG_COUNTER_INC(obj_newobj);
2478 (void)RB_DEBUG_COUNTER_INC_IF(obj_newobj_wb_unprotected, !wb_protected);
2479
2480 if (RB_UNLIKELY(stress_to_class)) {
2481 if (rb_hash_lookup2(stress_to_class, klass, Qundef) != Qundef) {
2482 rb_memerror();
2483 }
2484 }
2485
2486 size_t heap_idx = heap_idx_for_size(alloc_size);
2487
2489
2490 if (!RB_UNLIKELY(during_gc || ruby_gc_stressful) &&
2491 wb_protected) {
2492 obj = newobj_alloc(objspace, cache, heap_idx, false);
2493 newobj_init(klass, flags, wb_protected, objspace, obj);
2494 }
2495 else {
2496 RB_DEBUG_COUNTER_INC(obj_newobj_slowpath);
2497
2498 obj = wb_protected ?
2499 newobj_slowpath_wb_protected(klass, flags, objspace, cache, heap_idx) :
2500 newobj_slowpath_wb_unprotected(klass, flags, objspace, cache, heap_idx);
2501 }
2502
2503 return newobj_fill(obj, v1, v2, v3);
2504}
2505
2506static int
2507ptr_in_page_body_p(const void *ptr, const void *memb)
2508{
2509 struct heap_page *page = *(struct heap_page **)memb;
2510 uintptr_t p_body = (uintptr_t)page->body;
2511
2512 if ((uintptr_t)ptr >= p_body) {
2513 return (uintptr_t)ptr < (p_body + HEAP_PAGE_SIZE) ? 0 : 1;
2514 }
2515 else {
2516 return -1;
2517 }
2518}
2519
2520PUREFUNC(static inline struct heap_page *heap_page_for_ptr(rb_objspace_t *objspace, uintptr_t ptr);)
2521static inline struct heap_page *
2522heap_page_for_ptr(rb_objspace_t *objspace, uintptr_t ptr)
2523{
2524 struct heap_page **res;
2525
2526 if (ptr < (uintptr_t)heap_pages_lomem ||
2527 ptr > (uintptr_t)heap_pages_himem) {
2528 return NULL;
2529 }
2530
2531 res = bsearch((void *)ptr, rb_darray_ref(objspace->heap_pages.sorted, 0),
2532 rb_darray_size(objspace->heap_pages.sorted), sizeof(struct heap_page *),
2533 ptr_in_page_body_p);
2534
2535 if (res) {
2536 return *res;
2537 }
2538 else {
2539 return NULL;
2540 }
2541}
2542
2543PUREFUNC(static inline bool is_pointer_to_heap(rb_objspace_t *objspace, const void *ptr);)
2544static inline bool
2545is_pointer_to_heap(rb_objspace_t *objspace, const void *ptr)
2546{
2547 register uintptr_t p = (uintptr_t)ptr;
2548 register struct heap_page *page;
2549
2550 RB_DEBUG_COUNTER_INC(gc_isptr_trial);
2551
2552 if (p < heap_pages_lomem || p > heap_pages_himem) return FALSE;
2553 RB_DEBUG_COUNTER_INC(gc_isptr_range);
2554
2555 if (p % BASE_SLOT_SIZE != 0) return FALSE;
2556 RB_DEBUG_COUNTER_INC(gc_isptr_align);
2557
2558 page = heap_page_for_ptr(objspace, (uintptr_t)ptr);
2559 if (page) {
2560 RB_DEBUG_COUNTER_INC(gc_isptr_maybe);
2561 if (heap_page_in_global_empty_pages_pool(objspace, page)) {
2562 return FALSE;
2563 }
2564 else {
2565 if (p < page->start) return FALSE;
2566 if (p >= page->start + (page->total_slots * page->slot_size)) return FALSE;
2567 if ((NUM_IN_PAGE(p) * BASE_SLOT_SIZE) % page->slot_size != 0) return FALSE;
2568
2569 return TRUE;
2570 }
2571 }
2572 return FALSE;
2573}
2574
2575bool
2576rb_gc_impl_pointer_to_heap_p(void *objspace_ptr, const void *ptr)
2577{
2578 return is_pointer_to_heap(objspace_ptr, ptr);
2579}
2580
2581#define ZOMBIE_OBJ_KEPT_FLAGS (FL_FINALIZE)
2582
2583void
2584rb_gc_impl_make_zombie(void *objspace_ptr, VALUE obj, void (*dfree)(void *), void *data)
2585{
2586 rb_objspace_t *objspace = objspace_ptr;
2587
2588 struct RZombie *zombie = RZOMBIE(obj);
2589 zombie->basic.flags = T_ZOMBIE | (zombie->basic.flags & ZOMBIE_OBJ_KEPT_FLAGS);
2590 zombie->dfree = dfree;
2591 zombie->data = data;
2592 VALUE prev, next = heap_pages_deferred_final;
2593 do {
2594 zombie->next = prev = next;
2595 next = RUBY_ATOMIC_VALUE_CAS(heap_pages_deferred_final, prev, obj);
2596 } while (next != prev);
2597
2598 struct heap_page *page = GET_HEAP_PAGE(obj);
2599 page->final_slots++;
2600 page->heap->final_slots_count++;
2601}
2602
2603typedef int each_obj_callback(void *, void *, size_t, void *);
2604typedef int each_page_callback(struct heap_page *, void *);
2605
2608 bool reenable_incremental;
2609
2610 each_obj_callback *each_obj_callback;
2611 each_page_callback *each_page_callback;
2612 void *data;
2613
2614 struct heap_page **pages[HEAP_COUNT];
2615 size_t pages_counts[HEAP_COUNT];
2616};
2617
2618static VALUE
2619objspace_each_objects_ensure(VALUE arg)
2620{
2621 struct each_obj_data *data = (struct each_obj_data *)arg;
2622 rb_objspace_t *objspace = data->objspace;
2623
2624 /* Reenable incremental GC */
2625 if (data->reenable_incremental) {
2626 objspace->flags.dont_incremental = FALSE;
2627 }
2628
2629 for (int i = 0; i < HEAP_COUNT; i++) {
2630 struct heap_page **pages = data->pages[i];
2631 free(pages);
2632 }
2633
2634 return Qnil;
2635}
2636
2637static VALUE
2638objspace_each_objects_try(VALUE arg)
2639{
2640 struct each_obj_data *data = (struct each_obj_data *)arg;
2641 rb_objspace_t *objspace = data->objspace;
2642
2643 /* Copy pages from all heaps to their respective buffers. */
2644 for (int i = 0; i < HEAP_COUNT; i++) {
2645 rb_heap_t *heap = &heaps[i];
2646 size_t size = heap->total_pages * sizeof(struct heap_page *);
2647
2648 struct heap_page **pages = malloc(size);
2649 if (!pages) rb_memerror();
2650
2651 /* Set up pages buffer by iterating over all pages in the current eden
2652 * heap. This will be a snapshot of the state of the heap before we
2653 * call the callback over each page that exists in this buffer. Thus it
2654 * is safe for the callback to allocate objects without possibly entering
2655 * an infinite loop. */
2656 struct heap_page *page = 0;
2657 size_t pages_count = 0;
2658 ccan_list_for_each(&heap->pages, page, page_node) {
2659 pages[pages_count] = page;
2660 pages_count++;
2661 }
2662 data->pages[i] = pages;
2663 data->pages_counts[i] = pages_count;
2664 GC_ASSERT(pages_count == heap->total_pages);
2665 }
2666
2667 for (int i = 0; i < HEAP_COUNT; i++) {
2668 rb_heap_t *heap = &heaps[i];
2669 size_t pages_count = data->pages_counts[i];
2670 struct heap_page **pages = data->pages[i];
2671
2672 struct heap_page *page = ccan_list_top(&heap->pages, struct heap_page, page_node);
2673 for (size_t i = 0; i < pages_count; i++) {
2674 /* If we have reached the end of the linked list then there are no
2675 * more pages, so break. */
2676 if (page == NULL) break;
2677
2678 /* If this page does not match the one in the buffer, then move to
2679 * the next page in the buffer. */
2680 if (pages[i] != page) continue;
2681
2682 uintptr_t pstart = (uintptr_t)page->start;
2683 uintptr_t pend = pstart + (page->total_slots * heap->slot_size);
2684
2685 if (data->each_obj_callback &&
2686 (*data->each_obj_callback)((void *)pstart, (void *)pend, heap->slot_size, data->data)) {
2687 break;
2688 }
2689 if (data->each_page_callback &&
2690 (*data->each_page_callback)(page, data->data)) {
2691 break;
2692 }
2693
2694 page = ccan_list_next(&heap->pages, page, page_node);
2695 }
2696 }
2697
2698 return Qnil;
2699}
2700
2701static void
2702objspace_each_exec(bool protected, struct each_obj_data *each_obj_data)
2703{
2704 /* Disable incremental GC */
2706 bool reenable_incremental = FALSE;
2707 if (protected) {
2708 reenable_incremental = !objspace->flags.dont_incremental;
2709
2710 gc_rest(objspace);
2711 objspace->flags.dont_incremental = TRUE;
2712 }
2713
2714 each_obj_data->reenable_incremental = reenable_incremental;
2715 memset(&each_obj_data->pages, 0, sizeof(each_obj_data->pages));
2716 memset(&each_obj_data->pages_counts, 0, sizeof(each_obj_data->pages_counts));
2717 rb_ensure(objspace_each_objects_try, (VALUE)each_obj_data,
2718 objspace_each_objects_ensure, (VALUE)each_obj_data);
2719}
2720
2721static void
2722objspace_each_objects(rb_objspace_t *objspace, each_obj_callback *callback, void *data, bool protected)
2723{
2724 struct each_obj_data each_obj_data = {
2725 .objspace = objspace,
2726 .each_obj_callback = callback,
2727 .each_page_callback = NULL,
2728 .data = data,
2729 };
2730 objspace_each_exec(protected, &each_obj_data);
2731}
2732
2733void
2734rb_gc_impl_each_objects(void *objspace_ptr, each_obj_callback *callback, void *data)
2735{
2736 objspace_each_objects(objspace_ptr, callback, data, TRUE);
2737}
2738
2739#if GC_CAN_COMPILE_COMPACTION
2740static void
2741objspace_each_pages(rb_objspace_t *objspace, each_page_callback *callback, void *data, bool protected)
2742{
2743 struct each_obj_data each_obj_data = {
2744 .objspace = objspace,
2745 .each_obj_callback = NULL,
2746 .each_page_callback = callback,
2747 .data = data,
2748 };
2749 objspace_each_exec(protected, &each_obj_data);
2750}
2751#endif
2752
2753VALUE
2754rb_gc_impl_define_finalizer(void *objspace_ptr, VALUE obj, VALUE block)
2755{
2756 rb_objspace_t *objspace = objspace_ptr;
2757 VALUE table;
2758 st_data_t data;
2759
2760 GC_ASSERT(!OBJ_FROZEN(obj));
2761
2762 RBASIC(obj)->flags |= FL_FINALIZE;
2763
2764 int lev = RB_GC_VM_LOCK();
2765
2766 if (st_lookup(finalizer_table, obj, &data)) {
2767 table = (VALUE)data;
2768
2769 /* avoid duplicate block, table is usually small */
2770 {
2771 long len = RARRAY_LEN(table);
2772 long i;
2773
2774 for (i = 0; i < len; i++) {
2775 VALUE recv = RARRAY_AREF(table, i);
2776 if (rb_equal(recv, block)) {
2777 RB_GC_VM_UNLOCK(lev);
2778 return recv;
2779 }
2780 }
2781 }
2782
2783 rb_ary_push(table, block);
2784 }
2785 else {
2786 table = rb_ary_new3(2, rb_obj_id(obj), block);
2787 rb_obj_hide(table);
2788 st_add_direct(finalizer_table, obj, table);
2789 }
2790
2791 RB_GC_VM_UNLOCK(lev);
2792
2793 return block;
2794}
2795
2796void
2797rb_gc_impl_undefine_finalizer(void *objspace_ptr, VALUE obj)
2798{
2799 rb_objspace_t *objspace = objspace_ptr;
2800
2801 GC_ASSERT(!OBJ_FROZEN(obj));
2802
2803 st_data_t data = obj;
2804
2805 int lev = RB_GC_VM_LOCK();
2806 st_delete(finalizer_table, &data, 0);
2807 RB_GC_VM_UNLOCK(lev);
2808
2809 FL_UNSET(obj, FL_FINALIZE);
2810}
2811
2812void
2813rb_gc_impl_copy_finalizer(void *objspace_ptr, VALUE dest, VALUE obj)
2814{
2815 rb_objspace_t *objspace = objspace_ptr;
2816 VALUE table;
2817 st_data_t data;
2818
2819 if (!FL_TEST(obj, FL_FINALIZE)) return;
2820
2821 int lev = RB_GC_VM_LOCK();
2822 if (RB_LIKELY(st_lookup(finalizer_table, obj, &data))) {
2823 table = rb_ary_dup((VALUE)data);
2824 RARRAY_ASET(table, 0, rb_obj_id(dest));
2825 st_insert(finalizer_table, dest, table);
2826 FL_SET(dest, FL_FINALIZE);
2827 }
2828 else {
2829 rb_bug("rb_gc_copy_finalizer: FL_FINALIZE set but not found in finalizer_table: %s", rb_obj_info(obj));
2830 }
2831 RB_GC_VM_UNLOCK(lev);
2832}
2833
2834static VALUE
2835get_final(long i, void *data)
2836{
2837 VALUE table = (VALUE)data;
2838
2839 return RARRAY_AREF(table, i + 1);
2840}
2841
2842static void
2843run_final(rb_objspace_t *objspace, VALUE zombie)
2844{
2845 if (RZOMBIE(zombie)->dfree) {
2846 RZOMBIE(zombie)->dfree(RZOMBIE(zombie)->data);
2847 }
2848
2849 st_data_t key = (st_data_t)zombie;
2850 if (FL_TEST_RAW(zombie, FL_FINALIZE)) {
2851 FL_UNSET(zombie, FL_FINALIZE);
2852 st_data_t table;
2853 if (st_delete(finalizer_table, &key, &table)) {
2854 rb_gc_run_obj_finalizer(RARRAY_AREF(table, 0), RARRAY_LEN(table) - 1, get_final, (void *)table);
2855 }
2856 else {
2857 rb_bug("FL_FINALIZE flag is set, but finalizers are not found");
2858 }
2859 }
2860 else {
2861 GC_ASSERT(!st_lookup(finalizer_table, key, NULL));
2862 }
2863}
2864
2865static void
2866finalize_list(rb_objspace_t *objspace, VALUE zombie)
2867{
2868 while (zombie) {
2869 VALUE next_zombie;
2870 struct heap_page *page;
2871 rb_asan_unpoison_object(zombie, false);
2872 next_zombie = RZOMBIE(zombie)->next;
2873 page = GET_HEAP_PAGE(zombie);
2874
2875 int lev = RB_GC_VM_LOCK();
2876
2877 run_final(objspace, zombie);
2878 {
2879 GC_ASSERT(BUILTIN_TYPE(zombie) == T_ZOMBIE);
2880 GC_ASSERT(page->heap->final_slots_count > 0);
2881 GC_ASSERT(page->final_slots > 0);
2882
2883 page->heap->final_slots_count--;
2884 page->final_slots--;
2885 page->free_slots++;
2886 heap_page_add_freeobj(objspace, page, zombie);
2887 page->heap->total_freed_objects++;
2888 }
2889 RB_GC_VM_UNLOCK(lev);
2890
2891 zombie = next_zombie;
2892 }
2893}
2894
2895static void
2896finalize_deferred_heap_pages(rb_objspace_t *objspace)
2897{
2898 VALUE zombie;
2899 while ((zombie = RUBY_ATOMIC_VALUE_EXCHANGE(heap_pages_deferred_final, 0)) != 0) {
2900 finalize_list(objspace, zombie);
2901 }
2902}
2903
2904static void
2905finalize_deferred(rb_objspace_t *objspace)
2906{
2907 rb_gc_set_pending_interrupt();
2908 finalize_deferred_heap_pages(objspace);
2909 rb_gc_unset_pending_interrupt();
2910}
2911
2912static void
2913gc_finalize_deferred(void *dmy)
2914{
2915 rb_objspace_t *objspace = dmy;
2916 if (RUBY_ATOMIC_EXCHANGE(finalizing, 1)) return;
2917
2918 finalize_deferred(objspace);
2919 RUBY_ATOMIC_SET(finalizing, 0);
2920}
2921
2922static void
2923gc_finalize_deferred_register(rb_objspace_t *objspace)
2924{
2925 /* will enqueue a call to gc_finalize_deferred */
2926 rb_postponed_job_trigger(objspace->finalize_deferred_pjob);
2927}
2928
2929static int pop_mark_stack(mark_stack_t *stack, VALUE *data);
2930
2931static void
2932gc_abort(void *objspace_ptr)
2933{
2934 rb_objspace_t *objspace = objspace_ptr;
2935
2936 if (is_incremental_marking(objspace)) {
2937 /* Remove all objects from the mark stack. */
2938 VALUE obj;
2939 while (pop_mark_stack(&objspace->mark_stack, &obj));
2940
2941 objspace->flags.during_incremental_marking = FALSE;
2942 }
2943
2944 if (is_lazy_sweeping(objspace)) {
2945 for (int i = 0; i < HEAP_COUNT; i++) {
2946 rb_heap_t *heap = &heaps[i];
2947
2948 heap->sweeping_page = NULL;
2949 struct heap_page *page = NULL;
2950
2951 ccan_list_for_each(&heap->pages, page, page_node) {
2952 page->flags.before_sweep = false;
2953 }
2954 }
2955 }
2956
2957 for (int i = 0; i < HEAP_COUNT; i++) {
2958 rb_heap_t *heap = &heaps[i];
2959 rgengc_mark_and_rememberset_clear(objspace, heap);
2960 }
2961
2962 gc_mode_set(objspace, gc_mode_none);
2963}
2964
2965void
2966rb_gc_impl_shutdown_free_objects(void *objspace_ptr)
2967{
2968 rb_objspace_t *objspace = objspace_ptr;
2969
2970 for (size_t i = 0; i < rb_darray_size(objspace->heap_pages.sorted); i++) {
2971 struct heap_page *page = rb_darray_get(objspace->heap_pages.sorted, i);
2972 short stride = page->slot_size;
2973
2974 uintptr_t p = (uintptr_t)page->start;
2975 uintptr_t pend = p + page->total_slots * stride;
2976 for (; p < pend; p += stride) {
2977 VALUE vp = (VALUE)p;
2978 asan_unpoisoning_object(vp) {
2979 if (RB_BUILTIN_TYPE(vp) != T_NONE) {
2980 rb_gc_obj_free_vm_weak_references(vp);
2981 if (rb_gc_obj_free(objspace, vp)) {
2982 RBASIC(vp)->flags = 0;
2983 }
2984 }
2985 }
2986 }
2987 }
2988}
2989
2990static int
2991rb_gc_impl_shutdown_call_finalizer_i(st_data_t key, st_data_t val, st_data_t _data)
2992{
2993 VALUE obj = (VALUE)key;
2994 VALUE table = (VALUE)val;
2995
2996 GC_ASSERT(RB_FL_TEST(obj, FL_FINALIZE));
2997 GC_ASSERT(RB_BUILTIN_TYPE(val) == T_ARRAY);
2998
2999 rb_gc_run_obj_finalizer(RARRAY_AREF(table, 0), RARRAY_LEN(table) - 1, get_final, (void *)table);
3000
3001 FL_UNSET(obj, FL_FINALIZE);
3002
3003 return ST_DELETE;
3004}
3005
3006void
3007rb_gc_impl_shutdown_call_finalizer(void *objspace_ptr)
3008{
3009 rb_objspace_t *objspace = objspace_ptr;
3010
3011#if RGENGC_CHECK_MODE >= 2
3012 gc_verify_internal_consistency(objspace);
3013#endif
3014
3015 /* prohibit incremental GC */
3016 objspace->flags.dont_incremental = 1;
3017
3018 if (RUBY_ATOMIC_EXCHANGE(finalizing, 1)) {
3019 /* Abort incremental marking and lazy sweeping to speed up shutdown. */
3020 gc_abort(objspace);
3021 dont_gc_on();
3022 return;
3023 }
3024
3025 while (finalizer_table->num_entries) {
3026 st_foreach(finalizer_table, rb_gc_impl_shutdown_call_finalizer_i, 0);
3027 }
3028
3029 /* run finalizers */
3030 finalize_deferred(objspace);
3031 GC_ASSERT(heap_pages_deferred_final == 0);
3032
3033 /* Abort incremental marking and lazy sweeping to speed up shutdown. */
3034 gc_abort(objspace);
3035
3036 /* prohibit GC because force T_DATA finalizers can break an object graph consistency */
3037 dont_gc_on();
3038
3039 /* running data/file finalizers are part of garbage collection */
3040 unsigned int lock_lev;
3041 gc_enter(objspace, gc_enter_event_finalizer, &lock_lev);
3042
3043 /* run data/file object's finalizers */
3044 for (size_t i = 0; i < rb_darray_size(objspace->heap_pages.sorted); i++) {
3045 struct heap_page *page = rb_darray_get(objspace->heap_pages.sorted, i);
3046 short stride = page->slot_size;
3047
3048 uintptr_t p = (uintptr_t)page->start;
3049 uintptr_t pend = p + page->total_slots * stride;
3050 for (; p < pend; p += stride) {
3051 VALUE vp = (VALUE)p;
3052 asan_unpoisoning_object(vp) {
3053 if (rb_gc_shutdown_call_finalizer_p(vp)) {
3054 rb_gc_obj_free_vm_weak_references(vp);
3055 if (rb_gc_obj_free(objspace, vp)) {
3056 RBASIC(vp)->flags = 0;
3057 }
3058 }
3059 }
3060 }
3061 }
3062
3063 gc_exit(objspace, gc_enter_event_finalizer, &lock_lev);
3064
3065 finalize_deferred_heap_pages(objspace);
3066
3067 st_free_table(finalizer_table);
3068 finalizer_table = 0;
3069 RUBY_ATOMIC_SET(finalizing, 0);
3070}
3071
3072void
3073rb_gc_impl_each_object(void *objspace_ptr, void (*func)(VALUE obj, void *data), void *data)
3074{
3075 rb_objspace_t *objspace = objspace_ptr;
3076
3077 for (size_t i = 0; i < rb_darray_size(objspace->heap_pages.sorted); i++) {
3078 struct heap_page *page = rb_darray_get(objspace->heap_pages.sorted, i);
3079 short stride = page->slot_size;
3080
3081 uintptr_t p = (uintptr_t)page->start;
3082 uintptr_t pend = p + page->total_slots * stride;
3083 for (; p < pend; p += stride) {
3084 VALUE obj = (VALUE)p;
3085
3086 asan_unpoisoning_object(obj) {
3087 func(obj, data);
3088 }
3089 }
3090 }
3091}
3092
3093/*
3094 ------------------------ Garbage Collection ------------------------
3095*/
3096
3097/* Sweeping */
3098
3099static size_t
3100objspace_available_slots(rb_objspace_t *objspace)
3101{
3102 size_t total_slots = 0;
3103 for (int i = 0; i < HEAP_COUNT; i++) {
3104 rb_heap_t *heap = &heaps[i];
3105 total_slots += heap->total_slots;
3106 }
3107 return total_slots;
3108}
3109
3110static size_t
3111objspace_live_slots(rb_objspace_t *objspace)
3112{
3113 return total_allocated_objects(objspace) - total_freed_objects(objspace) - total_final_slots_count(objspace);
3114}
3115
3116static size_t
3117objspace_free_slots(rb_objspace_t *objspace)
3118{
3119 return objspace_available_slots(objspace) - objspace_live_slots(objspace) - total_final_slots_count(objspace);
3120}
3121
3122static void
3123gc_setup_mark_bits(struct heap_page *page)
3124{
3125 /* copy oldgen bitmap to mark bitmap */
3126 memcpy(&page->mark_bits[0], &page->uncollectible_bits[0], HEAP_PAGE_BITMAP_SIZE);
3127}
3128
3129static int gc_is_moveable_obj(rb_objspace_t *objspace, VALUE obj);
3130static VALUE gc_move(rb_objspace_t *objspace, VALUE scan, VALUE free, size_t src_slot_size, size_t slot_size);
3131
3132#if defined(_WIN32)
3133enum {HEAP_PAGE_LOCK = PAGE_NOACCESS, HEAP_PAGE_UNLOCK = PAGE_READWRITE};
3134
3135static BOOL
3136protect_page_body(struct heap_page_body *body, DWORD protect)
3137{
3138 DWORD old_protect;
3139 return VirtualProtect(body, HEAP_PAGE_SIZE, protect, &old_protect) != 0;
3140}
3141#elif defined(__wasi__)
3142// wasi-libc's mprotect emulation does not support PROT_NONE
3143enum {HEAP_PAGE_LOCK, HEAP_PAGE_UNLOCK};
3144#define protect_page_body(body, protect) 1
3145#else
3146enum {HEAP_PAGE_LOCK = PROT_NONE, HEAP_PAGE_UNLOCK = PROT_READ | PROT_WRITE};
3147#define protect_page_body(body, protect) !mprotect((body), HEAP_PAGE_SIZE, (protect))
3148#endif
3149
3150static void
3151lock_page_body(rb_objspace_t *objspace, struct heap_page_body *body)
3152{
3153 if (!protect_page_body(body, HEAP_PAGE_LOCK)) {
3154 rb_bug("Couldn't protect page %p, errno: %s", (void *)body, strerror(errno));
3155 }
3156 else {
3157 gc_report(5, objspace, "Protecting page in move %p\n", (void *)body);
3158 }
3159}
3160
3161static void
3162unlock_page_body(rb_objspace_t *objspace, struct heap_page_body *body)
3163{
3164 if (!protect_page_body(body, HEAP_PAGE_UNLOCK)) {
3165 rb_bug("Couldn't unprotect page %p, errno: %s", (void *)body, strerror(errno));
3166 }
3167 else {
3168 gc_report(5, objspace, "Unprotecting page in move %p\n", (void *)body);
3169 }
3170}
3171
3172static bool
3173try_move(rb_objspace_t *objspace, rb_heap_t *heap, struct heap_page *free_page, VALUE src)
3174{
3175 GC_ASSERT(gc_is_moveable_obj(objspace, src));
3176
3177 struct heap_page *src_page = GET_HEAP_PAGE(src);
3178 if (!free_page) {
3179 return false;
3180 }
3181
3182 /* We should return true if either src is successfully moved, or src is
3183 * unmoveable. A false return will cause the sweeping cursor to be
3184 * incremented to the next page, and src will attempt to move again */
3185 GC_ASSERT(RVALUE_MARKED(objspace, src));
3186
3187 asan_unlock_freelist(free_page);
3188 VALUE dest = (VALUE)free_page->freelist;
3189 asan_lock_freelist(free_page);
3190 if (dest) {
3191 rb_asan_unpoison_object(dest, false);
3192 }
3193 else {
3194 /* if we can't get something from the freelist then the page must be
3195 * full */
3196 return false;
3197 }
3198 asan_unlock_freelist(free_page);
3199 free_page->freelist = ((struct free_slot *)dest)->next;
3200 asan_lock_freelist(free_page);
3201
3202 GC_ASSERT(RB_BUILTIN_TYPE(dest) == T_NONE);
3203
3204 if (src_page->slot_size > free_page->slot_size) {
3205 objspace->rcompactor.moved_down_count_table[BUILTIN_TYPE(src)]++;
3206 }
3207 else if (free_page->slot_size > src_page->slot_size) {
3208 objspace->rcompactor.moved_up_count_table[BUILTIN_TYPE(src)]++;
3209 }
3210 objspace->rcompactor.moved_count_table[BUILTIN_TYPE(src)]++;
3211 objspace->rcompactor.total_moved++;
3212
3213 gc_move(objspace, src, dest, src_page->slot_size, free_page->slot_size);
3214 gc_pin(objspace, src);
3215 free_page->free_slots--;
3216
3217 return true;
3218}
3219
3220static void
3221gc_unprotect_pages(rb_objspace_t *objspace, rb_heap_t *heap)
3222{
3223 struct heap_page *cursor = heap->compact_cursor;
3224
3225 while (cursor) {
3226 unlock_page_body(objspace, cursor->body);
3227 cursor = ccan_list_next(&heap->pages, cursor, page_node);
3228 }
3229}
3230
3231static void gc_update_references(rb_objspace_t *objspace);
3232#if GC_CAN_COMPILE_COMPACTION
3233static void invalidate_moved_page(rb_objspace_t *objspace, struct heap_page *page);
3234#endif
3235
3236#if defined(__MINGW32__) || defined(_WIN32)
3237# define GC_COMPACTION_SUPPORTED 1
3238#else
3239/* If not MinGW, Windows, or does not have mmap, we cannot use mprotect for
3240 * the read barrier, so we must disable compaction. */
3241# define GC_COMPACTION_SUPPORTED (GC_CAN_COMPILE_COMPACTION && HEAP_PAGE_ALLOC_USE_MMAP)
3242#endif
3243
3244#if GC_CAN_COMPILE_COMPACTION
3245static void
3246read_barrier_handler(uintptr_t address)
3247{
3248 rb_objspace_t *objspace = (rb_objspace_t *)rb_gc_get_objspace();
3249
3250 struct heap_page_body *page_body = GET_PAGE_BODY(address);
3251
3252 /* If the page_body is NULL, then mprotect cannot handle it and will crash
3253 * with "Cannot allocate memory". */
3254 if (page_body == NULL) {
3255 rb_bug("read_barrier_handler: segmentation fault at %p", (void *)address);
3256 }
3257
3258 int lev = RB_GC_VM_LOCK();
3259 {
3260 unlock_page_body(objspace, page_body);
3261
3262 objspace->profile.read_barrier_faults++;
3263
3264 invalidate_moved_page(objspace, GET_HEAP_PAGE(address));
3265 }
3266 RB_GC_VM_UNLOCK(lev);
3267}
3268#endif
3269
3270#if !GC_CAN_COMPILE_COMPACTION
3271static void
3272uninstall_handlers(void)
3273{
3274 /* no-op */
3275}
3276
3277static void
3278install_handlers(void)
3279{
3280 /* no-op */
3281}
3282#elif defined(_WIN32)
3283static LPTOP_LEVEL_EXCEPTION_FILTER old_handler;
3284typedef void (*signal_handler)(int);
3285static signal_handler old_sigsegv_handler;
3286
3287static LONG WINAPI
3288read_barrier_signal(EXCEPTION_POINTERS *info)
3289{
3290 /* EXCEPTION_ACCESS_VIOLATION is what's raised by access to protected pages */
3291 if (info->ExceptionRecord->ExceptionCode == EXCEPTION_ACCESS_VIOLATION) {
3292 /* > The second array element specifies the virtual address of the inaccessible data.
3293 * https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-exception_record
3294 *
3295 * Use this address to invalidate the page */
3296 read_barrier_handler((uintptr_t)info->ExceptionRecord->ExceptionInformation[1]);
3297 return EXCEPTION_CONTINUE_EXECUTION;
3298 }
3299 else {
3300 return EXCEPTION_CONTINUE_SEARCH;
3301 }
3302}
3303
3304static void
3305uninstall_handlers(void)
3306{
3307 signal(SIGSEGV, old_sigsegv_handler);
3308 SetUnhandledExceptionFilter(old_handler);
3309}
3310
3311static void
3312install_handlers(void)
3313{
3314 /* Remove SEGV handler so that the Unhandled Exception Filter handles it */
3315 old_sigsegv_handler = signal(SIGSEGV, NULL);
3316 /* Unhandled Exception Filter has access to the violation address similar
3317 * to si_addr from sigaction */
3318 old_handler = SetUnhandledExceptionFilter(read_barrier_signal);
3319}
3320#else
3321static struct sigaction old_sigbus_handler;
3322static struct sigaction old_sigsegv_handler;
3323
3324#ifdef HAVE_MACH_TASK_EXCEPTION_PORTS
3325static exception_mask_t old_exception_masks[32];
3326static mach_port_t old_exception_ports[32];
3327static exception_behavior_t old_exception_behaviors[32];
3328static thread_state_flavor_t old_exception_flavors[32];
3329static mach_msg_type_number_t old_exception_count;
3330
3331static void
3332disable_mach_bad_access_exc(void)
3333{
3334 old_exception_count = sizeof(old_exception_masks) / sizeof(old_exception_masks[0]);
3335 task_swap_exception_ports(
3336 mach_task_self(), EXC_MASK_BAD_ACCESS,
3337 MACH_PORT_NULL, EXCEPTION_DEFAULT, 0,
3338 old_exception_masks, &old_exception_count,
3339 old_exception_ports, old_exception_behaviors, old_exception_flavors
3340 );
3341}
3342
3343static void
3344restore_mach_bad_access_exc(void)
3345{
3346 for (mach_msg_type_number_t i = 0; i < old_exception_count; i++) {
3347 task_set_exception_ports(
3348 mach_task_self(),
3349 old_exception_masks[i], old_exception_ports[i],
3350 old_exception_behaviors[i], old_exception_flavors[i]
3351 );
3352 }
3353}
3354#endif
3355
3356static void
3357read_barrier_signal(int sig, siginfo_t *info, void *data)
3358{
3359 // setup SEGV/BUS handlers for errors
3360 struct sigaction prev_sigbus, prev_sigsegv;
3361 sigaction(SIGBUS, &old_sigbus_handler, &prev_sigbus);
3362 sigaction(SIGSEGV, &old_sigsegv_handler, &prev_sigsegv);
3363
3364 // enable SIGBUS/SEGV
3365 sigset_t set, prev_set;
3366 sigemptyset(&set);
3367 sigaddset(&set, SIGBUS);
3368 sigaddset(&set, SIGSEGV);
3369 sigprocmask(SIG_UNBLOCK, &set, &prev_set);
3370#ifdef HAVE_MACH_TASK_EXCEPTION_PORTS
3371 disable_mach_bad_access_exc();
3372#endif
3373 // run handler
3374 read_barrier_handler((uintptr_t)info->si_addr);
3375
3376 // reset SEGV/BUS handlers
3377#ifdef HAVE_MACH_TASK_EXCEPTION_PORTS
3378 restore_mach_bad_access_exc();
3379#endif
3380 sigaction(SIGBUS, &prev_sigbus, NULL);
3381 sigaction(SIGSEGV, &prev_sigsegv, NULL);
3382 sigprocmask(SIG_SETMASK, &prev_set, NULL);
3383}
3384
3385static void
3386uninstall_handlers(void)
3387{
3388#ifdef HAVE_MACH_TASK_EXCEPTION_PORTS
3389 restore_mach_bad_access_exc();
3390#endif
3391 sigaction(SIGBUS, &old_sigbus_handler, NULL);
3392 sigaction(SIGSEGV, &old_sigsegv_handler, NULL);
3393}
3394
3395static void
3396install_handlers(void)
3397{
3398 struct sigaction action;
3399 memset(&action, 0, sizeof(struct sigaction));
3400 sigemptyset(&action.sa_mask);
3401 action.sa_sigaction = read_barrier_signal;
3402 action.sa_flags = SA_SIGINFO | SA_ONSTACK;
3403
3404 sigaction(SIGBUS, &action, &old_sigbus_handler);
3405 sigaction(SIGSEGV, &action, &old_sigsegv_handler);
3406#ifdef HAVE_MACH_TASK_EXCEPTION_PORTS
3407 disable_mach_bad_access_exc();
3408#endif
3409}
3410#endif
3411
3412static void
3413gc_compact_finish(rb_objspace_t *objspace)
3414{
3415 for (int i = 0; i < HEAP_COUNT; i++) {
3416 rb_heap_t *heap = &heaps[i];
3417 gc_unprotect_pages(objspace, heap);
3418 }
3419
3420 uninstall_handlers();
3421
3422 gc_update_references(objspace);
3423 objspace->profile.compact_count++;
3424
3425 for (int i = 0; i < HEAP_COUNT; i++) {
3426 rb_heap_t *heap = &heaps[i];
3427 heap->compact_cursor = NULL;
3428 heap->free_pages = NULL;
3429 heap->compact_cursor_index = 0;
3430 }
3431
3432 if (gc_prof_enabled(objspace)) {
3433 gc_profile_record *record = gc_prof_record(objspace);
3434 record->moved_objects = objspace->rcompactor.total_moved - record->moved_objects;
3435 }
3436 objspace->flags.during_compacting = FALSE;
3437}
3438
3440 struct heap_page *page;
3441 int final_slots;
3442 int freed_slots;
3443 int empty_slots;
3444};
3445
3446static inline void
3447gc_sweep_plane(rb_objspace_t *objspace, rb_heap_t *heap, uintptr_t p, bits_t bitset, struct gc_sweep_context *ctx)
3448{
3449 struct heap_page *sweep_page = ctx->page;
3450 short slot_size = sweep_page->slot_size;
3451 short slot_bits = slot_size / BASE_SLOT_SIZE;
3452 GC_ASSERT(slot_bits > 0);
3453
3454 do {
3455 VALUE vp = (VALUE)p;
3456 GC_ASSERT(vp % BASE_SLOT_SIZE == 0);
3457
3458 rb_asan_unpoison_object(vp, false);
3459 if (bitset & 1) {
3460 switch (BUILTIN_TYPE(vp)) {
3461 default: /* majority case */
3462 gc_report(2, objspace, "page_sweep: free %p\n", (void *)p);
3463#if RGENGC_CHECK_MODE
3464 if (!is_full_marking(objspace)) {
3465 if (RVALUE_OLD_P(objspace, vp)) rb_bug("page_sweep: %p - old while minor GC.", (void *)p);
3466 if (RVALUE_REMEMBERED(objspace, vp)) rb_bug("page_sweep: %p - remembered.", (void *)p);
3467 }
3468#endif
3469
3470 if (RVALUE_WB_UNPROTECTED(objspace, vp)) CLEAR_IN_BITMAP(GET_HEAP_WB_UNPROTECTED_BITS(vp), vp);
3471
3472#if RGENGC_CHECK_MODE
3473#define CHECK(x) if (x(objspace, vp) != FALSE) rb_bug("obj_free: " #x "(%s) != FALSE", rb_obj_info(vp))
3474 CHECK(RVALUE_WB_UNPROTECTED);
3475 CHECK(RVALUE_MARKED);
3476 CHECK(RVALUE_MARKING);
3477 CHECK(RVALUE_UNCOLLECTIBLE);
3478#undef CHECK
3479#endif
3480
3481 rb_gc_event_hook(vp, RUBY_INTERNAL_EVENT_FREEOBJ);
3482
3483 rb_gc_obj_free_vm_weak_references(vp);
3484 if (rb_gc_obj_free(objspace, vp)) {
3485 // always add free slots back to the swept pages freelist,
3486 // so that if we're compacting, we can re-use the slots
3487 (void)VALGRIND_MAKE_MEM_UNDEFINED((void*)p, BASE_SLOT_SIZE);
3488 heap_page_add_freeobj(objspace, sweep_page, vp);
3489 gc_report(3, objspace, "page_sweep: %s is added to freelist\n", rb_obj_info(vp));
3490 ctx->freed_slots++;
3491 }
3492 else {
3493 ctx->final_slots++;
3494 }
3495 break;
3496
3497 case T_MOVED:
3498 if (objspace->flags.during_compacting) {
3499 /* The sweep cursor shouldn't have made it to any
3500 * T_MOVED slots while the compact flag is enabled.
3501 * The sweep cursor and compact cursor move in
3502 * opposite directions, and when they meet references will
3503 * get updated and "during_compacting" should get disabled */
3504 rb_bug("T_MOVED shouldn't be seen until compaction is finished");
3505 }
3506 gc_report(3, objspace, "page_sweep: %s is added to freelist\n", rb_obj_info(vp));
3507 ctx->empty_slots++;
3508 heap_page_add_freeobj(objspace, sweep_page, vp);
3509 break;
3510 case T_ZOMBIE:
3511 /* already counted */
3512 break;
3513 case T_NONE:
3514 ctx->empty_slots++; /* already freed */
3515 break;
3516 }
3517 }
3518 p += slot_size;
3519 bitset >>= slot_bits;
3520 } while (bitset);
3521}
3522
3523static inline void
3524gc_sweep_page(rb_objspace_t *objspace, rb_heap_t *heap, struct gc_sweep_context *ctx)
3525{
3526 struct heap_page *sweep_page = ctx->page;
3527 GC_ASSERT(sweep_page->heap == heap);
3528
3529 uintptr_t p;
3530 bits_t *bits, bitset;
3531
3532 gc_report(2, objspace, "page_sweep: start.\n");
3533
3534#if RGENGC_CHECK_MODE
3535 if (!objspace->flags.immediate_sweep) {
3536 GC_ASSERT(sweep_page->flags.before_sweep == TRUE);
3537 }
3538#endif
3539 sweep_page->flags.before_sweep = FALSE;
3540 sweep_page->free_slots = 0;
3541
3542 p = (uintptr_t)sweep_page->start;
3543 bits = sweep_page->mark_bits;
3544
3545 int page_rvalue_count = sweep_page->total_slots * (sweep_page->slot_size / BASE_SLOT_SIZE);
3546 int out_of_range_bits = (NUM_IN_PAGE(p) + page_rvalue_count) % BITS_BITLENGTH;
3547 if (out_of_range_bits != 0) { // sizeof(RVALUE) == 64
3548 bits[BITMAP_INDEX(p) + page_rvalue_count / BITS_BITLENGTH] |= ~(((bits_t)1 << out_of_range_bits) - 1);
3549 }
3550
3551 /* The last bitmap plane may not be used if the last plane does not
3552 * have enough space for the slot_size. In that case, the last plane must
3553 * be skipped since none of the bits will be set. */
3554 int bitmap_plane_count = CEILDIV(NUM_IN_PAGE(p) + page_rvalue_count, BITS_BITLENGTH);
3555 GC_ASSERT(bitmap_plane_count == HEAP_PAGE_BITMAP_LIMIT - 1 ||
3556 bitmap_plane_count == HEAP_PAGE_BITMAP_LIMIT);
3557
3558 // Skip out of range slots at the head of the page
3559 bitset = ~bits[0];
3560 bitset >>= NUM_IN_PAGE(p);
3561 if (bitset) {
3562 gc_sweep_plane(objspace, heap, p, bitset, ctx);
3563 }
3564 p += (BITS_BITLENGTH - NUM_IN_PAGE(p)) * BASE_SLOT_SIZE;
3565
3566 for (int i = 1; i < bitmap_plane_count; i++) {
3567 bitset = ~bits[i];
3568 if (bitset) {
3569 gc_sweep_plane(objspace, heap, p, bitset, ctx);
3570 }
3571 p += BITS_BITLENGTH * BASE_SLOT_SIZE;
3572 }
3573
3574 if (!heap->compact_cursor) {
3575 gc_setup_mark_bits(sweep_page);
3576 }
3577
3578#if GC_PROFILE_MORE_DETAIL
3579 if (gc_prof_enabled(objspace)) {
3580 gc_profile_record *record = gc_prof_record(objspace);
3581 record->removing_objects += ctx->final_slots + ctx->freed_slots;
3582 record->empty_objects += ctx->empty_slots;
3583 }
3584#endif
3585 if (0) fprintf(stderr, "gc_sweep_page(%"PRIdSIZE"): total_slots: %d, freed_slots: %d, empty_slots: %d, final_slots: %d\n",
3586 rb_gc_count(),
3587 sweep_page->total_slots,
3588 ctx->freed_slots, ctx->empty_slots, ctx->final_slots);
3589
3590 sweep_page->free_slots += ctx->freed_slots + ctx->empty_slots;
3591 sweep_page->heap->total_freed_objects += ctx->freed_slots;
3592
3593 if (heap_pages_deferred_final && !finalizing) {
3594 gc_finalize_deferred_register(objspace);
3595 }
3596
3597#if RGENGC_CHECK_MODE
3598 short freelist_len = 0;
3599 asan_unlock_freelist(sweep_page);
3600 struct free_slot *ptr = sweep_page->freelist;
3601 while (ptr) {
3602 freelist_len++;
3603 rb_asan_unpoison_object((VALUE)ptr, false);
3604 struct free_slot *next = ptr->next;
3605 rb_asan_poison_object((VALUE)ptr);
3606 ptr = next;
3607 }
3608 asan_lock_freelist(sweep_page);
3609 if (freelist_len != sweep_page->free_slots) {
3610 rb_bug("inconsistent freelist length: expected %d but was %d", sweep_page->free_slots, freelist_len);
3611 }
3612#endif
3613
3614 gc_report(2, objspace, "page_sweep: end.\n");
3615}
3616
3617static const char *
3618gc_mode_name(enum gc_mode mode)
3619{
3620 switch (mode) {
3621 case gc_mode_none: return "none";
3622 case gc_mode_marking: return "marking";
3623 case gc_mode_sweeping: return "sweeping";
3624 case gc_mode_compacting: return "compacting";
3625 default: rb_bug("gc_mode_name: unknown mode: %d", (int)mode);
3626 }
3627}
3628
3629static void
3630gc_mode_transition(rb_objspace_t *objspace, enum gc_mode mode)
3631{
3632#if RGENGC_CHECK_MODE
3633 enum gc_mode prev_mode = gc_mode(objspace);
3634 switch (prev_mode) {
3635 case gc_mode_none: GC_ASSERT(mode == gc_mode_marking); break;
3636 case gc_mode_marking: GC_ASSERT(mode == gc_mode_sweeping); break;
3637 case gc_mode_sweeping: GC_ASSERT(mode == gc_mode_none || mode == gc_mode_compacting); break;
3638 case gc_mode_compacting: GC_ASSERT(mode == gc_mode_none); break;
3639 }
3640#endif
3641 if (0) fprintf(stderr, "gc_mode_transition: %s->%s\n", gc_mode_name(gc_mode(objspace)), gc_mode_name(mode));
3642 gc_mode_set(objspace, mode);
3643}
3644
3645static void
3646heap_page_freelist_append(struct heap_page *page, struct free_slot *freelist)
3647{
3648 if (freelist) {
3649 asan_unlock_freelist(page);
3650 if (page->freelist) {
3651 struct free_slot *p = page->freelist;
3652 rb_asan_unpoison_object((VALUE)p, false);
3653 while (p->next) {
3654 struct free_slot *prev = p;
3655 p = p->next;
3656 rb_asan_poison_object((VALUE)prev);
3657 rb_asan_unpoison_object((VALUE)p, false);
3658 }
3659 p->next = freelist;
3660 rb_asan_poison_object((VALUE)p);
3661 }
3662 else {
3663 page->freelist = freelist;
3664 }
3665 asan_lock_freelist(page);
3666 }
3667}
3668
3669static void
3670gc_sweep_start_heap(rb_objspace_t *objspace, rb_heap_t *heap)
3671{
3672 heap->sweeping_page = ccan_list_top(&heap->pages, struct heap_page, page_node);
3673 heap->free_pages = NULL;
3674 heap->pooled_pages = NULL;
3675 if (!objspace->flags.immediate_sweep) {
3676 struct heap_page *page = NULL;
3677
3678 ccan_list_for_each(&heap->pages, page, page_node) {
3679 page->flags.before_sweep = TRUE;
3680 }
3681 }
3682}
3683
3684#if defined(__GNUC__) && __GNUC__ == 4 && __GNUC_MINOR__ == 4
3685__attribute__((noinline))
3686#endif
3687
3688#if GC_CAN_COMPILE_COMPACTION
3689static void gc_sort_heap_by_compare_func(rb_objspace_t *objspace, gc_compact_compare_func compare_func);
3690static int compare_pinned_slots(const void *left, const void *right, void *d);
3691#endif
3692
3693static void
3694gc_ractor_newobj_cache_clear(void *c, void *data)
3695{
3696 rb_objspace_t *objspace = rb_gc_get_objspace();
3697 rb_ractor_newobj_cache_t *newobj_cache = c;
3698
3699 newobj_cache->incremental_mark_step_allocated_slots = 0;
3700
3701 for (size_t heap_idx = 0; heap_idx < HEAP_COUNT; heap_idx++) {
3702
3703 rb_ractor_newobj_heap_cache_t *cache = &newobj_cache->heap_caches[heap_idx];
3704
3705 rb_heap_t *heap = &heaps[heap_idx];
3706 RUBY_ATOMIC_SIZE_ADD(heap->total_allocated_objects, cache->allocated_objects_count);
3707 cache->allocated_objects_count = 0;
3708
3709 struct heap_page *page = cache->using_page;
3710 struct free_slot *freelist = cache->freelist;
3711 RUBY_DEBUG_LOG("ractor using_page:%p freelist:%p", (void *)page, (void *)freelist);
3712
3713 heap_page_freelist_append(page, freelist);
3714
3715 cache->using_page = NULL;
3716 cache->freelist = NULL;
3717 }
3718}
3719
3720static void
3721gc_sweep_start(rb_objspace_t *objspace)
3722{
3723 gc_mode_transition(objspace, gc_mode_sweeping);
3724 objspace->rincgc.pooled_slots = 0;
3725
3726#if GC_CAN_COMPILE_COMPACTION
3727 if (objspace->flags.during_compacting) {
3728 gc_sort_heap_by_compare_func(
3729 objspace,
3730 objspace->rcompactor.compare_func ? objspace->rcompactor.compare_func : compare_pinned_slots
3731 );
3732 }
3733#endif
3734
3735 for (int i = 0; i < HEAP_COUNT; i++) {
3736 rb_heap_t *heap = &heaps[i];
3737 gc_sweep_start_heap(objspace, heap);
3738
3739 /* We should call gc_sweep_finish_heap for size pools with no pages. */
3740 if (heap->sweeping_page == NULL) {
3741 GC_ASSERT(heap->total_pages == 0);
3742 GC_ASSERT(heap->total_slots == 0);
3743 gc_sweep_finish_heap(objspace, heap);
3744 }
3745 }
3746
3747 rb_gc_ractor_newobj_cache_foreach(gc_ractor_newobj_cache_clear, NULL);
3748}
3749
3750static void
3751gc_sweep_finish_heap(rb_objspace_t *objspace, rb_heap_t *heap)
3752{
3753 size_t total_slots = heap->total_slots;
3754 size_t swept_slots = heap->freed_slots + heap->empty_slots;
3755
3756 size_t init_slots = gc_params.heap_init_slots[heap - heaps];
3757 size_t min_free_slots = (size_t)(MAX(total_slots, init_slots) * gc_params.heap_free_slots_min_ratio);
3758
3759 if (swept_slots < min_free_slots &&
3760 /* The heap is a growth heap if it freed more slots than had empty slots. */
3761 ((heap->empty_slots == 0 && total_slots > 0) || heap->freed_slots > heap->empty_slots)) {
3762 /* If we don't have enough slots and we have pages on the tomb heap, move
3763 * pages from the tomb heap to the eden heap. This may prevent page
3764 * creation thrashing (frequently allocating and deallocting pages) and
3765 * GC thrashing (running GC more frequently than required). */
3766 struct heap_page *resurrected_page;
3767 while (swept_slots < min_free_slots &&
3768 (resurrected_page = heap_page_resurrect(objspace))) {
3769 heap_add_page(objspace, heap, resurrected_page);
3770 heap_add_freepage(heap, resurrected_page);
3771
3772 swept_slots += resurrected_page->free_slots;
3773 }
3774
3775 if (swept_slots < min_free_slots) {
3776 /* Grow this heap if we are in a major GC or if we haven't run at least
3777 * RVALUE_OLD_AGE minor GC since the last major GC. */
3778 if (is_full_marking(objspace) ||
3779 objspace->profile.count - objspace->rgengc.last_major_gc < RVALUE_OLD_AGE) {
3780 if (objspace->heap_pages.allocatable_slots < min_free_slots) {
3781 heap_allocatable_slots_expand(objspace, heap, swept_slots, heap->total_slots);
3782 }
3783 }
3784 else {
3785 gc_needs_major_flags |= GPR_FLAG_MAJOR_BY_NOFREE;
3786 heap->force_major_gc_count++;
3787 }
3788 }
3789 }
3790}
3791
3792static void
3793gc_sweep_finish(rb_objspace_t *objspace)
3794{
3795 gc_report(1, objspace, "gc_sweep_finish\n");
3796
3797 gc_prof_set_heap_info(objspace);
3798 heap_pages_free_unused_pages(objspace);
3799
3800 for (int i = 0; i < HEAP_COUNT; i++) {
3801 rb_heap_t *heap = &heaps[i];
3802
3803 heap->freed_slots = 0;
3804 heap->empty_slots = 0;
3805
3806 if (!will_be_incremental_marking(objspace)) {
3807 struct heap_page *end_page = heap->free_pages;
3808 if (end_page) {
3809 while (end_page->free_next) end_page = end_page->free_next;
3810 end_page->free_next = heap->pooled_pages;
3811 }
3812 else {
3813 heap->free_pages = heap->pooled_pages;
3814 }
3815 heap->pooled_pages = NULL;
3816 objspace->rincgc.pooled_slots = 0;
3817 }
3818 }
3819
3820 rb_gc_event_hook(0, RUBY_INTERNAL_EVENT_GC_END_SWEEP);
3821 gc_mode_transition(objspace, gc_mode_none);
3822
3823#if RGENGC_CHECK_MODE >= 2
3824 gc_verify_internal_consistency(objspace);
3825#endif
3826}
3827
3828static int
3829gc_sweep_step(rb_objspace_t *objspace, rb_heap_t *heap)
3830{
3831 struct heap_page *sweep_page = heap->sweeping_page;
3832 int swept_slots = 0;
3833 int pooled_slots = 0;
3834
3835 if (sweep_page == NULL) return FALSE;
3836
3837#if GC_ENABLE_LAZY_SWEEP
3838 gc_prof_sweep_timer_start(objspace);
3839#endif
3840
3841 do {
3842 RUBY_DEBUG_LOG("sweep_page:%p", (void *)sweep_page);
3843
3844 struct gc_sweep_context ctx = {
3845 .page = sweep_page,
3846 .final_slots = 0,
3847 .freed_slots = 0,
3848 .empty_slots = 0,
3849 };
3850 gc_sweep_page(objspace, heap, &ctx);
3851 int free_slots = ctx.freed_slots + ctx.empty_slots;
3852
3853 heap->sweeping_page = ccan_list_next(&heap->pages, sweep_page, page_node);
3854
3855 if (free_slots == sweep_page->total_slots) {
3856 /* There are no living objects, so move this page to the global empty pages. */
3857 heap_unlink_page(objspace, heap, sweep_page);
3858
3859 sweep_page->start = 0;
3860 sweep_page->total_slots = 0;
3861 sweep_page->slot_size = 0;
3862 sweep_page->heap = NULL;
3863 sweep_page->free_slots = 0;
3864
3865 asan_unlock_freelist(sweep_page);
3866 sweep_page->freelist = NULL;
3867 asan_lock_freelist(sweep_page);
3868
3869 asan_poison_memory_region(sweep_page->body, HEAP_PAGE_SIZE);
3870
3871 objspace->empty_pages_count++;
3872 sweep_page->free_next = objspace->empty_pages;
3873 objspace->empty_pages = sweep_page;
3874 }
3875 else if (free_slots > 0) {
3876 heap->freed_slots += ctx.freed_slots;
3877 heap->empty_slots += ctx.empty_slots;
3878
3879 if (pooled_slots < GC_INCREMENTAL_SWEEP_POOL_SLOT_COUNT) {
3880 heap_add_poolpage(objspace, heap, sweep_page);
3881 pooled_slots += free_slots;
3882 }
3883 else {
3884 heap_add_freepage(heap, sweep_page);
3885 swept_slots += free_slots;
3886 if (swept_slots > GC_INCREMENTAL_SWEEP_SLOT_COUNT) {
3887 break;
3888 }
3889 }
3890 }
3891 else {
3892 sweep_page->free_next = NULL;
3893 }
3894 } while ((sweep_page = heap->sweeping_page));
3895
3896 if (!heap->sweeping_page) {
3897 gc_sweep_finish_heap(objspace, heap);
3898
3899 if (!has_sweeping_pages(objspace)) {
3900 gc_sweep_finish(objspace);
3901 }
3902 }
3903
3904#if GC_ENABLE_LAZY_SWEEP
3905 gc_prof_sweep_timer_stop(objspace);
3906#endif
3907
3908 return heap->free_pages != NULL;
3909}
3910
3911static void
3912gc_sweep_rest(rb_objspace_t *objspace)
3913{
3914 for (int i = 0; i < HEAP_COUNT; i++) {
3915 rb_heap_t *heap = &heaps[i];
3916
3917 while (heap->sweeping_page) {
3918 gc_sweep_step(objspace, heap);
3919 }
3920 }
3921}
3922
3923static void
3924gc_sweep_continue(rb_objspace_t *objspace, rb_heap_t *sweep_heap)
3925{
3926 GC_ASSERT(dont_gc_val() == FALSE || objspace->profile.latest_gc_info & GPR_FLAG_METHOD);
3927 if (!GC_ENABLE_LAZY_SWEEP) return;
3928
3929 gc_sweeping_enter(objspace);
3930
3931 for (int i = 0; i < HEAP_COUNT; i++) {
3932 rb_heap_t *heap = &heaps[i];
3933 if (gc_sweep_step(objspace, heap)) {
3934 GC_ASSERT(heap->free_pages != NULL);
3935 }
3936 else if (heap == sweep_heap) {
3937 if (objspace->empty_pages_count > 0 || objspace->heap_pages.allocatable_slots > 0) {
3938 /* [Bug #21548]
3939 *
3940 * If this heap is the heap we want to sweep, but we weren't able
3941 * to free any slots, but we also either have empty pages or could
3942 * allocate new pages, then we want to preemptively claim a page
3943 * because it's possible that sweeping another heap will call
3944 * gc_sweep_finish_heap, which may use up all of the
3945 * empty/allocatable pages. If other heaps are not finished sweeping
3946 * then we do not finish this GC and we will end up triggering a new
3947 * GC cycle during this GC phase. */
3948 heap_page_allocate_and_initialize(objspace, heap);
3949
3950 GC_ASSERT(heap->free_pages != NULL);
3951 }
3952 else {
3953 /* Not allowed to create a new page so finish sweeping. */
3954 gc_sweep_rest(objspace);
3955 GC_ASSERT(gc_mode(objspace) == gc_mode_none);
3956 break;
3957 }
3958 }
3959 }
3960
3961 gc_sweeping_exit(objspace);
3962}
3963
3964VALUE
3965rb_gc_impl_location(void *objspace_ptr, VALUE value)
3966{
3967 VALUE destination;
3968
3969 asan_unpoisoning_object(value) {
3970 if (BUILTIN_TYPE(value) == T_MOVED) {
3971 destination = (VALUE)RMOVED(value)->destination;
3972 GC_ASSERT(BUILTIN_TYPE(destination) != T_NONE);
3973 }
3974 else {
3975 destination = value;
3976 }
3977 }
3978
3979 return destination;
3980}
3981
3982#if GC_CAN_COMPILE_COMPACTION
3983static void
3984invalidate_moved_plane(rb_objspace_t *objspace, struct heap_page *page, uintptr_t p, bits_t bitset)
3985{
3986 if (bitset) {
3987 do {
3988 if (bitset & 1) {
3989 VALUE forwarding_object = (VALUE)p;
3990 VALUE object;
3991
3992 if (BUILTIN_TYPE(forwarding_object) == T_MOVED) {
3993 GC_ASSERT(RVALUE_PINNED(objspace, forwarding_object));
3994 GC_ASSERT(!RVALUE_MARKED(objspace, forwarding_object));
3995
3996 CLEAR_IN_BITMAP(GET_HEAP_PINNED_BITS(forwarding_object), forwarding_object);
3997
3998 object = rb_gc_impl_location(objspace, forwarding_object);
3999
4000 uint32_t original_shape_id = 0;
4001 if (RB_TYPE_P(object, T_OBJECT)) {
4002 original_shape_id = RMOVED(forwarding_object)->original_shape_id;
4003 }
4004
4005 gc_move(objspace, object, forwarding_object, GET_HEAP_PAGE(object)->slot_size, page->slot_size);
4006 /* forwarding_object is now our actual object, and "object"
4007 * is the free slot for the original page */
4008
4009 if (original_shape_id) {
4010 rb_gc_set_shape(forwarding_object, original_shape_id);
4011 }
4012
4013 struct heap_page *orig_page = GET_HEAP_PAGE(object);
4014 orig_page->free_slots++;
4015 heap_page_add_freeobj(objspace, orig_page, object);
4016
4017 GC_ASSERT(RVALUE_MARKED(objspace, forwarding_object));
4018 GC_ASSERT(BUILTIN_TYPE(forwarding_object) != T_MOVED);
4019 GC_ASSERT(BUILTIN_TYPE(forwarding_object) != T_NONE);
4020 }
4021 }
4022 p += BASE_SLOT_SIZE;
4023 bitset >>= 1;
4024 } while (bitset);
4025 }
4026}
4027
4028static void
4029invalidate_moved_page(rb_objspace_t *objspace, struct heap_page *page)
4030{
4031 int i;
4032 bits_t *mark_bits, *pin_bits;
4033 bits_t bitset;
4034
4035 mark_bits = page->mark_bits;
4036 pin_bits = page->pinned_bits;
4037
4038 uintptr_t p = page->start;
4039
4040 // Skip out of range slots at the head of the page
4041 bitset = pin_bits[0] & ~mark_bits[0];
4042 bitset >>= NUM_IN_PAGE(p);
4043 invalidate_moved_plane(objspace, page, p, bitset);
4044 p += (BITS_BITLENGTH - NUM_IN_PAGE(p)) * BASE_SLOT_SIZE;
4045
4046 for (i=1; i < HEAP_PAGE_BITMAP_LIMIT; i++) {
4047 /* Moved objects are pinned but never marked. We reuse the pin bits
4048 * to indicate there is a moved object in this slot. */
4049 bitset = pin_bits[i] & ~mark_bits[i];
4050
4051 invalidate_moved_plane(objspace, page, p, bitset);
4052 p += BITS_BITLENGTH * BASE_SLOT_SIZE;
4053 }
4054}
4055#endif
4056
4057static void
4058gc_compact_start(rb_objspace_t *objspace)
4059{
4060 struct heap_page *page = NULL;
4061 gc_mode_transition(objspace, gc_mode_compacting);
4062
4063 for (int i = 0; i < HEAP_COUNT; i++) {
4064 rb_heap_t *heap = &heaps[i];
4065 ccan_list_for_each(&heap->pages, page, page_node) {
4066 page->flags.before_sweep = TRUE;
4067 }
4068
4069 heap->compact_cursor = ccan_list_tail(&heap->pages, struct heap_page, page_node);
4070 heap->compact_cursor_index = 0;
4071 }
4072
4073 if (gc_prof_enabled(objspace)) {
4074 gc_profile_record *record = gc_prof_record(objspace);
4075 record->moved_objects = objspace->rcompactor.total_moved;
4076 }
4077
4078 memset(objspace->rcompactor.considered_count_table, 0, T_MASK * sizeof(size_t));
4079 memset(objspace->rcompactor.moved_count_table, 0, T_MASK * sizeof(size_t));
4080 memset(objspace->rcompactor.moved_up_count_table, 0, T_MASK * sizeof(size_t));
4081 memset(objspace->rcompactor.moved_down_count_table, 0, T_MASK * sizeof(size_t));
4082
4083 /* Set up read barrier for pages containing MOVED objects */
4084 install_handlers();
4085}
4086
4087static void gc_sweep_compact(rb_objspace_t *objspace);
4088
4089static void
4090gc_sweep(rb_objspace_t *objspace)
4091{
4092 gc_sweeping_enter(objspace);
4093
4094 const unsigned int immediate_sweep = objspace->flags.immediate_sweep;
4095
4096 gc_report(1, objspace, "gc_sweep: immediate: %d\n", immediate_sweep);
4097
4098 gc_sweep_start(objspace);
4099 if (objspace->flags.during_compacting) {
4100 gc_sweep_compact(objspace);
4101 }
4102
4103 if (immediate_sweep) {
4104#if !GC_ENABLE_LAZY_SWEEP
4105 gc_prof_sweep_timer_start(objspace);
4106#endif
4107 gc_sweep_rest(objspace);
4108#if !GC_ENABLE_LAZY_SWEEP
4109 gc_prof_sweep_timer_stop(objspace);
4110#endif
4111 }
4112 else {
4113
4114 /* Sweep every size pool. */
4115 for (int i = 0; i < HEAP_COUNT; i++) {
4116 rb_heap_t *heap = &heaps[i];
4117 gc_sweep_step(objspace, heap);
4118 }
4119 }
4120
4121 gc_sweeping_exit(objspace);
4122}
4123
4124/* Marking - Marking stack */
4125
4126static stack_chunk_t *
4127stack_chunk_alloc(void)
4128{
4129 stack_chunk_t *res;
4130
4131 res = malloc(sizeof(stack_chunk_t));
4132 if (!res)
4133 rb_memerror();
4134
4135 return res;
4136}
4137
4138static inline int
4139is_mark_stack_empty(mark_stack_t *stack)
4140{
4141 return stack->chunk == NULL;
4142}
4143
4144static size_t
4145mark_stack_size(mark_stack_t *stack)
4146{
4147 size_t size = stack->index;
4148 stack_chunk_t *chunk = stack->chunk ? stack->chunk->next : NULL;
4149
4150 while (chunk) {
4151 size += stack->limit;
4152 chunk = chunk->next;
4153 }
4154 return size;
4155}
4156
4157static void
4158add_stack_chunk_cache(mark_stack_t *stack, stack_chunk_t *chunk)
4159{
4160 chunk->next = stack->cache;
4161 stack->cache = chunk;
4162 stack->cache_size++;
4163}
4164
4165static void
4166shrink_stack_chunk_cache(mark_stack_t *stack)
4167{
4168 stack_chunk_t *chunk;
4169
4170 if (stack->unused_cache_size > (stack->cache_size/2)) {
4171 chunk = stack->cache;
4172 stack->cache = stack->cache->next;
4173 stack->cache_size--;
4174 free(chunk);
4175 }
4176 stack->unused_cache_size = stack->cache_size;
4177}
4178
4179static void
4180push_mark_stack_chunk(mark_stack_t *stack)
4181{
4182 stack_chunk_t *next;
4183
4184 GC_ASSERT(stack->index == stack->limit);
4185
4186 if (stack->cache_size > 0) {
4187 next = stack->cache;
4188 stack->cache = stack->cache->next;
4189 stack->cache_size--;
4190 if (stack->unused_cache_size > stack->cache_size)
4191 stack->unused_cache_size = stack->cache_size;
4192 }
4193 else {
4194 next = stack_chunk_alloc();
4195 }
4196 next->next = stack->chunk;
4197 stack->chunk = next;
4198 stack->index = 0;
4199}
4200
4201static void
4202pop_mark_stack_chunk(mark_stack_t *stack)
4203{
4204 stack_chunk_t *prev;
4205
4206 prev = stack->chunk->next;
4207 GC_ASSERT(stack->index == 0);
4208 add_stack_chunk_cache(stack, stack->chunk);
4209 stack->chunk = prev;
4210 stack->index = stack->limit;
4211}
4212
4213static void
4214mark_stack_chunk_list_free(stack_chunk_t *chunk)
4215{
4216 stack_chunk_t *next = NULL;
4217
4218 while (chunk != NULL) {
4219 next = chunk->next;
4220 free(chunk);
4221 chunk = next;
4222 }
4223}
4224
4225static void
4226free_stack_chunks(mark_stack_t *stack)
4227{
4228 mark_stack_chunk_list_free(stack->chunk);
4229}
4230
4231static void
4232mark_stack_free_cache(mark_stack_t *stack)
4233{
4234 mark_stack_chunk_list_free(stack->cache);
4235 stack->cache_size = 0;
4236 stack->unused_cache_size = 0;
4237}
4238
4239static void
4240push_mark_stack(mark_stack_t *stack, VALUE obj)
4241{
4242 switch (BUILTIN_TYPE(obj)) {
4243 case T_OBJECT:
4244 case T_CLASS:
4245 case T_MODULE:
4246 case T_FLOAT:
4247 case T_STRING:
4248 case T_REGEXP:
4249 case T_ARRAY:
4250 case T_HASH:
4251 case T_STRUCT:
4252 case T_BIGNUM:
4253 case T_FILE:
4254 case T_DATA:
4255 case T_MATCH:
4256 case T_COMPLEX:
4257 case T_RATIONAL:
4258 case T_TRUE:
4259 case T_FALSE:
4260 case T_SYMBOL:
4261 case T_IMEMO:
4262 case T_ICLASS:
4263 if (stack->index == stack->limit) {
4264 push_mark_stack_chunk(stack);
4265 }
4266 stack->chunk->data[stack->index++] = obj;
4267 return;
4268
4269 case T_NONE:
4270 case T_NIL:
4271 case T_FIXNUM:
4272 case T_MOVED:
4273 case T_ZOMBIE:
4274 case T_UNDEF:
4275 case T_MASK:
4276 rb_bug("push_mark_stack() called for broken object");
4277 break;
4278
4279 case T_NODE:
4280 rb_bug("push_mark_stack: unexpected T_NODE object");
4281 break;
4282 }
4283
4284 rb_bug("rb_gc_mark(): unknown data type 0x%x(%p) %s",
4285 BUILTIN_TYPE(obj), (void *)obj,
4286 is_pointer_to_heap((rb_objspace_t *)rb_gc_get_objspace(), (void *)obj) ? "corrupted object" : "non object");
4287}
4288
4289static int
4290pop_mark_stack(mark_stack_t *stack, VALUE *data)
4291{
4292 if (is_mark_stack_empty(stack)) {
4293 return FALSE;
4294 }
4295 if (stack->index == 1) {
4296 *data = stack->chunk->data[--stack->index];
4297 pop_mark_stack_chunk(stack);
4298 }
4299 else {
4300 *data = stack->chunk->data[--stack->index];
4301 }
4302 return TRUE;
4303}
4304
4305static void
4306init_mark_stack(mark_stack_t *stack)
4307{
4308 int i;
4309
4310 MEMZERO(stack, mark_stack_t, 1);
4311 stack->index = stack->limit = STACK_CHUNK_SIZE;
4312
4313 for (i=0; i < 4; i++) {
4314 add_stack_chunk_cache(stack, stack_chunk_alloc());
4315 }
4316 stack->unused_cache_size = stack->cache_size;
4317}
4318
4319/* Marking */
4320
4321static void
4322rgengc_check_relation(rb_objspace_t *objspace, VALUE obj)
4323{
4324 const VALUE old_parent = objspace->rgengc.parent_object;
4325
4326 if (old_parent) { /* parent object is old */
4327 if (RVALUE_WB_UNPROTECTED(objspace, obj) || !RVALUE_OLD_P(objspace, obj)) {
4328 rgengc_remember(objspace, old_parent);
4329 }
4330 }
4331
4332 GC_ASSERT(old_parent == objspace->rgengc.parent_object);
4333}
4334
4335static inline int
4336gc_mark_set(rb_objspace_t *objspace, VALUE obj)
4337{
4338 if (RVALUE_MARKED(objspace, obj)) return 0;
4339 MARK_IN_BITMAP(GET_HEAP_MARK_BITS(obj), obj);
4340 return 1;
4341}
4342
4343static void
4344gc_aging(rb_objspace_t *objspace, VALUE obj)
4345{
4346 /* Disable aging if Major GC's are disabled. This will prevent longish lived
4347 * objects filling up the heap at the expense of marking many more objects.
4348 *
4349 * We should always pre-warm our process when disabling majors, by running
4350 * GC manually several times so that most objects likely to become oldgen
4351 * are already oldgen.
4352 */
4353 if(!gc_config_full_mark_val)
4354 return;
4355
4356 struct heap_page *page = GET_HEAP_PAGE(obj);
4357
4358 GC_ASSERT(RVALUE_MARKING(objspace, obj) == FALSE);
4359 check_rvalue_consistency(objspace, obj);
4360
4361 if (!RVALUE_PAGE_WB_UNPROTECTED(page, obj)) {
4362 if (!RVALUE_OLD_P(objspace, obj)) {
4363 gc_report(3, objspace, "gc_aging: YOUNG: %s\n", rb_obj_info(obj));
4364 RVALUE_AGE_INC(objspace, obj);
4365 }
4366 else if (is_full_marking(objspace)) {
4367 GC_ASSERT(RVALUE_PAGE_UNCOLLECTIBLE(page, obj) == FALSE);
4368 RVALUE_PAGE_OLD_UNCOLLECTIBLE_SET(objspace, page, obj);
4369 }
4370 }
4371 check_rvalue_consistency(objspace, obj);
4372
4373 objspace->marked_slots++;
4374}
4375
4376static void
4377gc_grey(rb_objspace_t *objspace, VALUE obj)
4378{
4379#if RGENGC_CHECK_MODE
4380 if (RVALUE_MARKED(objspace, obj) == FALSE) rb_bug("gc_grey: %s is not marked.", rb_obj_info(obj));
4381 if (RVALUE_MARKING(objspace, obj) == TRUE) rb_bug("gc_grey: %s is marking/remembered.", rb_obj_info(obj));
4382#endif
4383
4384 if (is_incremental_marking(objspace)) {
4385 MARK_IN_BITMAP(GET_HEAP_MARKING_BITS(obj), obj);
4386 }
4387
4388 push_mark_stack(&objspace->mark_stack, obj);
4389}
4390
4391static void
4392gc_mark(rb_objspace_t *objspace, VALUE obj)
4393{
4394 GC_ASSERT(during_gc);
4395
4396 rgengc_check_relation(objspace, obj);
4397 if (!gc_mark_set(objspace, obj)) return; /* already marked */
4398
4399 if (0) { // for debug GC marking miss
4400 if (objspace->rgengc.parent_object) {
4401 RUBY_DEBUG_LOG("%p (%s) parent:%p (%s)",
4402 (void *)obj, obj_type_name(obj),
4403 (void *)objspace->rgengc.parent_object, obj_type_name(objspace->rgengc.parent_object));
4404 }
4405 else {
4406 RUBY_DEBUG_LOG("%p (%s)", (void *)obj, obj_type_name(obj));
4407 }
4408 }
4409
4410 if (RB_UNLIKELY(RB_TYPE_P(obj, T_NONE))) {
4411 rb_obj_info_dump(obj);
4412 rb_bug("try to mark T_NONE object"); /* check here will help debugging */
4413 }
4414
4415 gc_aging(objspace, obj);
4416 gc_grey(objspace, obj);
4417}
4418
4419static inline void
4420gc_pin(rb_objspace_t *objspace, VALUE obj)
4421{
4422 GC_ASSERT(!SPECIAL_CONST_P(obj));
4423 if (RB_UNLIKELY(objspace->flags.during_compacting)) {
4424 if (RB_LIKELY(during_gc)) {
4425 if (!RVALUE_PINNED(objspace, obj)) {
4426 GC_ASSERT(GET_HEAP_PAGE(obj)->pinned_slots <= GET_HEAP_PAGE(obj)->total_slots);
4427 GET_HEAP_PAGE(obj)->pinned_slots++;
4428 MARK_IN_BITMAP(GET_HEAP_PINNED_BITS(obj), obj);
4429 }
4430 }
4431 }
4432}
4433
4434static inline void
4435gc_mark_and_pin(rb_objspace_t *objspace, VALUE obj)
4436{
4437 gc_pin(objspace, obj);
4438 gc_mark(objspace, obj);
4439}
4440
4441void
4442rb_gc_impl_mark_and_move(void *objspace_ptr, VALUE *ptr)
4443{
4444 rb_objspace_t *objspace = objspace_ptr;
4445
4446 if (RB_UNLIKELY(objspace->flags.during_reference_updating)) {
4447 GC_ASSERT(objspace->flags.during_compacting);
4448 GC_ASSERT(during_gc);
4449
4450 VALUE destination = rb_gc_impl_location(objspace, *ptr);
4451 if (destination != *ptr) {
4452 *ptr = destination;
4453 }
4454 }
4455 else {
4456 gc_mark(objspace, *ptr);
4457 }
4458}
4459
4460void
4461rb_gc_impl_mark(void *objspace_ptr, VALUE obj)
4462{
4463 rb_objspace_t *objspace = objspace_ptr;
4464
4465 gc_mark(objspace, obj);
4466}
4467
4468void
4469rb_gc_impl_mark_and_pin(void *objspace_ptr, VALUE obj)
4470{
4471 rb_objspace_t *objspace = objspace_ptr;
4472
4473 gc_mark_and_pin(objspace, obj);
4474}
4475
4476void
4477rb_gc_impl_mark_maybe(void *objspace_ptr, VALUE obj)
4478{
4479 rb_objspace_t *objspace = objspace_ptr;
4480
4481 (void)VALGRIND_MAKE_MEM_DEFINED(&obj, sizeof(obj));
4482
4483 if (is_pointer_to_heap(objspace, (void *)obj)) {
4484 asan_unpoisoning_object(obj) {
4485 /* Garbage can live on the stack, so do not mark or pin */
4486 switch (BUILTIN_TYPE(obj)) {
4487 case T_ZOMBIE:
4488 case T_NONE:
4489 break;
4490 default:
4491 gc_mark_and_pin(objspace, obj);
4492 break;
4493 }
4494 }
4495 }
4496}
4497
4498void
4499rb_gc_impl_mark_weak(void *objspace_ptr, VALUE *ptr)
4500{
4501 rb_objspace_t *objspace = objspace_ptr;
4502
4503 GC_ASSERT(objspace->rgengc.parent_object == 0 || FL_TEST(objspace->rgengc.parent_object, FL_WB_PROTECTED));
4504
4505 VALUE obj = *ptr;
4506
4507 if (RB_UNLIKELY(RB_TYPE_P(obj, T_NONE))) {
4508 rb_obj_info_dump(obj);
4509 rb_bug("try to mark T_NONE object");
4510 }
4511
4512 /* If we are in a minor GC and the other object is old, then obj should
4513 * already be marked and cannot be reclaimed in this GC cycle so we don't
4514 * need to add it to the weak references list. */
4515 if (!is_full_marking(objspace) && RVALUE_OLD_P(objspace, obj)) {
4516 GC_ASSERT(RVALUE_MARKED(objspace, obj));
4517 GC_ASSERT(!objspace->flags.during_compacting);
4518
4519 return;
4520 }
4521
4522 rgengc_check_relation(objspace, obj);
4523
4524 rb_darray_append_without_gc(&objspace->weak_references, ptr);
4525
4526 objspace->profile.weak_references_count++;
4527}
4528
4529void
4530rb_gc_impl_remove_weak(void *objspace_ptr, VALUE parent_obj, VALUE *ptr)
4531{
4532 rb_objspace_t *objspace = objspace_ptr;
4533
4534 /* If we're not incremental marking, then the state of the objects can't
4535 * change so we don't need to do anything. */
4536 if (!is_incremental_marking(objspace)) return;
4537 /* If parent_obj has not been marked, then ptr has not yet been marked
4538 * weak, so we don't need to do anything. */
4539 if (!RVALUE_MARKED(objspace, parent_obj)) return;
4540
4541 VALUE **ptr_ptr;
4542 rb_darray_foreach(objspace->weak_references, i, ptr_ptr) {
4543 if (*ptr_ptr == ptr) {
4544 *ptr_ptr = NULL;
4545 break;
4546 }
4547 }
4548}
4549
4550static int
4551pin_value(st_data_t key, st_data_t value, st_data_t data)
4552{
4553 rb_gc_impl_mark_and_pin((void *)data, (VALUE)value);
4554
4555 return ST_CONTINUE;
4556}
4557
4558static void
4559mark_roots(rb_objspace_t *objspace, const char **categoryp)
4560{
4561#define MARK_CHECKPOINT(category) do { \
4562 if (categoryp) *categoryp = category; \
4563} while (0)
4564
4565 MARK_CHECKPOINT("objspace");
4566 objspace->rgengc.parent_object = Qfalse;
4567
4568 if (finalizer_table != NULL) {
4569 st_foreach(finalizer_table, pin_value, (st_data_t)objspace);
4570 }
4571
4572 if (stress_to_class) rb_gc_mark(stress_to_class);
4573
4574 rb_gc_save_machine_context();
4575 rb_gc_mark_roots(objspace, categoryp);
4576}
4577
4578static inline void
4579gc_mark_set_parent(rb_objspace_t *objspace, VALUE obj)
4580{
4581 if (RVALUE_OLD_P(objspace, obj)) {
4582 objspace->rgengc.parent_object = obj;
4583 }
4584 else {
4585 objspace->rgengc.parent_object = Qfalse;
4586 }
4587}
4588
4589static void
4590gc_mark_children(rb_objspace_t *objspace, VALUE obj)
4591{
4592 gc_mark_set_parent(objspace, obj);
4593 rb_gc_mark_children(objspace, obj);
4594}
4595
4600static inline int
4601gc_mark_stacked_objects(rb_objspace_t *objspace, int incremental, size_t count)
4602{
4603 mark_stack_t *mstack = &objspace->mark_stack;
4604 VALUE obj;
4605 size_t marked_slots_at_the_beginning = objspace->marked_slots;
4606 size_t popped_count = 0;
4607
4608 while (pop_mark_stack(mstack, &obj)) {
4609 if (obj == Qundef) continue; /* skip */
4610
4611 if (RGENGC_CHECK_MODE && !RVALUE_MARKED(objspace, obj)) {
4612 rb_bug("gc_mark_stacked_objects: %s is not marked.", rb_obj_info(obj));
4613 }
4614 gc_mark_children(objspace, obj);
4615
4616 if (incremental) {
4617 if (RGENGC_CHECK_MODE && !RVALUE_MARKING(objspace, obj)) {
4618 rb_bug("gc_mark_stacked_objects: incremental, but marking bit is 0");
4619 }
4620 CLEAR_IN_BITMAP(GET_HEAP_MARKING_BITS(obj), obj);
4621 popped_count++;
4622
4623 if (popped_count + (objspace->marked_slots - marked_slots_at_the_beginning) > count) {
4624 break;
4625 }
4626 }
4627 else {
4628 /* just ignore marking bits */
4629 }
4630 }
4631
4632 if (RGENGC_CHECK_MODE >= 3) gc_verify_internal_consistency(objspace);
4633
4634 if (is_mark_stack_empty(mstack)) {
4635 shrink_stack_chunk_cache(mstack);
4636 return TRUE;
4637 }
4638 else {
4639 return FALSE;
4640 }
4641}
4642
4643static int
4644gc_mark_stacked_objects_incremental(rb_objspace_t *objspace, size_t count)
4645{
4646 return gc_mark_stacked_objects(objspace, TRUE, count);
4647}
4648
4649static int
4650gc_mark_stacked_objects_all(rb_objspace_t *objspace)
4651{
4652 return gc_mark_stacked_objects(objspace, FALSE, 0);
4653}
4654
4655#if RGENGC_CHECK_MODE >= 4
4656
4657#define MAKE_ROOTSIG(obj) (((VALUE)(obj) << 1) | 0x01)
4658#define IS_ROOTSIG(obj) ((VALUE)(obj) & 0x01)
4659#define GET_ROOTSIG(obj) ((const char *)((VALUE)(obj) >> 1))
4660
4661struct reflist {
4662 VALUE *list;
4663 int pos;
4664 int size;
4665};
4666
4667static struct reflist *
4668reflist_create(VALUE obj)
4669{
4670 struct reflist *refs = xmalloc(sizeof(struct reflist));
4671 refs->size = 1;
4672 refs->list = ALLOC_N(VALUE, refs->size);
4673 refs->list[0] = obj;
4674 refs->pos = 1;
4675 return refs;
4676}
4677
4678static void
4679reflist_destruct(struct reflist *refs)
4680{
4681 xfree(refs->list);
4682 xfree(refs);
4683}
4684
4685static void
4686reflist_add(struct reflist *refs, VALUE obj)
4687{
4688 if (refs->pos == refs->size) {
4689 refs->size *= 2;
4690 SIZED_REALLOC_N(refs->list, VALUE, refs->size, refs->size/2);
4691 }
4692
4693 refs->list[refs->pos++] = obj;
4694}
4695
4696static void
4697reflist_dump(struct reflist *refs)
4698{
4699 int i;
4700 for (i=0; i<refs->pos; i++) {
4701 VALUE obj = refs->list[i];
4702 if (IS_ROOTSIG(obj)) { /* root */
4703 fprintf(stderr, "<root@%s>", GET_ROOTSIG(obj));
4704 }
4705 else {
4706 fprintf(stderr, "<%s>", rb_obj_info(obj));
4707 }
4708 if (i+1 < refs->pos) fprintf(stderr, ", ");
4709 }
4710}
4711
4712static int
4713reflist_referred_from_machine_context(struct reflist *refs)
4714{
4715 int i;
4716 for (i=0; i<refs->pos; i++) {
4717 VALUE obj = refs->list[i];
4718 if (IS_ROOTSIG(obj) && strcmp(GET_ROOTSIG(obj), "machine_context") == 0) return 1;
4719 }
4720 return 0;
4721}
4722
4723struct allrefs {
4725 /* a -> obj1
4726 * b -> obj1
4727 * c -> obj1
4728 * c -> obj2
4729 * d -> obj3
4730 * #=> {obj1 => [a, b, c], obj2 => [c, d]}
4731 */
4732 struct st_table *references;
4733 const char *category;
4734 VALUE root_obj;
4736};
4737
4738static int
4739allrefs_add(struct allrefs *data, VALUE obj)
4740{
4741 struct reflist *refs;
4742 st_data_t r;
4743
4744 if (st_lookup(data->references, obj, &r)) {
4745 refs = (struct reflist *)r;
4746 reflist_add(refs, data->root_obj);
4747 return 0;
4748 }
4749 else {
4750 refs = reflist_create(data->root_obj);
4751 st_insert(data->references, obj, (st_data_t)refs);
4752 return 1;
4753 }
4754}
4755
4756static void
4757allrefs_i(VALUE obj, void *ptr)
4758{
4759 struct allrefs *data = (struct allrefs *)ptr;
4760
4761 if (allrefs_add(data, obj)) {
4762 push_mark_stack(&data->mark_stack, obj);
4763 }
4764}
4765
4766static void
4767allrefs_roots_i(VALUE obj, void *ptr)
4768{
4769 struct allrefs *data = (struct allrefs *)ptr;
4770 if (strlen(data->category) == 0) rb_bug("!!!");
4771 data->root_obj = MAKE_ROOTSIG(data->category);
4772
4773 if (allrefs_add(data, obj)) {
4774 push_mark_stack(&data->mark_stack, obj);
4775 }
4776}
4777#define PUSH_MARK_FUNC_DATA(v) do { \
4778 struct gc_mark_func_data_struct *prev_mark_func_data = GET_VM()->gc.mark_func_data; \
4779 GET_VM()->gc.mark_func_data = (v);
4780
4781#define POP_MARK_FUNC_DATA() GET_VM()->gc.mark_func_data = prev_mark_func_data;} while (0)
4782
4783static st_table *
4784objspace_allrefs(rb_objspace_t *objspace)
4785{
4786 struct allrefs data;
4787 struct gc_mark_func_data_struct mfd;
4788 VALUE obj;
4789 int prev_dont_gc = dont_gc_val();
4790 dont_gc_on();
4791
4792 data.objspace = objspace;
4793 data.references = st_init_numtable();
4794 init_mark_stack(&data.mark_stack);
4795
4796 mfd.mark_func = allrefs_roots_i;
4797 mfd.data = &data;
4798
4799 /* traverse root objects */
4800 PUSH_MARK_FUNC_DATA(&mfd);
4801 GET_VM()->gc.mark_func_data = &mfd;
4802 mark_roots(objspace, &data.category);
4803 POP_MARK_FUNC_DATA();
4804
4805 /* traverse rest objects reachable from root objects */
4806 while (pop_mark_stack(&data.mark_stack, &obj)) {
4807 rb_objspace_reachable_objects_from(data.root_obj = obj, allrefs_i, &data);
4808 }
4809 free_stack_chunks(&data.mark_stack);
4810
4811 dont_gc_set(prev_dont_gc);
4812 return data.references;
4813}
4814
4815static int
4816objspace_allrefs_destruct_i(st_data_t key, st_data_t value, st_data_t ptr)
4817{
4818 struct reflist *refs = (struct reflist *)value;
4819 reflist_destruct(refs);
4820 return ST_CONTINUE;
4821}
4822
4823static void
4824objspace_allrefs_destruct(struct st_table *refs)
4825{
4826 st_foreach(refs, objspace_allrefs_destruct_i, 0);
4827 st_free_table(refs);
4828}
4829
4830#if RGENGC_CHECK_MODE >= 5
4831static int
4832allrefs_dump_i(st_data_t k, st_data_t v, st_data_t ptr)
4833{
4834 VALUE obj = (VALUE)k;
4835 struct reflist *refs = (struct reflist *)v;
4836 fprintf(stderr, "[allrefs_dump_i] %s <- ", rb_obj_info(obj));
4837 reflist_dump(refs);
4838 fprintf(stderr, "\n");
4839 return ST_CONTINUE;
4840}
4841
4842static void
4843allrefs_dump(rb_objspace_t *objspace)
4844{
4845 VALUE size = objspace->rgengc.allrefs_table->num_entries;
4846 fprintf(stderr, "[all refs] (size: %"PRIuVALUE")\n", size);
4847 st_foreach(objspace->rgengc.allrefs_table, allrefs_dump_i, 0);
4848}
4849#endif
4850
4851static int
4852gc_check_after_marks_i(st_data_t k, st_data_t v, st_data_t ptr)
4853{
4854 VALUE obj = k;
4855 struct reflist *refs = (struct reflist *)v;
4857
4858 /* object should be marked or oldgen */
4859 if (!RVALUE_MARKED(objspace, obj)) {
4860 fprintf(stderr, "gc_check_after_marks_i: %s is not marked and not oldgen.\n", rb_obj_info(obj));
4861 fprintf(stderr, "gc_check_after_marks_i: %p is referred from ", (void *)obj);
4862 reflist_dump(refs);
4863
4864 if (reflist_referred_from_machine_context(refs)) {
4865 fprintf(stderr, " (marked from machine stack).\n");
4866 /* marked from machine context can be false positive */
4867 }
4868 else {
4869 objspace->rgengc.error_count++;
4870 fprintf(stderr, "\n");
4871 }
4872 }
4873 return ST_CONTINUE;
4874}
4875
4876static void
4877gc_marks_check(rb_objspace_t *objspace, st_foreach_callback_func *checker_func, const char *checker_name)
4878{
4879 size_t saved_malloc_increase = objspace->malloc_params.increase;
4880#if RGENGC_ESTIMATE_OLDMALLOC
4881 size_t saved_oldmalloc_increase = objspace->rgengc.oldmalloc_increase;
4882#endif
4883 VALUE already_disabled = rb_objspace_gc_disable(objspace);
4884
4885 objspace->rgengc.allrefs_table = objspace_allrefs(objspace);
4886
4887 if (checker_func) {
4888 st_foreach(objspace->rgengc.allrefs_table, checker_func, (st_data_t)objspace);
4889 }
4890
4891 if (objspace->rgengc.error_count > 0) {
4892#if RGENGC_CHECK_MODE >= 5
4893 allrefs_dump(objspace);
4894#endif
4895 if (checker_name) rb_bug("%s: GC has problem.", checker_name);
4896 }
4897
4898 objspace_allrefs_destruct(objspace->rgengc.allrefs_table);
4899 objspace->rgengc.allrefs_table = 0;
4900
4901 if (already_disabled == Qfalse) rb_objspace_gc_enable(objspace);
4902 objspace->malloc_params.increase = saved_malloc_increase;
4903#if RGENGC_ESTIMATE_OLDMALLOC
4904 objspace->rgengc.oldmalloc_increase = saved_oldmalloc_increase;
4905#endif
4906}
4907#endif /* RGENGC_CHECK_MODE >= 4 */
4908
4911 int err_count;
4912 size_t live_object_count;
4913 size_t zombie_object_count;
4914
4915 VALUE parent;
4916 size_t old_object_count;
4917 size_t remembered_shady_count;
4918};
4919
4920static void
4921check_generation_i(const VALUE child, void *ptr)
4922{
4924 const VALUE parent = data->parent;
4925
4926 if (RGENGC_CHECK_MODE) GC_ASSERT(RVALUE_OLD_P(data->objspace, parent));
4927
4928 if (!RVALUE_OLD_P(data->objspace, child)) {
4929 if (!RVALUE_REMEMBERED(data->objspace, parent) &&
4930 !RVALUE_REMEMBERED(data->objspace, child) &&
4931 !RVALUE_UNCOLLECTIBLE(data->objspace, child)) {
4932 fprintf(stderr, "verify_internal_consistency_reachable_i: WB miss (O->Y) %s -> %s\n", rb_obj_info(parent), rb_obj_info(child));
4933 data->err_count++;
4934 }
4935 }
4936}
4937
4938static void
4939check_color_i(const VALUE child, void *ptr)
4940{
4942 const VALUE parent = data->parent;
4943
4944 if (!RVALUE_WB_UNPROTECTED(data->objspace, parent) && RVALUE_WHITE_P(data->objspace, child)) {
4945 fprintf(stderr, "verify_internal_consistency_reachable_i: WB miss (B->W) - %s -> %s\n",
4946 rb_obj_info(parent), rb_obj_info(child));
4947 data->err_count++;
4948 }
4949}
4950
4951static void
4952check_children_i(const VALUE child, void *ptr)
4953{
4955 if (check_rvalue_consistency_force(data->objspace, child, FALSE) != 0) {
4956 fprintf(stderr, "check_children_i: %s has error (referenced from %s)",
4957 rb_obj_info(child), rb_obj_info(data->parent));
4958
4959 data->err_count++;
4960 }
4961}
4962
4963static int
4964verify_internal_consistency_i(void *page_start, void *page_end, size_t stride,
4966{
4967 VALUE obj;
4968 rb_objspace_t *objspace = data->objspace;
4969
4970 for (obj = (VALUE)page_start; obj != (VALUE)page_end; obj += stride) {
4971 asan_unpoisoning_object(obj) {
4972 if (!rb_gc_impl_garbage_object_p(objspace, obj)) {
4973 /* count objects */
4974 data->live_object_count++;
4975 data->parent = obj;
4976
4977 /* Normally, we don't expect T_MOVED objects to be in the heap.
4978 * But they can stay alive on the stack, */
4979 if (!gc_object_moved_p(objspace, obj)) {
4980 /* moved slots don't have children */
4981 rb_objspace_reachable_objects_from(obj, check_children_i, (void *)data);
4982 }
4983
4984 /* check health of children */
4985 if (RVALUE_OLD_P(objspace, obj)) data->old_object_count++;
4986 if (RVALUE_WB_UNPROTECTED(objspace, obj) && RVALUE_UNCOLLECTIBLE(objspace, obj)) data->remembered_shady_count++;
4987
4988 if (!is_marking(objspace) && RVALUE_OLD_P(objspace, obj)) {
4989 /* reachable objects from an oldgen object should be old or (young with remember) */
4990 data->parent = obj;
4991 rb_objspace_reachable_objects_from(obj, check_generation_i, (void *)data);
4992 }
4993
4994 if (is_incremental_marking(objspace)) {
4995 if (RVALUE_BLACK_P(objspace, obj)) {
4996 /* reachable objects from black objects should be black or grey objects */
4997 data->parent = obj;
4998 rb_objspace_reachable_objects_from(obj, check_color_i, (void *)data);
4999 }
5000 }
5001 }
5002 else {
5003 if (BUILTIN_TYPE(obj) == T_ZOMBIE) {
5004 data->zombie_object_count++;
5005
5006 if ((RBASIC(obj)->flags & ~ZOMBIE_OBJ_KEPT_FLAGS) != T_ZOMBIE) {
5007 fprintf(stderr, "verify_internal_consistency_i: T_ZOMBIE has extra flags set: %s\n",
5008 rb_obj_info(obj));
5009 data->err_count++;
5010 }
5011
5012 if (!!FL_TEST(obj, FL_FINALIZE) != !!st_is_member(finalizer_table, obj)) {
5013 fprintf(stderr, "verify_internal_consistency_i: FL_FINALIZE %s but %s finalizer_table: %s\n",
5014 FL_TEST(obj, FL_FINALIZE) ? "set" : "not set", st_is_member(finalizer_table, obj) ? "in" : "not in",
5015 rb_obj_info(obj));
5016 data->err_count++;
5017 }
5018 }
5019 }
5020 }
5021 }
5022
5023 return 0;
5024}
5025
5026static int
5027gc_verify_heap_page(rb_objspace_t *objspace, struct heap_page *page, VALUE obj)
5028{
5029 unsigned int has_remembered_shady = FALSE;
5030 unsigned int has_remembered_old = FALSE;
5031 int remembered_old_objects = 0;
5032 int free_objects = 0;
5033 int zombie_objects = 0;
5034
5035 short slot_size = page->slot_size;
5036 uintptr_t start = (uintptr_t)page->start;
5037 uintptr_t end = start + page->total_slots * slot_size;
5038
5039 for (uintptr_t ptr = start; ptr < end; ptr += slot_size) {
5040 VALUE val = (VALUE)ptr;
5041 asan_unpoisoning_object(val) {
5042 enum ruby_value_type type = BUILTIN_TYPE(val);
5043
5044 if (type == T_NONE) free_objects++;
5045 if (type == T_ZOMBIE) zombie_objects++;
5046 if (RVALUE_PAGE_UNCOLLECTIBLE(page, val) && RVALUE_PAGE_WB_UNPROTECTED(page, val)) {
5047 has_remembered_shady = TRUE;
5048 }
5049 if (RVALUE_PAGE_MARKING(page, val)) {
5050 has_remembered_old = TRUE;
5051 remembered_old_objects++;
5052 }
5053 }
5054 }
5055
5056 if (!is_incremental_marking(objspace) &&
5057 page->flags.has_remembered_objects == FALSE && has_remembered_old == TRUE) {
5058
5059 for (uintptr_t ptr = start; ptr < end; ptr += slot_size) {
5060 VALUE val = (VALUE)ptr;
5061 if (RVALUE_PAGE_MARKING(page, val)) {
5062 fprintf(stderr, "marking -> %s\n", rb_obj_info(val));
5063 }
5064 }
5065 rb_bug("page %p's has_remembered_objects should be false, but there are remembered old objects (%d). %s",
5066 (void *)page, remembered_old_objects, obj ? rb_obj_info(obj) : "");
5067 }
5068
5069 if (page->flags.has_uncollectible_wb_unprotected_objects == FALSE && has_remembered_shady == TRUE) {
5070 rb_bug("page %p's has_remembered_shady should be false, but there are remembered shady objects. %s",
5071 (void *)page, obj ? rb_obj_info(obj) : "");
5072 }
5073
5074 if (0) {
5075 /* free_slots may not equal to free_objects */
5076 if (page->free_slots != free_objects) {
5077 rb_bug("page %p's free_slots should be %d, but %d", (void *)page, page->free_slots, free_objects);
5078 }
5079 }
5080 if (page->final_slots != zombie_objects) {
5081 rb_bug("page %p's final_slots should be %d, but %d", (void *)page, page->final_slots, zombie_objects);
5082 }
5083
5084 return remembered_old_objects;
5085}
5086
5087static int
5088gc_verify_heap_pages_(rb_objspace_t *objspace, struct ccan_list_head *head)
5089{
5090 int remembered_old_objects = 0;
5091 struct heap_page *page = 0;
5092
5093 ccan_list_for_each(head, page, page_node) {
5094 asan_unlock_freelist(page);
5095 struct free_slot *p = page->freelist;
5096 while (p) {
5097 VALUE vp = (VALUE)p;
5098 VALUE prev = vp;
5099 rb_asan_unpoison_object(vp, false);
5100 if (BUILTIN_TYPE(vp) != T_NONE) {
5101 fprintf(stderr, "freelist slot expected to be T_NONE but was: %s\n", rb_obj_info(vp));
5102 }
5103 p = p->next;
5104 rb_asan_poison_object(prev);
5105 }
5106 asan_lock_freelist(page);
5107
5108 if (page->flags.has_remembered_objects == FALSE) {
5109 remembered_old_objects += gc_verify_heap_page(objspace, page, Qfalse);
5110 }
5111 }
5112
5113 return remembered_old_objects;
5114}
5115
5116static int
5117gc_verify_heap_pages(rb_objspace_t *objspace)
5118{
5119 int remembered_old_objects = 0;
5120 for (int i = 0; i < HEAP_COUNT; i++) {
5121 remembered_old_objects += gc_verify_heap_pages_(objspace, &((&heaps[i])->pages));
5122 }
5123 return remembered_old_objects;
5124}
5125
5126static void
5127gc_verify_internal_consistency_(rb_objspace_t *objspace)
5128{
5129 struct verify_internal_consistency_struct data = {0};
5130
5131 data.objspace = objspace;
5132 gc_report(5, objspace, "gc_verify_internal_consistency: start\n");
5133
5134 /* check relations */
5135 for (size_t i = 0; i < rb_darray_size(objspace->heap_pages.sorted); i++) {
5136 struct heap_page *page = rb_darray_get(objspace->heap_pages.sorted, i);
5137 short slot_size = page->slot_size;
5138
5139 uintptr_t start = (uintptr_t)page->start;
5140 uintptr_t end = start + page->total_slots * slot_size;
5141
5142 verify_internal_consistency_i((void *)start, (void *)end, slot_size, &data);
5143 }
5144
5145 if (data.err_count != 0) {
5146#if RGENGC_CHECK_MODE >= 5
5147 objspace->rgengc.error_count = data.err_count;
5148 gc_marks_check(objspace, NULL, NULL);
5149 allrefs_dump(objspace);
5150#endif
5151 rb_bug("gc_verify_internal_consistency: found internal inconsistency.");
5152 }
5153
5154 /* check heap_page status */
5155 gc_verify_heap_pages(objspace);
5156
5157 /* check counters */
5158
5159 if (!is_lazy_sweeping(objspace) &&
5160 !finalizing &&
5161 !rb_gc_multi_ractor_p()) {
5162 if (objspace_live_slots(objspace) != data.live_object_count) {
5163 fprintf(stderr, "heap_pages_final_slots: %"PRIdSIZE", total_freed_objects: %"PRIdSIZE"\n",
5164 total_final_slots_count(objspace), total_freed_objects(objspace));
5165 rb_bug("inconsistent live slot number: expect %"PRIuSIZE", but %"PRIuSIZE".",
5166 objspace_live_slots(objspace), data.live_object_count);
5167 }
5168 }
5169
5170 if (!is_marking(objspace)) {
5171 if (objspace->rgengc.old_objects != data.old_object_count) {
5172 rb_bug("inconsistent old slot number: expect %"PRIuSIZE", but %"PRIuSIZE".",
5173 objspace->rgengc.old_objects, data.old_object_count);
5174 }
5175 if (objspace->rgengc.uncollectible_wb_unprotected_objects != data.remembered_shady_count) {
5176 rb_bug("inconsistent number of wb unprotected objects: expect %"PRIuSIZE", but %"PRIuSIZE".",
5177 objspace->rgengc.uncollectible_wb_unprotected_objects, data.remembered_shady_count);
5178 }
5179 }
5180
5181 if (!finalizing) {
5182 size_t list_count = 0;
5183
5184 {
5185 VALUE z = heap_pages_deferred_final;
5186 while (z) {
5187 list_count++;
5188 z = RZOMBIE(z)->next;
5189 }
5190 }
5191
5192 if (total_final_slots_count(objspace) != data.zombie_object_count ||
5193 total_final_slots_count(objspace) != list_count) {
5194
5195 rb_bug("inconsistent finalizing object count:\n"
5196 " expect %"PRIuSIZE"\n"
5197 " but %"PRIuSIZE" zombies\n"
5198 " heap_pages_deferred_final list has %"PRIuSIZE" items.",
5199 total_final_slots_count(objspace),
5200 data.zombie_object_count,
5201 list_count);
5202 }
5203 }
5204
5205 gc_report(5, objspace, "gc_verify_internal_consistency: OK\n");
5206}
5207
5208static void
5209gc_verify_internal_consistency(void *objspace_ptr)
5210{
5211 rb_objspace_t *objspace = objspace_ptr;
5212
5213 unsigned int lev = RB_GC_VM_LOCK();
5214 {
5215 rb_gc_vm_barrier(); // stop other ractors
5216
5217 unsigned int prev_during_gc = during_gc;
5218 during_gc = FALSE; // stop gc here
5219 {
5220 gc_verify_internal_consistency_(objspace);
5221 }
5222 during_gc = prev_during_gc;
5223 }
5224 RB_GC_VM_UNLOCK(lev);
5225}
5226
5227static void
5228heap_move_pooled_pages_to_free_pages(rb_heap_t *heap)
5229{
5230 if (heap->pooled_pages) {
5231 if (heap->free_pages) {
5232 struct heap_page *free_pages_tail = heap->free_pages;
5233 while (free_pages_tail->free_next) {
5234 free_pages_tail = free_pages_tail->free_next;
5235 }
5236 free_pages_tail->free_next = heap->pooled_pages;
5237 }
5238 else {
5239 heap->free_pages = heap->pooled_pages;
5240 }
5241
5242 heap->pooled_pages = NULL;
5243 }
5244}
5245
5246static int
5247gc_remember_unprotected(rb_objspace_t *objspace, VALUE obj)
5248{
5249 struct heap_page *page = GET_HEAP_PAGE(obj);
5250 bits_t *uncollectible_bits = &page->uncollectible_bits[0];
5251
5252 if (!MARKED_IN_BITMAP(uncollectible_bits, obj)) {
5253 page->flags.has_uncollectible_wb_unprotected_objects = TRUE;
5254 MARK_IN_BITMAP(uncollectible_bits, obj);
5255 objspace->rgengc.uncollectible_wb_unprotected_objects++;
5256
5257#if RGENGC_PROFILE > 0
5258 objspace->profile.total_remembered_shady_object_count++;
5259#if RGENGC_PROFILE >= 2
5260 objspace->profile.remembered_shady_object_count_types[BUILTIN_TYPE(obj)]++;
5261#endif
5262#endif
5263 return TRUE;
5264 }
5265 else {
5266 return FALSE;
5267 }
5268}
5269
5270static inline void
5271gc_marks_wb_unprotected_objects_plane(rb_objspace_t *objspace, uintptr_t p, bits_t bits)
5272{
5273 if (bits) {
5274 do {
5275 if (bits & 1) {
5276 gc_report(2, objspace, "gc_marks_wb_unprotected_objects: marked shady: %s\n", rb_obj_info((VALUE)p));
5277 GC_ASSERT(RVALUE_WB_UNPROTECTED(objspace, (VALUE)p));
5278 GC_ASSERT(RVALUE_MARKED(objspace, (VALUE)p));
5279 gc_mark_children(objspace, (VALUE)p);
5280 }
5281 p += BASE_SLOT_SIZE;
5282 bits >>= 1;
5283 } while (bits);
5284 }
5285}
5286
5287static void
5288gc_marks_wb_unprotected_objects(rb_objspace_t *objspace, rb_heap_t *heap)
5289{
5290 struct heap_page *page = 0;
5291
5292 ccan_list_for_each(&heap->pages, page, page_node) {
5293 bits_t *mark_bits = page->mark_bits;
5294 bits_t *wbun_bits = page->wb_unprotected_bits;
5295 uintptr_t p = page->start;
5296 size_t j;
5297
5298 bits_t bits = mark_bits[0] & wbun_bits[0];
5299 bits >>= NUM_IN_PAGE(p);
5300 gc_marks_wb_unprotected_objects_plane(objspace, p, bits);
5301 p += (BITS_BITLENGTH - NUM_IN_PAGE(p)) * BASE_SLOT_SIZE;
5302
5303 for (j=1; j<HEAP_PAGE_BITMAP_LIMIT; j++) {
5304 bits_t bits = mark_bits[j] & wbun_bits[j];
5305
5306 gc_marks_wb_unprotected_objects_plane(objspace, p, bits);
5307 p += BITS_BITLENGTH * BASE_SLOT_SIZE;
5308 }
5309 }
5310
5311 gc_mark_stacked_objects_all(objspace);
5312}
5313
5314static void
5315gc_update_weak_references(rb_objspace_t *objspace)
5316{
5317 size_t retained_weak_references_count = 0;
5318 VALUE **ptr_ptr;
5319 rb_darray_foreach(objspace->weak_references, i, ptr_ptr) {
5320 if (!*ptr_ptr) continue;
5321
5322 VALUE obj = **ptr_ptr;
5323
5324 if (RB_SPECIAL_CONST_P(obj)) continue;
5325
5326 if (!RVALUE_MARKED(objspace, obj)) {
5327 **ptr_ptr = Qundef;
5328 }
5329 else {
5330 retained_weak_references_count++;
5331 }
5332 }
5333
5334 objspace->profile.retained_weak_references_count = retained_weak_references_count;
5335
5336 rb_darray_clear(objspace->weak_references);
5337 rb_darray_resize_capa_without_gc(&objspace->weak_references, retained_weak_references_count);
5338}
5339
5340static void
5341gc_marks_finish(rb_objspace_t *objspace)
5342{
5343 /* finish incremental GC */
5344 if (is_incremental_marking(objspace)) {
5345 if (RGENGC_CHECK_MODE && is_mark_stack_empty(&objspace->mark_stack) == 0) {
5346 rb_bug("gc_marks_finish: mark stack is not empty (%"PRIdSIZE").",
5347 mark_stack_size(&objspace->mark_stack));
5348 }
5349
5350 mark_roots(objspace, NULL);
5351 while (gc_mark_stacked_objects_incremental(objspace, INT_MAX) == false);
5352
5353#if RGENGC_CHECK_MODE >= 2
5354 if (gc_verify_heap_pages(objspace) != 0) {
5355 rb_bug("gc_marks_finish (incremental): there are remembered old objects.");
5356 }
5357#endif
5358
5359 objspace->flags.during_incremental_marking = FALSE;
5360 /* check children of all marked wb-unprotected objects */
5361 for (int i = 0; i < HEAP_COUNT; i++) {
5362 gc_marks_wb_unprotected_objects(objspace, &heaps[i]);
5363 }
5364 }
5365
5366 gc_update_weak_references(objspace);
5367
5368#if RGENGC_CHECK_MODE >= 2
5369 gc_verify_internal_consistency(objspace);
5370#endif
5371
5372#if RGENGC_CHECK_MODE >= 4
5373 during_gc = FALSE;
5374 gc_marks_check(objspace, gc_check_after_marks_i, "after_marks");
5375 during_gc = TRUE;
5376#endif
5377
5378 {
5379 const unsigned long r_mul = objspace->live_ractor_cache_count > 8 ? 8 : objspace->live_ractor_cache_count; // upto 8
5380
5381 size_t total_slots = objspace_available_slots(objspace);
5382 size_t sweep_slots = total_slots - objspace->marked_slots; /* will be swept slots */
5383 size_t max_free_slots = (size_t)(total_slots * gc_params.heap_free_slots_max_ratio);
5384 size_t min_free_slots = (size_t)(total_slots * gc_params.heap_free_slots_min_ratio);
5385 if (min_free_slots < gc_params.heap_free_slots * r_mul) {
5386 min_free_slots = gc_params.heap_free_slots * r_mul;
5387 }
5388
5389 int full_marking = is_full_marking(objspace);
5390
5391 GC_ASSERT(objspace_available_slots(objspace) >= objspace->marked_slots);
5392
5393 /* Setup freeable slots. */
5394 size_t total_init_slots = 0;
5395 for (int i = 0; i < HEAP_COUNT; i++) {
5396 total_init_slots += gc_params.heap_init_slots[i] * r_mul;
5397 }
5398
5399 if (max_free_slots < total_init_slots) {
5400 max_free_slots = total_init_slots;
5401 }
5402
5403 if (sweep_slots > max_free_slots) {
5404 heap_pages_freeable_pages = (sweep_slots - max_free_slots) / HEAP_PAGE_OBJ_LIMIT;
5405 }
5406 else {
5407 heap_pages_freeable_pages = 0;
5408 }
5409
5410 if (objspace->heap_pages.allocatable_slots == 0 && sweep_slots < min_free_slots) {
5411 if (!full_marking) {
5412 if (objspace->profile.count - objspace->rgengc.last_major_gc < RVALUE_OLD_AGE) {
5413 full_marking = TRUE;
5414 }
5415 else {
5416 gc_report(1, objspace, "gc_marks_finish: next is full GC!!)\n");
5417 gc_needs_major_flags |= GPR_FLAG_MAJOR_BY_NOFREE;
5418 }
5419 }
5420
5421 if (full_marking) {
5422 heap_allocatable_slots_expand(objspace, NULL, sweep_slots, total_slots);
5423 }
5424 }
5425
5426 if (full_marking) {
5427 /* See the comment about RUBY_GC_HEAP_OLDOBJECT_LIMIT_FACTOR */
5428 const double r = gc_params.oldobject_limit_factor;
5429 objspace->rgengc.uncollectible_wb_unprotected_objects_limit = MAX(
5430 (size_t)(objspace->rgengc.uncollectible_wb_unprotected_objects * r),
5431 (size_t)(objspace->rgengc.old_objects * gc_params.uncollectible_wb_unprotected_objects_limit_ratio)
5432 );
5433 objspace->rgengc.old_objects_limit = (size_t)(objspace->rgengc.old_objects * r);
5434 }
5435
5436 if (objspace->rgengc.uncollectible_wb_unprotected_objects > objspace->rgengc.uncollectible_wb_unprotected_objects_limit) {
5437 gc_needs_major_flags |= GPR_FLAG_MAJOR_BY_SHADY;
5438 }
5439 if (objspace->rgengc.old_objects > objspace->rgengc.old_objects_limit) {
5440 gc_needs_major_flags |= GPR_FLAG_MAJOR_BY_OLDGEN;
5441 }
5442
5443 gc_report(1, objspace, "gc_marks_finish (marks %"PRIdSIZE" objects, "
5444 "old %"PRIdSIZE" objects, total %"PRIdSIZE" slots, "
5445 "sweep %"PRIdSIZE" slots, allocatable %"PRIdSIZE" slots, next GC: %s)\n",
5446 objspace->marked_slots, objspace->rgengc.old_objects, objspace_available_slots(objspace), sweep_slots, objspace->heap_pages.allocatable_slots,
5447 gc_needs_major_flags ? "major" : "minor");
5448 }
5449
5450 // TODO: refactor so we don't need to call this
5451 rb_ractor_finish_marking();
5452
5453 rb_gc_event_hook(0, RUBY_INTERNAL_EVENT_GC_END_MARK);
5454}
5455
5456static bool
5457gc_compact_heap_cursors_met_p(rb_heap_t *heap)
5458{
5459 return heap->sweeping_page == heap->compact_cursor;
5460}
5461
5462
5463static rb_heap_t *
5464gc_compact_destination_pool(rb_objspace_t *objspace, rb_heap_t *src_pool, VALUE obj)
5465{
5466 size_t obj_size = rb_gc_obj_optimal_size(obj);
5467 if (obj_size == 0) {
5468 return src_pool;
5469 }
5470
5471 size_t idx = 0;
5472 if (rb_gc_impl_size_allocatable_p(obj_size)) {
5473 idx = heap_idx_for_size(obj_size);
5474 }
5475
5476 return &heaps[idx];
5477}
5478
5479static bool
5480gc_compact_move(rb_objspace_t *objspace, rb_heap_t *heap, VALUE src)
5481{
5482 GC_ASSERT(BUILTIN_TYPE(src) != T_MOVED);
5483 GC_ASSERT(gc_is_moveable_obj(objspace, src));
5484
5485 rb_heap_t *dest_pool = gc_compact_destination_pool(objspace, heap, src);
5486 uint32_t orig_shape = 0;
5487 uint32_t new_shape = 0;
5488
5489 if (gc_compact_heap_cursors_met_p(dest_pool)) {
5490 return dest_pool != heap;
5491 }
5492
5493 if (RB_TYPE_P(src, T_OBJECT)) {
5494 orig_shape = rb_gc_get_shape(src);
5495
5496 if (dest_pool != heap) {
5497 new_shape = rb_gc_rebuild_shape(src, dest_pool - heaps);
5498
5499 if (new_shape == 0) {
5500 dest_pool = heap;
5501 }
5502 }
5503 }
5504
5505 while (!try_move(objspace, dest_pool, dest_pool->free_pages, src)) {
5506 struct gc_sweep_context ctx = {
5507 .page = dest_pool->sweeping_page,
5508 .final_slots = 0,
5509 .freed_slots = 0,
5510 .empty_slots = 0,
5511 };
5512
5513 /* The page of src could be partially compacted, so it may contain
5514 * T_MOVED. Sweeping a page may read objects on this page, so we
5515 * need to lock the page. */
5516 lock_page_body(objspace, GET_PAGE_BODY(src));
5517 gc_sweep_page(objspace, dest_pool, &ctx);
5518 unlock_page_body(objspace, GET_PAGE_BODY(src));
5519
5520 if (dest_pool->sweeping_page->free_slots > 0) {
5521 heap_add_freepage(dest_pool, dest_pool->sweeping_page);
5522 }
5523
5524 dest_pool->sweeping_page = ccan_list_next(&dest_pool->pages, dest_pool->sweeping_page, page_node);
5525 if (gc_compact_heap_cursors_met_p(dest_pool)) {
5526 return dest_pool != heap;
5527 }
5528 }
5529
5530 if (orig_shape != 0) {
5531 if (new_shape != 0) {
5532 VALUE dest = rb_gc_impl_location(objspace, src);
5533 rb_gc_set_shape(dest, new_shape);
5534 }
5535 RMOVED(src)->original_shape_id = orig_shape;
5536 }
5537
5538 return true;
5539}
5540
5541static bool
5542gc_compact_plane(rb_objspace_t *objspace, rb_heap_t *heap, uintptr_t p, bits_t bitset, struct heap_page *page)
5543{
5544 short slot_size = page->slot_size;
5545 short slot_bits = slot_size / BASE_SLOT_SIZE;
5546 GC_ASSERT(slot_bits > 0);
5547
5548 do {
5549 VALUE vp = (VALUE)p;
5550 GC_ASSERT(vp % BASE_SLOT_SIZE == 0);
5551
5552 if (bitset & 1) {
5553 objspace->rcompactor.considered_count_table[BUILTIN_TYPE(vp)]++;
5554
5555 if (gc_is_moveable_obj(objspace, vp)) {
5556 if (!gc_compact_move(objspace, heap, vp)) {
5557 //the cursors met. bubble up
5558 return false;
5559 }
5560 }
5561 }
5562 p += slot_size;
5563 bitset >>= slot_bits;
5564 } while (bitset);
5565
5566 return true;
5567}
5568
5569// Iterate up all the objects in page, moving them to where they want to go
5570static bool
5571gc_compact_page(rb_objspace_t *objspace, rb_heap_t *heap, struct heap_page *page)
5572{
5573 GC_ASSERT(page == heap->compact_cursor);
5574
5575 bits_t *mark_bits, *pin_bits;
5576 bits_t bitset;
5577 uintptr_t p = page->start;
5578
5579 mark_bits = page->mark_bits;
5580 pin_bits = page->pinned_bits;
5581
5582 // objects that can be moved are marked and not pinned
5583 bitset = (mark_bits[0] & ~pin_bits[0]);
5584 bitset >>= NUM_IN_PAGE(p);
5585 if (bitset) {
5586 if (!gc_compact_plane(objspace, heap, (uintptr_t)p, bitset, page))
5587 return false;
5588 }
5589 p += (BITS_BITLENGTH - NUM_IN_PAGE(p)) * BASE_SLOT_SIZE;
5590
5591 for (int j = 1; j < HEAP_PAGE_BITMAP_LIMIT; j++) {
5592 bitset = (mark_bits[j] & ~pin_bits[j]);
5593 if (bitset) {
5594 if (!gc_compact_plane(objspace, heap, (uintptr_t)p, bitset, page))
5595 return false;
5596 }
5597 p += BITS_BITLENGTH * BASE_SLOT_SIZE;
5598 }
5599
5600 return true;
5601}
5602
5603static bool
5604gc_compact_all_compacted_p(rb_objspace_t *objspace)
5605{
5606 for (int i = 0; i < HEAP_COUNT; i++) {
5607 rb_heap_t *heap = &heaps[i];
5608
5609 if (heap->total_pages > 0 &&
5610 !gc_compact_heap_cursors_met_p(heap)) {
5611 return false;
5612 }
5613 }
5614
5615 return true;
5616}
5617
5618static void
5619gc_sweep_compact(rb_objspace_t *objspace)
5620{
5621 gc_compact_start(objspace);
5622#if RGENGC_CHECK_MODE >= 2
5623 gc_verify_internal_consistency(objspace);
5624#endif
5625
5626 while (!gc_compact_all_compacted_p(objspace)) {
5627 for (int i = 0; i < HEAP_COUNT; i++) {
5628 rb_heap_t *heap = &heaps[i];
5629
5630 if (gc_compact_heap_cursors_met_p(heap)) {
5631 continue;
5632 }
5633
5634 struct heap_page *start_page = heap->compact_cursor;
5635
5636 if (!gc_compact_page(objspace, heap, start_page)) {
5637 lock_page_body(objspace, start_page->body);
5638
5639 continue;
5640 }
5641
5642 // If we get here, we've finished moving all objects on the compact_cursor page
5643 // So we can lock it and move the cursor on to the next one.
5644 lock_page_body(objspace, start_page->body);
5645 heap->compact_cursor = ccan_list_prev(&heap->pages, heap->compact_cursor, page_node);
5646 }
5647 }
5648
5649 gc_compact_finish(objspace);
5650
5651#if RGENGC_CHECK_MODE >= 2
5652 gc_verify_internal_consistency(objspace);
5653#endif
5654}
5655
5656static void
5657gc_marks_rest(rb_objspace_t *objspace)
5658{
5659 gc_report(1, objspace, "gc_marks_rest\n");
5660
5661 for (int i = 0; i < HEAP_COUNT; i++) {
5662 (&heaps[i])->pooled_pages = NULL;
5663 }
5664
5665 if (is_incremental_marking(objspace)) {
5666 while (gc_mark_stacked_objects_incremental(objspace, INT_MAX) == FALSE);
5667 }
5668 else {
5669 gc_mark_stacked_objects_all(objspace);
5670 }
5671
5672 gc_marks_finish(objspace);
5673}
5674
5675static bool
5676gc_marks_step(rb_objspace_t *objspace, size_t slots)
5677{
5678 bool marking_finished = false;
5679
5680 GC_ASSERT(is_marking(objspace));
5681 if (gc_mark_stacked_objects_incremental(objspace, slots)) {
5682 gc_marks_finish(objspace);
5683
5684 marking_finished = true;
5685 }
5686
5687 return marking_finished;
5688}
5689
5690static bool
5691gc_marks_continue(rb_objspace_t *objspace, rb_heap_t *heap)
5692{
5693 GC_ASSERT(dont_gc_val() == FALSE || objspace->profile.latest_gc_info & GPR_FLAG_METHOD);
5694 bool marking_finished = true;
5695
5696 gc_marking_enter(objspace);
5697
5698 if (heap->free_pages) {
5699 gc_report(2, objspace, "gc_marks_continue: has pooled pages");
5700
5701 marking_finished = gc_marks_step(objspace, objspace->rincgc.step_slots);
5702 }
5703 else {
5704 gc_report(2, objspace, "gc_marks_continue: no more pooled pages (stack depth: %"PRIdSIZE").\n",
5705 mark_stack_size(&objspace->mark_stack));
5706 heap->force_incremental_marking_finish_count++;
5707 gc_marks_rest(objspace);
5708 }
5709
5710 gc_marking_exit(objspace);
5711
5712 return marking_finished;
5713}
5714
5715static void
5716gc_marks_start(rb_objspace_t *objspace, int full_mark)
5717{
5718 /* start marking */
5719 gc_report(1, objspace, "gc_marks_start: (%s)\n", full_mark ? "full" : "minor");
5720 gc_mode_transition(objspace, gc_mode_marking);
5721
5722 if (full_mark) {
5723 size_t incremental_marking_steps = (objspace->rincgc.pooled_slots / INCREMENTAL_MARK_STEP_ALLOCATIONS) + 1;
5724 objspace->rincgc.step_slots = (objspace->marked_slots * 2) / incremental_marking_steps;
5725
5726 if (0) fprintf(stderr, "objspace->marked_slots: %"PRIdSIZE", "
5727 "objspace->rincgc.pooled_page_num: %"PRIdSIZE", "
5728 "objspace->rincgc.step_slots: %"PRIdSIZE", \n",
5729 objspace->marked_slots, objspace->rincgc.pooled_slots, objspace->rincgc.step_slots);
5730 objspace->flags.during_minor_gc = FALSE;
5731 if (ruby_enable_autocompact) {
5732 objspace->flags.during_compacting |= TRUE;
5733 }
5734 objspace->profile.major_gc_count++;
5735 objspace->rgengc.uncollectible_wb_unprotected_objects = 0;
5736 objspace->rgengc.old_objects = 0;
5737 objspace->rgengc.last_major_gc = objspace->profile.count;
5738 objspace->marked_slots = 0;
5739
5740 for (int i = 0; i < HEAP_COUNT; i++) {
5741 rb_heap_t *heap = &heaps[i];
5742 rgengc_mark_and_rememberset_clear(objspace, heap);
5743 heap_move_pooled_pages_to_free_pages(heap);
5744
5745 if (objspace->flags.during_compacting) {
5746 struct heap_page *page = NULL;
5747
5748 ccan_list_for_each(&heap->pages, page, page_node) {
5749 page->pinned_slots = 0;
5750 }
5751 }
5752 }
5753 }
5754 else {
5755 objspace->flags.during_minor_gc = TRUE;
5756 objspace->marked_slots =
5757 objspace->rgengc.old_objects + objspace->rgengc.uncollectible_wb_unprotected_objects; /* uncollectible objects are marked already */
5758 objspace->profile.minor_gc_count++;
5759
5760 for (int i = 0; i < HEAP_COUNT; i++) {
5761 rgengc_rememberset_mark(objspace, &heaps[i]);
5762 }
5763 }
5764
5765 mark_roots(objspace, NULL);
5766
5767 gc_report(1, objspace, "gc_marks_start: (%s) end, stack in %"PRIdSIZE"\n",
5768 full_mark ? "full" : "minor", mark_stack_size(&objspace->mark_stack));
5769}
5770
5771static bool
5772gc_marks(rb_objspace_t *objspace, int full_mark)
5773{
5774 gc_prof_mark_timer_start(objspace);
5775 gc_marking_enter(objspace);
5776
5777 bool marking_finished = false;
5778
5779 /* setup marking */
5780
5781 gc_marks_start(objspace, full_mark);
5782 if (!is_incremental_marking(objspace)) {
5783 gc_marks_rest(objspace);
5784 marking_finished = true;
5785 }
5786
5787#if RGENGC_PROFILE > 0
5788 if (gc_prof_record(objspace)) {
5789 gc_profile_record *record = gc_prof_record(objspace);
5790 record->old_objects = objspace->rgengc.old_objects;
5791 }
5792#endif
5793
5794 gc_marking_exit(objspace);
5795 gc_prof_mark_timer_stop(objspace);
5796
5797 return marking_finished;
5798}
5799
5800/* RGENGC */
5801
5802static void
5803gc_report_body(int level, rb_objspace_t *objspace, const char *fmt, ...)
5804{
5805 if (level <= RGENGC_DEBUG) {
5806 char buf[1024];
5807 FILE *out = stderr;
5808 va_list args;
5809 const char *status = " ";
5810
5811 if (during_gc) {
5812 status = is_full_marking(objspace) ? "+" : "-";
5813 }
5814 else {
5815 if (is_lazy_sweeping(objspace)) {
5816 status = "S";
5817 }
5818 if (is_incremental_marking(objspace)) {
5819 status = "M";
5820 }
5821 }
5822
5823 va_start(args, fmt);
5824 vsnprintf(buf, 1024, fmt, args);
5825 va_end(args);
5826
5827 fprintf(out, "%s|", status);
5828 fputs(buf, out);
5829 }
5830}
5831
5832/* bit operations */
5833
5834static int
5835rgengc_remembersetbits_set(rb_objspace_t *objspace, VALUE obj)
5836{
5837 struct heap_page *page = GET_HEAP_PAGE(obj);
5838 bits_t *bits = &page->remembered_bits[0];
5839
5840 if (MARKED_IN_BITMAP(bits, obj)) {
5841 return FALSE;
5842 }
5843 else {
5844 page->flags.has_remembered_objects = TRUE;
5845 MARK_IN_BITMAP(bits, obj);
5846 return TRUE;
5847 }
5848}
5849
5850/* wb, etc */
5851
5852/* return FALSE if already remembered */
5853static int
5854rgengc_remember(rb_objspace_t *objspace, VALUE obj)
5855{
5856 gc_report(6, objspace, "rgengc_remember: %s %s\n", rb_obj_info(obj),
5857 RVALUE_REMEMBERED(objspace, obj) ? "was already remembered" : "is remembered now");
5858
5859 check_rvalue_consistency(objspace, obj);
5860
5861 if (RGENGC_CHECK_MODE) {
5862 if (RVALUE_WB_UNPROTECTED(objspace, obj)) rb_bug("rgengc_remember: %s is not wb protected.", rb_obj_info(obj));
5863 }
5864
5865#if RGENGC_PROFILE > 0
5866 if (!RVALUE_REMEMBERED(objspace, obj)) {
5867 if (RVALUE_WB_UNPROTECTED(objspace, obj) == 0) {
5868 objspace->profile.total_remembered_normal_object_count++;
5869#if RGENGC_PROFILE >= 2
5870 objspace->profile.remembered_normal_object_count_types[BUILTIN_TYPE(obj)]++;
5871#endif
5872 }
5873 }
5874#endif /* RGENGC_PROFILE > 0 */
5875
5876 return rgengc_remembersetbits_set(objspace, obj);
5877}
5878
5879#ifndef PROFILE_REMEMBERSET_MARK
5880#define PROFILE_REMEMBERSET_MARK 0
5881#endif
5882
5883static inline void
5884rgengc_rememberset_mark_plane(rb_objspace_t *objspace, uintptr_t p, bits_t bitset)
5885{
5886 if (bitset) {
5887 do {
5888 if (bitset & 1) {
5889 VALUE obj = (VALUE)p;
5890 gc_report(2, objspace, "rgengc_rememberset_mark: mark %s\n", rb_obj_info(obj));
5891 GC_ASSERT(RVALUE_UNCOLLECTIBLE(objspace, obj));
5892 GC_ASSERT(RVALUE_OLD_P(objspace, obj) || RVALUE_WB_UNPROTECTED(objspace, obj));
5893
5894 gc_mark_children(objspace, obj);
5895 }
5896 p += BASE_SLOT_SIZE;
5897 bitset >>= 1;
5898 } while (bitset);
5899 }
5900}
5901
5902static void
5903rgengc_rememberset_mark(rb_objspace_t *objspace, rb_heap_t *heap)
5904{
5905 size_t j;
5906 struct heap_page *page = 0;
5907#if PROFILE_REMEMBERSET_MARK
5908 int has_old = 0, has_shady = 0, has_both = 0, skip = 0;
5909#endif
5910 gc_report(1, objspace, "rgengc_rememberset_mark: start\n");
5911
5912 ccan_list_for_each(&heap->pages, page, page_node) {
5913 if (page->flags.has_remembered_objects | page->flags.has_uncollectible_wb_unprotected_objects) {
5914 uintptr_t p = page->start;
5915 bits_t bitset, bits[HEAP_PAGE_BITMAP_LIMIT];
5916 bits_t *remembered_bits = page->remembered_bits;
5917 bits_t *uncollectible_bits = page->uncollectible_bits;
5918 bits_t *wb_unprotected_bits = page->wb_unprotected_bits;
5919#if PROFILE_REMEMBERSET_MARK
5920 if (page->flags.has_remembered_objects && page->flags.has_uncollectible_wb_unprotected_objects) has_both++;
5921 else if (page->flags.has_remembered_objects) has_old++;
5922 else if (page->flags.has_uncollectible_wb_unprotected_objects) has_shady++;
5923#endif
5924 for (j=0; j<HEAP_PAGE_BITMAP_LIMIT; j++) {
5925 bits[j] = remembered_bits[j] | (uncollectible_bits[j] & wb_unprotected_bits[j]);
5926 remembered_bits[j] = 0;
5927 }
5928 page->flags.has_remembered_objects = FALSE;
5929
5930 bitset = bits[0];
5931 bitset >>= NUM_IN_PAGE(p);
5932 rgengc_rememberset_mark_plane(objspace, p, bitset);
5933 p += (BITS_BITLENGTH - NUM_IN_PAGE(p)) * BASE_SLOT_SIZE;
5934
5935 for (j=1; j < HEAP_PAGE_BITMAP_LIMIT; j++) {
5936 bitset = bits[j];
5937 rgengc_rememberset_mark_plane(objspace, p, bitset);
5938 p += BITS_BITLENGTH * BASE_SLOT_SIZE;
5939 }
5940 }
5941#if PROFILE_REMEMBERSET_MARK
5942 else {
5943 skip++;
5944 }
5945#endif
5946 }
5947
5948#if PROFILE_REMEMBERSET_MARK
5949 fprintf(stderr, "%d\t%d\t%d\t%d\n", has_both, has_old, has_shady, skip);
5950#endif
5951 gc_report(1, objspace, "rgengc_rememberset_mark: finished\n");
5952}
5953
5954static void
5955rgengc_mark_and_rememberset_clear(rb_objspace_t *objspace, rb_heap_t *heap)
5956{
5957 struct heap_page *page = 0;
5958
5959 ccan_list_for_each(&heap->pages, page, page_node) {
5960 memset(&page->mark_bits[0], 0, HEAP_PAGE_BITMAP_SIZE);
5961 memset(&page->uncollectible_bits[0], 0, HEAP_PAGE_BITMAP_SIZE);
5962 memset(&page->marking_bits[0], 0, HEAP_PAGE_BITMAP_SIZE);
5963 memset(&page->remembered_bits[0], 0, HEAP_PAGE_BITMAP_SIZE);
5964 memset(&page->pinned_bits[0], 0, HEAP_PAGE_BITMAP_SIZE);
5965 page->flags.has_uncollectible_wb_unprotected_objects = FALSE;
5966 page->flags.has_remembered_objects = FALSE;
5967 }
5968}
5969
5970/* RGENGC: APIs */
5971
5972NOINLINE(static void gc_writebarrier_generational(VALUE a, VALUE b, rb_objspace_t *objspace));
5973
5974static void
5975gc_writebarrier_generational(VALUE a, VALUE b, rb_objspace_t *objspace)
5976{
5977 if (RGENGC_CHECK_MODE) {
5978 if (!RVALUE_OLD_P(objspace, a)) rb_bug("gc_writebarrier_generational: %s is not an old object.", rb_obj_info(a));
5979 if ( RVALUE_OLD_P(objspace, b)) rb_bug("gc_writebarrier_generational: %s is an old object.", rb_obj_info(b));
5980 if (is_incremental_marking(objspace)) rb_bug("gc_writebarrier_generational: called while incremental marking: %s -> %s", rb_obj_info(a), rb_obj_info(b));
5981 }
5982
5983 /* mark `a' and remember (default behavior) */
5984 if (!RVALUE_REMEMBERED(objspace, a)) {
5985 int lev = RB_GC_VM_LOCK_NO_BARRIER();
5986 {
5987 rgengc_remember(objspace, a);
5988 }
5989 RB_GC_VM_UNLOCK_NO_BARRIER(lev);
5990
5991 gc_report(1, objspace, "gc_writebarrier_generational: %s (remembered) -> %s\n", rb_obj_info(a), rb_obj_info(b));
5992 }
5993
5994 check_rvalue_consistency(objspace, a);
5995 check_rvalue_consistency(objspace, b);
5996}
5997
5998static void
5999gc_mark_from(rb_objspace_t *objspace, VALUE obj, VALUE parent)
6000{
6001 gc_mark_set_parent(objspace, parent);
6002 rgengc_check_relation(objspace, obj);
6003 if (gc_mark_set(objspace, obj) == FALSE) return;
6004 gc_aging(objspace, obj);
6005 gc_grey(objspace, obj);
6006}
6007
6008NOINLINE(static void gc_writebarrier_incremental(VALUE a, VALUE b, rb_objspace_t *objspace));
6009
6010static void
6011gc_writebarrier_incremental(VALUE a, VALUE b, rb_objspace_t *objspace)
6012{
6013 gc_report(2, objspace, "gc_writebarrier_incremental: [LG] %p -> %s\n", (void *)a, rb_obj_info(b));
6014
6015 if (RVALUE_BLACK_P(objspace, a)) {
6016 if (RVALUE_WHITE_P(objspace, b)) {
6017 if (!RVALUE_WB_UNPROTECTED(objspace, a)) {
6018 gc_report(2, objspace, "gc_writebarrier_incremental: [IN] %p -> %s\n", (void *)a, rb_obj_info(b));
6019 gc_mark_from(objspace, b, a);
6020 }
6021 }
6022 else if (RVALUE_OLD_P(objspace, a) && !RVALUE_OLD_P(objspace, b)) {
6023 rgengc_remember(objspace, a);
6024 }
6025
6026 if (RB_UNLIKELY(objspace->flags.during_compacting)) {
6027 MARK_IN_BITMAP(GET_HEAP_PINNED_BITS(b), b);
6028 }
6029 }
6030}
6031
6032void
6033rb_gc_impl_writebarrier(void *objspace_ptr, VALUE a, VALUE b)
6034{
6035 rb_objspace_t *objspace = objspace_ptr;
6036
6037 if (RGENGC_CHECK_MODE) {
6038 if (SPECIAL_CONST_P(a)) rb_bug("rb_gc_writebarrier: a is special const: %"PRIxVALUE, a);
6039 }
6040
6041 if (SPECIAL_CONST_P(b)) return;
6042
6043 GC_ASSERT(RB_BUILTIN_TYPE(a) != T_NONE);
6044 GC_ASSERT(RB_BUILTIN_TYPE(a) != T_MOVED);
6045 GC_ASSERT(RB_BUILTIN_TYPE(a) != T_ZOMBIE);
6046 GC_ASSERT(RB_BUILTIN_TYPE(b) != T_NONE);
6047 GC_ASSERT(RB_BUILTIN_TYPE(b) != T_MOVED);
6048 GC_ASSERT(RB_BUILTIN_TYPE(b) != T_ZOMBIE);
6049
6050 retry:
6051 if (!is_incremental_marking(objspace)) {
6052 if (!RVALUE_OLD_P(objspace, a) || RVALUE_OLD_P(objspace, b)) {
6053 // do nothing
6054 }
6055 else {
6056 gc_writebarrier_generational(a, b, objspace);
6057 }
6058 }
6059 else {
6060 bool retry = false;
6061 /* slow path */
6062 int lev = RB_GC_VM_LOCK_NO_BARRIER();
6063 {
6064 if (is_incremental_marking(objspace)) {
6065 gc_writebarrier_incremental(a, b, objspace);
6066 }
6067 else {
6068 retry = true;
6069 }
6070 }
6071 RB_GC_VM_UNLOCK_NO_BARRIER(lev);
6072
6073 if (retry) goto retry;
6074 }
6075 return;
6076}
6077
6078void
6079rb_gc_impl_writebarrier_unprotect(void *objspace_ptr, VALUE obj)
6080{
6081 rb_objspace_t *objspace = objspace_ptr;
6082
6083 if (RVALUE_WB_UNPROTECTED(objspace, obj)) {
6084 return;
6085 }
6086 else {
6087 gc_report(2, objspace, "rb_gc_writebarrier_unprotect: %s %s\n", rb_obj_info(obj),
6088 RVALUE_REMEMBERED(objspace, obj) ? " (already remembered)" : "");
6089
6090 unsigned int lev = RB_GC_VM_LOCK_NO_BARRIER();
6091 {
6092 if (RVALUE_OLD_P(objspace, obj)) {
6093 gc_report(1, objspace, "rb_gc_writebarrier_unprotect: %s\n", rb_obj_info(obj));
6094 RVALUE_DEMOTE(objspace, obj);
6095 gc_mark_set(objspace, obj);
6096 gc_remember_unprotected(objspace, obj);
6097
6098#if RGENGC_PROFILE
6099 objspace->profile.total_shade_operation_count++;
6100#if RGENGC_PROFILE >= 2
6101 objspace->profile.shade_operation_count_types[BUILTIN_TYPE(obj)]++;
6102#endif /* RGENGC_PROFILE >= 2 */
6103#endif /* RGENGC_PROFILE */
6104 }
6105 else {
6106 RVALUE_AGE_RESET(obj);
6107 }
6108
6109 RB_DEBUG_COUNTER_INC(obj_wb_unprotect);
6110 MARK_IN_BITMAP(GET_HEAP_WB_UNPROTECTED_BITS(obj), obj);
6111 }
6112 RB_GC_VM_UNLOCK_NO_BARRIER(lev);
6113 }
6114}
6115
6116void
6117rb_gc_impl_copy_attributes(void *objspace_ptr, VALUE dest, VALUE obj)
6118{
6119 rb_objspace_t *objspace = objspace_ptr;
6120
6121 if (RVALUE_WB_UNPROTECTED(objspace, obj)) {
6122 rb_gc_impl_writebarrier_unprotect(objspace, dest);
6123 }
6124 rb_gc_impl_copy_finalizer(objspace, dest, obj);
6125}
6126
6127const char *
6128rb_gc_impl_active_gc_name(void)
6129{
6130 return "default";
6131}
6132
6133void
6134rb_gc_impl_writebarrier_remember(void *objspace_ptr, VALUE obj)
6135{
6136 rb_objspace_t *objspace = objspace_ptr;
6137
6138 gc_report(1, objspace, "rb_gc_writebarrier_remember: %s\n", rb_obj_info(obj));
6139
6140 if (is_incremental_marking(objspace) || RVALUE_OLD_P(objspace, obj)) {
6141 int lev = RB_GC_VM_LOCK_NO_BARRIER();
6142 {
6143 if (is_incremental_marking(objspace)) {
6144 if (RVALUE_BLACK_P(objspace, obj)) {
6145 gc_grey(objspace, obj);
6146 }
6147 }
6148 else if (RVALUE_OLD_P(objspace, obj)) {
6149 rgengc_remember(objspace, obj);
6150 }
6151 }
6152 RB_GC_VM_UNLOCK_NO_BARRIER(lev);
6153 }
6154}
6155
6157 // Must be ID only
6158 ID ID_wb_protected, ID_age, ID_old, ID_uncollectible, ID_marking,
6159 ID_marked, ID_pinned, ID_object_id, ID_shareable;
6160};
6161
6162#define RB_GC_OBJECT_METADATA_ENTRY_COUNT (sizeof(struct rb_gc_object_metadata_names) / sizeof(ID))
6163static struct rb_gc_object_metadata_entry object_metadata_entries[RB_GC_OBJECT_METADATA_ENTRY_COUNT + 1];
6164
6166rb_gc_impl_object_metadata(void *objspace_ptr, VALUE obj)
6167{
6168 rb_objspace_t *objspace = objspace_ptr;
6169 size_t n = 0;
6170 static struct rb_gc_object_metadata_names names;
6171
6172 if (!names.ID_marked) {
6173#define I(s) names.ID_##s = rb_intern(#s)
6174 I(wb_protected);
6175 I(age);
6176 I(old);
6177 I(uncollectible);
6178 I(marking);
6179 I(marked);
6180 I(pinned);
6181 I(object_id);
6182 I(shareable);
6183#undef I
6184 }
6185
6186#define SET_ENTRY(na, v) do { \
6187 GC_ASSERT(n <= RB_GC_OBJECT_METADATA_ENTRY_COUNT); \
6188 object_metadata_entries[n].name = names.ID_##na; \
6189 object_metadata_entries[n].val = v; \
6190 n++; \
6191} while (0)
6192
6193 if (!RVALUE_WB_UNPROTECTED(objspace, obj)) SET_ENTRY(wb_protected, Qtrue);
6194 SET_ENTRY(age, INT2FIX(RVALUE_AGE_GET(obj)));
6195 if (RVALUE_OLD_P(objspace, obj)) SET_ENTRY(old, Qtrue);
6196 if (RVALUE_UNCOLLECTIBLE(objspace, obj)) SET_ENTRY(uncollectible, Qtrue);
6197 if (RVALUE_MARKING(objspace, obj)) SET_ENTRY(marking, Qtrue);
6198 if (RVALUE_MARKED(objspace, obj)) SET_ENTRY(marked, Qtrue);
6199 if (RVALUE_PINNED(objspace, obj)) SET_ENTRY(pinned, Qtrue);
6200 if (rb_obj_id_p(obj)) SET_ENTRY(object_id, rb_obj_id(obj));
6201 if (FL_TEST(obj, FL_SHAREABLE)) SET_ENTRY(shareable, Qtrue);
6202
6203 object_metadata_entries[n].name = 0;
6204 object_metadata_entries[n].val = 0;
6205#undef SET_ENTRY
6206
6207 return object_metadata_entries;
6208}
6209
6210void *
6211rb_gc_impl_ractor_cache_alloc(void *objspace_ptr, void *ractor)
6212{
6213 rb_objspace_t *objspace = objspace_ptr;
6214
6215 objspace->live_ractor_cache_count++;
6216
6217 return calloc1(sizeof(rb_ractor_newobj_cache_t));
6218}
6219
6220void
6221rb_gc_impl_ractor_cache_free(void *objspace_ptr, void *cache)
6222{
6223 rb_objspace_t *objspace = objspace_ptr;
6224
6225 objspace->live_ractor_cache_count--;
6226 gc_ractor_newobj_cache_clear(cache, NULL);
6227 free(cache);
6228}
6229
6230static void
6231heap_ready_to_gc(rb_objspace_t *objspace, rb_heap_t *heap)
6232{
6233 if (!heap->free_pages) {
6234 if (!heap_page_allocate_and_initialize(objspace, heap)) {
6235 objspace->heap_pages.allocatable_slots = 1;
6236 heap_page_allocate_and_initialize(objspace, heap);
6237 }
6238 }
6239}
6240
6241static int
6242ready_to_gc(rb_objspace_t *objspace)
6243{
6244 if (dont_gc_val() || during_gc) {
6245 for (int i = 0; i < HEAP_COUNT; i++) {
6246 rb_heap_t *heap = &heaps[i];
6247 heap_ready_to_gc(objspace, heap);
6248 }
6249 return FALSE;
6250 }
6251 else {
6252 return TRUE;
6253 }
6254}
6255
6256static void
6257gc_reset_malloc_info(rb_objspace_t *objspace, bool full_mark)
6258{
6259 gc_prof_set_malloc_info(objspace);
6260 {
6261 size_t inc = RUBY_ATOMIC_SIZE_EXCHANGE(malloc_increase, 0);
6262 size_t old_limit = malloc_limit;
6263
6264 if (inc > malloc_limit) {
6265 malloc_limit = (size_t)(inc * gc_params.malloc_limit_growth_factor);
6266 if (malloc_limit > gc_params.malloc_limit_max) {
6267 malloc_limit = gc_params.malloc_limit_max;
6268 }
6269 }
6270 else {
6271 malloc_limit = (size_t)(malloc_limit * 0.98); /* magic number */
6272 if (malloc_limit < gc_params.malloc_limit_min) {
6273 malloc_limit = gc_params.malloc_limit_min;
6274 }
6275 }
6276
6277 if (0) {
6278 if (old_limit != malloc_limit) {
6279 fprintf(stderr, "[%"PRIuSIZE"] malloc_limit: %"PRIuSIZE" -> %"PRIuSIZE"\n",
6280 rb_gc_count(), old_limit, malloc_limit);
6281 }
6282 else {
6283 fprintf(stderr, "[%"PRIuSIZE"] malloc_limit: not changed (%"PRIuSIZE")\n",
6284 rb_gc_count(), malloc_limit);
6285 }
6286 }
6287 }
6288
6289 /* reset oldmalloc info */
6290#if RGENGC_ESTIMATE_OLDMALLOC
6291 if (!full_mark) {
6292 if (objspace->rgengc.oldmalloc_increase > objspace->rgengc.oldmalloc_increase_limit) {
6293 gc_needs_major_flags |= GPR_FLAG_MAJOR_BY_OLDMALLOC;
6294 objspace->rgengc.oldmalloc_increase_limit =
6295 (size_t)(objspace->rgengc.oldmalloc_increase_limit * gc_params.oldmalloc_limit_growth_factor);
6296
6297 if (objspace->rgengc.oldmalloc_increase_limit > gc_params.oldmalloc_limit_max) {
6298 objspace->rgengc.oldmalloc_increase_limit = gc_params.oldmalloc_limit_max;
6299 }
6300 }
6301
6302 if (0) fprintf(stderr, "%"PRIdSIZE"\t%d\t%"PRIuSIZE"\t%"PRIuSIZE"\t%"PRIdSIZE"\n",
6303 rb_gc_count(),
6304 gc_needs_major_flags,
6305 objspace->rgengc.oldmalloc_increase,
6306 objspace->rgengc.oldmalloc_increase_limit,
6307 gc_params.oldmalloc_limit_max);
6308 }
6309 else {
6310 /* major GC */
6311 objspace->rgengc.oldmalloc_increase = 0;
6312
6313 if ((objspace->profile.latest_gc_info & GPR_FLAG_MAJOR_BY_OLDMALLOC) == 0) {
6314 objspace->rgengc.oldmalloc_increase_limit =
6315 (size_t)(objspace->rgengc.oldmalloc_increase_limit / ((gc_params.oldmalloc_limit_growth_factor - 1)/10 + 1));
6316 if (objspace->rgengc.oldmalloc_increase_limit < gc_params.oldmalloc_limit_min) {
6317 objspace->rgengc.oldmalloc_increase_limit = gc_params.oldmalloc_limit_min;
6318 }
6319 }
6320 }
6321#endif
6322}
6323
6324static int
6325garbage_collect(rb_objspace_t *objspace, unsigned int reason)
6326{
6327 int ret;
6328
6329 int lev = RB_GC_VM_LOCK();
6330 {
6331#if GC_PROFILE_MORE_DETAIL
6332 objspace->profile.prepare_time = getrusage_time();
6333#endif
6334
6335 gc_rest(objspace);
6336
6337#if GC_PROFILE_MORE_DETAIL
6338 objspace->profile.prepare_time = getrusage_time() - objspace->profile.prepare_time;
6339#endif
6340
6341 ret = gc_start(objspace, reason);
6342 }
6343 RB_GC_VM_UNLOCK(lev);
6344
6345 return ret;
6346}
6347
6348static int
6349gc_start(rb_objspace_t *objspace, unsigned int reason)
6350{
6351 unsigned int do_full_mark = !!(reason & GPR_FLAG_FULL_MARK);
6352
6353 if (!rb_darray_size(objspace->heap_pages.sorted)) return TRUE; /* heap is not ready */
6354 if (!(reason & GPR_FLAG_METHOD) && !ready_to_gc(objspace)) return TRUE; /* GC is not allowed */
6355
6356 GC_ASSERT(gc_mode(objspace) == gc_mode_none, "gc_mode is %s\n", gc_mode_name(gc_mode(objspace)));
6357 GC_ASSERT(!is_lazy_sweeping(objspace));
6358 GC_ASSERT(!is_incremental_marking(objspace));
6359
6360 unsigned int lock_lev;
6361 gc_enter(objspace, gc_enter_event_start, &lock_lev);
6362
6363 /* reason may be clobbered, later, so keep set immediate_sweep here */
6364 objspace->flags.immediate_sweep = !!(reason & GPR_FLAG_IMMEDIATE_SWEEP);
6365
6366#if RGENGC_CHECK_MODE >= 2
6367 gc_verify_internal_consistency(objspace);
6368#endif
6369
6370 if (ruby_gc_stressful) {
6371 int flag = FIXNUM_P(ruby_gc_stress_mode) ? FIX2INT(ruby_gc_stress_mode) : 0;
6372
6373 if ((flag & (1 << gc_stress_no_major)) == 0) {
6374 do_full_mark = TRUE;
6375 }
6376
6377 objspace->flags.immediate_sweep = !(flag & (1<<gc_stress_no_immediate_sweep));
6378 }
6379
6380 if (gc_needs_major_flags) {
6381 reason |= gc_needs_major_flags;
6382 do_full_mark = TRUE;
6383 }
6384
6385 /* if major gc has been disabled, never do a full mark */
6386 if (!gc_config_full_mark_val) {
6387 do_full_mark = FALSE;
6388 }
6389 gc_needs_major_flags = GPR_FLAG_NONE;
6390
6391 if (do_full_mark && (reason & GPR_FLAG_MAJOR_MASK) == 0) {
6392 reason |= GPR_FLAG_MAJOR_BY_FORCE; /* GC by CAPI, METHOD, and so on. */
6393 }
6394
6395 if (objspace->flags.dont_incremental ||
6396 reason & GPR_FLAG_IMMEDIATE_MARK ||
6397 ruby_gc_stressful) {
6398 objspace->flags.during_incremental_marking = FALSE;
6399 }
6400 else {
6401 objspace->flags.during_incremental_marking = do_full_mark;
6402 }
6403
6404 /* Explicitly enable compaction (GC.compact) */
6405 if (do_full_mark && ruby_enable_autocompact) {
6406 objspace->flags.during_compacting = TRUE;
6407#if RGENGC_CHECK_MODE
6408 objspace->rcompactor.compare_func = ruby_autocompact_compare_func;
6409#endif
6410 }
6411 else {
6412 objspace->flags.during_compacting = !!(reason & GPR_FLAG_COMPACT);
6413 }
6414
6415 if (!GC_ENABLE_LAZY_SWEEP || objspace->flags.dont_incremental) {
6416 objspace->flags.immediate_sweep = TRUE;
6417 }
6418
6419 if (objspace->flags.immediate_sweep) reason |= GPR_FLAG_IMMEDIATE_SWEEP;
6420
6421 gc_report(1, objspace, "gc_start(reason: %x) => %u, %d, %d\n",
6422 reason,
6423 do_full_mark, !is_incremental_marking(objspace), objspace->flags.immediate_sweep);
6424
6425 RB_DEBUG_COUNTER_INC(gc_count);
6426
6427 if (reason & GPR_FLAG_MAJOR_MASK) {
6428 (void)RB_DEBUG_COUNTER_INC_IF(gc_major_nofree, reason & GPR_FLAG_MAJOR_BY_NOFREE);
6429 (void)RB_DEBUG_COUNTER_INC_IF(gc_major_oldgen, reason & GPR_FLAG_MAJOR_BY_OLDGEN);
6430 (void)RB_DEBUG_COUNTER_INC_IF(gc_major_shady, reason & GPR_FLAG_MAJOR_BY_SHADY);
6431 (void)RB_DEBUG_COUNTER_INC_IF(gc_major_force, reason & GPR_FLAG_MAJOR_BY_FORCE);
6432#if RGENGC_ESTIMATE_OLDMALLOC
6433 (void)RB_DEBUG_COUNTER_INC_IF(gc_major_oldmalloc, reason & GPR_FLAG_MAJOR_BY_OLDMALLOC);
6434#endif
6435 }
6436 else {
6437 (void)RB_DEBUG_COUNTER_INC_IF(gc_minor_newobj, reason & GPR_FLAG_NEWOBJ);
6438 (void)RB_DEBUG_COUNTER_INC_IF(gc_minor_malloc, reason & GPR_FLAG_MALLOC);
6439 (void)RB_DEBUG_COUNTER_INC_IF(gc_minor_method, reason & GPR_FLAG_METHOD);
6440 (void)RB_DEBUG_COUNTER_INC_IF(gc_minor_capi, reason & GPR_FLAG_CAPI);
6441 (void)RB_DEBUG_COUNTER_INC_IF(gc_minor_stress, reason & GPR_FLAG_STRESS);
6442 }
6443
6444 objspace->profile.count++;
6445 objspace->profile.latest_gc_info = reason;
6446 objspace->profile.total_allocated_objects_at_gc_start = total_allocated_objects(objspace);
6447 objspace->profile.heap_used_at_gc_start = rb_darray_size(objspace->heap_pages.sorted);
6448 objspace->profile.weak_references_count = 0;
6449 objspace->profile.retained_weak_references_count = 0;
6450 gc_prof_setup_new_record(objspace, reason);
6451 gc_reset_malloc_info(objspace, do_full_mark);
6452
6453 rb_gc_event_hook(0, RUBY_INTERNAL_EVENT_GC_START);
6454
6455 GC_ASSERT(during_gc);
6456
6457 gc_prof_timer_start(objspace);
6458 {
6459 if (gc_marks(objspace, do_full_mark)) {
6460 gc_sweep(objspace);
6461 }
6462 }
6463 gc_prof_timer_stop(objspace);
6464
6465 gc_exit(objspace, gc_enter_event_start, &lock_lev);
6466 return TRUE;
6467}
6468
6469static void
6470gc_rest(rb_objspace_t *objspace)
6471{
6472 if (is_incremental_marking(objspace) || is_lazy_sweeping(objspace)) {
6473 unsigned int lock_lev;
6474 gc_enter(objspace, gc_enter_event_rest, &lock_lev);
6475
6476 if (RGENGC_CHECK_MODE >= 2) gc_verify_internal_consistency(objspace);
6477
6478 if (is_incremental_marking(objspace)) {
6479 gc_marking_enter(objspace);
6480 gc_marks_rest(objspace);
6481 gc_marking_exit(objspace);
6482
6483 gc_sweep(objspace);
6484 }
6485
6486 if (is_lazy_sweeping(objspace)) {
6487 gc_sweeping_enter(objspace);
6488 gc_sweep_rest(objspace);
6489 gc_sweeping_exit(objspace);
6490 }
6491
6492 gc_exit(objspace, gc_enter_event_rest, &lock_lev);
6493 }
6494}
6495
6498 unsigned int reason;
6499};
6500
6501static void
6502gc_current_status_fill(rb_objspace_t *objspace, char *buff)
6503{
6504 int i = 0;
6505 if (is_marking(objspace)) {
6506 buff[i++] = 'M';
6507 if (is_full_marking(objspace)) buff[i++] = 'F';
6508 if (is_incremental_marking(objspace)) buff[i++] = 'I';
6509 }
6510 else if (is_sweeping(objspace)) {
6511 buff[i++] = 'S';
6512 if (is_lazy_sweeping(objspace)) buff[i++] = 'L';
6513 }
6514 else {
6515 buff[i++] = 'N';
6516 }
6517 buff[i] = '\0';
6518}
6519
6520static const char *
6521gc_current_status(rb_objspace_t *objspace)
6522{
6523 static char buff[0x10];
6524 gc_current_status_fill(objspace, buff);
6525 return buff;
6526}
6527
6528#if PRINT_ENTER_EXIT_TICK
6529
6530static tick_t last_exit_tick;
6531static tick_t enter_tick;
6532static int enter_count = 0;
6533static char last_gc_status[0x10];
6534
6535static inline void
6536gc_record(rb_objspace_t *objspace, int direction, const char *event)
6537{
6538 if (direction == 0) { /* enter */
6539 enter_count++;
6540 enter_tick = tick();
6541 gc_current_status_fill(objspace, last_gc_status);
6542 }
6543 else { /* exit */
6544 tick_t exit_tick = tick();
6545 char current_gc_status[0x10];
6546 gc_current_status_fill(objspace, current_gc_status);
6547#if 1
6548 /* [last mutator time] [gc time] [event] */
6549 fprintf(stderr, "%"PRItick"\t%"PRItick"\t%s\t[%s->%s|%c]\n",
6550 enter_tick - last_exit_tick,
6551 exit_tick - enter_tick,
6552 event,
6553 last_gc_status, current_gc_status,
6554 (objspace->profile.latest_gc_info & GPR_FLAG_MAJOR_MASK) ? '+' : '-');
6555 last_exit_tick = exit_tick;
6556#else
6557 /* [enter_tick] [gc time] [event] */
6558 fprintf(stderr, "%"PRItick"\t%"PRItick"\t%s\t[%s->%s|%c]\n",
6559 enter_tick,
6560 exit_tick - enter_tick,
6561 event,
6562 last_gc_status, current_gc_status,
6563 (objspace->profile.latest_gc_info & GPR_FLAG_MAJOR_MASK) ? '+' : '-');
6564#endif
6565 }
6566}
6567#else /* PRINT_ENTER_EXIT_TICK */
6568static inline void
6569gc_record(rb_objspace_t *objspace, int direction, const char *event)
6570{
6571 /* null */
6572}
6573#endif /* PRINT_ENTER_EXIT_TICK */
6574
6575static const char *
6576gc_enter_event_cstr(enum gc_enter_event event)
6577{
6578 switch (event) {
6579 case gc_enter_event_start: return "start";
6580 case gc_enter_event_continue: return "continue";
6581 case gc_enter_event_rest: return "rest";
6582 case gc_enter_event_finalizer: return "finalizer";
6583 }
6584 return NULL;
6585}
6586
6587static void
6588gc_enter_count(enum gc_enter_event event)
6589{
6590 switch (event) {
6591 case gc_enter_event_start: RB_DEBUG_COUNTER_INC(gc_enter_start); break;
6592 case gc_enter_event_continue: RB_DEBUG_COUNTER_INC(gc_enter_continue); break;
6593 case gc_enter_event_rest: RB_DEBUG_COUNTER_INC(gc_enter_rest); break;
6594 case gc_enter_event_finalizer: RB_DEBUG_COUNTER_INC(gc_enter_finalizer); break;
6595 }
6596}
6597
6598static bool current_process_time(struct timespec *ts);
6599
6600static void
6601gc_clock_start(struct timespec *ts)
6602{
6603 if (!current_process_time(ts)) {
6604 ts->tv_sec = 0;
6605 ts->tv_nsec = 0;
6606 }
6607}
6608
6609static unsigned long long
6610gc_clock_end(struct timespec *ts)
6611{
6612 struct timespec end_time;
6613
6614 if ((ts->tv_sec > 0 || ts->tv_nsec > 0) &&
6615 current_process_time(&end_time) &&
6616 end_time.tv_sec >= ts->tv_sec) {
6617 return (unsigned long long)(end_time.tv_sec - ts->tv_sec) * (1000 * 1000 * 1000) +
6618 (end_time.tv_nsec - ts->tv_nsec);
6619 }
6620
6621 return 0;
6622}
6623
6624static inline void
6625gc_enter(rb_objspace_t *objspace, enum gc_enter_event event, unsigned int *lock_lev)
6626{
6627 *lock_lev = RB_GC_VM_LOCK();
6628
6629 switch (event) {
6630 case gc_enter_event_rest:
6631 if (!is_marking(objspace)) break;
6632 // fall through
6633 case gc_enter_event_start:
6634 case gc_enter_event_continue:
6635 // stop other ractors
6636 rb_gc_vm_barrier();
6637 break;
6638 default:
6639 break;
6640 }
6641
6642 gc_enter_count(event);
6643 if (RB_UNLIKELY(during_gc != 0)) rb_bug("during_gc != 0");
6644 if (RGENGC_CHECK_MODE >= 3) gc_verify_internal_consistency(objspace);
6645
6646 during_gc = TRUE;
6647 RUBY_DEBUG_LOG("%s (%s)",gc_enter_event_cstr(event), gc_current_status(objspace));
6648 gc_report(1, objspace, "gc_enter: %s [%s]\n", gc_enter_event_cstr(event), gc_current_status(objspace));
6649 gc_record(objspace, 0, gc_enter_event_cstr(event));
6650
6651 rb_gc_event_hook(0, RUBY_INTERNAL_EVENT_GC_ENTER);
6652}
6653
6654static inline void
6655gc_exit(rb_objspace_t *objspace, enum gc_enter_event event, unsigned int *lock_lev)
6656{
6657 GC_ASSERT(during_gc != 0);
6658
6659 rb_gc_event_hook(0, RUBY_INTERNAL_EVENT_GC_EXIT);
6660
6661 gc_record(objspace, 1, gc_enter_event_cstr(event));
6662 RUBY_DEBUG_LOG("%s (%s)", gc_enter_event_cstr(event), gc_current_status(objspace));
6663 gc_report(1, objspace, "gc_exit: %s [%s]\n", gc_enter_event_cstr(event), gc_current_status(objspace));
6664 during_gc = FALSE;
6665
6666 RB_GC_VM_UNLOCK(*lock_lev);
6667}
6668
6669#ifndef MEASURE_GC
6670#define MEASURE_GC (objspace->flags.measure_gc)
6671#endif
6672
6673static void
6674gc_marking_enter(rb_objspace_t *objspace)
6675{
6676 GC_ASSERT(during_gc != 0);
6677
6678 if (MEASURE_GC) {
6679 gc_clock_start(&objspace->profile.marking_start_time);
6680 }
6681}
6682
6683static void
6684gc_marking_exit(rb_objspace_t *objspace)
6685{
6686 GC_ASSERT(during_gc != 0);
6687
6688 if (MEASURE_GC) {
6689 objspace->profile.marking_time_ns += gc_clock_end(&objspace->profile.marking_start_time);
6690 }
6691}
6692
6693static void
6694gc_sweeping_enter(rb_objspace_t *objspace)
6695{
6696 GC_ASSERT(during_gc != 0);
6697
6698 if (MEASURE_GC) {
6699 gc_clock_start(&objspace->profile.sweeping_start_time);
6700 }
6701}
6702
6703static void
6704gc_sweeping_exit(rb_objspace_t *objspace)
6705{
6706 GC_ASSERT(during_gc != 0);
6707
6708 if (MEASURE_GC) {
6709 objspace->profile.sweeping_time_ns += gc_clock_end(&objspace->profile.sweeping_start_time);
6710 }
6711}
6712
6713static void *
6714gc_with_gvl(void *ptr)
6715{
6716 struct objspace_and_reason *oar = (struct objspace_and_reason *)ptr;
6717 return (void *)(VALUE)garbage_collect(oar->objspace, oar->reason);
6718}
6719
6720int ruby_thread_has_gvl_p(void);
6721
6722static int
6723garbage_collect_with_gvl(rb_objspace_t *objspace, unsigned int reason)
6724{
6725 if (dont_gc_val()) {
6726 return TRUE;
6727 }
6728 else if (!ruby_native_thread_p()) {
6729 return TRUE;
6730 }
6731 else if (!ruby_thread_has_gvl_p()) {
6732 void *ret;
6733 struct objspace_and_reason oar;
6734 oar.objspace = objspace;
6735 oar.reason = reason;
6736 ret = rb_thread_call_with_gvl(gc_with_gvl, (void *)&oar);
6737
6738 return !!ret;
6739 }
6740 else {
6741 return garbage_collect(objspace, reason);
6742 }
6743}
6744
6745static int
6746gc_set_candidate_object_i(void *vstart, void *vend, size_t stride, void *data)
6747{
6749
6750 VALUE v = (VALUE)vstart;
6751 for (; v != (VALUE)vend; v += stride) {
6752 asan_unpoisoning_object(v) {
6753 switch (BUILTIN_TYPE(v)) {
6754 case T_NONE:
6755 case T_ZOMBIE:
6756 break;
6757 default:
6758 rb_gc_prepare_heap_process_object(v);
6759 if (!RVALUE_OLD_P(objspace, v) && !RVALUE_WB_UNPROTECTED(objspace, v)) {
6760 RVALUE_AGE_SET_CANDIDATE(objspace, v);
6761 }
6762 }
6763 }
6764 }
6765
6766 return 0;
6767}
6768
6769void
6770rb_gc_impl_start(void *objspace_ptr, bool full_mark, bool immediate_mark, bool immediate_sweep, bool compact)
6771{
6772 rb_objspace_t *objspace = objspace_ptr;
6773 unsigned int reason = (GPR_FLAG_FULL_MARK |
6774 GPR_FLAG_IMMEDIATE_MARK |
6775 GPR_FLAG_IMMEDIATE_SWEEP |
6776 GPR_FLAG_METHOD);
6777
6778 int full_marking_p = gc_config_full_mark_val;
6779 gc_config_full_mark_set(TRUE);
6780
6781 /* For now, compact implies full mark / sweep, so ignore other flags */
6782 if (compact) {
6783 GC_ASSERT(GC_COMPACTION_SUPPORTED);
6784
6785 reason |= GPR_FLAG_COMPACT;
6786 }
6787 else {
6788 if (!full_mark) reason &= ~GPR_FLAG_FULL_MARK;
6789 if (!immediate_mark) reason &= ~GPR_FLAG_IMMEDIATE_MARK;
6790 if (!immediate_sweep) reason &= ~GPR_FLAG_IMMEDIATE_SWEEP;
6791 }
6792
6793 garbage_collect(objspace, reason);
6794 gc_finalize_deferred(objspace);
6795
6796 gc_config_full_mark_set(full_marking_p);
6797}
6798
6799void
6800rb_gc_impl_prepare_heap(void *objspace_ptr)
6801{
6802 rb_objspace_t *objspace = objspace_ptr;
6803
6804 size_t orig_total_slots = objspace_available_slots(objspace);
6805 size_t orig_allocatable_slots = objspace->heap_pages.allocatable_slots;
6806
6807 rb_gc_impl_each_objects(objspace, gc_set_candidate_object_i, objspace_ptr);
6808
6809 double orig_max_free_slots = gc_params.heap_free_slots_max_ratio;
6810 /* Ensure that all empty pages are moved onto empty_pages. */
6811 gc_params.heap_free_slots_max_ratio = 0.0;
6812 rb_gc_impl_start(objspace, true, true, true, true);
6813 gc_params.heap_free_slots_max_ratio = orig_max_free_slots;
6814
6815 objspace->heap_pages.allocatable_slots = 0;
6816 heap_pages_freeable_pages = objspace->empty_pages_count;
6817 heap_pages_free_unused_pages(objspace_ptr);
6818 GC_ASSERT(heap_pages_freeable_pages == 0);
6819 GC_ASSERT(objspace->empty_pages_count == 0);
6820 objspace->heap_pages.allocatable_slots = orig_allocatable_slots;
6821
6822 size_t total_slots = objspace_available_slots(objspace);
6823 if (orig_total_slots > total_slots) {
6824 objspace->heap_pages.allocatable_slots += orig_total_slots - total_slots;
6825 }
6826
6827#if defined(HAVE_MALLOC_TRIM) && !defined(RUBY_ALTERNATIVE_MALLOC_HEADER)
6828 malloc_trim(0);
6829#endif
6830}
6831
6832static int
6833gc_is_moveable_obj(rb_objspace_t *objspace, VALUE obj)
6834{
6835 GC_ASSERT(!SPECIAL_CONST_P(obj));
6836
6837 switch (BUILTIN_TYPE(obj)) {
6838 case T_NONE:
6839 case T_MOVED:
6840 case T_ZOMBIE:
6841 return FALSE;
6842 case T_SYMBOL:
6843 // TODO: restore original behavior
6844 // if (RSYMBOL(obj)->id & ~ID_SCOPE_MASK) {
6845 // return FALSE;
6846 // }
6847 return false;
6848 /* fall through */
6849 case T_STRING:
6850 case T_OBJECT:
6851 case T_FLOAT:
6852 case T_IMEMO:
6853 case T_ARRAY:
6854 case T_BIGNUM:
6855 case T_ICLASS:
6856 case T_MODULE:
6857 case T_REGEXP:
6858 case T_DATA:
6859 case T_MATCH:
6860 case T_STRUCT:
6861 case T_HASH:
6862 case T_FILE:
6863 case T_COMPLEX:
6864 case T_RATIONAL:
6865 case T_NODE:
6866 case T_CLASS:
6867 if (FL_TEST_RAW(obj, FL_FINALIZE)) {
6868 /* The finalizer table is a numtable. It looks up objects by address.
6869 * We can't mark the keys in the finalizer table because that would
6870 * prevent the objects from being collected. This check prevents
6871 * objects that are keys in the finalizer table from being moved
6872 * without directly pinning them. */
6873 GC_ASSERT(st_is_member(finalizer_table, obj));
6874
6875 return FALSE;
6876 }
6877 GC_ASSERT(RVALUE_MARKED(objspace, obj));
6878 GC_ASSERT(!RVALUE_PINNED(objspace, obj));
6879
6880 return TRUE;
6881
6882 default:
6883 rb_bug("gc_is_moveable_obj: unreachable (%d)", (int)BUILTIN_TYPE(obj));
6884 break;
6885 }
6886
6887 return FALSE;
6888}
6889
6890void rb_mv_generic_ivar(VALUE src, VALUE dst);
6891
6892static VALUE
6893gc_move(rb_objspace_t *objspace, VALUE src, VALUE dest, size_t src_slot_size, size_t slot_size)
6894{
6895 int marked;
6896 int wb_unprotected;
6897 int uncollectible;
6898 int age;
6899
6900 gc_report(4, objspace, "Moving object: %p -> %p\n", (void *)src, (void *)dest);
6901
6902 GC_ASSERT(BUILTIN_TYPE(src) != T_NONE);
6903 GC_ASSERT(!MARKED_IN_BITMAP(GET_HEAP_MARK_BITS(dest), dest));
6904
6905 GC_ASSERT(!RVALUE_MARKING(objspace, src));
6906
6907 /* Save off bits for current object. */
6908 marked = RVALUE_MARKED(objspace, src);
6909 wb_unprotected = RVALUE_WB_UNPROTECTED(objspace, src);
6910 uncollectible = RVALUE_UNCOLLECTIBLE(objspace, src);
6911 bool remembered = RVALUE_REMEMBERED(objspace, src);
6912 age = RVALUE_AGE_GET(src);
6913
6914 /* Clear bits for eventual T_MOVED */
6915 CLEAR_IN_BITMAP(GET_HEAP_MARK_BITS(src), src);
6916 CLEAR_IN_BITMAP(GET_HEAP_WB_UNPROTECTED_BITS(src), src);
6917 CLEAR_IN_BITMAP(GET_HEAP_UNCOLLECTIBLE_BITS(src), src);
6918 CLEAR_IN_BITMAP(GET_HEAP_PAGE(src)->remembered_bits, src);
6919
6920 /* Move the object */
6921 memcpy((void *)dest, (void *)src, MIN(src_slot_size, slot_size));
6922
6923 if (RVALUE_OVERHEAD > 0) {
6924 void *dest_overhead = (void *)(((uintptr_t)dest) + slot_size - RVALUE_OVERHEAD);
6925 void *src_overhead = (void *)(((uintptr_t)src) + src_slot_size - RVALUE_OVERHEAD);
6926
6927 memcpy(dest_overhead, src_overhead, RVALUE_OVERHEAD);
6928 }
6929
6930 memset((void *)src, 0, src_slot_size);
6931 RVALUE_AGE_RESET(src);
6932
6933 /* Set bits for object in new location */
6934 if (remembered) {
6935 MARK_IN_BITMAP(GET_HEAP_PAGE(dest)->remembered_bits, dest);
6936 }
6937 else {
6938 CLEAR_IN_BITMAP(GET_HEAP_PAGE(dest)->remembered_bits, dest);
6939 }
6940
6941 if (marked) {
6942 MARK_IN_BITMAP(GET_HEAP_MARK_BITS(dest), dest);
6943 }
6944 else {
6945 CLEAR_IN_BITMAP(GET_HEAP_MARK_BITS(dest), dest);
6946 }
6947
6948 if (wb_unprotected) {
6949 MARK_IN_BITMAP(GET_HEAP_WB_UNPROTECTED_BITS(dest), dest);
6950 }
6951 else {
6952 CLEAR_IN_BITMAP(GET_HEAP_WB_UNPROTECTED_BITS(dest), dest);
6953 }
6954
6955 if (uncollectible) {
6956 MARK_IN_BITMAP(GET_HEAP_UNCOLLECTIBLE_BITS(dest), dest);
6957 }
6958 else {
6959 CLEAR_IN_BITMAP(GET_HEAP_UNCOLLECTIBLE_BITS(dest), dest);
6960 }
6961
6962 RVALUE_AGE_SET(dest, age);
6963 /* Assign forwarding address */
6964 RMOVED(src)->flags = T_MOVED;
6965 RMOVED(src)->dummy = Qundef;
6966 RMOVED(src)->destination = dest;
6967 GC_ASSERT(BUILTIN_TYPE(dest) != T_NONE);
6968
6969 GET_HEAP_PAGE(src)->heap->total_freed_objects++;
6970 GET_HEAP_PAGE(dest)->heap->total_allocated_objects++;
6971
6972 return src;
6973}
6974
6975#if GC_CAN_COMPILE_COMPACTION
6976static int
6977compare_pinned_slots(const void *left, const void *right, void *dummy)
6978{
6979 struct heap_page *left_page;
6980 struct heap_page *right_page;
6981
6982 left_page = *(struct heap_page * const *)left;
6983 right_page = *(struct heap_page * const *)right;
6984
6985 return left_page->pinned_slots - right_page->pinned_slots;
6986}
6987
6988static int
6989compare_free_slots(const void *left, const void *right, void *dummy)
6990{
6991 struct heap_page *left_page;
6992 struct heap_page *right_page;
6993
6994 left_page = *(struct heap_page * const *)left;
6995 right_page = *(struct heap_page * const *)right;
6996
6997 return left_page->free_slots - right_page->free_slots;
6998}
6999
7000static void
7001gc_sort_heap_by_compare_func(rb_objspace_t *objspace, gc_compact_compare_func compare_func)
7002{
7003 for (int j = 0; j < HEAP_COUNT; j++) {
7004 rb_heap_t *heap = &heaps[j];
7005
7006 size_t total_pages = heap->total_pages;
7007 size_t size = rb_size_mul_or_raise(total_pages, sizeof(struct heap_page *), rb_eRuntimeError);
7008 struct heap_page *page = 0, **page_list = malloc(size);
7009 size_t i = 0;
7010
7011 heap->free_pages = NULL;
7012 ccan_list_for_each(&heap->pages, page, page_node) {
7013 page_list[i++] = page;
7014 GC_ASSERT(page);
7015 }
7016
7017 GC_ASSERT((size_t)i == total_pages);
7018
7019 /* Sort the heap so "filled pages" are first. `heap_add_page` adds to the
7020 * head of the list, so empty pages will end up at the start of the heap */
7021 ruby_qsort(page_list, total_pages, sizeof(struct heap_page *), compare_func, NULL);
7022
7023 /* Reset the eden heap */
7024 ccan_list_head_init(&heap->pages);
7025
7026 for (i = 0; i < total_pages; i++) {
7027 ccan_list_add(&heap->pages, &page_list[i]->page_node);
7028 if (page_list[i]->free_slots != 0) {
7029 heap_add_freepage(heap, page_list[i]);
7030 }
7031 }
7032
7033 free(page_list);
7034 }
7035}
7036#endif
7037
7038bool
7039rb_gc_impl_object_moved_p(void *objspace_ptr, VALUE obj)
7040{
7041 return gc_object_moved_p(objspace_ptr, obj);
7042}
7043
7044static int
7045gc_ref_update(void *vstart, void *vend, size_t stride, rb_objspace_t *objspace, struct heap_page *page)
7046{
7047 VALUE v = (VALUE)vstart;
7048
7049 page->flags.has_uncollectible_wb_unprotected_objects = FALSE;
7050 page->flags.has_remembered_objects = FALSE;
7051
7052 /* For each object on the page */
7053 for (; v != (VALUE)vend; v += stride) {
7054 asan_unpoisoning_object(v) {
7055 switch (BUILTIN_TYPE(v)) {
7056 case T_NONE:
7057 case T_MOVED:
7058 case T_ZOMBIE:
7059 break;
7060 default:
7061 if (RVALUE_WB_UNPROTECTED(objspace, v)) {
7062 page->flags.has_uncollectible_wb_unprotected_objects = TRUE;
7063 }
7064 if (RVALUE_REMEMBERED(objspace, v)) {
7065 page->flags.has_remembered_objects = TRUE;
7066 }
7067 if (page->flags.before_sweep) {
7068 if (RVALUE_MARKED(objspace, v)) {
7069 rb_gc_update_object_references(objspace, v);
7070 }
7071 }
7072 else {
7073 rb_gc_update_object_references(objspace, v);
7074 }
7075 }
7076 }
7077 }
7078
7079 return 0;
7080}
7081
7082static int
7083gc_update_references_weak_table_i(VALUE obj, void *data)
7084{
7085 int ret;
7086 asan_unpoisoning_object(obj) {
7087 ret = BUILTIN_TYPE(obj) == T_MOVED ? ST_REPLACE : ST_CONTINUE;
7088 }
7089 return ret;
7090}
7091
7092static int
7093gc_update_references_weak_table_replace_i(VALUE *obj, void *data)
7094{
7095 *obj = rb_gc_location(*obj);
7096
7097 return ST_CONTINUE;
7098}
7099
7100static void
7101gc_update_references(rb_objspace_t *objspace)
7102{
7103 objspace->flags.during_reference_updating = true;
7104
7105 rb_gc_before_updating_jit_code();
7106
7107 struct heap_page *page = NULL;
7108
7109 for (int i = 0; i < HEAP_COUNT; i++) {
7110 bool should_set_mark_bits = TRUE;
7111 rb_heap_t *heap = &heaps[i];
7112
7113 ccan_list_for_each(&heap->pages, page, page_node) {
7114 uintptr_t start = (uintptr_t)page->start;
7115 uintptr_t end = start + (page->total_slots * heap->slot_size);
7116
7117 gc_ref_update((void *)start, (void *)end, heap->slot_size, objspace, page);
7118 if (page == heap->sweeping_page) {
7119 should_set_mark_bits = FALSE;
7120 }
7121 if (should_set_mark_bits) {
7122 gc_setup_mark_bits(page);
7123 }
7124 }
7125 }
7126
7127 gc_update_table_refs(finalizer_table);
7128
7129 rb_gc_update_vm_references((void *)objspace);
7130
7131 for (int table = 0; table < RB_GC_VM_WEAK_TABLE_COUNT; table++) {
7132 rb_gc_vm_weak_table_foreach(
7133 gc_update_references_weak_table_i,
7134 gc_update_references_weak_table_replace_i,
7135 NULL,
7136 false,
7137 table
7138 );
7139 }
7140
7141 rb_gc_after_updating_jit_code();
7142
7143 objspace->flags.during_reference_updating = false;
7144}
7145
7146#if GC_CAN_COMPILE_COMPACTION
7147static void
7148root_obj_check_moved_i(const char *category, VALUE obj, void *data)
7149{
7150 rb_objspace_t *objspace = data;
7151
7152 if (gc_object_moved_p(objspace, obj)) {
7153 rb_bug("ROOT %s points to MOVED: %p -> %s", category, (void *)obj, rb_obj_info(rb_gc_impl_location(objspace, obj)));
7154 }
7155}
7156
7157static void
7158reachable_object_check_moved_i(VALUE ref, void *data)
7159{
7160 VALUE parent = (VALUE)data;
7161 if (gc_object_moved_p(rb_gc_get_objspace(), ref)) {
7162 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)));
7163 }
7164}
7165
7166static int
7167heap_check_moved_i(void *vstart, void *vend, size_t stride, void *data)
7168{
7169 rb_objspace_t *objspace = data;
7170
7171 VALUE v = (VALUE)vstart;
7172 for (; v != (VALUE)vend; v += stride) {
7173 if (gc_object_moved_p(objspace, v)) {
7174 /* Moved object still on the heap, something may have a reference. */
7175 }
7176 else {
7177 asan_unpoisoning_object(v) {
7178 switch (BUILTIN_TYPE(v)) {
7179 case T_NONE:
7180 case T_ZOMBIE:
7181 break;
7182 default:
7183 if (!rb_gc_impl_garbage_object_p(objspace, v)) {
7184 rb_objspace_reachable_objects_from(v, reachable_object_check_moved_i, (void *)v);
7185 }
7186 }
7187 }
7188 }
7189 }
7190
7191 return 0;
7192}
7193#endif
7194
7195bool
7196rb_gc_impl_during_gc_p(void *objspace_ptr)
7197{
7198 rb_objspace_t *objspace = objspace_ptr;
7199
7200 return during_gc;
7201}
7202
7203#if RGENGC_PROFILE >= 2
7204
7205static const char*
7206type_name(int type, VALUE obj)
7207{
7208 switch ((enum ruby_value_type)type) {
7209 case RUBY_T_NONE: return "T_NONE";
7210 case RUBY_T_OBJECT: return "T_OBJECT";
7211 case RUBY_T_CLASS: return "T_CLASS";
7212 case RUBY_T_MODULE: return "T_MODULE";
7213 case RUBY_T_FLOAT: return "T_FLOAT";
7214 case RUBY_T_STRING: return "T_STRING";
7215 case RUBY_T_REGEXP: return "T_REGEXP";
7216 case RUBY_T_ARRAY: return "T_ARRAY";
7217 case RUBY_T_HASH: return "T_HASH";
7218 case RUBY_T_STRUCT: return "T_STRUCT";
7219 case RUBY_T_BIGNUM: return "T_BIGNUM";
7220 case RUBY_T_FILE: return "T_FILE";
7221 case RUBY_T_DATA: return "T_DATA";
7222 case RUBY_T_MATCH: return "T_MATCH";
7223 case RUBY_T_COMPLEX: return "T_COMPLEX";
7224 case RUBY_T_RATIONAL: return "T_RATIONAL";
7225 case RUBY_T_NIL: return "T_NIL";
7226 case RUBY_T_TRUE: return "T_TRUE";
7227 case RUBY_T_FALSE: return "T_FALSE";
7228 case RUBY_T_SYMBOL: return "T_SYMBOL";
7229 case RUBY_T_FIXNUM: return "T_FIXNUM";
7230 case RUBY_T_UNDEF: return "T_UNDEF";
7231 case RUBY_T_IMEMO: return "T_IMEMO";
7232 case RUBY_T_NODE: return "T_NODE";
7233 case RUBY_T_ICLASS: return "T_ICLASS";
7234 case RUBY_T_ZOMBIE: return "T_ZOMBIE";
7235 case RUBY_T_MOVED: return "T_MOVED";
7236 default: return "unknown";
7237 }
7238}
7239
7240static void
7241gc_count_add_each_types(VALUE hash, const char *name, const size_t *types)
7242{
7243 VALUE result = rb_hash_new_with_size(T_MASK);
7244 int i;
7245 for (i=0; i<T_MASK; i++) {
7246 const char *type = type_name(i, 0);
7247 rb_hash_aset(result, ID2SYM(rb_intern(type)), SIZET2NUM(types[i]));
7248 }
7249 rb_hash_aset(hash, ID2SYM(rb_intern(name)), result);
7250}
7251#endif
7252
7253size_t
7254rb_gc_impl_gc_count(void *objspace_ptr)
7255{
7256 rb_objspace_t *objspace = objspace_ptr;
7257
7258 return objspace->profile.count;
7259}
7260
7261static VALUE
7262gc_info_decode(rb_objspace_t *objspace, const VALUE hash_or_key, const unsigned int orig_flags)
7263{
7264 static VALUE sym_major_by = Qnil, sym_gc_by, sym_immediate_sweep, sym_have_finalizer, sym_state, sym_need_major_by;
7265 static VALUE sym_nofree, sym_oldgen, sym_shady, sym_force, sym_stress;
7266#if RGENGC_ESTIMATE_OLDMALLOC
7267 static VALUE sym_oldmalloc;
7268#endif
7269 static VALUE sym_newobj, sym_malloc, sym_method, sym_capi;
7270 static VALUE sym_none, sym_marking, sym_sweeping;
7271 static VALUE sym_weak_references_count, sym_retained_weak_references_count;
7272 VALUE hash = Qnil, key = Qnil;
7273 VALUE major_by, need_major_by;
7274 unsigned int flags = orig_flags ? orig_flags : objspace->profile.latest_gc_info;
7275
7276 if (SYMBOL_P(hash_or_key)) {
7277 key = hash_or_key;
7278 }
7279 else if (RB_TYPE_P(hash_or_key, T_HASH)) {
7280 hash = hash_or_key;
7281 }
7282 else {
7283 rb_bug("gc_info_decode: non-hash or symbol given");
7284 }
7285
7286 if (NIL_P(sym_major_by)) {
7287#define S(s) sym_##s = ID2SYM(rb_intern_const(#s))
7288 S(major_by);
7289 S(gc_by);
7290 S(immediate_sweep);
7291 S(have_finalizer);
7292 S(state);
7293 S(need_major_by);
7294
7295 S(stress);
7296 S(nofree);
7297 S(oldgen);
7298 S(shady);
7299 S(force);
7300#if RGENGC_ESTIMATE_OLDMALLOC
7301 S(oldmalloc);
7302#endif
7303 S(newobj);
7304 S(malloc);
7305 S(method);
7306 S(capi);
7307
7308 S(none);
7309 S(marking);
7310 S(sweeping);
7311
7312 S(weak_references_count);
7313 S(retained_weak_references_count);
7314#undef S
7315 }
7316
7317#define SET(name, attr) \
7318 if (key == sym_##name) \
7319 return (attr); \
7320 else if (hash != Qnil) \
7321 rb_hash_aset(hash, sym_##name, (attr));
7322
7323 major_by =
7324 (flags & GPR_FLAG_MAJOR_BY_NOFREE) ? sym_nofree :
7325 (flags & GPR_FLAG_MAJOR_BY_OLDGEN) ? sym_oldgen :
7326 (flags & GPR_FLAG_MAJOR_BY_SHADY) ? sym_shady :
7327 (flags & GPR_FLAG_MAJOR_BY_FORCE) ? sym_force :
7328#if RGENGC_ESTIMATE_OLDMALLOC
7329 (flags & GPR_FLAG_MAJOR_BY_OLDMALLOC) ? sym_oldmalloc :
7330#endif
7331 Qnil;
7332 SET(major_by, major_by);
7333
7334 if (orig_flags == 0) { /* set need_major_by only if flags not set explicitly */
7335 unsigned int need_major_flags = gc_needs_major_flags;
7336 need_major_by =
7337 (need_major_flags & GPR_FLAG_MAJOR_BY_NOFREE) ? sym_nofree :
7338 (need_major_flags & GPR_FLAG_MAJOR_BY_OLDGEN) ? sym_oldgen :
7339 (need_major_flags & GPR_FLAG_MAJOR_BY_SHADY) ? sym_shady :
7340 (need_major_flags & GPR_FLAG_MAJOR_BY_FORCE) ? sym_force :
7341#if RGENGC_ESTIMATE_OLDMALLOC
7342 (need_major_flags & GPR_FLAG_MAJOR_BY_OLDMALLOC) ? sym_oldmalloc :
7343#endif
7344 Qnil;
7345 SET(need_major_by, need_major_by);
7346 }
7347
7348 SET(gc_by,
7349 (flags & GPR_FLAG_NEWOBJ) ? sym_newobj :
7350 (flags & GPR_FLAG_MALLOC) ? sym_malloc :
7351 (flags & GPR_FLAG_METHOD) ? sym_method :
7352 (flags & GPR_FLAG_CAPI) ? sym_capi :
7353 (flags & GPR_FLAG_STRESS) ? sym_stress :
7354 Qnil
7355 );
7356
7357 SET(have_finalizer, (flags & GPR_FLAG_HAVE_FINALIZE) ? Qtrue : Qfalse);
7358 SET(immediate_sweep, (flags & GPR_FLAG_IMMEDIATE_SWEEP) ? Qtrue : Qfalse);
7359
7360 if (orig_flags == 0) {
7361 SET(state, gc_mode(objspace) == gc_mode_none ? sym_none :
7362 gc_mode(objspace) == gc_mode_marking ? sym_marking : sym_sweeping);
7363 }
7364
7365 SET(weak_references_count, LONG2FIX(objspace->profile.weak_references_count));
7366 SET(retained_weak_references_count, LONG2FIX(objspace->profile.retained_weak_references_count));
7367#undef SET
7368
7369 if (!NIL_P(key)) {
7370 // Matched key should return above
7371 return Qundef;
7372 }
7373
7374 return hash;
7375}
7376
7377VALUE
7378rb_gc_impl_latest_gc_info(void *objspace_ptr, VALUE key)
7379{
7380 rb_objspace_t *objspace = objspace_ptr;
7381
7382 return gc_info_decode(objspace, key, 0);
7383}
7384
7385
7386enum gc_stat_sym {
7387 gc_stat_sym_count,
7388 gc_stat_sym_time,
7389 gc_stat_sym_marking_time,
7390 gc_stat_sym_sweeping_time,
7391 gc_stat_sym_heap_allocated_pages,
7392 gc_stat_sym_heap_empty_pages,
7393 gc_stat_sym_heap_allocatable_slots,
7394 gc_stat_sym_heap_available_slots,
7395 gc_stat_sym_heap_live_slots,
7396 gc_stat_sym_heap_free_slots,
7397 gc_stat_sym_heap_final_slots,
7398 gc_stat_sym_heap_marked_slots,
7399 gc_stat_sym_heap_eden_pages,
7400 gc_stat_sym_total_allocated_pages,
7401 gc_stat_sym_total_freed_pages,
7402 gc_stat_sym_total_allocated_objects,
7403 gc_stat_sym_total_freed_objects,
7404 gc_stat_sym_malloc_increase_bytes,
7405 gc_stat_sym_malloc_increase_bytes_limit,
7406 gc_stat_sym_minor_gc_count,
7407 gc_stat_sym_major_gc_count,
7408 gc_stat_sym_compact_count,
7409 gc_stat_sym_read_barrier_faults,
7410 gc_stat_sym_total_moved_objects,
7411 gc_stat_sym_remembered_wb_unprotected_objects,
7412 gc_stat_sym_remembered_wb_unprotected_objects_limit,
7413 gc_stat_sym_old_objects,
7414 gc_stat_sym_old_objects_limit,
7415#if RGENGC_ESTIMATE_OLDMALLOC
7416 gc_stat_sym_oldmalloc_increase_bytes,
7417 gc_stat_sym_oldmalloc_increase_bytes_limit,
7418#endif
7419 gc_stat_sym_weak_references_count,
7420#if RGENGC_PROFILE
7421 gc_stat_sym_total_generated_normal_object_count,
7422 gc_stat_sym_total_generated_shady_object_count,
7423 gc_stat_sym_total_shade_operation_count,
7424 gc_stat_sym_total_promoted_count,
7425 gc_stat_sym_total_remembered_normal_object_count,
7426 gc_stat_sym_total_remembered_shady_object_count,
7427#endif
7428 gc_stat_sym_last
7429};
7430
7431static VALUE gc_stat_symbols[gc_stat_sym_last];
7432
7433static void
7434setup_gc_stat_symbols(void)
7435{
7436 if (gc_stat_symbols[0] == 0) {
7437#define S(s) gc_stat_symbols[gc_stat_sym_##s] = ID2SYM(rb_intern_const(#s))
7438 S(count);
7439 S(time);
7440 S(marking_time),
7441 S(sweeping_time),
7442 S(heap_allocated_pages);
7443 S(heap_empty_pages);
7444 S(heap_allocatable_slots);
7445 S(heap_available_slots);
7446 S(heap_live_slots);
7447 S(heap_free_slots);
7448 S(heap_final_slots);
7449 S(heap_marked_slots);
7450 S(heap_eden_pages);
7451 S(total_allocated_pages);
7452 S(total_freed_pages);
7453 S(total_allocated_objects);
7454 S(total_freed_objects);
7455 S(malloc_increase_bytes);
7456 S(malloc_increase_bytes_limit);
7457 S(minor_gc_count);
7458 S(major_gc_count);
7459 S(compact_count);
7460 S(read_barrier_faults);
7461 S(total_moved_objects);
7462 S(remembered_wb_unprotected_objects);
7463 S(remembered_wb_unprotected_objects_limit);
7464 S(old_objects);
7465 S(old_objects_limit);
7466#if RGENGC_ESTIMATE_OLDMALLOC
7467 S(oldmalloc_increase_bytes);
7468 S(oldmalloc_increase_bytes_limit);
7469#endif
7470 S(weak_references_count);
7471#if RGENGC_PROFILE
7472 S(total_generated_normal_object_count);
7473 S(total_generated_shady_object_count);
7474 S(total_shade_operation_count);
7475 S(total_promoted_count);
7476 S(total_remembered_normal_object_count);
7477 S(total_remembered_shady_object_count);
7478#endif /* RGENGC_PROFILE */
7479#undef S
7480 }
7481}
7482
7483static uint64_t
7484ns_to_ms(uint64_t ns)
7485{
7486 return ns / (1000 * 1000);
7487}
7488
7489VALUE
7490rb_gc_impl_stat(void *objspace_ptr, VALUE hash_or_sym)
7491{
7492 rb_objspace_t *objspace = objspace_ptr;
7493 VALUE hash = Qnil, key = Qnil;
7494
7495 setup_gc_stat_symbols();
7496
7497 if (RB_TYPE_P(hash_or_sym, T_HASH)) {
7498 hash = hash_or_sym;
7499 }
7500 else if (SYMBOL_P(hash_or_sym)) {
7501 key = hash_or_sym;
7502 }
7503 else {
7504 rb_bug("non-hash or symbol given");
7505 }
7506
7507#define SET(name, attr) \
7508 if (key == gc_stat_symbols[gc_stat_sym_##name]) \
7509 return SIZET2NUM(attr); \
7510 else if (hash != Qnil) \
7511 rb_hash_aset(hash, gc_stat_symbols[gc_stat_sym_##name], SIZET2NUM(attr));
7512
7513 SET(count, objspace->profile.count);
7514 SET(time, (size_t)ns_to_ms(objspace->profile.marking_time_ns + objspace->profile.sweeping_time_ns)); // TODO: UINT64T2NUM
7515 SET(marking_time, (size_t)ns_to_ms(objspace->profile.marking_time_ns));
7516 SET(sweeping_time, (size_t)ns_to_ms(objspace->profile.sweeping_time_ns));
7517
7518 /* implementation dependent counters */
7519 SET(heap_allocated_pages, rb_darray_size(objspace->heap_pages.sorted));
7520 SET(heap_empty_pages, objspace->empty_pages_count)
7521 SET(heap_allocatable_slots, objspace->heap_pages.allocatable_slots);
7522 SET(heap_available_slots, objspace_available_slots(objspace));
7523 SET(heap_live_slots, objspace_live_slots(objspace));
7524 SET(heap_free_slots, objspace_free_slots(objspace));
7525 SET(heap_final_slots, total_final_slots_count(objspace));
7526 SET(heap_marked_slots, objspace->marked_slots);
7527 SET(heap_eden_pages, heap_eden_total_pages(objspace));
7528 SET(total_allocated_pages, objspace->heap_pages.allocated_pages);
7529 SET(total_freed_pages, objspace->heap_pages.freed_pages);
7530 SET(total_allocated_objects, total_allocated_objects(objspace));
7531 SET(total_freed_objects, total_freed_objects(objspace));
7532 SET(malloc_increase_bytes, malloc_increase);
7533 SET(malloc_increase_bytes_limit, malloc_limit);
7534 SET(minor_gc_count, objspace->profile.minor_gc_count);
7535 SET(major_gc_count, objspace->profile.major_gc_count);
7536 SET(compact_count, objspace->profile.compact_count);
7537 SET(read_barrier_faults, objspace->profile.read_barrier_faults);
7538 SET(total_moved_objects, objspace->rcompactor.total_moved);
7539 SET(remembered_wb_unprotected_objects, objspace->rgengc.uncollectible_wb_unprotected_objects);
7540 SET(remembered_wb_unprotected_objects_limit, objspace->rgengc.uncollectible_wb_unprotected_objects_limit);
7541 SET(old_objects, objspace->rgengc.old_objects);
7542 SET(old_objects_limit, objspace->rgengc.old_objects_limit);
7543#if RGENGC_ESTIMATE_OLDMALLOC
7544 SET(oldmalloc_increase_bytes, objspace->rgengc.oldmalloc_increase);
7545 SET(oldmalloc_increase_bytes_limit, objspace->rgengc.oldmalloc_increase_limit);
7546#endif
7547
7548#if RGENGC_PROFILE
7549 SET(total_generated_normal_object_count, objspace->profile.total_generated_normal_object_count);
7550 SET(total_generated_shady_object_count, objspace->profile.total_generated_shady_object_count);
7551 SET(total_shade_operation_count, objspace->profile.total_shade_operation_count);
7552 SET(total_promoted_count, objspace->profile.total_promoted_count);
7553 SET(total_remembered_normal_object_count, objspace->profile.total_remembered_normal_object_count);
7554 SET(total_remembered_shady_object_count, objspace->profile.total_remembered_shady_object_count);
7555#endif /* RGENGC_PROFILE */
7556#undef SET
7557
7558 if (!NIL_P(key)) {
7559 // Matched key should return above
7560 return Qundef;
7561 }
7562
7563#if defined(RGENGC_PROFILE) && RGENGC_PROFILE >= 2
7564 if (hash != Qnil) {
7565 gc_count_add_each_types(hash, "generated_normal_object_count_types", objspace->profile.generated_normal_object_count_types);
7566 gc_count_add_each_types(hash, "generated_shady_object_count_types", objspace->profile.generated_shady_object_count_types);
7567 gc_count_add_each_types(hash, "shade_operation_count_types", objspace->profile.shade_operation_count_types);
7568 gc_count_add_each_types(hash, "promoted_types", objspace->profile.promoted_types);
7569 gc_count_add_each_types(hash, "remembered_normal_object_count_types", objspace->profile.remembered_normal_object_count_types);
7570 gc_count_add_each_types(hash, "remembered_shady_object_count_types", objspace->profile.remembered_shady_object_count_types);
7571 }
7572#endif
7573
7574 return hash;
7575}
7576
7577enum gc_stat_heap_sym {
7578 gc_stat_heap_sym_slot_size,
7579 gc_stat_heap_sym_heap_eden_pages,
7580 gc_stat_heap_sym_heap_eden_slots,
7581 gc_stat_heap_sym_total_allocated_pages,
7582 gc_stat_heap_sym_force_major_gc_count,
7583 gc_stat_heap_sym_force_incremental_marking_finish_count,
7584 gc_stat_heap_sym_total_allocated_objects,
7585 gc_stat_heap_sym_total_freed_objects,
7586 gc_stat_heap_sym_last
7587};
7588
7589static VALUE gc_stat_heap_symbols[gc_stat_heap_sym_last];
7590
7591static void
7592setup_gc_stat_heap_symbols(void)
7593{
7594 if (gc_stat_heap_symbols[0] == 0) {
7595#define S(s) gc_stat_heap_symbols[gc_stat_heap_sym_##s] = ID2SYM(rb_intern_const(#s))
7596 S(slot_size);
7597 S(heap_eden_pages);
7598 S(heap_eden_slots);
7599 S(total_allocated_pages);
7600 S(force_major_gc_count);
7601 S(force_incremental_marking_finish_count);
7602 S(total_allocated_objects);
7603 S(total_freed_objects);
7604#undef S
7605 }
7606}
7607
7608static VALUE
7609stat_one_heap(rb_heap_t *heap, VALUE hash, VALUE key)
7610{
7611#define SET(name, attr) \
7612 if (key == gc_stat_heap_symbols[gc_stat_heap_sym_##name]) \
7613 return SIZET2NUM(attr); \
7614 else if (hash != Qnil) \
7615 rb_hash_aset(hash, gc_stat_heap_symbols[gc_stat_heap_sym_##name], SIZET2NUM(attr));
7616
7617 SET(slot_size, heap->slot_size);
7618 SET(heap_eden_pages, heap->total_pages);
7619 SET(heap_eden_slots, heap->total_slots);
7620 SET(total_allocated_pages, heap->total_allocated_pages);
7621 SET(force_major_gc_count, heap->force_major_gc_count);
7622 SET(force_incremental_marking_finish_count, heap->force_incremental_marking_finish_count);
7623 SET(total_allocated_objects, heap->total_allocated_objects);
7624 SET(total_freed_objects, heap->total_freed_objects);
7625#undef SET
7626
7627 if (!NIL_P(key)) {
7628 // Matched key should return above
7629 return Qundef;
7630 }
7631
7632 return hash;
7633}
7634
7635VALUE
7636rb_gc_impl_stat_heap(void *objspace_ptr, VALUE heap_name, VALUE hash_or_sym)
7637{
7638 rb_objspace_t *objspace = objspace_ptr;
7639
7640 setup_gc_stat_heap_symbols();
7641
7642 if (NIL_P(heap_name)) {
7643 if (!RB_TYPE_P(hash_or_sym, T_HASH)) {
7644 rb_bug("non-hash given");
7645 }
7646
7647 for (int i = 0; i < HEAP_COUNT; i++) {
7648 VALUE hash = rb_hash_aref(hash_or_sym, INT2FIX(i));
7649 if (NIL_P(hash)) {
7650 hash = rb_hash_new();
7651 rb_hash_aset(hash_or_sym, INT2FIX(i), hash);
7652 }
7653
7654 stat_one_heap(&heaps[i], hash, Qnil);
7655 }
7656 }
7657 else if (FIXNUM_P(heap_name)) {
7658 int heap_idx = FIX2INT(heap_name);
7659
7660 if (heap_idx < 0 || heap_idx >= HEAP_COUNT) {
7661 rb_raise(rb_eArgError, "size pool index out of range");
7662 }
7663
7664 if (SYMBOL_P(hash_or_sym)) {
7665 return stat_one_heap(&heaps[heap_idx], Qnil, hash_or_sym);
7666 }
7667 else if (RB_TYPE_P(hash_or_sym, T_HASH)) {
7668 return stat_one_heap(&heaps[heap_idx], hash_or_sym, Qnil);
7669 }
7670 else {
7671 rb_bug("non-hash or symbol given");
7672 }
7673 }
7674 else {
7675 rb_bug("heap_name must be nil or an Integer");
7676 }
7677
7678 return hash_or_sym;
7679}
7680
7681/* I could include internal.h for this, but doing so undefines some Array macros
7682 * necessary for initialising objects, and I don't want to include all the array
7683 * headers to get them back
7684 * TODO: Investigate why RARRAY_AREF gets undefined in internal.h
7685 */
7686#ifndef RBOOL
7687#define RBOOL(v) (v ? Qtrue : Qfalse)
7688#endif
7689
7690VALUE
7691rb_gc_impl_config_get(void *objspace_ptr)
7692{
7693#define sym(name) ID2SYM(rb_intern_const(name))
7694 rb_objspace_t *objspace = objspace_ptr;
7695 VALUE hash = rb_hash_new();
7696
7697 rb_hash_aset(hash, sym("rgengc_allow_full_mark"), RBOOL(gc_config_full_mark_val));
7698
7699 return hash;
7700}
7701
7702static int
7703gc_config_set_key(VALUE key, VALUE value, VALUE data)
7704{
7706 if (rb_sym2id(key) == rb_intern("rgengc_allow_full_mark")) {
7707 gc_rest(objspace);
7708 gc_config_full_mark_set(RTEST(value));
7709 }
7710 return ST_CONTINUE;
7711}
7712
7713void
7714rb_gc_impl_config_set(void *objspace_ptr, VALUE hash)
7715{
7716 rb_objspace_t *objspace = objspace_ptr;
7717
7718 if (!RB_TYPE_P(hash, T_HASH)) {
7719 rb_raise(rb_eArgError, "expected keyword arguments");
7720 }
7721
7722 rb_hash_foreach(hash, gc_config_set_key, (st_data_t)objspace);
7723}
7724
7725VALUE
7726rb_gc_impl_stress_get(void *objspace_ptr)
7727{
7728 rb_objspace_t *objspace = objspace_ptr;
7729 return ruby_gc_stress_mode;
7730}
7731
7732void
7733rb_gc_impl_stress_set(void *objspace_ptr, VALUE flag)
7734{
7735 rb_objspace_t *objspace = objspace_ptr;
7736
7737 objspace->flags.gc_stressful = RTEST(flag);
7738 objspace->gc_stress_mode = flag;
7739}
7740
7741static int
7742get_envparam_size(const char *name, size_t *default_value, size_t lower_bound)
7743{
7744 const char *ptr = getenv(name);
7745 ssize_t val;
7746
7747 if (ptr != NULL && *ptr) {
7748 size_t unit = 0;
7749 char *end;
7750#if SIZEOF_SIZE_T == SIZEOF_LONG_LONG
7751 val = strtoll(ptr, &end, 0);
7752#else
7753 val = strtol(ptr, &end, 0);
7754#endif
7755 switch (*end) {
7756 case 'k': case 'K':
7757 unit = 1024;
7758 ++end;
7759 break;
7760 case 'm': case 'M':
7761 unit = 1024*1024;
7762 ++end;
7763 break;
7764 case 'g': case 'G':
7765 unit = 1024*1024*1024;
7766 ++end;
7767 break;
7768 }
7769 while (*end && isspace((unsigned char)*end)) end++;
7770 if (*end) {
7771 if (RTEST(ruby_verbose)) fprintf(stderr, "invalid string for %s: %s\n", name, ptr);
7772 return 0;
7773 }
7774 if (unit > 0) {
7775 if (val < -(ssize_t)(SIZE_MAX / 2 / unit) || (ssize_t)(SIZE_MAX / 2 / unit) < val) {
7776 if (RTEST(ruby_verbose)) fprintf(stderr, "%s=%s is ignored because it overflows\n", name, ptr);
7777 return 0;
7778 }
7779 val *= unit;
7780 }
7781 if (val > 0 && (size_t)val > lower_bound) {
7782 if (RTEST(ruby_verbose)) {
7783 fprintf(stderr, "%s=%"PRIdSIZE" (default value: %"PRIuSIZE")\n", name, val, *default_value);
7784 }
7785 *default_value = (size_t)val;
7786 return 1;
7787 }
7788 else {
7789 if (RTEST(ruby_verbose)) {
7790 fprintf(stderr, "%s=%"PRIdSIZE" (default value: %"PRIuSIZE") is ignored because it must be greater than %"PRIuSIZE".\n",
7791 name, val, *default_value, lower_bound);
7792 }
7793 return 0;
7794 }
7795 }
7796 return 0;
7797}
7798
7799static int
7800get_envparam_double(const char *name, double *default_value, double lower_bound, double upper_bound, int accept_zero)
7801{
7802 const char *ptr = getenv(name);
7803 double val;
7804
7805 if (ptr != NULL && *ptr) {
7806 char *end;
7807 val = strtod(ptr, &end);
7808 if (!*ptr || *end) {
7809 if (RTEST(ruby_verbose)) fprintf(stderr, "invalid string for %s: %s\n", name, ptr);
7810 return 0;
7811 }
7812
7813 if (accept_zero && val == 0.0) {
7814 goto accept;
7815 }
7816 else if (val <= lower_bound) {
7817 if (RTEST(ruby_verbose)) {
7818 fprintf(stderr, "%s=%f (default value: %f) is ignored because it must be greater than %f.\n",
7819 name, val, *default_value, lower_bound);
7820 }
7821 }
7822 else if (upper_bound != 0.0 && /* ignore upper_bound if it is 0.0 */
7823 val > upper_bound) {
7824 if (RTEST(ruby_verbose)) {
7825 fprintf(stderr, "%s=%f (default value: %f) is ignored because it must be lower than %f.\n",
7826 name, val, *default_value, upper_bound);
7827 }
7828 }
7829 else {
7830 goto accept;
7831 }
7832 }
7833 return 0;
7834
7835 accept:
7836 if (RTEST(ruby_verbose)) fprintf(stderr, "%s=%f (default value: %f)\n", name, val, *default_value);
7837 *default_value = val;
7838 return 1;
7839}
7840
7841/*
7842 * GC tuning environment variables
7843 *
7844 * * RUBY_GC_HEAP_FREE_SLOTS
7845 * - Prepare at least this amount of slots after GC.
7846 * - Allocate slots if there are not enough slots.
7847 * * RUBY_GC_HEAP_GROWTH_FACTOR (new from 2.1)
7848 * - Allocate slots by this factor.
7849 * - (next slots number) = (current slots number) * (this factor)
7850 * * RUBY_GC_HEAP_GROWTH_MAX_SLOTS (new from 2.1)
7851 * - Allocation rate is limited to this number of slots.
7852 * * RUBY_GC_HEAP_FREE_SLOTS_MIN_RATIO (new from 2.4)
7853 * - Allocate additional pages when the number of free slots is
7854 * lower than the value (total_slots * (this ratio)).
7855 * * RUBY_GC_HEAP_FREE_SLOTS_GOAL_RATIO (new from 2.4)
7856 * - Allocate slots to satisfy this formula:
7857 * free_slots = total_slots * goal_ratio
7858 * - In other words, prepare (total_slots * goal_ratio) free slots.
7859 * - if this value is 0.0, then use RUBY_GC_HEAP_GROWTH_FACTOR directly.
7860 * * RUBY_GC_HEAP_FREE_SLOTS_MAX_RATIO (new from 2.4)
7861 * - Allow to free pages when the number of free slots is
7862 * greater than the value (total_slots * (this ratio)).
7863 * * RUBY_GC_HEAP_OLDOBJECT_LIMIT_FACTOR (new from 2.1.1)
7864 * - Do full GC when the number of old objects is more than R * N
7865 * where R is this factor and
7866 * N is the number of old objects just after last full GC.
7867 *
7868 * * obsolete
7869 * * RUBY_FREE_MIN -> RUBY_GC_HEAP_FREE_SLOTS (from 2.1)
7870 * * RUBY_HEAP_MIN_SLOTS -> RUBY_GC_HEAP_INIT_SLOTS (from 2.1)
7871 *
7872 * * RUBY_GC_MALLOC_LIMIT
7873 * * RUBY_GC_MALLOC_LIMIT_MAX (new from 2.1)
7874 * * RUBY_GC_MALLOC_LIMIT_GROWTH_FACTOR (new from 2.1)
7875 *
7876 * * RUBY_GC_OLDMALLOC_LIMIT (new from 2.1)
7877 * * RUBY_GC_OLDMALLOC_LIMIT_MAX (new from 2.1)
7878 * * RUBY_GC_OLDMALLOC_LIMIT_GROWTH_FACTOR (new from 2.1)
7879 */
7880
7881void
7882rb_gc_impl_set_params(void *objspace_ptr)
7883{
7884 rb_objspace_t *objspace = objspace_ptr;
7885 /* RUBY_GC_HEAP_FREE_SLOTS */
7886 if (get_envparam_size("RUBY_GC_HEAP_FREE_SLOTS", &gc_params.heap_free_slots, 0)) {
7887 /* ok */
7888 }
7889
7890 for (int i = 0; i < HEAP_COUNT; i++) {
7891 char env_key[sizeof("RUBY_GC_HEAP_" "_INIT_SLOTS") + DECIMAL_SIZE_OF_BITS(sizeof(int) * CHAR_BIT)];
7892 snprintf(env_key, sizeof(env_key), "RUBY_GC_HEAP_%d_INIT_SLOTS", i);
7893
7894 get_envparam_size(env_key, &gc_params.heap_init_slots[i], 0);
7895 }
7896
7897 get_envparam_double("RUBY_GC_HEAP_GROWTH_FACTOR", &gc_params.growth_factor, 1.0, 0.0, FALSE);
7898 get_envparam_size ("RUBY_GC_HEAP_GROWTH_MAX_SLOTS", &gc_params.growth_max_slots, 0);
7899 get_envparam_double("RUBY_GC_HEAP_FREE_SLOTS_MIN_RATIO", &gc_params.heap_free_slots_min_ratio,
7900 0.0, 1.0, FALSE);
7901 get_envparam_double("RUBY_GC_HEAP_FREE_SLOTS_MAX_RATIO", &gc_params.heap_free_slots_max_ratio,
7902 gc_params.heap_free_slots_min_ratio, 1.0, FALSE);
7903 get_envparam_double("RUBY_GC_HEAP_FREE_SLOTS_GOAL_RATIO", &gc_params.heap_free_slots_goal_ratio,
7904 gc_params.heap_free_slots_min_ratio, gc_params.heap_free_slots_max_ratio, TRUE);
7905 get_envparam_double("RUBY_GC_HEAP_OLDOBJECT_LIMIT_FACTOR", &gc_params.oldobject_limit_factor, 0.0, 0.0, TRUE);
7906 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);
7907
7908 if (get_envparam_size("RUBY_GC_MALLOC_LIMIT", &gc_params.malloc_limit_min, 0)) {
7909 malloc_limit = gc_params.malloc_limit_min;
7910 }
7911 get_envparam_size ("RUBY_GC_MALLOC_LIMIT_MAX", &gc_params.malloc_limit_max, 0);
7912 if (!gc_params.malloc_limit_max) { /* ignore max-check if 0 */
7913 gc_params.malloc_limit_max = SIZE_MAX;
7914 }
7915 get_envparam_double("RUBY_GC_MALLOC_LIMIT_GROWTH_FACTOR", &gc_params.malloc_limit_growth_factor, 1.0, 0.0, FALSE);
7916
7917#if RGENGC_ESTIMATE_OLDMALLOC
7918 if (get_envparam_size("RUBY_GC_OLDMALLOC_LIMIT", &gc_params.oldmalloc_limit_min, 0)) {
7919 objspace->rgengc.oldmalloc_increase_limit = gc_params.oldmalloc_limit_min;
7920 }
7921 get_envparam_size ("RUBY_GC_OLDMALLOC_LIMIT_MAX", &gc_params.oldmalloc_limit_max, 0);
7922 get_envparam_double("RUBY_GC_OLDMALLOC_LIMIT_GROWTH_FACTOR", &gc_params.oldmalloc_limit_growth_factor, 1.0, 0.0, FALSE);
7923#endif
7924}
7925
7926static inline size_t
7927objspace_malloc_size(rb_objspace_t *objspace, void *ptr, size_t hint)
7928{
7929#ifdef HAVE_MALLOC_USABLE_SIZE
7930 if (!hint) {
7931 hint = malloc_usable_size(ptr);
7932 }
7933#endif
7934 return hint;
7935}
7936
7937enum memop_type {
7938 MEMOP_TYPE_MALLOC = 0,
7939 MEMOP_TYPE_FREE,
7940 MEMOP_TYPE_REALLOC
7941};
7942
7943static inline void
7944atomic_sub_nounderflow(size_t *var, size_t sub)
7945{
7946 if (sub == 0) return;
7947
7948 while (1) {
7949 size_t val = *var;
7950 if (val < sub) sub = val;
7951 if (RUBY_ATOMIC_SIZE_CAS(*var, val, val-sub) == val) break;
7952 }
7953}
7954
7955#define gc_stress_full_mark_after_malloc_p() \
7956 (FIXNUM_P(ruby_gc_stress_mode) && (FIX2LONG(ruby_gc_stress_mode) & (1<<gc_stress_full_mark_after_malloc)))
7957
7958static void
7959objspace_malloc_gc_stress(rb_objspace_t *objspace)
7960{
7961 if (ruby_gc_stressful && ruby_native_thread_p()) {
7962 unsigned int reason = (GPR_FLAG_IMMEDIATE_MARK | GPR_FLAG_IMMEDIATE_SWEEP |
7963 GPR_FLAG_STRESS | GPR_FLAG_MALLOC);
7964
7965 if (gc_stress_full_mark_after_malloc_p()) {
7966 reason |= GPR_FLAG_FULL_MARK;
7967 }
7968 garbage_collect_with_gvl(objspace, reason);
7969 }
7970}
7971
7972static inline bool
7973objspace_malloc_increase_report(rb_objspace_t *objspace, void *mem, size_t new_size, size_t old_size, enum memop_type type, bool gc_allowed)
7974{
7975 if (0) fprintf(stderr, "increase - ptr: %p, type: %s, new_size: %"PRIdSIZE", old_size: %"PRIdSIZE"\n",
7976 mem,
7977 type == MEMOP_TYPE_MALLOC ? "malloc" :
7978 type == MEMOP_TYPE_FREE ? "free " :
7979 type == MEMOP_TYPE_REALLOC ? "realloc": "error",
7980 new_size, old_size);
7981 return false;
7982}
7983
7984static bool
7985objspace_malloc_increase_body(rb_objspace_t *objspace, void *mem, size_t new_size, size_t old_size, enum memop_type type, bool gc_allowed)
7986{
7987 if (new_size > old_size) {
7988 RUBY_ATOMIC_SIZE_ADD(malloc_increase, new_size - old_size);
7989#if RGENGC_ESTIMATE_OLDMALLOC
7990 RUBY_ATOMIC_SIZE_ADD(objspace->rgengc.oldmalloc_increase, new_size - old_size);
7991#endif
7992 }
7993 else {
7994 atomic_sub_nounderflow(&malloc_increase, old_size - new_size);
7995#if RGENGC_ESTIMATE_OLDMALLOC
7996 atomic_sub_nounderflow(&objspace->rgengc.oldmalloc_increase, old_size - new_size);
7997#endif
7998 }
7999
8000 if (type == MEMOP_TYPE_MALLOC && gc_allowed) {
8001 retry:
8002 if (malloc_increase > malloc_limit && ruby_native_thread_p() && !dont_gc_val()) {
8003 if (ruby_thread_has_gvl_p() && is_lazy_sweeping(objspace)) {
8004 gc_rest(objspace); /* gc_rest can reduce malloc_increase */
8005 goto retry;
8006 }
8007 garbage_collect_with_gvl(objspace, GPR_FLAG_MALLOC);
8008 }
8009 }
8010
8011#if MALLOC_ALLOCATED_SIZE
8012 if (new_size >= old_size) {
8013 RUBY_ATOMIC_SIZE_ADD(objspace->malloc_params.allocated_size, new_size - old_size);
8014 }
8015 else {
8016 size_t dec_size = old_size - new_size;
8017
8018#if MALLOC_ALLOCATED_SIZE_CHECK
8019 size_t allocated_size = objspace->malloc_params.allocated_size;
8020 if (allocated_size < dec_size) {
8021 rb_bug("objspace_malloc_increase: underflow malloc_params.allocated_size.");
8022 }
8023#endif
8024 atomic_sub_nounderflow(&objspace->malloc_params.allocated_size, dec_size);
8025 }
8026
8027 switch (type) {
8028 case MEMOP_TYPE_MALLOC:
8029 RUBY_ATOMIC_SIZE_INC(objspace->malloc_params.allocations);
8030 break;
8031 case MEMOP_TYPE_FREE:
8032 {
8033 size_t allocations = objspace->malloc_params.allocations;
8034 if (allocations > 0) {
8035 atomic_sub_nounderflow(&objspace->malloc_params.allocations, 1);
8036 }
8037#if MALLOC_ALLOCATED_SIZE_CHECK
8038 else {
8039 GC_ASSERT(objspace->malloc_params.allocations > 0);
8040 }
8041#endif
8042 }
8043 break;
8044 case MEMOP_TYPE_REALLOC: /* ignore */ break;
8045 }
8046#endif
8047 return true;
8048}
8049
8050#define objspace_malloc_increase(...) \
8051 for (bool malloc_increase_done = objspace_malloc_increase_report(__VA_ARGS__); \
8052 !malloc_increase_done; \
8053 malloc_increase_done = objspace_malloc_increase_body(__VA_ARGS__))
8054
8055struct malloc_obj_info { /* 4 words */
8056 size_t size;
8057};
8058
8059static inline size_t
8060objspace_malloc_prepare(rb_objspace_t *objspace, size_t size)
8061{
8062 if (size == 0) size = 1;
8063
8064#if CALC_EXACT_MALLOC_SIZE
8065 size += sizeof(struct malloc_obj_info);
8066#endif
8067
8068 return size;
8069}
8070
8071static bool
8072malloc_during_gc_p(rb_objspace_t *objspace)
8073{
8074 /* malloc is not allowed during GC when we're not using multiple ractors
8075 * (since ractors can run while another thread is sweeping) and when we
8076 * have the GVL (since if we don't have the GVL, we'll try to acquire the
8077 * GVL which will block and ensure the other thread finishes GC). */
8078 return during_gc && !dont_gc_val() && !rb_gc_multi_ractor_p() && ruby_thread_has_gvl_p();
8079}
8080
8081static inline void *
8082objspace_malloc_fixup(rb_objspace_t *objspace, void *mem, size_t size, bool gc_allowed)
8083{
8084 size = objspace_malloc_size(objspace, mem, size);
8085 objspace_malloc_increase(objspace, mem, size, 0, MEMOP_TYPE_MALLOC, gc_allowed) {}
8086
8087#if CALC_EXACT_MALLOC_SIZE
8088 {
8089 struct malloc_obj_info *info = mem;
8090 info->size = size;
8091 mem = info + 1;
8092 }
8093#endif
8094
8095 return mem;
8096}
8097
8098#if defined(__GNUC__) && RUBY_DEBUG
8099#define RB_BUG_INSTEAD_OF_RB_MEMERROR 1
8100#endif
8101
8102#ifndef RB_BUG_INSTEAD_OF_RB_MEMERROR
8103# define RB_BUG_INSTEAD_OF_RB_MEMERROR 0
8104#endif
8105
8106#define GC_MEMERROR(...) \
8107 ((RB_BUG_INSTEAD_OF_RB_MEMERROR+0) ? rb_bug("" __VA_ARGS__) : (void)0)
8108
8109#define TRY_WITH_GC(siz, expr) do { \
8110 const gc_profile_record_flag gpr = \
8111 GPR_FLAG_FULL_MARK | \
8112 GPR_FLAG_IMMEDIATE_MARK | \
8113 GPR_FLAG_IMMEDIATE_SWEEP | \
8114 GPR_FLAG_MALLOC; \
8115 objspace_malloc_gc_stress(objspace); \
8116 \
8117 if (RB_LIKELY((expr))) { \
8118 /* Success on 1st try */ \
8119 } \
8120 else if (gc_allowed && !garbage_collect_with_gvl(objspace, gpr)) { \
8121 /* @shyouhei thinks this doesn't happen */ \
8122 GC_MEMERROR("TRY_WITH_GC: could not GC"); \
8123 } \
8124 else if ((expr)) { \
8125 /* Success on 2nd try */ \
8126 } \
8127 else { \
8128 GC_MEMERROR("TRY_WITH_GC: could not allocate:" \
8129 "%"PRIdSIZE" bytes for %s", \
8130 siz, # expr); \
8131 } \
8132 } while (0)
8133
8134static void
8135check_malloc_not_in_gc(rb_objspace_t *objspace, const char *msg)
8136{
8137 if (RB_UNLIKELY(malloc_during_gc_p(objspace))) {
8138 dont_gc_on();
8139 during_gc = false;
8140 rb_bug("Cannot %s during GC", msg);
8141 }
8142}
8143
8144void
8145rb_gc_impl_free(void *objspace_ptr, void *ptr, size_t old_size)
8146{
8147 rb_objspace_t *objspace = objspace_ptr;
8148
8149 if (!ptr) {
8150 /*
8151 * ISO/IEC 9899 says "If ptr is a null pointer, no action occurs" since
8152 * its first version. We would better follow.
8153 */
8154 return;
8155 }
8156#if CALC_EXACT_MALLOC_SIZE
8157 struct malloc_obj_info *info = (struct malloc_obj_info *)ptr - 1;
8158 ptr = info;
8159 old_size = info->size;
8160#endif
8161 old_size = objspace_malloc_size(objspace, ptr, old_size);
8162
8163 objspace_malloc_increase(objspace, ptr, 0, old_size, MEMOP_TYPE_FREE, true) {
8164 free(ptr);
8165 ptr = NULL;
8166 RB_DEBUG_COUNTER_INC(heap_xfree);
8167 }
8168}
8169
8170void *
8171rb_gc_impl_malloc(void *objspace_ptr, size_t size, bool gc_allowed)
8172{
8173 rb_objspace_t *objspace = objspace_ptr;
8174 check_malloc_not_in_gc(objspace, "malloc");
8175
8176 void *mem;
8177
8178 size = objspace_malloc_prepare(objspace, size);
8179 TRY_WITH_GC(size, mem = malloc(size));
8180 RB_DEBUG_COUNTER_INC(heap_xmalloc);
8181 if (!mem) return mem;
8182 return objspace_malloc_fixup(objspace, mem, size, gc_allowed);
8183}
8184
8185void *
8186rb_gc_impl_calloc(void *objspace_ptr, size_t size, bool gc_allowed)
8187{
8188 rb_objspace_t *objspace = objspace_ptr;
8189
8190 if (RB_UNLIKELY(malloc_during_gc_p(objspace))) {
8191 rb_warn("calloc during GC detected, this could cause crashes if it triggers another GC");
8192#if RGENGC_CHECK_MODE || RUBY_DEBUG
8193 rb_bug("Cannot calloc during GC");
8194#endif
8195 }
8196
8197 void *mem;
8198
8199 size = objspace_malloc_prepare(objspace, size);
8200 TRY_WITH_GC(size, mem = calloc1(size));
8201 if (!mem) return mem;
8202 return objspace_malloc_fixup(objspace, mem, size, gc_allowed);
8203}
8204
8205void *
8206rb_gc_impl_realloc(void *objspace_ptr, void *ptr, size_t new_size, size_t old_size, bool gc_allowed)
8207{
8208 rb_objspace_t *objspace = objspace_ptr;
8209
8210 check_malloc_not_in_gc(objspace, "realloc");
8211
8212 void *mem;
8213
8214 if (!ptr) return rb_gc_impl_malloc(objspace, new_size, gc_allowed);
8215
8216 /*
8217 * The behavior of realloc(ptr, 0) is implementation defined.
8218 * Therefore we don't use realloc(ptr, 0) for portability reason.
8219 * see http://www.open-std.org/jtc1/sc22/wg14/www/docs/dr_400.htm
8220 */
8221 if (new_size == 0) {
8222 if ((mem = rb_gc_impl_malloc(objspace, 0, gc_allowed)) != NULL) {
8223 /*
8224 * - OpenBSD's malloc(3) man page says that when 0 is passed, it
8225 * returns a non-NULL pointer to an access-protected memory page.
8226 * The returned pointer cannot be read / written at all, but
8227 * still be a valid argument of free().
8228 *
8229 * https://man.openbsd.org/malloc.3
8230 *
8231 * - Linux's malloc(3) man page says that it _might_ perhaps return
8232 * a non-NULL pointer when its argument is 0. That return value
8233 * is safe (and is expected) to be passed to free().
8234 *
8235 * https://man7.org/linux/man-pages/man3/malloc.3.html
8236 *
8237 * - As I read the implementation jemalloc's malloc() returns fully
8238 * normal 16 bytes memory region when its argument is 0.
8239 *
8240 * - As I read the implementation musl libc's malloc() returns
8241 * fully normal 32 bytes memory region when its argument is 0.
8242 *
8243 * - Other malloc implementations can also return non-NULL.
8244 */
8245 rb_gc_impl_free(objspace, ptr, old_size);
8246 return mem;
8247 }
8248 else {
8249 /*
8250 * It is dangerous to return NULL here, because that could lead to
8251 * RCE. Fallback to 1 byte instead of zero.
8252 *
8253 * https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2019-11932
8254 */
8255 new_size = 1;
8256 }
8257 }
8258
8259#if CALC_EXACT_MALLOC_SIZE
8260 {
8261 struct malloc_obj_info *info = (struct malloc_obj_info *)ptr - 1;
8262 new_size += sizeof(struct malloc_obj_info);
8263 ptr = info;
8264 old_size = info->size;
8265 }
8266#endif
8267
8268 old_size = objspace_malloc_size(objspace, ptr, old_size);
8269 TRY_WITH_GC(new_size, mem = RB_GNUC_EXTENSION_BLOCK(realloc(ptr, new_size)));
8270 if (!mem) return mem;
8271 new_size = objspace_malloc_size(objspace, mem, new_size);
8272
8273#if CALC_EXACT_MALLOC_SIZE
8274 {
8275 struct malloc_obj_info *info = mem;
8276 info->size = new_size;
8277 mem = info + 1;
8278 }
8279#endif
8280
8281 objspace_malloc_increase(objspace, mem, new_size, old_size, MEMOP_TYPE_REALLOC, gc_allowed);
8282
8283 RB_DEBUG_COUNTER_INC(heap_xrealloc);
8284 return mem;
8285}
8286
8287void
8288rb_gc_impl_adjust_memory_usage(void *objspace_ptr, ssize_t diff)
8289{
8290 rb_objspace_t *objspace = objspace_ptr;
8291
8292 if (diff > 0) {
8293 objspace_malloc_increase(objspace, 0, diff, 0, MEMOP_TYPE_REALLOC, true);
8294 }
8295 else if (diff < 0) {
8296 objspace_malloc_increase(objspace, 0, 0, -diff, MEMOP_TYPE_REALLOC, true);
8297 }
8298}
8299
8300// TODO: move GC profiler stuff back into gc.c
8301/*
8302 ------------------------------ GC profiler ------------------------------
8303*/
8304
8305#define GC_PROFILE_RECORD_DEFAULT_SIZE 100
8306
8307static bool
8308current_process_time(struct timespec *ts)
8309{
8310#if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_PROCESS_CPUTIME_ID)
8311 {
8312 static int try_clock_gettime = 1;
8313 if (try_clock_gettime && clock_gettime(CLOCK_PROCESS_CPUTIME_ID, ts) == 0) {
8314 return true;
8315 }
8316 else {
8317 try_clock_gettime = 0;
8318 }
8319 }
8320#endif
8321
8322#ifdef RUSAGE_SELF
8323 {
8324 struct rusage usage;
8325 struct timeval time;
8326 if (getrusage(RUSAGE_SELF, &usage) == 0) {
8327 time = usage.ru_utime;
8328 ts->tv_sec = time.tv_sec;
8329 ts->tv_nsec = (int32_t)time.tv_usec * 1000;
8330 return true;
8331 }
8332 }
8333#endif
8334
8335#ifdef _WIN32
8336 {
8337 FILETIME creation_time, exit_time, kernel_time, user_time;
8338 ULARGE_INTEGER ui;
8339
8340 if (GetProcessTimes(GetCurrentProcess(),
8341 &creation_time, &exit_time, &kernel_time, &user_time) != 0) {
8342 memcpy(&ui, &user_time, sizeof(FILETIME));
8343#define PER100NSEC (uint64_t)(1000 * 1000 * 10)
8344 ts->tv_nsec = (long)(ui.QuadPart % PER100NSEC);
8345 ts->tv_sec = (time_t)(ui.QuadPart / PER100NSEC);
8346 return true;
8347 }
8348 }
8349#endif
8350
8351 return false;
8352}
8353
8354static double
8355getrusage_time(void)
8356{
8357 struct timespec ts;
8358 if (current_process_time(&ts)) {
8359 return ts.tv_sec + ts.tv_nsec * 1e-9;
8360 }
8361 else {
8362 return 0.0;
8363 }
8364}
8365
8366
8367static inline void
8368gc_prof_setup_new_record(rb_objspace_t *objspace, unsigned int reason)
8369{
8370 if (objspace->profile.run) {
8371 size_t index = objspace->profile.next_index;
8372 gc_profile_record *record;
8373
8374 /* create new record */
8375 objspace->profile.next_index++;
8376
8377 if (!objspace->profile.records) {
8378 objspace->profile.size = GC_PROFILE_RECORD_DEFAULT_SIZE;
8379 objspace->profile.records = malloc(xmalloc2_size(sizeof(gc_profile_record), objspace->profile.size));
8380 }
8381 if (index >= objspace->profile.size) {
8382 void *ptr;
8383 objspace->profile.size += 1000;
8384 ptr = realloc(objspace->profile.records, xmalloc2_size(sizeof(gc_profile_record), objspace->profile.size));
8385 if (!ptr) rb_memerror();
8386 objspace->profile.records = ptr;
8387 }
8388 if (!objspace->profile.records) {
8389 rb_bug("gc_profile malloc or realloc miss");
8390 }
8391 record = objspace->profile.current_record = &objspace->profile.records[objspace->profile.next_index - 1];
8392 MEMZERO(record, gc_profile_record, 1);
8393
8394 /* setup before-GC parameter */
8395 record->flags = reason | (ruby_gc_stressful ? GPR_FLAG_STRESS : 0);
8396#if MALLOC_ALLOCATED_SIZE
8397 record->allocated_size = malloc_allocated_size;
8398#endif
8399#if GC_PROFILE_MORE_DETAIL && GC_PROFILE_DETAIL_MEMORY
8400#ifdef RUSAGE_SELF
8401 {
8402 struct rusage usage;
8403 if (getrusage(RUSAGE_SELF, &usage) == 0) {
8404 record->maxrss = usage.ru_maxrss;
8405 record->minflt = usage.ru_minflt;
8406 record->majflt = usage.ru_majflt;
8407 }
8408 }
8409#endif
8410#endif
8411 }
8412}
8413
8414static inline void
8415gc_prof_timer_start(rb_objspace_t *objspace)
8416{
8417 if (gc_prof_enabled(objspace)) {
8418 gc_profile_record *record = gc_prof_record(objspace);
8419#if GC_PROFILE_MORE_DETAIL
8420 record->prepare_time = objspace->profile.prepare_time;
8421#endif
8422 record->gc_time = 0;
8423 record->gc_invoke_time = getrusage_time();
8424 }
8425}
8426
8427static double
8428elapsed_time_from(double time)
8429{
8430 double now = getrusage_time();
8431 if (now > time) {
8432 return now - time;
8433 }
8434 else {
8435 return 0;
8436 }
8437}
8438
8439static inline void
8440gc_prof_timer_stop(rb_objspace_t *objspace)
8441{
8442 if (gc_prof_enabled(objspace)) {
8443 gc_profile_record *record = gc_prof_record(objspace);
8444 record->gc_time = elapsed_time_from(record->gc_invoke_time);
8445 record->gc_invoke_time -= objspace->profile.invoke_time;
8446 }
8447}
8448
8449#ifdef BUILDING_MODULAR_GC
8450# define RUBY_DTRACE_GC_HOOK(name)
8451#else
8452# define RUBY_DTRACE_GC_HOOK(name) \
8453 do {if (RUBY_DTRACE_GC_##name##_ENABLED()) RUBY_DTRACE_GC_##name();} while (0)
8454#endif
8455
8456static inline void
8457gc_prof_mark_timer_start(rb_objspace_t *objspace)
8458{
8459 RUBY_DTRACE_GC_HOOK(MARK_BEGIN);
8460#if GC_PROFILE_MORE_DETAIL
8461 if (gc_prof_enabled(objspace)) {
8462 gc_prof_record(objspace)->gc_mark_time = getrusage_time();
8463 }
8464#endif
8465}
8466
8467static inline void
8468gc_prof_mark_timer_stop(rb_objspace_t *objspace)
8469{
8470 RUBY_DTRACE_GC_HOOK(MARK_END);
8471#if GC_PROFILE_MORE_DETAIL
8472 if (gc_prof_enabled(objspace)) {
8473 gc_profile_record *record = gc_prof_record(objspace);
8474 record->gc_mark_time = elapsed_time_from(record->gc_mark_time);
8475 }
8476#endif
8477}
8478
8479static inline void
8480gc_prof_sweep_timer_start(rb_objspace_t *objspace)
8481{
8482 RUBY_DTRACE_GC_HOOK(SWEEP_BEGIN);
8483 if (gc_prof_enabled(objspace)) {
8484 gc_profile_record *record = gc_prof_record(objspace);
8485
8486 if (record->gc_time > 0 || GC_PROFILE_MORE_DETAIL) {
8487 objspace->profile.gc_sweep_start_time = getrusage_time();
8488 }
8489 }
8490}
8491
8492static inline void
8493gc_prof_sweep_timer_stop(rb_objspace_t *objspace)
8494{
8495 RUBY_DTRACE_GC_HOOK(SWEEP_END);
8496
8497 if (gc_prof_enabled(objspace)) {
8498 double sweep_time;
8499 gc_profile_record *record = gc_prof_record(objspace);
8500
8501 if (record->gc_time > 0) {
8502 sweep_time = elapsed_time_from(objspace->profile.gc_sweep_start_time);
8503 /* need to accumulate GC time for lazy sweep after gc() */
8504 record->gc_time += sweep_time;
8505 }
8506 else if (GC_PROFILE_MORE_DETAIL) {
8507 sweep_time = elapsed_time_from(objspace->profile.gc_sweep_start_time);
8508 }
8509
8510#if GC_PROFILE_MORE_DETAIL
8511 record->gc_sweep_time += sweep_time;
8512 if (heap_pages_deferred_final) record->flags |= GPR_FLAG_HAVE_FINALIZE;
8513#endif
8514 if (heap_pages_deferred_final) objspace->profile.latest_gc_info |= GPR_FLAG_HAVE_FINALIZE;
8515 }
8516}
8517
8518static inline void
8519gc_prof_set_malloc_info(rb_objspace_t *objspace)
8520{
8521#if GC_PROFILE_MORE_DETAIL
8522 if (gc_prof_enabled(objspace)) {
8523 gc_profile_record *record = gc_prof_record(objspace);
8524 record->allocate_increase = malloc_increase;
8525 record->allocate_limit = malloc_limit;
8526 }
8527#endif
8528}
8529
8530static inline void
8531gc_prof_set_heap_info(rb_objspace_t *objspace)
8532{
8533 if (gc_prof_enabled(objspace)) {
8534 gc_profile_record *record = gc_prof_record(objspace);
8535 size_t live = objspace->profile.total_allocated_objects_at_gc_start - total_freed_objects(objspace);
8536 size_t total = objspace->profile.heap_used_at_gc_start * HEAP_PAGE_OBJ_LIMIT;
8537
8538#if GC_PROFILE_MORE_DETAIL
8539 record->heap_use_pages = objspace->profile.heap_used_at_gc_start;
8540 record->heap_live_objects = live;
8541 record->heap_free_objects = total - live;
8542#endif
8543
8544 record->heap_total_objects = total;
8545 record->heap_use_size = live * BASE_SLOT_SIZE;
8546 record->heap_total_size = total * BASE_SLOT_SIZE;
8547 }
8548}
8549
8550/*
8551 * call-seq:
8552 * GC::Profiler.clear -> nil
8553 *
8554 * Clears the \GC profiler data.
8555 *
8556 */
8557
8558static VALUE
8559gc_profile_clear(VALUE _)
8560{
8561 rb_objspace_t *objspace = rb_gc_get_objspace();
8562 void *p = objspace->profile.records;
8563 objspace->profile.records = NULL;
8564 objspace->profile.size = 0;
8565 objspace->profile.next_index = 0;
8566 objspace->profile.current_record = 0;
8567 free(p);
8568 return Qnil;
8569}
8570
8571/*
8572 * call-seq:
8573 * GC::Profiler.raw_data -> [Hash, ...]
8574 *
8575 * Returns an Array of individual raw profile data Hashes ordered
8576 * from earliest to latest by +:GC_INVOKE_TIME+.
8577 *
8578 * For example:
8579 *
8580 * [
8581 * {
8582 * :GC_TIME=>1.3000000000000858e-05,
8583 * :GC_INVOKE_TIME=>0.010634999999999999,
8584 * :HEAP_USE_SIZE=>289640,
8585 * :HEAP_TOTAL_SIZE=>588960,
8586 * :HEAP_TOTAL_OBJECTS=>14724,
8587 * :GC_IS_MARKED=>false
8588 * },
8589 * # ...
8590 * ]
8591 *
8592 * The keys mean:
8593 *
8594 * +:GC_TIME+::
8595 * Time elapsed in seconds for this GC run
8596 * +:GC_INVOKE_TIME+::
8597 * Time elapsed in seconds from startup to when the GC was invoked
8598 * +:HEAP_USE_SIZE+::
8599 * Total bytes of heap used
8600 * +:HEAP_TOTAL_SIZE+::
8601 * Total size of heap in bytes
8602 * +:HEAP_TOTAL_OBJECTS+::
8603 * Total number of objects
8604 * +:GC_IS_MARKED+::
8605 * Returns +true+ if the GC is in mark phase
8606 *
8607 * If ruby was built with +GC_PROFILE_MORE_DETAIL+, you will also have access
8608 * to the following hash keys:
8609 *
8610 * +:GC_MARK_TIME+::
8611 * +:GC_SWEEP_TIME+::
8612 * +:ALLOCATE_INCREASE+::
8613 * +:ALLOCATE_LIMIT+::
8614 * +:HEAP_USE_PAGES+::
8615 * +:HEAP_LIVE_OBJECTS+::
8616 * +:HEAP_FREE_OBJECTS+::
8617 * +:HAVE_FINALIZE+::
8618 *
8619 */
8620
8621static VALUE
8622gc_profile_record_get(VALUE _)
8623{
8624 VALUE prof;
8625 VALUE gc_profile = rb_ary_new();
8626 size_t i;
8627 rb_objspace_t *objspace = rb_gc_get_objspace();
8628
8629 if (!objspace->profile.run) {
8630 return Qnil;
8631 }
8632
8633 for (i =0; i < objspace->profile.next_index; i++) {
8634 gc_profile_record *record = &objspace->profile.records[i];
8635
8636 prof = rb_hash_new();
8637 rb_hash_aset(prof, ID2SYM(rb_intern("GC_FLAGS")), gc_info_decode(objspace, rb_hash_new(), record->flags));
8638 rb_hash_aset(prof, ID2SYM(rb_intern("GC_TIME")), DBL2NUM(record->gc_time));
8639 rb_hash_aset(prof, ID2SYM(rb_intern("GC_INVOKE_TIME")), DBL2NUM(record->gc_invoke_time));
8640 rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_USE_SIZE")), SIZET2NUM(record->heap_use_size));
8641 rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_TOTAL_SIZE")), SIZET2NUM(record->heap_total_size));
8642 rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_TOTAL_OBJECTS")), SIZET2NUM(record->heap_total_objects));
8643 rb_hash_aset(prof, ID2SYM(rb_intern("MOVED_OBJECTS")), SIZET2NUM(record->moved_objects));
8644 rb_hash_aset(prof, ID2SYM(rb_intern("GC_IS_MARKED")), Qtrue);
8645#if GC_PROFILE_MORE_DETAIL
8646 rb_hash_aset(prof, ID2SYM(rb_intern("GC_MARK_TIME")), DBL2NUM(record->gc_mark_time));
8647 rb_hash_aset(prof, ID2SYM(rb_intern("GC_SWEEP_TIME")), DBL2NUM(record->gc_sweep_time));
8648 rb_hash_aset(prof, ID2SYM(rb_intern("ALLOCATE_INCREASE")), SIZET2NUM(record->allocate_increase));
8649 rb_hash_aset(prof, ID2SYM(rb_intern("ALLOCATE_LIMIT")), SIZET2NUM(record->allocate_limit));
8650 rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_USE_PAGES")), SIZET2NUM(record->heap_use_pages));
8651 rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_LIVE_OBJECTS")), SIZET2NUM(record->heap_live_objects));
8652 rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_FREE_OBJECTS")), SIZET2NUM(record->heap_free_objects));
8653
8654 rb_hash_aset(prof, ID2SYM(rb_intern("REMOVING_OBJECTS")), SIZET2NUM(record->removing_objects));
8655 rb_hash_aset(prof, ID2SYM(rb_intern("EMPTY_OBJECTS")), SIZET2NUM(record->empty_objects));
8656
8657 rb_hash_aset(prof, ID2SYM(rb_intern("HAVE_FINALIZE")), (record->flags & GPR_FLAG_HAVE_FINALIZE) ? Qtrue : Qfalse);
8658#endif
8659
8660#if RGENGC_PROFILE > 0
8661 rb_hash_aset(prof, ID2SYM(rb_intern("OLD_OBJECTS")), SIZET2NUM(record->old_objects));
8662 rb_hash_aset(prof, ID2SYM(rb_intern("REMEMBERED_NORMAL_OBJECTS")), SIZET2NUM(record->remembered_normal_objects));
8663 rb_hash_aset(prof, ID2SYM(rb_intern("REMEMBERED_SHADY_OBJECTS")), SIZET2NUM(record->remembered_shady_objects));
8664#endif
8665 rb_ary_push(gc_profile, prof);
8666 }
8667
8668 return gc_profile;
8669}
8670
8671#if GC_PROFILE_MORE_DETAIL
8672#define MAJOR_REASON_MAX 0x10
8673
8674static char *
8675gc_profile_dump_major_reason(unsigned int flags, char *buff)
8676{
8677 unsigned int reason = flags & GPR_FLAG_MAJOR_MASK;
8678 int i = 0;
8679
8680 if (reason == GPR_FLAG_NONE) {
8681 buff[0] = '-';
8682 buff[1] = 0;
8683 }
8684 else {
8685#define C(x, s) \
8686 if (reason & GPR_FLAG_MAJOR_BY_##x) { \
8687 buff[i++] = #x[0]; \
8688 if (i >= MAJOR_REASON_MAX) rb_bug("gc_profile_dump_major_reason: overflow"); \
8689 buff[i] = 0; \
8690 }
8691 C(NOFREE, N);
8692 C(OLDGEN, O);
8693 C(SHADY, S);
8694#if RGENGC_ESTIMATE_OLDMALLOC
8695 C(OLDMALLOC, M);
8696#endif
8697#undef C
8698 }
8699 return buff;
8700}
8701#endif
8702
8703
8704
8705static void
8706gc_profile_dump_on(VALUE out, VALUE (*append)(VALUE, VALUE))
8707{
8708 rb_objspace_t *objspace = rb_gc_get_objspace();
8709 size_t count = objspace->profile.next_index;
8710#ifdef MAJOR_REASON_MAX
8711 char reason_str[MAJOR_REASON_MAX];
8712#endif
8713
8714 if (objspace->profile.run && count /* > 1 */) {
8715 size_t i;
8716 const gc_profile_record *record;
8717
8718 append(out, rb_sprintf("GC %"PRIuSIZE" invokes.\n", objspace->profile.count));
8719 append(out, rb_str_new_cstr("Index Invoke Time(sec) Use Size(byte) Total Size(byte) Total Object GC Time(ms)\n"));
8720
8721 for (i = 0; i < count; i++) {
8722 record = &objspace->profile.records[i];
8723 append(out, rb_sprintf("%5"PRIuSIZE" %19.3f %20"PRIuSIZE" %20"PRIuSIZE" %20"PRIuSIZE" %30.20f\n",
8724 i+1, record->gc_invoke_time, record->heap_use_size,
8725 record->heap_total_size, record->heap_total_objects, record->gc_time*1000));
8726 }
8727
8728#if GC_PROFILE_MORE_DETAIL
8729 const char *str = "\n\n" \
8730 "More detail.\n" \
8731 "Prepare Time = Previously GC's rest sweep time\n"
8732 "Index Flags Allocate Inc. Allocate Limit"
8733#if CALC_EXACT_MALLOC_SIZE
8734 " Allocated Size"
8735#endif
8736 " Use Page Mark Time(ms) Sweep Time(ms) Prepare Time(ms) LivingObj FreeObj RemovedObj EmptyObj"
8737#if RGENGC_PROFILE
8738 " OldgenObj RemNormObj RemShadObj"
8739#endif
8740#if GC_PROFILE_DETAIL_MEMORY
8741 " MaxRSS(KB) MinorFLT MajorFLT"
8742#endif
8743 "\n";
8744 append(out, rb_str_new_cstr(str));
8745
8746 for (i = 0; i < count; i++) {
8747 record = &objspace->profile.records[i];
8748 append(out, rb_sprintf("%5"PRIuSIZE" %4s/%c/%6s%c %13"PRIuSIZE" %15"PRIuSIZE
8749#if CALC_EXACT_MALLOC_SIZE
8750 " %15"PRIuSIZE
8751#endif
8752 " %9"PRIuSIZE" %17.12f %17.12f %17.12f %10"PRIuSIZE" %10"PRIuSIZE" %10"PRIuSIZE" %10"PRIuSIZE
8753#if RGENGC_PROFILE
8754 "%10"PRIuSIZE" %10"PRIuSIZE" %10"PRIuSIZE
8755#endif
8756#if GC_PROFILE_DETAIL_MEMORY
8757 "%11ld %8ld %8ld"
8758#endif
8759
8760 "\n",
8761 i+1,
8762 gc_profile_dump_major_reason(record->flags, reason_str),
8763 (record->flags & GPR_FLAG_HAVE_FINALIZE) ? 'F' : '.',
8764 (record->flags & GPR_FLAG_NEWOBJ) ? "NEWOBJ" :
8765 (record->flags & GPR_FLAG_MALLOC) ? "MALLOC" :
8766 (record->flags & GPR_FLAG_METHOD) ? "METHOD" :
8767 (record->flags & GPR_FLAG_CAPI) ? "CAPI__" : "??????",
8768 (record->flags & GPR_FLAG_STRESS) ? '!' : ' ',
8769 record->allocate_increase, record->allocate_limit,
8770#if CALC_EXACT_MALLOC_SIZE
8771 record->allocated_size,
8772#endif
8773 record->heap_use_pages,
8774 record->gc_mark_time*1000,
8775 record->gc_sweep_time*1000,
8776 record->prepare_time*1000,
8777
8778 record->heap_live_objects,
8779 record->heap_free_objects,
8780 record->removing_objects,
8781 record->empty_objects
8782#if RGENGC_PROFILE
8783 ,
8784 record->old_objects,
8785 record->remembered_normal_objects,
8786 record->remembered_shady_objects
8787#endif
8788#if GC_PROFILE_DETAIL_MEMORY
8789 ,
8790 record->maxrss / 1024,
8791 record->minflt,
8792 record->majflt
8793#endif
8794
8795 ));
8796 }
8797#endif
8798 }
8799}
8800
8801/*
8802 * call-seq:
8803 * GC::Profiler.result -> String
8804 *
8805 * Returns a profile data report such as:
8806 *
8807 * GC 1 invokes.
8808 * Index Invoke Time(sec) Use Size(byte) Total Size(byte) Total Object GC time(ms)
8809 * 1 0.012 159240 212940 10647 0.00000000000001530000
8810 */
8811
8812static VALUE
8813gc_profile_result(VALUE _)
8814{
8815 VALUE str = rb_str_buf_new(0);
8816 gc_profile_dump_on(str, rb_str_buf_append);
8817 return str;
8818}
8819
8820/*
8821 * call-seq:
8822 * GC::Profiler.report
8823 * GC::Profiler.report(io)
8824 *
8825 * Writes the GC::Profiler.result to <tt>$stdout</tt> or the given IO object.
8826 *
8827 */
8828
8829static VALUE
8830gc_profile_report(int argc, VALUE *argv, VALUE self)
8831{
8832 VALUE out;
8833
8834 out = (!rb_check_arity(argc, 0, 1) ? rb_stdout : argv[0]);
8835 gc_profile_dump_on(out, rb_io_write);
8836
8837 return Qnil;
8838}
8839
8840/*
8841 * call-seq:
8842 * GC::Profiler.total_time -> float
8843 *
8844 * The total time used for garbage collection in seconds
8845 */
8846
8847static VALUE
8848gc_profile_total_time(VALUE self)
8849{
8850 double time = 0;
8851 rb_objspace_t *objspace = rb_gc_get_objspace();
8852
8853 if (objspace->profile.run && objspace->profile.next_index > 0) {
8854 size_t i;
8855 size_t count = objspace->profile.next_index;
8856
8857 for (i = 0; i < count; i++) {
8858 time += objspace->profile.records[i].gc_time;
8859 }
8860 }
8861 return DBL2NUM(time);
8862}
8863
8864/*
8865 * call-seq:
8866 * GC::Profiler.enabled? -> true or false
8867 *
8868 * The current status of \GC profile mode.
8869 */
8870
8871static VALUE
8872gc_profile_enable_get(VALUE self)
8873{
8874 rb_objspace_t *objspace = rb_gc_get_objspace();
8875 return objspace->profile.run ? Qtrue : Qfalse;
8876}
8877
8878/*
8879 * call-seq:
8880 * GC::Profiler.enable -> nil
8881 *
8882 * Starts the \GC profiler.
8883 *
8884 */
8885
8886static VALUE
8887gc_profile_enable(VALUE _)
8888{
8889 rb_objspace_t *objspace = rb_gc_get_objspace();
8890 objspace->profile.run = TRUE;
8891 objspace->profile.current_record = 0;
8892 return Qnil;
8893}
8894
8895/*
8896 * call-seq:
8897 * GC::Profiler.disable -> nil
8898 *
8899 * Stops the \GC profiler.
8900 *
8901 */
8902
8903static VALUE
8904gc_profile_disable(VALUE _)
8905{
8906 rb_objspace_t *objspace = rb_gc_get_objspace();
8907
8908 objspace->profile.run = FALSE;
8909 objspace->profile.current_record = 0;
8910 return Qnil;
8911}
8912
8913/*
8914 * call-seq:
8915 * GC.verify_internal_consistency -> nil
8916 *
8917 * Verify internal consistency.
8918 *
8919 * This method is implementation specific.
8920 * Now this method checks generational consistency
8921 * if RGenGC is supported.
8922 */
8923static VALUE
8924gc_verify_internal_consistency_m(VALUE dummy)
8925{
8926 gc_verify_internal_consistency(rb_gc_get_objspace());
8927 return Qnil;
8928}
8929
8930#if GC_CAN_COMPILE_COMPACTION
8931/*
8932 * call-seq:
8933 * GC.auto_compact = flag
8934 *
8935 * Updates automatic compaction mode.
8936 *
8937 * When enabled, the compactor will execute on every major collection.
8938 *
8939 * Enabling compaction will degrade performance on major collections.
8940 */
8941static VALUE
8942gc_set_auto_compact(VALUE _, VALUE v)
8943{
8944 GC_ASSERT(GC_COMPACTION_SUPPORTED);
8945
8946 ruby_enable_autocompact = RTEST(v);
8947
8948#if RGENGC_CHECK_MODE
8949 ruby_autocompact_compare_func = NULL;
8950
8951 if (SYMBOL_P(v)) {
8952 ID id = RB_SYM2ID(v);
8953 if (id == rb_intern("empty")) {
8954 ruby_autocompact_compare_func = compare_free_slots;
8955 }
8956 }
8957#endif
8958
8959 return v;
8960}
8961#else
8962# define gc_set_auto_compact rb_f_notimplement
8963#endif
8964
8965#if GC_CAN_COMPILE_COMPACTION
8966/*
8967 * call-seq:
8968 * GC.auto_compact -> true or false
8969 *
8970 * Returns whether or not automatic compaction has been enabled.
8971 */
8972static VALUE
8973gc_get_auto_compact(VALUE _)
8974{
8975 return ruby_enable_autocompact ? Qtrue : Qfalse;
8976}
8977#else
8978# define gc_get_auto_compact rb_f_notimplement
8979#endif
8980
8981#if GC_CAN_COMPILE_COMPACTION
8982/*
8983 * call-seq:
8984 * GC.latest_compact_info -> hash
8985 *
8986 * Returns information about object moved in the most recent \GC compaction.
8987 *
8988 * The returned +hash+ contains the following keys:
8989 *
8990 * [considered]
8991 * Hash containing the type of the object as the key and the number of
8992 * objects of that type that were considered for movement.
8993 * [moved]
8994 * Hash containing the type of the object as the key and the number of
8995 * objects of that type that were actually moved.
8996 * [moved_up]
8997 * Hash containing the type of the object as the key and the number of
8998 * objects of that type that were increased in size.
8999 * [moved_down]
9000 * Hash containing the type of the object as the key and the number of
9001 * objects of that type that were decreased in size.
9002 *
9003 * Some objects can't be moved (due to pinning) so these numbers can be used to
9004 * calculate compaction efficiency.
9005 */
9006static VALUE
9007gc_compact_stats(VALUE self)
9008{
9009 rb_objspace_t *objspace = rb_gc_get_objspace();
9010 VALUE h = rb_hash_new();
9011 VALUE considered = rb_hash_new();
9012 VALUE moved = rb_hash_new();
9013 VALUE moved_up = rb_hash_new();
9014 VALUE moved_down = rb_hash_new();
9015
9016 for (size_t i = 0; i < T_MASK; i++) {
9017 if (objspace->rcompactor.considered_count_table[i]) {
9018 rb_hash_aset(considered, type_sym(i), SIZET2NUM(objspace->rcompactor.considered_count_table[i]));
9019 }
9020
9021 if (objspace->rcompactor.moved_count_table[i]) {
9022 rb_hash_aset(moved, type_sym(i), SIZET2NUM(objspace->rcompactor.moved_count_table[i]));
9023 }
9024
9025 if (objspace->rcompactor.moved_up_count_table[i]) {
9026 rb_hash_aset(moved_up, type_sym(i), SIZET2NUM(objspace->rcompactor.moved_up_count_table[i]));
9027 }
9028
9029 if (objspace->rcompactor.moved_down_count_table[i]) {
9030 rb_hash_aset(moved_down, type_sym(i), SIZET2NUM(objspace->rcompactor.moved_down_count_table[i]));
9031 }
9032 }
9033
9034 rb_hash_aset(h, ID2SYM(rb_intern("considered")), considered);
9035 rb_hash_aset(h, ID2SYM(rb_intern("moved")), moved);
9036 rb_hash_aset(h, ID2SYM(rb_intern("moved_up")), moved_up);
9037 rb_hash_aset(h, ID2SYM(rb_intern("moved_down")), moved_down);
9038
9039 return h;
9040}
9041#else
9042# define gc_compact_stats rb_f_notimplement
9043#endif
9044
9045#if GC_CAN_COMPILE_COMPACTION
9046/*
9047 * call-seq:
9048 * GC.compact -> hash
9049 *
9050 * This function compacts objects together in Ruby's heap. It eliminates
9051 * unused space (or fragmentation) in the heap by moving objects in to that
9052 * unused space.
9053 *
9054 * The returned +hash+ contains statistics about the objects that were moved;
9055 * see GC.latest_compact_info.
9056 *
9057 * This method is only expected to work on CRuby.
9058 *
9059 * To test whether \GC compaction is supported, use the idiom:
9060 *
9061 * GC.respond_to?(:compact)
9062 */
9063static VALUE
9064gc_compact(VALUE self)
9065{
9066 rb_objspace_t *objspace = rb_gc_get_objspace();
9067 int full_marking_p = gc_config_full_mark_val;
9068 gc_config_full_mark_set(TRUE);
9069
9070 /* Run GC with compaction enabled */
9071 rb_gc_impl_start(rb_gc_get_objspace(), true, true, true, true);
9072 gc_config_full_mark_set(full_marking_p);
9073
9074 return gc_compact_stats(self);
9075}
9076#else
9077# define gc_compact rb_f_notimplement
9078#endif
9079
9080#if GC_CAN_COMPILE_COMPACTION
9081struct desired_compaction_pages_i_data {
9083 size_t required_slots[HEAP_COUNT];
9084};
9085
9086static int
9087desired_compaction_pages_i(struct heap_page *page, void *data)
9088{
9089 struct desired_compaction_pages_i_data *tdata = data;
9090 rb_objspace_t *objspace = tdata->objspace;
9091 VALUE vstart = (VALUE)page->start;
9092 VALUE vend = vstart + (VALUE)(page->total_slots * page->heap->slot_size);
9093
9094
9095 for (VALUE v = vstart; v != vend; v += page->heap->slot_size) {
9096 asan_unpoisoning_object(v) {
9097 /* skip T_NONEs; they won't be moved */
9098 if (BUILTIN_TYPE(v) != T_NONE) {
9099 rb_heap_t *dest_pool = gc_compact_destination_pool(objspace, page->heap, v);
9100 size_t dest_pool_idx = dest_pool - heaps;
9101 tdata->required_slots[dest_pool_idx]++;
9102 }
9103 }
9104 }
9105
9106 return 0;
9107}
9108
9109/* call-seq:
9110 * GC.verify_compaction_references(toward: nil, double_heap: false) -> hash
9111 *
9112 * Verify compaction reference consistency.
9113 *
9114 * This method is implementation specific. During compaction, objects that
9115 * were moved are replaced with T_MOVED objects. No object should have a
9116 * reference to a T_MOVED object after compaction.
9117 *
9118 * This function expands the heap to ensure room to move all objects,
9119 * compacts the heap to make sure everything moves, updates all references,
9120 * then performs a full \GC. If any object contains a reference to a T_MOVED
9121 * object, that object should be pushed on the mark stack, and will
9122 * make a SEGV.
9123 */
9124static VALUE
9125gc_verify_compaction_references(int argc, VALUE* argv, VALUE self)
9126{
9127 static ID keywords[3] = {0};
9128 if (!keywords[0]) {
9129 keywords[0] = rb_intern("toward");
9130 keywords[1] = rb_intern("double_heap");
9131 keywords[2] = rb_intern("expand_heap");
9132 }
9133
9134 VALUE options;
9135 rb_scan_args_kw(rb_keyword_given_p(), argc, argv, ":", &options);
9136
9137 VALUE arguments[3] = { Qnil, Qfalse, Qfalse };
9138 int kwarg_count = rb_get_kwargs(options, keywords, 0, 3, arguments);
9139 bool toward_empty = kwarg_count > 0 && SYMBOL_P(arguments[0]) && SYM2ID(arguments[0]) == rb_intern("empty");
9140 bool expand_heap = (kwarg_count > 1 && RTEST(arguments[1])) || (kwarg_count > 2 && RTEST(arguments[2]));
9141
9142 rb_objspace_t *objspace = rb_gc_get_objspace();
9143
9144 /* Clear the heap. */
9145 rb_gc_impl_start(objspace, true, true, true, false);
9146
9147 unsigned int lev = RB_GC_VM_LOCK();
9148 {
9149 gc_rest(objspace);
9150
9151 /* if both double_heap and expand_heap are set, expand_heap takes precedence */
9152 if (expand_heap) {
9153 struct desired_compaction_pages_i_data desired_compaction = {
9154 .objspace = objspace,
9155 .required_slots = {0},
9156 };
9157 /* Work out how many objects want to be in each size pool, taking account of moves */
9158 objspace_each_pages(objspace, desired_compaction_pages_i, &desired_compaction, TRUE);
9159
9160 /* Find out which pool has the most pages */
9161 size_t max_existing_pages = 0;
9162 for (int i = 0; i < HEAP_COUNT; i++) {
9163 rb_heap_t *heap = &heaps[i];
9164 max_existing_pages = MAX(max_existing_pages, heap->total_pages);
9165 }
9166
9167 /* Add pages to each size pool so that compaction is guaranteed to move every object */
9168 for (int i = 0; i < HEAP_COUNT; i++) {
9169 rb_heap_t *heap = &heaps[i];
9170
9171 size_t pages_to_add = 0;
9172 /*
9173 * Step 1: Make sure every pool has the same number of pages, by adding empty pages
9174 * to smaller pools. This is required to make sure the compact cursor can advance
9175 * through all of the pools in `gc_sweep_compact` without hitting the "sweep &
9176 * compact cursors met" condition on some pools before fully compacting others
9177 */
9178 pages_to_add += max_existing_pages - heap->total_pages;
9179 /*
9180 * Step 2: Now add additional free pages to each size pool sufficient to hold all objects
9181 * that want to be in that size pool, whether moved into it or moved within it
9182 */
9183 objspace->heap_pages.allocatable_slots = desired_compaction.required_slots[i];
9184 while (objspace->heap_pages.allocatable_slots > 0) {
9185 heap_page_allocate_and_initialize(objspace, heap);
9186 }
9187 /*
9188 * Step 3: Add two more pages so that the compact & sweep cursors will meet _after_ all objects
9189 * have been moved, and not on the last iteration of the `gc_sweep_compact` loop
9190 */
9191 pages_to_add += 2;
9192
9193 for (; pages_to_add > 0; pages_to_add--) {
9194 heap_page_allocate_and_initialize_force(objspace, heap);
9195 }
9196 }
9197 }
9198
9199 if (toward_empty) {
9200 objspace->rcompactor.compare_func = compare_free_slots;
9201 }
9202 }
9203 RB_GC_VM_UNLOCK(lev);
9204
9205 rb_gc_impl_start(rb_gc_get_objspace(), true, true, true, true);
9206
9207 rb_objspace_reachable_objects_from_root(root_obj_check_moved_i, objspace);
9208 objspace_each_objects(objspace, heap_check_moved_i, objspace, TRUE);
9209
9210 objspace->rcompactor.compare_func = NULL;
9211
9212 return gc_compact_stats(self);
9213}
9214#else
9215# define gc_verify_compaction_references rb_f_notimplement
9216#endif
9217
9218void
9219rb_gc_impl_objspace_free(void *objspace_ptr)
9220{
9221 rb_objspace_t *objspace = objspace_ptr;
9222
9223 if (is_lazy_sweeping(objspace))
9224 rb_bug("lazy sweeping underway when freeing object space");
9225
9226 free(objspace->profile.records);
9227 objspace->profile.records = NULL;
9228
9229 for (size_t i = 0; i < rb_darray_size(objspace->heap_pages.sorted); i++) {
9230 heap_page_free(objspace, rb_darray_get(objspace->heap_pages.sorted, i));
9231 }
9232 rb_darray_free_without_gc(objspace->heap_pages.sorted);
9233 heap_pages_lomem = 0;
9234 heap_pages_himem = 0;
9235
9236 for (int i = 0; i < HEAP_COUNT; i++) {
9237 rb_heap_t *heap = &heaps[i];
9238 heap->total_pages = 0;
9239 heap->total_slots = 0;
9240 }
9241
9242 free_stack_chunks(&objspace->mark_stack);
9243 mark_stack_free_cache(&objspace->mark_stack);
9244
9245 rb_darray_free_without_gc(objspace->weak_references);
9246
9247 free(objspace);
9248}
9249
9250#if MALLOC_ALLOCATED_SIZE
9251/*
9252 * call-seq:
9253 * GC.malloc_allocated_size -> Integer
9254 *
9255 * Returns the size of memory allocated by malloc().
9256 *
9257 * Only available if ruby was built with +CALC_EXACT_MALLOC_SIZE+.
9258 */
9259
9260static VALUE
9261gc_malloc_allocated_size(VALUE self)
9262{
9263 rb_objspace_t *objspace = (rb_objspace_t *)rb_gc_get_objspace();
9264 return ULL2NUM(objspace->malloc_params.allocated_size);
9265}
9266
9267/*
9268 * call-seq:
9269 * GC.malloc_allocations -> Integer
9270 *
9271 * Returns the number of malloc() allocations.
9272 *
9273 * Only available if ruby was built with +CALC_EXACT_MALLOC_SIZE+.
9274 */
9275
9276static VALUE
9277gc_malloc_allocations(VALUE self)
9278{
9279 rb_objspace_t *objspace = (rb_objspace_t *)rb_gc_get_objspace();
9280 return ULL2NUM(objspace->malloc_params.allocations);
9281}
9282#endif
9283
9284void rb_gc_impl_before_fork(void *objspace_ptr) { /* no-op */ }
9285void rb_gc_impl_after_fork(void *objspace_ptr, rb_pid_t pid) {
9286 if (pid == 0) { /* child process */
9287 rb_gc_ractor_newobj_cache_foreach(gc_ractor_newobj_cache_clear, NULL);
9288 }
9289}
9290
9291VALUE rb_ident_hash_new_with_size(st_index_t size);
9292
9293/*
9294 * call-seq:
9295 * GC.add_stress_to_class(class[, ...])
9296 *
9297 * Raises NoMemoryError when allocating an instance of the given classes.
9298 *
9299 */
9300static VALUE
9301rb_gcdebug_add_stress_to_class(int argc, VALUE *argv, VALUE self)
9302{
9303 rb_objspace_t *objspace = rb_gc_get_objspace();
9304
9305 if (!stress_to_class) {
9306 set_stress_to_class(rb_ident_hash_new_with_size(argc));
9307 }
9308
9309 for (int i = 0; i < argc; i++) {
9310 VALUE klass = argv[i];
9311 rb_hash_aset(stress_to_class, klass, Qtrue);
9312 }
9313
9314 return self;
9315}
9316
9317/*
9318 * call-seq:
9319 * GC.remove_stress_to_class(class[, ...])
9320 *
9321 * No longer raises NoMemoryError when allocating an instance of the
9322 * given classes.
9323 *
9324 */
9325static VALUE
9326rb_gcdebug_remove_stress_to_class(int argc, VALUE *argv, VALUE self)
9327{
9328 rb_objspace_t *objspace = rb_gc_get_objspace();
9329
9330 if (stress_to_class) {
9331 for (int i = 0; i < argc; ++i) {
9332 rb_hash_delete(stress_to_class, argv[i]);
9333 }
9334
9335 if (rb_hash_size(stress_to_class) == 0) {
9336 stress_to_class = 0;
9337 }
9338 }
9339
9340 return Qnil;
9341}
9342
9343void *
9344rb_gc_impl_objspace_alloc(void)
9345{
9346 rb_objspace_t *objspace = calloc1(sizeof(rb_objspace_t));
9347
9348 return objspace;
9349}
9350
9351void
9352rb_gc_impl_objspace_init(void *objspace_ptr)
9353{
9354 rb_objspace_t *objspace = objspace_ptr;
9355
9356 gc_config_full_mark_set(TRUE);
9357
9358 objspace->flags.measure_gc = true;
9359 malloc_limit = gc_params.malloc_limit_min;
9360 objspace->finalize_deferred_pjob = rb_postponed_job_preregister(0, gc_finalize_deferred, objspace);
9361 if (objspace->finalize_deferred_pjob == POSTPONED_JOB_HANDLE_INVALID) {
9362 rb_bug("Could not preregister postponed job for GC");
9363 }
9364
9365 for (int i = 0; i < HEAP_COUNT; i++) {
9366 rb_heap_t *heap = &heaps[i];
9367
9368 heap->slot_size = (1 << i) * BASE_SLOT_SIZE;
9369
9370 ccan_list_head_init(&heap->pages);
9371 }
9372
9373 rb_darray_make_without_gc(&objspace->heap_pages.sorted, 0);
9374 rb_darray_make_without_gc(&objspace->weak_references, 0);
9375
9376 // TODO: debug why on Windows Ruby crashes on boot when GC is on.
9377#ifdef _WIN32
9378 dont_gc_on();
9379#endif
9380
9381#if defined(INIT_HEAP_PAGE_ALLOC_USE_MMAP)
9382 /* Need to determine if we can use mmap at runtime. */
9383 heap_page_alloc_use_mmap = INIT_HEAP_PAGE_ALLOC_USE_MMAP;
9384#endif
9385#if RGENGC_ESTIMATE_OLDMALLOC
9386 objspace->rgengc.oldmalloc_increase_limit = gc_params.oldmalloc_limit_min;
9387#endif
9388 /* Set size pools allocatable pages. */
9389 for (int i = 0; i < HEAP_COUNT; i++) {
9390 /* Set the default value of heap_init_slots. */
9391 gc_params.heap_init_slots[i] = GC_HEAP_INIT_SLOTS;
9392 }
9393
9394 init_mark_stack(&objspace->mark_stack);
9395
9396 objspace->profile.invoke_time = getrusage_time();
9397 finalizer_table = st_init_numtable();
9398}
9399
9400void
9401rb_gc_impl_init(void)
9402{
9403 VALUE gc_constants = rb_hash_new();
9404 rb_hash_aset(gc_constants, ID2SYM(rb_intern("DEBUG")), GC_DEBUG ? Qtrue : Qfalse);
9405 rb_hash_aset(gc_constants, ID2SYM(rb_intern("BASE_SLOT_SIZE")), SIZET2NUM(BASE_SLOT_SIZE - RVALUE_OVERHEAD));
9406 rb_hash_aset(gc_constants, ID2SYM(rb_intern("RBASIC_SIZE")), SIZET2NUM(sizeof(struct RBasic)));
9407 rb_hash_aset(gc_constants, ID2SYM(rb_intern("RVALUE_OVERHEAD")), SIZET2NUM(RVALUE_OVERHEAD));
9408 rb_hash_aset(gc_constants, ID2SYM(rb_intern("HEAP_PAGE_OBJ_LIMIT")), SIZET2NUM(HEAP_PAGE_OBJ_LIMIT));
9409 rb_hash_aset(gc_constants, ID2SYM(rb_intern("HEAP_PAGE_BITMAP_SIZE")), SIZET2NUM(HEAP_PAGE_BITMAP_SIZE));
9410 rb_hash_aset(gc_constants, ID2SYM(rb_intern("HEAP_PAGE_SIZE")), SIZET2NUM(HEAP_PAGE_SIZE));
9411 rb_hash_aset(gc_constants, ID2SYM(rb_intern("HEAP_COUNT")), LONG2FIX(HEAP_COUNT));
9412 rb_hash_aset(gc_constants, ID2SYM(rb_intern("RVARGC_MAX_ALLOCATE_SIZE")), LONG2FIX(heap_slot_size(HEAP_COUNT - 1)));
9413 rb_hash_aset(gc_constants, ID2SYM(rb_intern("RVALUE_OLD_AGE")), LONG2FIX(RVALUE_OLD_AGE));
9414 if (RB_BUG_INSTEAD_OF_RB_MEMERROR+0) {
9415 rb_hash_aset(gc_constants, ID2SYM(rb_intern("RB_BUG_INSTEAD_OF_RB_MEMERROR")), Qtrue);
9416 }
9417 OBJ_FREEZE(gc_constants);
9418 /* Internal constants in the garbage collector. */
9419 rb_define_const(rb_mGC, "INTERNAL_CONSTANTS", gc_constants);
9420
9421 if (GC_COMPACTION_SUPPORTED) {
9422 rb_define_singleton_method(rb_mGC, "compact", gc_compact, 0);
9423 rb_define_singleton_method(rb_mGC, "auto_compact", gc_get_auto_compact, 0);
9424 rb_define_singleton_method(rb_mGC, "auto_compact=", gc_set_auto_compact, 1);
9425 rb_define_singleton_method(rb_mGC, "latest_compact_info", gc_compact_stats, 0);
9426 rb_define_singleton_method(rb_mGC, "verify_compaction_references", gc_verify_compaction_references, -1);
9427 }
9428 else {
9432 rb_define_singleton_method(rb_mGC, "latest_compact_info", rb_f_notimplement, 0);
9433 rb_define_singleton_method(rb_mGC, "verify_compaction_references", rb_f_notimplement, -1);
9434 }
9435
9436 if (GC_DEBUG_STRESS_TO_CLASS) {
9437 rb_define_singleton_method(rb_mGC, "add_stress_to_class", rb_gcdebug_add_stress_to_class, -1);
9438 rb_define_singleton_method(rb_mGC, "remove_stress_to_class", rb_gcdebug_remove_stress_to_class, -1);
9439 }
9440
9441 /* internal methods */
9442 rb_define_singleton_method(rb_mGC, "verify_internal_consistency", gc_verify_internal_consistency_m, 0);
9443
9444#if MALLOC_ALLOCATED_SIZE
9445 rb_define_singleton_method(rb_mGC, "malloc_allocated_size", gc_malloc_allocated_size, 0);
9446 rb_define_singleton_method(rb_mGC, "malloc_allocations", gc_malloc_allocations, 0);
9447#endif
9448
9449 VALUE rb_mProfiler = rb_define_module_under(rb_mGC, "Profiler");
9450 rb_define_singleton_method(rb_mProfiler, "enabled?", gc_profile_enable_get, 0);
9451 rb_define_singleton_method(rb_mProfiler, "enable", gc_profile_enable, 0);
9452 rb_define_singleton_method(rb_mProfiler, "raw_data", gc_profile_record_get, 0);
9453 rb_define_singleton_method(rb_mProfiler, "disable", gc_profile_disable, 0);
9454 rb_define_singleton_method(rb_mProfiler, "clear", gc_profile_clear, 0);
9455 rb_define_singleton_method(rb_mProfiler, "result", gc_profile_result, 0);
9456 rb_define_singleton_method(rb_mProfiler, "report", gc_profile_report, -1);
9457 rb_define_singleton_method(rb_mProfiler, "total_time", gc_profile_total_time, 0);
9458
9459 {
9460 VALUE opts;
9461 /* \GC build options */
9462 rb_define_const(rb_mGC, "OPTS", opts = rb_ary_new());
9463#define OPT(o) if (o) rb_ary_push(opts, rb_interned_str(#o, sizeof(#o) - 1))
9464 OPT(GC_DEBUG);
9465 OPT(USE_RGENGC);
9466 OPT(RGENGC_DEBUG);
9467 OPT(RGENGC_CHECK_MODE);
9468 OPT(RGENGC_PROFILE);
9469 OPT(RGENGC_ESTIMATE_OLDMALLOC);
9470 OPT(GC_PROFILE_MORE_DETAIL);
9471 OPT(GC_ENABLE_LAZY_SWEEP);
9472 OPT(CALC_EXACT_MALLOC_SIZE);
9473 OPT(MALLOC_ALLOCATED_SIZE);
9474 OPT(MALLOC_ALLOCATED_SIZE_CHECK);
9475 OPT(GC_PROFILE_DETAIL_MEMORY);
9476 OPT(GC_COMPACTION_SUPPORTED);
9477#undef OPT
9478 OBJ_FREEZE(opts);
9479 }
9480}
#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:1784
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:1750
#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:1620
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:3146
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:2922
#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:174
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:3723
VALUE rb_str_buf_new(long capa)
Allocates a "string buffer".
Definition string.c:1683
#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:1514
const char * rb_sourcefile(void)
Resembles __FILE__.
Definition vm.c:1898
VALUE rb_f_notimplement(int argc, const VALUE *argv, VALUE obj, VALUE marker)
Raises rb_eNotImpError.
Definition vm_method.c:789
int rb_sourceline(void)
Resembles __LINE__.
Definition vm.c:1912
#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
VALUE flags
Per-object flags.
Definition rbasic.h:81
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