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