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