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