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