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