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