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