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