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