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