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