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