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