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