1#include "ruby/internal/config.h"
8# ifdef HAVE_SYS_PRCTL_H
13#if !defined(PAGE_SIZE) && defined(HAVE_SYS_USER_H)
18#ifdef BUILDING_MODULAR_GC
19# define nlz_int64(x) (x == 0 ? 64 : (unsigned int)__builtin_clzll((unsigned long long)x))
21# include "internal/bits.h"
31#include "ccan/list/list.h"
34#include "gc/gc_impl.h"
36#ifndef BUILDING_MODULAR_GC
40#ifdef BUILDING_MODULAR_GC
41# define RB_DEBUG_COUNTER_INC(_name) ((void)0)
42# define RB_DEBUG_COUNTER_INC_IF(_name, cond) (!!(cond))
44# include "debug_counter.h"
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)
55# define VALGRIND_MAKE_MEM_DEFINED(ptr, size) ((void)(ptr), (void)(size))
56# define VALGRIND_MAKE_MEM_UNDEFINED(ptr, size) ((void)(ptr), (void)(size))
58# include "internal/sanitizers.h"
62#ifndef HAVE_MALLOC_USABLE_SIZE
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)
72#ifdef HAVE_MALLOC_USABLE_SIZE
73# ifdef RUBY_ALTERNATIVE_MALLOC_HEADER
75# elif defined(HAVE_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>
84#ifdef HAVE_MALLOC_TRIM
89# include <emscripten/emmalloc.h>
93#ifdef HAVE_MACH_TASK_EXCEPTION_PORTS
94# include <mach/task.h>
95# include <mach/mach_init.h>
96# include <mach/mach_port.h>
100# define VM_CHECK_MODE RUBY_DEBUG
104#ifndef RACTOR_CHECK_MODE
105# define RACTOR_CHECK_MODE (VM_CHECK_MODE || RUBY_DEBUG) && (SIZEOF_UINT64_T == SIZEOF_VALUE)
108#ifndef RUBY_DEBUG_LOG
109# define RUBY_DEBUG_LOG(...)
112#ifndef GC_HEAP_INIT_SLOTS
113#define GC_HEAP_INIT_SLOTS 10000
115#ifndef GC_HEAP_FREE_SLOTS
116#define GC_HEAP_FREE_SLOTS 4096
118#ifndef GC_HEAP_GROWTH_FACTOR
119#define GC_HEAP_GROWTH_FACTOR 1.8
121#ifndef GC_HEAP_GROWTH_MAX_SLOTS
122#define GC_HEAP_GROWTH_MAX_SLOTS 0
124#ifndef GC_HEAP_REMEMBERED_WB_UNPROTECTED_OBJECTS_LIMIT_RATIO
125# define GC_HEAP_REMEMBERED_WB_UNPROTECTED_OBJECTS_LIMIT_RATIO 0.01
127#ifndef GC_HEAP_OLDOBJECT_LIMIT_FACTOR
128#define GC_HEAP_OLDOBJECT_LIMIT_FACTOR 2.0
131#ifndef GC_HEAP_FREE_SLOTS_MIN_RATIO
132#define GC_HEAP_FREE_SLOTS_MIN_RATIO 0.20
134#ifndef GC_HEAP_FREE_SLOTS_GOAL_RATIO
135#define GC_HEAP_FREE_SLOTS_GOAL_RATIO 0.40
137#ifndef GC_HEAP_FREE_SLOTS_MAX_RATIO
138#define GC_HEAP_FREE_SLOTS_MAX_RATIO 0.65
141#ifndef GC_MALLOC_LIMIT_MIN
142#define GC_MALLOC_LIMIT_MIN (16 * 1024 * 1024 )
144#ifndef GC_MALLOC_LIMIT_MAX
145#define GC_MALLOC_LIMIT_MAX (32 * 1024 * 1024 )
147#ifndef GC_MALLOC_LIMIT_GROWTH_FACTOR
148#define GC_MALLOC_LIMIT_GROWTH_FACTOR 1.4
151#ifndef GC_OLDMALLOC_LIMIT_MIN
152#define GC_OLDMALLOC_LIMIT_MIN (16 * 1024 * 1024 )
154#ifndef GC_OLDMALLOC_LIMIT_GROWTH_FACTOR
155#define GC_OLDMALLOC_LIMIT_GROWTH_FACTOR 1.2
157#ifndef GC_OLDMALLOC_LIMIT_MAX
158#define GC_OLDMALLOC_LIMIT_MAX (128 * 1024 * 1024 )
161#ifndef GC_MALLOC_INCREASE_LOCAL_THRESHOLD
162#define GC_MALLOC_INCREASE_LOCAL_THRESHOLD (8 * 1024 )
165#ifdef RB_THREAD_LOCAL_SPECIFIER
166#define USE_MALLOC_INCREASE_LOCAL 1
167static RB_THREAD_LOCAL_SPECIFIER
int malloc_increase_local;
169#define USE_MALLOC_INCREASE_LOCAL 0
172#ifndef GC_CAN_COMPILE_COMPACTION
174# define GC_CAN_COMPILE_COMPACTION 0
176# define GC_CAN_COMPILE_COMPACTION 1
180#ifndef PRINT_ENTER_EXIT_TICK
181# define PRINT_ENTER_EXIT_TICK 0
183#ifndef PRINT_ROOT_TICKS
184#define PRINT_ROOT_TICKS 0
187#define USE_TICK_T (PRINT_ENTER_EXIT_TICK || PRINT_ROOT_TICKS)
196 size_t allocated_objects_count;
197} rb_ractor_newobj_heap_cache_t;
200 size_t incremental_mark_step_allocated_slots;
201 rb_ractor_newobj_heap_cache_t heap_caches[HEAP_COUNT];
202} rb_ractor_newobj_cache_t;
205 size_t heap_init_slots[HEAP_COUNT];
206 size_t heap_free_slots;
207 double growth_factor;
208 size_t growth_max_slots;
210 double heap_free_slots_min_ratio;
211 double heap_free_slots_goal_ratio;
212 double heap_free_slots_max_ratio;
213 double uncollectible_wb_unprotected_objects_limit_ratio;
214 double oldobject_limit_factor;
216 size_t malloc_limit_min;
217 size_t malloc_limit_max;
218 double malloc_limit_growth_factor;
220 size_t oldmalloc_limit_min;
221 size_t oldmalloc_limit_max;
222 double oldmalloc_limit_growth_factor;
226 { GC_HEAP_INIT_SLOTS },
228 GC_HEAP_GROWTH_FACTOR,
229 GC_HEAP_GROWTH_MAX_SLOTS,
231 GC_HEAP_FREE_SLOTS_MIN_RATIO,
232 GC_HEAP_FREE_SLOTS_GOAL_RATIO,
233 GC_HEAP_FREE_SLOTS_MAX_RATIO,
234 GC_HEAP_REMEMBERED_WB_UNPROTECTED_OBJECTS_LIMIT_RATIO,
235 GC_HEAP_OLDOBJECT_LIMIT_FACTOR,
239 GC_MALLOC_LIMIT_GROWTH_FACTOR,
241 GC_OLDMALLOC_LIMIT_MIN,
242 GC_OLDMALLOC_LIMIT_MAX,
243 GC_OLDMALLOC_LIMIT_GROWTH_FACTOR,
262#define RGENGC_DEBUG -1
264#define RGENGC_DEBUG 0
267#if RGENGC_DEBUG < 0 && !defined(_MSC_VER)
268# define RGENGC_DEBUG_ENABLED(level) (-(RGENGC_DEBUG) >= (level) && ruby_rgengc_debug >= (level))
269#elif defined(HAVE_VA_ARGS_MACRO)
270# define RGENGC_DEBUG_ENABLED(level) ((RGENGC_DEBUG) >= (level))
272# define RGENGC_DEBUG_ENABLED(level) 0
274int ruby_rgengc_debug;
281#ifndef RGENGC_PROFILE
282# define RGENGC_PROFILE 0
291#ifndef RGENGC_ESTIMATE_OLDMALLOC
292# define RGENGC_ESTIMATE_OLDMALLOC 1
295#ifndef GC_PROFILE_MORE_DETAIL
296# define GC_PROFILE_MORE_DETAIL 0
298#ifndef GC_PROFILE_DETAIL_MEMORY
299# define GC_PROFILE_DETAIL_MEMORY 0
301#ifndef GC_ENABLE_LAZY_SWEEP
302# define GC_ENABLE_LAZY_SWEEP 1
304#ifndef CALC_EXACT_MALLOC_SIZE
305# define CALC_EXACT_MALLOC_SIZE 0
307#if defined(HAVE_MALLOC_USABLE_SIZE) || CALC_EXACT_MALLOC_SIZE > 0
308# ifndef MALLOC_ALLOCATED_SIZE
309# define MALLOC_ALLOCATED_SIZE 0
312# define MALLOC_ALLOCATED_SIZE 0
314#ifndef MALLOC_ALLOCATED_SIZE_CHECK
315# define MALLOC_ALLOCATED_SIZE_CHECK 0
318#ifndef GC_DEBUG_STRESS_TO_CLASS
319# define GC_DEBUG_STRESS_TO_CLASS RUBY_DEBUG
323 GPR_FLAG_NONE = 0x000,
325 GPR_FLAG_MAJOR_BY_NOFREE = 0x001,
326 GPR_FLAG_MAJOR_BY_OLDGEN = 0x002,
327 GPR_FLAG_MAJOR_BY_SHADY = 0x004,
328 GPR_FLAG_MAJOR_BY_FORCE = 0x008,
329#if RGENGC_ESTIMATE_OLDMALLOC
330 GPR_FLAG_MAJOR_BY_OLDMALLOC = 0x020,
332 GPR_FLAG_MAJOR_MASK = 0x0ff,
335 GPR_FLAG_NEWOBJ = 0x100,
336 GPR_FLAG_MALLOC = 0x200,
337 GPR_FLAG_METHOD = 0x400,
338 GPR_FLAG_CAPI = 0x800,
339 GPR_FLAG_STRESS = 0x1000,
342 GPR_FLAG_IMMEDIATE_SWEEP = 0x2000,
343 GPR_FLAG_HAVE_FINALIZE = 0x4000,
344 GPR_FLAG_IMMEDIATE_MARK = 0x8000,
345 GPR_FLAG_FULL_MARK = 0x10000,
346 GPR_FLAG_COMPACT = 0x20000,
349 (GPR_FLAG_FULL_MARK | GPR_FLAG_IMMEDIATE_MARK |
350 GPR_FLAG_IMMEDIATE_SWEEP | GPR_FLAG_CAPI),
351} gc_profile_record_flag;
357 double gc_invoke_time;
359 size_t heap_total_objects;
360 size_t heap_use_size;
361 size_t heap_total_size;
362 size_t moved_objects;
364#if GC_PROFILE_MORE_DETAIL
366 double gc_sweep_time;
368 size_t heap_use_pages;
369 size_t heap_live_objects;
370 size_t heap_free_objects;
372 size_t allocate_increase;
373 size_t allocate_limit;
376 size_t removing_objects;
377 size_t empty_objects;
378#if GC_PROFILE_DETAIL_MEMORY
384#if MALLOC_ALLOCATED_SIZE
385 size_t allocated_size;
388#if RGENGC_PROFILE > 0
390 size_t remembered_normal_objects;
391 size_t remembered_shady_objects;
399 uint32_t original_shape_id;
402#define RMOVED(obj) ((struct RMoved *)(obj))
404typedef uintptr_t bits_t;
406 BITS_SIZE =
sizeof(bits_t),
407 BITS_BITLENGTH = ( BITS_SIZE * CHAR_BIT )
420#define STACK_CHUNK_SIZE 500
423 VALUE data[STACK_CHUNK_SIZE];
428 stack_chunk_t *chunk;
429 stack_chunk_t *cache;
433 size_t unused_cache_size;
436typedef int (*gc_compact_compare_func)(
const void *l,
const void *r,
void *d);
440 bits_t slot_bits_mask;
443 size_t total_allocated_pages;
444 size_t force_major_gc_count;
445 size_t force_incremental_marking_finish_count;
446 size_t total_allocated_objects;
447 size_t total_freed_objects;
448 size_t final_slots_count;
455 struct ccan_list_head pages;
458 uintptr_t compact_cursor_index;
467 gc_stress_no_immediate_sweep,
468 gc_stress_full_mark_after_malloc,
482#if RGENGC_ESTIMATE_OLDMALLOC
483 size_t oldmalloc_increase;
489#if MALLOC_ALLOCATED_SIZE
490 size_t allocated_size;
500 unsigned int mode : 2;
501 unsigned int immediate_sweep : 1;
502 unsigned int dont_gc : 1;
503 unsigned int dont_incremental : 1;
504 unsigned int during_gc : 1;
505 unsigned int during_compacting : 1;
506 unsigned int during_reference_updating : 1;
507 unsigned int gc_stressful: 1;
508 unsigned int has_newobj_hook: 1;
509 unsigned int during_minor_gc : 1;
510 unsigned int during_incremental_marking : 1;
511 unsigned int measure_gc : 1;
516 rb_heap_t heaps[HEAP_COUNT];
517 size_t empty_pages_count;
524 mark_stack_t mark_stack;
530 size_t allocated_pages;
533 size_t freeable_pages;
535 size_t allocatable_slots;
538 VALUE deferred_final;
545 unsigned int latest_gc_info;
551#if GC_PROFILE_MORE_DETAIL
556 size_t minor_gc_count;
557 size_t major_gc_count;
558 size_t compact_count;
559 size_t read_barrier_faults;
560#if RGENGC_PROFILE > 0
561 size_t total_generated_normal_object_count;
562 size_t total_generated_shady_object_count;
563 size_t total_shade_operation_count;
564 size_t total_promoted_count;
565 size_t total_remembered_normal_object_count;
566 size_t total_remembered_shady_object_count;
568#if RGENGC_PROFILE >= 2
569 size_t generated_normal_object_count_types[
RUBY_T_MASK];
570 size_t generated_shady_object_count_types[
RUBY_T_MASK];
573 size_t remembered_normal_object_count_types[
RUBY_T_MASK];
574 size_t remembered_shady_object_count_types[
RUBY_T_MASK];
579 double gc_sweep_start_time;
580 size_t total_allocated_objects_at_gc_start;
581 size_t heap_used_at_gc_start;
585 unsigned long long marking_time_ns;
587 unsigned long long sweeping_time_ns;
588 struct timespec sweeping_start_time;
591 size_t weak_references_count;
592 size_t retained_weak_references_count;
595 VALUE gc_stress_mode;
598 bool parent_object_old_p;
602 size_t last_major_gc;
603 size_t uncollectible_wb_unprotected_objects;
604 size_t uncollectible_wb_unprotected_objects_limit;
606 size_t old_objects_limit;
608#if RGENGC_ESTIMATE_OLDMALLOC
609 size_t oldmalloc_increase_limit;
612#if RGENGC_CHECK_MODE >= 2
619 size_t considered_count_table[
T_MASK];
620 size_t moved_count_table[
T_MASK];
621 size_t moved_up_count_table[
T_MASK];
622 size_t moved_down_count_table[
T_MASK];
626 gc_compact_compare_func compare_func;
634#if GC_DEBUG_STRESS_TO_CLASS
635 VALUE stress_to_class;
638 rb_darray(
VALUE *) weak_references;
641 unsigned long live_ractor_cache_count;
643 int fork_vm_lock_lev;
646#ifndef HEAP_PAGE_ALIGN_LOG
648#define HEAP_PAGE_ALIGN_LOG 16
651#if RACTOR_CHECK_MODE || GC_DEBUG
652struct rvalue_overhead {
653# if RACTOR_CHECK_MODE
654 uint32_t _ractor_belonging_id;
663# define RVALUE_OVERHEAD (sizeof(struct { \
665 struct rvalue_overhead overhead; \
669size_t rb_gc_impl_obj_slot_size(
VALUE obj);
670# define GET_RVALUE_OVERHEAD(obj) ((struct rvalue_overhead *)((uintptr_t)obj + rb_gc_impl_obj_slot_size(obj)))
672# ifndef RVALUE_OVERHEAD
673# define RVALUE_OVERHEAD 0
677#define BASE_SLOT_SIZE (sizeof(struct RBasic) + sizeof(VALUE[RBIMPL_RVALUE_EMBED_LEN_MAX]) + RVALUE_OVERHEAD)
680# define MAX(a, b) (((a) > (b)) ? (a) : (b))
683# define MIN(a, b) (((a) < (b)) ? (a) : (b))
685#define roomof(x, y) (((x) + (y) - 1) / (y))
686#define CEILDIV(i, mod) roomof(i, mod)
688 HEAP_PAGE_ALIGN = (1UL << HEAP_PAGE_ALIGN_LOG),
689 HEAP_PAGE_ALIGN_MASK = (~(~0UL << HEAP_PAGE_ALIGN_LOG)),
690 HEAP_PAGE_SIZE = HEAP_PAGE_ALIGN,
691 HEAP_PAGE_OBJ_LIMIT = (
unsigned int)((HEAP_PAGE_SIZE -
sizeof(
struct heap_page_header)) / BASE_SLOT_SIZE),
692 HEAP_PAGE_BITMAP_LIMIT = CEILDIV(CEILDIV(HEAP_PAGE_SIZE, BASE_SLOT_SIZE), BITS_BITLENGTH),
693 HEAP_PAGE_BITMAP_SIZE = (BITS_SIZE * HEAP_PAGE_BITMAP_LIMIT),
695#define HEAP_PAGE_ALIGN (1 << HEAP_PAGE_ALIGN_LOG)
696#define HEAP_PAGE_SIZE HEAP_PAGE_ALIGN
698#if !defined(INCREMENTAL_MARK_STEP_ALLOCATIONS)
699# define INCREMENTAL_MARK_STEP_ALLOCATIONS 500
702#undef INIT_HEAP_PAGE_ALLOC_USE_MMAP
708static const bool HEAP_PAGE_ALLOC_USE_MMAP =
false;
710#elif defined(__wasm__)
714static const bool HEAP_PAGE_ALLOC_USE_MMAP =
false;
716#elif HAVE_CONST_PAGE_SIZE
718static const bool HEAP_PAGE_ALLOC_USE_MMAP = (PAGE_SIZE <= HEAP_PAGE_SIZE);
720#elif defined(PAGE_MAX_SIZE) && (PAGE_MAX_SIZE <= HEAP_PAGE_SIZE)
722static const bool HEAP_PAGE_ALLOC_USE_MMAP =
true;
724#elif defined(PAGE_SIZE)
726# define INIT_HEAP_PAGE_ALLOC_USE_MMAP (PAGE_SIZE <= HEAP_PAGE_SIZE)
728#elif defined(HAVE_SYSCONF) && defined(_SC_PAGE_SIZE)
730# define INIT_HEAP_PAGE_ALLOC_USE_MMAP (sysconf(_SC_PAGE_SIZE) <= HEAP_PAGE_SIZE)
734static const bool HEAP_PAGE_ALLOC_USE_MMAP =
false;
737#ifdef INIT_HEAP_PAGE_ALLOC_USE_MMAP
739# define HEAP_PAGE_ALLOC_USE_MMAP (heap_page_alloc_use_mmap != false)
741static bool heap_page_alloc_use_mmap;
744#define RVALUE_AGE_BIT_COUNT 2
745#define RVALUE_AGE_BIT_MASK (((bits_t)1 << RVALUE_AGE_BIT_COUNT) - 1)
746#define RVALUE_OLD_AGE 3
754 unsigned short slot_size;
755 unsigned short total_slots;
756 unsigned short free_slots;
757 unsigned short final_slots;
758 unsigned short pinned_slots;
760 unsigned int before_sweep : 1;
761 unsigned int has_remembered_objects : 1;
762 unsigned int has_uncollectible_wb_unprotected_objects : 1;
771 struct ccan_list_node page_node;
773 bits_t wb_unprotected_bits[HEAP_PAGE_BITMAP_LIMIT];
775 bits_t mark_bits[HEAP_PAGE_BITMAP_LIMIT];
776 bits_t uncollectible_bits[HEAP_PAGE_BITMAP_LIMIT];
777 bits_t marking_bits[HEAP_PAGE_BITMAP_LIMIT];
779 bits_t remembered_bits[HEAP_PAGE_BITMAP_LIMIT];
782 bits_t pinned_bits[HEAP_PAGE_BITMAP_LIMIT];
783 bits_t age_bits[HEAP_PAGE_BITMAP_LIMIT * RVALUE_AGE_BIT_COUNT];
790asan_lock_freelist(
struct heap_page *page)
792 asan_poison_memory_region(&page->freelist,
sizeof(
struct free_list *));
799asan_unlock_freelist(
struct heap_page *page)
801 asan_unpoison_memory_region(&page->freelist,
sizeof(
struct free_list *),
false);
805heap_page_in_global_empty_pages_pool(rb_objspace_t *
objspace,
struct heap_page *page)
807 if (page->total_slots == 0) {
808 GC_ASSERT(page->start == 0);
809 GC_ASSERT(page->slot_size == 0);
810 GC_ASSERT(page->heap == NULL);
811 GC_ASSERT(page->free_slots == 0);
812 asan_unpoisoning_memory_region(&page->freelist,
sizeof(&page->freelist)) {
813 GC_ASSERT(page->freelist == NULL);
819 GC_ASSERT(page->start != 0);
820 GC_ASSERT(page->slot_size != 0);
821 GC_ASSERT(page->heap != NULL);
827#define GET_PAGE_BODY(x) ((struct heap_page_body *)((bits_t)(x) & ~(HEAP_PAGE_ALIGN_MASK)))
828#define GET_PAGE_HEADER(x) (&GET_PAGE_BODY(x)->header)
829#define GET_HEAP_PAGE(x) (GET_PAGE_HEADER(x)->page)
831#define NUM_IN_PAGE(p) (((bits_t)(p) & HEAP_PAGE_ALIGN_MASK) / BASE_SLOT_SIZE)
832#define BITMAP_INDEX(p) (NUM_IN_PAGE(p) / BITS_BITLENGTH )
833#define BITMAP_OFFSET(p) (NUM_IN_PAGE(p) & (BITS_BITLENGTH-1))
834#define BITMAP_BIT(p) ((bits_t)1 << BITMAP_OFFSET(p))
837#define MARKED_IN_BITMAP(bits, p) ((bits)[BITMAP_INDEX(p)] & BITMAP_BIT(p))
838#define MARK_IN_BITMAP(bits, p) ((bits)[BITMAP_INDEX(p)] = (bits)[BITMAP_INDEX(p)] | BITMAP_BIT(p))
839#define CLEAR_IN_BITMAP(bits, p) ((bits)[BITMAP_INDEX(p)] = (bits)[BITMAP_INDEX(p)] & ~BITMAP_BIT(p))
842#define GET_HEAP_MARK_BITS(x) (&GET_HEAP_PAGE(x)->mark_bits[0])
843#define GET_HEAP_PINNED_BITS(x) (&GET_HEAP_PAGE(x)->pinned_bits[0])
844#define GET_HEAP_UNCOLLECTIBLE_BITS(x) (&GET_HEAP_PAGE(x)->uncollectible_bits[0])
845#define GET_HEAP_WB_UNPROTECTED_BITS(x) (&GET_HEAP_PAGE(x)->wb_unprotected_bits[0])
846#define GET_HEAP_MARKING_BITS(x) (&GET_HEAP_PAGE(x)->marking_bits[0])
848#define RVALUE_AGE_BITMAP_INDEX(n) (NUM_IN_PAGE(n) / (BITS_BITLENGTH / RVALUE_AGE_BIT_COUNT))
849#define RVALUE_AGE_BITMAP_OFFSET(n) ((NUM_IN_PAGE(n) % (BITS_BITLENGTH / RVALUE_AGE_BIT_COUNT)) * RVALUE_AGE_BIT_COUNT)
852RVALUE_AGE_GET(
VALUE obj)
854 bits_t *age_bits = GET_HEAP_PAGE(obj)->age_bits;
855 return (
int)(age_bits[RVALUE_AGE_BITMAP_INDEX(obj)] >> RVALUE_AGE_BITMAP_OFFSET(obj)) & RVALUE_AGE_BIT_MASK;
859RVALUE_AGE_SET_BITMAP(
VALUE obj,
int age)
862 bits_t *age_bits = GET_HEAP_PAGE(obj)->age_bits;
864 age_bits[RVALUE_AGE_BITMAP_INDEX(obj)] &= ~(RVALUE_AGE_BIT_MASK << (RVALUE_AGE_BITMAP_OFFSET(obj)));
866 age_bits[RVALUE_AGE_BITMAP_INDEX(obj)] |= ((bits_t)age << RVALUE_AGE_BITMAP_OFFSET(obj));
870RVALUE_AGE_SET(
VALUE obj,
int age)
872 RVALUE_AGE_SET_BITMAP(obj, age);
873 if (age == RVALUE_OLD_AGE) {
881#define malloc_limit objspace->malloc_params.limit
882#define malloc_increase objspace->malloc_counters.increase
883#define malloc_allocated_size objspace->malloc_params.allocated_size
884#define heap_pages_lomem objspace->heap_pages.range[0]
885#define heap_pages_himem objspace->heap_pages.range[1]
886#define heap_pages_freeable_pages objspace->heap_pages.freeable_pages
887#define heap_pages_deferred_final objspace->heap_pages.deferred_final
888#define heaps objspace->heaps
889#define during_gc objspace->flags.during_gc
890#define finalizing objspace->atomic_flags.finalizing
891#define finalizer_table objspace->finalizer_table
892#define ruby_gc_stressful objspace->flags.gc_stressful
893#define ruby_gc_stress_mode objspace->gc_stress_mode
894#if GC_DEBUG_STRESS_TO_CLASS
895#define stress_to_class objspace->stress_to_class
896#define set_stress_to_class(c) (stress_to_class = (c))
898#define stress_to_class ((void)objspace, 0)
899#define set_stress_to_class(c) ((void)objspace, (c))
903#define dont_gc_on() (fprintf(stderr, "dont_gc_on@%s:%d\n", __FILE__, __LINE__), objspace->flags.dont_gc = 1)
904#define dont_gc_off() (fprintf(stderr, "dont_gc_off@%s:%d\n", __FILE__, __LINE__), objspace->flags.dont_gc = 0)
905#define dont_gc_set(b) (fprintf(stderr, "dont_gc_set(%d)@%s:%d\n", __FILE__, __LINE__), objspace->flags.dont_gc = (int)(b))
906#define dont_gc_val() (objspace->flags.dont_gc)
908#define dont_gc_on() (objspace->flags.dont_gc = 1)
909#define dont_gc_off() (objspace->flags.dont_gc = 0)
910#define dont_gc_set(b) (objspace->flags.dont_gc = (int)(b))
911#define dont_gc_val() (objspace->flags.dont_gc)
914#define gc_config_full_mark_set(b) (objspace->gc_config.full_mark = (int)(b))
915#define gc_config_full_mark_val (objspace->gc_config.full_mark)
917#ifndef DURING_GC_COULD_MALLOC_REGION_START
918# define DURING_GC_COULD_MALLOC_REGION_START() \
919 assert(rb_during_gc()); \
920 bool _prev_enabled = rb_gc_impl_gc_enabled_p(objspace); \
921 rb_gc_impl_gc_disable(objspace, false)
924#ifndef DURING_GC_COULD_MALLOC_REGION_END
925# define DURING_GC_COULD_MALLOC_REGION_END() \
926 if (_prev_enabled) rb_gc_impl_gc_enable(objspace)
929static inline enum gc_mode
930gc_mode_verify(
enum gc_mode mode)
932#if RGENGC_CHECK_MODE > 0
935 case gc_mode_marking:
936 case gc_mode_sweeping:
937 case gc_mode_compacting:
940 rb_bug(
"gc_mode_verify: unreachable (%d)", (
int)mode);
947has_sweeping_pages(rb_objspace_t *
objspace)
949 for (
int i = 0; i < HEAP_COUNT; i++) {
950 if ((&heaps[i])->sweeping_page) {
958heap_eden_total_pages(rb_objspace_t *
objspace)
961 for (
int i = 0; i < HEAP_COUNT; i++) {
962 count += (&heaps[i])->total_pages;
968total_allocated_objects(rb_objspace_t *
objspace)
971 for (
int i = 0; i < HEAP_COUNT; i++) {
972 rb_heap_t *heap = &heaps[i];
973 count += heap->total_allocated_objects;
979total_freed_objects(rb_objspace_t *
objspace)
982 for (
int i = 0; i < HEAP_COUNT; i++) {
983 rb_heap_t *heap = &heaps[i];
984 count += heap->total_freed_objects;
990total_final_slots_count(rb_objspace_t *
objspace)
993 for (
int i = 0; i < HEAP_COUNT; i++) {
994 rb_heap_t *heap = &heaps[i];
995 count += heap->final_slots_count;
1000#define gc_mode(objspace) gc_mode_verify((enum gc_mode)(objspace)->flags.mode)
1001#define gc_mode_set(objspace, m) ((objspace)->flags.mode = (unsigned int)gc_mode_verify(m))
1002#define gc_needs_major_flags objspace->rgengc.need_major_gc
1004#define is_marking(objspace) (gc_mode(objspace) == gc_mode_marking)
1005#define is_sweeping(objspace) (gc_mode(objspace) == gc_mode_sweeping)
1006#define is_full_marking(objspace) ((objspace)->flags.during_minor_gc == FALSE)
1007#define is_incremental_marking(objspace) ((objspace)->flags.during_incremental_marking != FALSE)
1008#define will_be_incremental_marking(objspace) ((objspace)->rgengc.need_major_gc != GPR_FLAG_NONE)
1009#define GC_INCREMENTAL_SWEEP_SLOT_COUNT 2048
1010#define GC_INCREMENTAL_SWEEP_POOL_SLOT_COUNT 1024
1011#define is_lazy_sweeping(objspace) (GC_ENABLE_LAZY_SWEEP && has_sweeping_pages(objspace))
1013#define needs_continue_sweeping(objspace, heap) \
1014 ((heap)->free_pages == NULL && is_lazy_sweeping(objspace))
1016#if SIZEOF_LONG == SIZEOF_VOIDP
1017# define obj_id_to_ref(objid) ((objid) ^ FIXNUM_FLAG)
1018#elif SIZEOF_LONG_LONG == SIZEOF_VOIDP
1019# define obj_id_to_ref(objid) (FIXNUM_P(objid) ? \
1020 ((objid) ^ FIXNUM_FLAG) : (NUM2PTR(objid) << 1))
1022# error not supported
1028 void (*dfree)(
void *);
1032#define RZOMBIE(o) ((struct RZombie *)(o))
1034static bool ruby_enable_autocompact =
false;
1035#if RGENGC_CHECK_MODE
1036static gc_compact_compare_func ruby_autocompact_compare_func;
1039static void init_mark_stack(mark_stack_t *stack);
1040static int garbage_collect(rb_objspace_t *,
unsigned int reason);
1042static int gc_start(rb_objspace_t *
objspace,
unsigned int reason);
1043static void gc_rest(rb_objspace_t *
objspace);
1045enum gc_enter_event {
1046 gc_enter_event_start,
1047 gc_enter_event_continue,
1048 gc_enter_event_rest,
1049 gc_enter_event_finalizer,
1052static inline void gc_enter(rb_objspace_t *
objspace,
enum gc_enter_event event,
unsigned int *lock_lev);
1053static inline void gc_exit(rb_objspace_t *
objspace,
enum gc_enter_event event,
unsigned int *lock_lev);
1054static void gc_marking_enter(rb_objspace_t *
objspace);
1055static void gc_marking_exit(rb_objspace_t *
objspace);
1056static void gc_sweeping_enter(rb_objspace_t *
objspace);
1057static void gc_sweeping_exit(rb_objspace_t *
objspace);
1058static bool gc_marks_continue(rb_objspace_t *
objspace, rb_heap_t *heap);
1060static void gc_sweep(rb_objspace_t *
objspace);
1061static void gc_sweep_finish_heap(rb_objspace_t *
objspace, rb_heap_t *heap);
1062static void gc_sweep_continue(rb_objspace_t *
objspace, rb_heap_t *heap);
1068static int gc_mark_stacked_objects_incremental(rb_objspace_t *,
size_t count);
1069NO_SANITIZE(
"memory",
static inline bool is_pointer_to_heap(rb_objspace_t *
objspace,
const void *
ptr));
1071static void gc_verify_internal_consistency(
void *objspace_ptr);
1073static double getrusage_time(
void);
1074static inline void gc_prof_setup_new_record(rb_objspace_t *
objspace,
unsigned int reason);
1075static inline void gc_prof_timer_start(rb_objspace_t *);
1076static inline void gc_prof_timer_stop(rb_objspace_t *);
1077static inline void gc_prof_mark_timer_start(rb_objspace_t *);
1078static inline void gc_prof_mark_timer_stop(rb_objspace_t *);
1079static inline void gc_prof_sweep_timer_start(rb_objspace_t *);
1080static inline void gc_prof_sweep_timer_stop(rb_objspace_t *);
1081static inline void gc_prof_set_malloc_info(rb_objspace_t *);
1082static inline void gc_prof_set_heap_info(rb_objspace_t *);
1084#define gc_prof_record(objspace) (objspace)->profile.current_record
1085#define gc_prof_enabled(objspace) ((objspace)->profile.run && (objspace)->profile.current_record)
1087#ifdef HAVE_VA_ARGS_MACRO
1088# define gc_report(level, objspace, ...) \
1089 if (!RGENGC_DEBUG_ENABLED(level)) {} else gc_report_body(level, objspace, __VA_ARGS__)
1091# define gc_report if (!RGENGC_DEBUG_ENABLED(0)) {} else gc_report_body
1093PRINTF_ARGS(
static void gc_report_body(
int level, rb_objspace_t *
objspace,
const char *fmt, ...), 3, 4);
1095static void gc_finalize_deferred(
void *dmy);
1106#if defined(__GNUC__) && defined(__i386__)
1107typedef unsigned long long tick_t;
1108#define PRItick "llu"
1112 unsigned long long int x;
1113 __asm__ __volatile__ (
"rdtsc" :
"=A" (x));
1117#elif defined(__GNUC__) && defined(__x86_64__)
1118typedef unsigned long long tick_t;
1119#define PRItick "llu"
1121static __inline__ tick_t
1124 unsigned long hi, lo;
1125 __asm__ __volatile__ (
"rdtsc" :
"=a"(lo),
"=d"(hi));
1126 return ((
unsigned long long)lo)|( ((
unsigned long long)hi)<<32);
1129#elif defined(__powerpc64__) && (GCC_VERSION_SINCE(4,8,0) || defined(__clang__))
1130typedef unsigned long long tick_t;
1131#define PRItick "llu"
1133static __inline__ tick_t
1136 unsigned long long val = __builtin_ppc_get_timebase();
1140#elif defined(__POWERPC__) && defined(__APPLE__)
1144typedef unsigned long long tick_t;
1145#define PRItick "llu"
1147static __inline__ tick_t
1150 unsigned long int upper, lower, tmp;
1151 # define mftbu(r) __asm__ volatile("mftbu %0" : "=r"(r))
1152 # define mftb(r) __asm__ volatile("mftb %0" : "=r"(r))
1157 }
while (tmp != upper);
1158 return ((tick_t)upper << 32) | lower;
1161#elif defined(__aarch64__) && defined(__GNUC__)
1162typedef unsigned long tick_t;
1165static __inline__ tick_t
1169 __asm__ __volatile__ (
"mrs %0, cntvct_el0" :
"=r" (val));
1174#elif defined(_WIN32) && defined(_MSC_VER)
1176typedef unsigned __int64 tick_t;
1177#define PRItick "llu"
1186typedef clock_t tick_t;
1187#define PRItick "llu"
1196#define MEASURE_LINE(expr) expr
1199static inline VALUE check_rvalue_consistency(rb_objspace_t *
objspace,
const VALUE obj);
1201#define RVALUE_MARKED_BITMAP(obj) MARKED_IN_BITMAP(GET_HEAP_MARK_BITS(obj), (obj))
1202#define RVALUE_WB_UNPROTECTED_BITMAP(obj) MARKED_IN_BITMAP(GET_HEAP_WB_UNPROTECTED_BITS(obj), (obj))
1203#define RVALUE_MARKING_BITMAP(obj) MARKED_IN_BITMAP(GET_HEAP_MARKING_BITS(obj), (obj))
1204#define RVALUE_UNCOLLECTIBLE_BITMAP(obj) MARKED_IN_BITMAP(GET_HEAP_UNCOLLECTIBLE_BITS(obj), (obj))
1205#define RVALUE_PINNED_BITMAP(obj) MARKED_IN_BITMAP(GET_HEAP_PINNED_BITS(obj), (obj))
1210 check_rvalue_consistency(
objspace, obj);
1211 return RVALUE_MARKED_BITMAP(obj) != 0;
1217 check_rvalue_consistency(
objspace, obj);
1218 return RVALUE_PINNED_BITMAP(obj) != 0;
1224 check_rvalue_consistency(
objspace, obj);
1225 return RVALUE_WB_UNPROTECTED_BITMAP(obj) != 0;
1231 check_rvalue_consistency(
objspace, obj);
1232 return RVALUE_MARKING_BITMAP(obj) != 0;
1238 check_rvalue_consistency(
objspace, obj);
1239 return MARKED_IN_BITMAP(GET_HEAP_PAGE(obj)->remembered_bits, obj) != 0;
1245 check_rvalue_consistency(
objspace, obj);
1246 return RVALUE_UNCOLLECTIBLE_BITMAP(obj) != 0;
1249#define RVALUE_PAGE_WB_UNPROTECTED(page, obj) MARKED_IN_BITMAP((page)->wb_unprotected_bits, (obj))
1250#define RVALUE_PAGE_UNCOLLECTIBLE(page, obj) MARKED_IN_BITMAP((page)->uncollectible_bits, (obj))
1251#define RVALUE_PAGE_MARKING(page, obj) MARKED_IN_BITMAP((page)->marking_bits, (obj))
1253static int rgengc_remember(rb_objspace_t *
objspace,
VALUE obj);
1254static void rgengc_mark_and_rememberset_clear(rb_objspace_t *
objspace, rb_heap_t *heap);
1255static void rgengc_rememberset_mark(rb_objspace_t *
objspace, rb_heap_t *heap);
1258check_rvalue_consistency_force(rb_objspace_t *
objspace,
const VALUE obj,
int terminate)
1262 int lev = RB_GC_VM_LOCK_NO_BARRIER();
1265 fprintf(stderr,
"check_rvalue_consistency: %p is a special const.\n", (
void *)obj);
1268 else if (!is_pointer_to_heap(
objspace, (
void *)obj)) {
1270 while (empty_page) {
1271 if ((uintptr_t)empty_page->body <= (uintptr_t)obj &&
1272 (uintptr_t)obj < (uintptr_t)empty_page->body + HEAP_PAGE_SIZE) {
1273 GC_ASSERT(heap_page_in_global_empty_pages_pool(
objspace, empty_page));
1274 fprintf(stderr,
"check_rvalue_consistency: %p is in an empty page (%p).\n",
1275 (
void *)obj, (
void *)empty_page);
1280 fprintf(stderr,
"check_rvalue_consistency: %p is not a Ruby object.\n", (
void *)obj);
1286 const int wb_unprotected_bit = RVALUE_WB_UNPROTECTED_BITMAP(obj) != 0;
1287 const int uncollectible_bit = RVALUE_UNCOLLECTIBLE_BITMAP(obj) != 0;
1288 const int mark_bit = RVALUE_MARKED_BITMAP(obj) != 0;
1289 const int marking_bit = RVALUE_MARKING_BITMAP(obj) != 0;
1290 const int remembered_bit = MARKED_IN_BITMAP(GET_HEAP_PAGE(obj)->remembered_bits, obj) != 0;
1291 const int age = RVALUE_AGE_GET((
VALUE)obj);
1293 if (heap_page_in_global_empty_pages_pool(
objspace, GET_HEAP_PAGE(obj))) {
1294 fprintf(stderr,
"check_rvalue_consistency: %s is in tomb page.\n", rb_obj_info(obj));
1298 fprintf(stderr,
"check_rvalue_consistency: %s is T_NONE.\n", rb_obj_info(obj));
1302 fprintf(stderr,
"check_rvalue_consistency: %s is T_ZOMBIE.\n", rb_obj_info(obj));
1307 rb_obj_memsize_of((
VALUE)obj);
1314 if (age > 0 && wb_unprotected_bit) {
1315 fprintf(stderr,
"check_rvalue_consistency: %s is not WB protected, but age is %d > 0.\n", rb_obj_info(obj), age);
1319 if (!is_marking(
objspace) && uncollectible_bit && !mark_bit) {
1320 fprintf(stderr,
"check_rvalue_consistency: %s is uncollectible, but is not marked while !gc.\n", rb_obj_info(obj));
1325 if (uncollectible_bit && age != RVALUE_OLD_AGE && !wb_unprotected_bit) {
1326 fprintf(stderr,
"check_rvalue_consistency: %s is uncollectible, but not old (age: %d) and not WB unprotected.\n",
1327 rb_obj_info(obj), age);
1330 if (remembered_bit && age != RVALUE_OLD_AGE) {
1331 fprintf(stderr,
"check_rvalue_consistency: %s is remembered, but not old (age: %d).\n",
1332 rb_obj_info(obj), age);
1344 if (is_incremental_marking(
objspace) && marking_bit) {
1345 if (!is_marking(
objspace) && !mark_bit) {
1346 fprintf(stderr,
"check_rvalue_consistency: %s is marking, but not marked.\n", rb_obj_info(obj));
1352 RB_GC_VM_UNLOCK_NO_BARRIER(lev);
1354 if (err > 0 && terminate) {
1355 rb_bug(
"check_rvalue_consistency_force: there is %d errors.", err);
1360#if RGENGC_CHECK_MODE == 0
1362check_rvalue_consistency(rb_objspace_t *
objspace,
const VALUE obj)
1368check_rvalue_consistency(rb_objspace_t *
objspace,
const VALUE obj)
1370 check_rvalue_consistency_force(
objspace, obj, TRUE);
1380 asan_unpoisoning_object(obj) {
1389 GC_ASSERT(!RB_SPECIAL_CONST_P(obj));
1390 check_rvalue_consistency(
objspace, obj);
1393 return RB_OBJ_PROMOTED_RAW(obj);
1399 MARK_IN_BITMAP(&page->uncollectible_bits[0], obj);
1402#if RGENGC_PROFILE >= 2
1403 objspace->profile.total_promoted_count++;
1409RVALUE_OLD_UNCOLLECTIBLE_SET(rb_objspace_t *
objspace,
VALUE obj)
1411 RB_DEBUG_COUNTER_INC(obj_promote);
1412 RVALUE_PAGE_OLD_UNCOLLECTIBLE_SET(
objspace, GET_HEAP_PAGE(obj), obj);
1419 int age = RVALUE_AGE_GET((
VALUE)obj);
1421 if (RGENGC_CHECK_MODE && age == RVALUE_OLD_AGE) {
1422 rb_bug(
"RVALUE_AGE_INC: can not increment age of OLD object %s.", rb_obj_info(obj));
1426 RVALUE_AGE_SET(obj, age);
1428 if (age == RVALUE_OLD_AGE) {
1429 RVALUE_OLD_UNCOLLECTIBLE_SET(
objspace, obj);
1432 check_rvalue_consistency(
objspace, obj);
1438 check_rvalue_consistency(
objspace, obj);
1439 GC_ASSERT(!RVALUE_OLD_P(
objspace, obj));
1440 RVALUE_AGE_SET(obj, RVALUE_OLD_AGE - 1);
1441 check_rvalue_consistency(
objspace, obj);
1445RVALUE_AGE_RESET(
VALUE obj)
1447 RVALUE_AGE_SET(obj, 0);
1453 check_rvalue_consistency(
objspace, obj);
1454 GC_ASSERT(RVALUE_OLD_P(
objspace, obj));
1456 if (!is_incremental_marking(
objspace) && RVALUE_REMEMBERED(
objspace, obj)) {
1457 CLEAR_IN_BITMAP(GET_HEAP_PAGE(obj)->remembered_bits, obj);
1460 CLEAR_IN_BITMAP(GET_HEAP_UNCOLLECTIBLE_BITS(obj), obj);
1461 RVALUE_AGE_RESET(obj);
1463 if (RVALUE_MARKED(
objspace, obj)) {
1467 check_rvalue_consistency(
objspace, obj);
1479 return !RVALUE_MARKED(
objspace, obj);
1483rb_gc_impl_gc_enabled_p(
void *objspace_ptr)
1485 rb_objspace_t *
objspace = objspace_ptr;
1486 return !dont_gc_val();
1490rb_gc_impl_gc_enable(
void *objspace_ptr)
1492 rb_objspace_t *
objspace = objspace_ptr;
1498rb_gc_impl_gc_disable(
void *objspace_ptr,
bool finish_current_gc)
1500 rb_objspace_t *
objspace = objspace_ptr;
1502 if (finish_current_gc) {
1516 return calloc(1, n);
1520rb_gc_impl_set_event_hook(
void *objspace_ptr,
const rb_event_flag_t event)
1522 rb_objspace_t *
objspace = objspace_ptr;
1528rb_gc_impl_get_total_time(
void *objspace_ptr)
1530 rb_objspace_t *
objspace = objspace_ptr;
1532 unsigned long long marking_time =
objspace->profile.marking_time_ns;
1533 unsigned long long sweeping_time =
objspace->profile.sweeping_time_ns;
1535 return marking_time + sweeping_time;
1539rb_gc_impl_set_measure_total_time(
void *objspace_ptr,
VALUE flag)
1541 rb_objspace_t *
objspace = objspace_ptr;
1547rb_gc_impl_get_measure_total_time(
void *objspace_ptr)
1549 rb_objspace_t *
objspace = objspace_ptr;
1555minimum_slots_for_heap(rb_objspace_t *
objspace, rb_heap_t *heap)
1557 size_t heap_idx = heap - heaps;
1558 return gc_params.heap_init_slots[heap_idx];
1563rb_gc_impl_garbage_object_p(
void *objspace_ptr,
VALUE ptr)
1565 rb_objspace_t *
objspace = objspace_ptr;
1569 asan_unpoisoning_object(
ptr) {
1581 if (dead)
return true;
1582 return is_lazy_sweeping(
objspace) && GET_HEAP_PAGE(
ptr)->flags.before_sweep &&
1586static void free_stack_chunks(mark_stack_t *);
1587static void mark_stack_free_cache(mark_stack_t *);
1593 rb_asan_unpoison_object(obj,
false);
1595 asan_unlock_freelist(page);
1599 slot->next = page->freelist;
1600 page->freelist = slot;
1601 asan_lock_freelist(page);
1604 GC_ASSERT(RVALUE_AGE_GET(obj) == 0);
1606 if (RGENGC_CHECK_MODE &&
1608 !(page->start <= (uintptr_t)obj &&
1609 (uintptr_t)obj < ((uintptr_t)page->start + (page->total_slots * page->slot_size)) &&
1610 obj % BASE_SLOT_SIZE == 0)) {
1611 rb_bug(
"heap_page_add_freeobj: %p is not rvalue.", (
void *)obj);
1614 rb_asan_poison_object(obj);
1615 gc_report(3,
objspace,
"heap_page_add_freeobj: add %p to freelist\n", (
void *)obj);
1619heap_allocatable_slots_expand(rb_objspace_t *
objspace,
1620 rb_heap_t *heap,
size_t free_slots,
size_t total_slots)
1622 double goal_ratio = gc_params.heap_free_slots_goal_ratio;
1623 size_t target_total_slots;
1625 if (goal_ratio == 0.0) {
1626 target_total_slots = (size_t)(total_slots * gc_params.growth_factor);
1628 else if (total_slots == 0) {
1629 target_total_slots = minimum_slots_for_heap(
objspace, heap);
1635 double f = (double)(total_slots - free_slots) / ((1 - goal_ratio) * total_slots);
1637 if (f > gc_params.growth_factor) f = gc_params.growth_factor;
1638 if (f < 1.0) f = 1.1;
1640 target_total_slots = (size_t)(f * total_slots);
1644 "free_slots(%8"PRIuSIZE
")/total_slots(%8"PRIuSIZE
")=%1.2f,"
1645 " G(%1.2f), f(%1.2f),"
1646 " total_slots(%8"PRIuSIZE
") => target_total_slots(%8"PRIuSIZE
")\n",
1647 free_slots, total_slots, free_slots/(
double)total_slots,
1648 goal_ratio, f, total_slots, target_total_slots);
1652 if (gc_params.growth_max_slots > 0) {
1653 size_t max_total_slots = (size_t)(total_slots + gc_params.growth_max_slots);
1654 if (target_total_slots > max_total_slots) target_total_slots = max_total_slots;
1657 size_t extend_slot_count = target_total_slots - total_slots;
1659 if (extend_slot_count == 0) extend_slot_count = 1;
1661 objspace->heap_pages.allocatable_slots += extend_slot_count;
1665heap_add_freepage(rb_heap_t *heap,
struct heap_page *page)
1667 asan_unlock_freelist(page);
1668 GC_ASSERT(page->free_slots != 0);
1669 GC_ASSERT(page->freelist != NULL);
1671 page->free_next = heap->free_pages;
1672 heap->free_pages = page;
1674 RUBY_DEBUG_LOG(
"page:%p freelist:%p", (
void *)page, (
void *)page->freelist);
1676 asan_lock_freelist(page);
1680heap_add_poolpage(rb_objspace_t *
objspace, rb_heap_t *heap,
struct heap_page *page)
1682 asan_unlock_freelist(page);
1683 GC_ASSERT(page->free_slots != 0);
1684 GC_ASSERT(page->freelist != NULL);
1686 page->free_next = heap->pooled_pages;
1687 heap->pooled_pages = page;
1688 objspace->rincgc.pooled_slots += page->free_slots;
1690 asan_lock_freelist(page);
1694heap_unlink_page(rb_objspace_t *
objspace, rb_heap_t *heap,
struct heap_page *page)
1696 ccan_list_del(&page->page_node);
1697 heap->total_pages--;
1698 heap->total_slots -= page->total_slots;
1702gc_aligned_free(
void *
ptr,
size_t size)
1704#if defined __MINGW32__
1705 __mingw_aligned_free(
ptr);
1708#elif defined(HAVE_POSIX_MEMALIGN) || defined(HAVE_MEMALIGN)
1711 free(((
void**)
ptr)[-1]);
1718 GC_ASSERT((uintptr_t)page_body % HEAP_PAGE_ALIGN == 0);
1720 if (HEAP_PAGE_ALLOC_USE_MMAP) {
1722 GC_ASSERT(HEAP_PAGE_SIZE % sysconf(_SC_PAGE_SIZE) == 0);
1723 if (munmap(page_body, HEAP_PAGE_SIZE)) {
1724 rb_bug(
"heap_page_body_free: munmap failed");
1729 gc_aligned_free(page_body, HEAP_PAGE_SIZE);
1736 objspace->heap_pages.freed_pages++;
1737 heap_page_body_free(page->body);
1742heap_pages_free_unused_pages(rb_objspace_t *
objspace)
1744 if (
objspace->empty_pages != NULL && heap_pages_freeable_pages > 0) {
1745 GC_ASSERT(
objspace->empty_pages_count > 0);
1750 for (i = j = 0; i < rb_darray_size(
objspace->heap_pages.sorted); i++) {
1753 if (heap_page_in_global_empty_pages_pool(
objspace, page) && heap_pages_freeable_pages > 0) {
1755 heap_pages_freeable_pages--;
1758 if (heap_page_in_global_empty_pages_pool(
objspace, page)) {
1759 page->free_next =
objspace->empty_pages;
1765 rb_darray_set(
objspace->heap_pages.sorted, j, page);
1771 rb_darray_pop(
objspace->heap_pages.sorted, i - j);
1772 GC_ASSERT(rb_darray_size(
objspace->heap_pages.sorted) == j);
1775 uintptr_t himem = (uintptr_t)hipage->body + HEAP_PAGE_SIZE;
1776 GC_ASSERT(himem <= heap_pages_himem);
1777 heap_pages_himem = himem;
1780 uintptr_t lomem = (uintptr_t)lopage->body +
sizeof(
struct heap_page_header);
1781 GC_ASSERT(lomem >= heap_pages_lomem);
1782 heap_pages_lomem = lomem;
1787gc_aligned_malloc(
size_t alignment,
size_t size)
1790 GC_ASSERT(((alignment - 1) & alignment) == 0);
1791 GC_ASSERT(alignment %
sizeof(
void*) == 0);
1795#if defined __MINGW32__
1796 res = __mingw_aligned_malloc(size, alignment);
1798 void *_aligned_malloc(
size_t,
size_t);
1799 res = _aligned_malloc(size, alignment);
1800#elif defined(HAVE_POSIX_MEMALIGN)
1801 if (posix_memalign(&res, alignment, size) != 0) {
1804#elif defined(HAVE_MEMALIGN)
1805 res = memalign(alignment, size);
1808 res = malloc(alignment + size +
sizeof(
void*));
1809 aligned = (
char*)res + alignment +
sizeof(
void*);
1810 aligned -= ((
VALUE)aligned & (alignment - 1));
1811 ((
void**)aligned)[-1] = res;
1812 res = (
void*)aligned;
1815 GC_ASSERT((uintptr_t)res % alignment == 0);
1821heap_page_body_allocate(
void)
1825 if (HEAP_PAGE_ALLOC_USE_MMAP) {
1827 GC_ASSERT(HEAP_PAGE_ALIGN % sysconf(_SC_PAGE_SIZE) == 0);
1829 size_t mmap_size = HEAP_PAGE_ALIGN + HEAP_PAGE_SIZE;
1830 char *
ptr = mmap(NULL, mmap_size,
1831 PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
1832 if (
ptr == MAP_FAILED) {
1841#if defined(HAVE_SYS_PRCTL_H) && defined(PR_SET_VMA) && defined(PR_SET_VMA_ANON_NAME)
1842 prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME,
ptr, mmap_size,
"Ruby:GC:default:heap_page_body_allocate");
1846 char *aligned =
ptr + HEAP_PAGE_ALIGN;
1847 aligned -= ((
VALUE)aligned & (HEAP_PAGE_ALIGN - 1));
1848 GC_ASSERT(aligned >
ptr);
1849 GC_ASSERT(aligned <=
ptr + HEAP_PAGE_ALIGN);
1851 size_t start_out_of_range_size = aligned -
ptr;
1852 GC_ASSERT(start_out_of_range_size % sysconf(_SC_PAGE_SIZE) == 0);
1853 if (start_out_of_range_size > 0) {
1854 if (munmap(
ptr, start_out_of_range_size)) {
1855 rb_bug(
"heap_page_body_allocate: munmap failed for start");
1859 size_t end_out_of_range_size = HEAP_PAGE_ALIGN - start_out_of_range_size;
1860 GC_ASSERT(end_out_of_range_size % sysconf(_SC_PAGE_SIZE) == 0);
1861 if (end_out_of_range_size > 0) {
1862 if (munmap(aligned + HEAP_PAGE_SIZE, end_out_of_range_size)) {
1863 rb_bug(
"heap_page_body_allocate: munmap failed for end");
1871 page_body = gc_aligned_malloc(HEAP_PAGE_ALIGN, HEAP_PAGE_SIZE);
1874 GC_ASSERT((uintptr_t)page_body % HEAP_PAGE_ALIGN == 0);
1880heap_page_resurrect(rb_objspace_t *
objspace)
1883 if (
objspace->empty_pages == NULL) {
1884 GC_ASSERT(
objspace->empty_pages_count == 0);
1887 GC_ASSERT(
objspace->empty_pages_count > 0);
1890 objspace->empty_pages = page->free_next;
1897heap_page_allocate(rb_objspace_t *
objspace)
1900 if (page_body == 0) {
1906 heap_page_body_free(page_body);
1911 uintptr_t end = (uintptr_t)page_body + HEAP_PAGE_SIZE;
1914 size_t hi = rb_darray_size(
objspace->heap_pages.sorted);
1918 size_t mid = (lo + hi) / 2;
1919 mid_page = rb_darray_get(
objspace->heap_pages.sorted, mid);
1920 if ((uintptr_t)mid_page->start < start) {
1923 else if ((uintptr_t)mid_page->start > start) {
1927 rb_bug(
"same heap page is allocated: %p at %"PRIuVALUE, (
void *)page_body, (
VALUE)mid);
1931 rb_darray_insert_without_gc(&
objspace->heap_pages.sorted, hi, page);
1933 if (heap_pages_lomem == 0 || heap_pages_lomem > start) heap_pages_lomem = start;
1934 if (heap_pages_himem < end) heap_pages_himem = end;
1936 page->body = page_body;
1937 page_body->header.page = page;
1939 objspace->heap_pages.allocated_pages++;
1948 GC_ASSERT(!heap->sweeping_page);
1949 GC_ASSERT(heap_page_in_global_empty_pages_pool(
objspace, page));
1953 if (start % BASE_SLOT_SIZE != 0) {
1954 int delta = BASE_SLOT_SIZE - (start % BASE_SLOT_SIZE);
1955 start = start + delta;
1956 GC_ASSERT(NUM_IN_PAGE(start) == 0 || NUM_IN_PAGE(start) == 1);
1962 if (NUM_IN_PAGE(start) == 1) {
1963 start += heap->slot_size - BASE_SLOT_SIZE;
1966 GC_ASSERT(NUM_IN_PAGE(start) * BASE_SLOT_SIZE % heap->slot_size == 0);
1969 int slot_count = (int)((HEAP_PAGE_SIZE - (start - (uintptr_t)page->body))/heap->slot_size);
1971 page->start = start;
1972 page->total_slots = slot_count;
1973 page->slot_size = heap->slot_size;
1976 asan_unlock_freelist(page);
1977 page->freelist = NULL;
1978 asan_unpoison_memory_region(page->body, HEAP_PAGE_SIZE,
false);
1979 for (
VALUE p = (
VALUE)start; p < start + (slot_count * heap->slot_size); p += heap->slot_size) {
1980 heap_page_add_freeobj(
objspace, page, p);
1982 asan_lock_freelist(page);
1984 page->free_slots = slot_count;
1986 heap->total_allocated_pages++;
1988 ccan_list_add_tail(&heap->pages, &page->page_node);
1989 heap->total_pages++;
1990 heap->total_slots += page->total_slots;
1994heap_page_allocate_and_initialize(rb_objspace_t *
objspace, rb_heap_t *heap)
1996 gc_report(1,
objspace,
"heap_page_allocate_and_initialize: rb_darray_size(objspace->heap_pages.sorted): %"PRIdSIZE
", "
1997 "allocatable_slots: %"PRIdSIZE
", heap->total_pages: %"PRIdSIZE
"\n",
1998 rb_darray_size(
objspace->heap_pages.sorted),
objspace->heap_pages.allocatable_slots, heap->total_pages);
2000 bool allocated =
false;
2003 if (page == NULL &&
objspace->heap_pages.allocatable_slots > 0) {
2004 page = heap_page_allocate(
objspace);
2007 GC_ASSERT(page != NULL);
2011 heap_add_page(
objspace, heap, page);
2012 heap_add_freepage(heap, page);
2015 if (
objspace->heap_pages.allocatable_slots > (
size_t)page->total_slots) {
2016 objspace->heap_pages.allocatable_slots -= page->total_slots;
2019 objspace->heap_pages.allocatable_slots = 0;
2024 return page != NULL;
2028heap_page_allocate_and_initialize_force(rb_objspace_t *
objspace, rb_heap_t *heap)
2030 size_t prev_allocatable_slots =
objspace->heap_pages.allocatable_slots;
2032 objspace->heap_pages.allocatable_slots = 1;
2033 heap_page_allocate_and_initialize(
objspace, heap);
2034 GC_ASSERT(heap->free_pages != NULL);
2035 objspace->heap_pages.allocatable_slots = prev_allocatable_slots;
2039gc_continue(rb_objspace_t *
objspace, rb_heap_t *heap)
2041 unsigned int lock_lev;
2042 bool needs_gc = is_incremental_marking(
objspace) || needs_continue_sweeping(
objspace, heap);
2043 if (!needs_gc)
return;
2045 gc_enter(
objspace, gc_enter_event_continue, &lock_lev);
2048 if (is_incremental_marking(
objspace)) {
2049 if (gc_marks_continue(
objspace, heap)) {
2054 if (needs_continue_sweeping(
objspace, heap)) {
2058 gc_exit(
objspace, gc_enter_event_continue, &lock_lev);
2062heap_prepare(rb_objspace_t *
objspace, rb_heap_t *heap)
2064 GC_ASSERT(heap->free_pages == NULL);
2066 if (heap->total_slots < gc_params.heap_init_slots[heap - heaps] &&
2067 heap->sweeping_page == NULL) {
2068 heap_page_allocate_and_initialize_force(
objspace, heap);
2069 GC_ASSERT(heap->free_pages != NULL);
2076 if (heap->free_pages == NULL) {
2077 heap_page_allocate_and_initialize(
objspace, heap);
2082 if (heap->free_pages == NULL) {
2083 GC_ASSERT(
objspace->empty_pages_count == 0);
2084 GC_ASSERT(
objspace->heap_pages.allocatable_slots == 0);
2086 if (gc_start(
objspace, GPR_FLAG_NEWOBJ) == FALSE) {
2090 if (
objspace->heap_pages.allocatable_slots == 0 && !gc_config_full_mark_val) {
2091 heap_allocatable_slots_expand(
objspace, heap,
2092 heap->freed_slots + heap->empty_slots,
2094 GC_ASSERT(
objspace->heap_pages.allocatable_slots > 0);
2102 if (heap->free_pages == NULL && !heap_page_allocate_and_initialize(
objspace, heap)) {
2103 if (gc_needs_major_flags == GPR_FLAG_NONE) {
2104 rb_bug(
"cannot create a new page after GC");
2107 if (gc_start(
objspace, GPR_FLAG_NEWOBJ) == FALSE) {
2114 if (heap->free_pages == NULL &&
2115 !heap_page_allocate_and_initialize(
objspace, heap)) {
2116 rb_bug(
"cannot create a new page after major GC");
2124 GC_ASSERT(heap->free_pages != NULL);
2128static inline const char*
2129rb_gc_impl_source_location_cstr(
int *
ptr)
2150 RBASIC(obj)->flags = flags;
2152#if RBASIC_SHAPE_ID_FIELD
2153 RBASIC(obj)->shape_id = 0;
2158 RVALUE_AGE_SET_CANDIDATE(
objspace, obj);
2161#if RACTOR_CHECK_MODE
2162 void rb_ractor_setup_belonging(
VALUE obj);
2163 rb_ractor_setup_belonging(obj);
2166#if RGENGC_CHECK_MODE
2167 int lev = RB_GC_VM_LOCK_NO_BARRIER();
2169 check_rvalue_consistency(
objspace, obj);
2171 GC_ASSERT(RVALUE_MARKED(
objspace, obj) == FALSE);
2172 GC_ASSERT(RVALUE_MARKING(
objspace, obj) == FALSE);
2173 GC_ASSERT(RVALUE_OLD_P(
objspace, obj) == FALSE);
2174 GC_ASSERT(RVALUE_WB_UNPROTECTED(
objspace, obj) == FALSE);
2176 if (RVALUE_REMEMBERED(
objspace, obj)) rb_bug(
"newobj: %s is remembered.", rb_obj_info(obj));
2178 RB_GC_VM_UNLOCK_NO_BARRIER(lev);
2181 if (RB_UNLIKELY(wb_protected == FALSE)) {
2182 MARK_IN_BITMAP(GET_HEAP_WB_UNPROTECTED_BITS(obj), obj);
2187 objspace->profile.total_generated_normal_object_count++;
2188#if RGENGC_PROFILE >= 2
2193 objspace->profile.total_generated_shady_object_count++;
2194#if RGENGC_PROFILE >= 2
2201 GET_RVALUE_OVERHEAD(obj)->file = rb_gc_impl_source_location_cstr(&GET_RVALUE_OVERHEAD(obj)->line);
2205 gc_report(5,
objspace,
"newobj: %s\n", rb_obj_info(obj));
2212rb_gc_impl_obj_slot_size(
VALUE obj)
2214 return GET_HEAP_PAGE(obj)->slot_size - RVALUE_OVERHEAD;
2218rb_gc_impl_pinned_p(
void *objspace_ptr,
VALUE obj)
2220 return RVALUE_PINNED((rb_objspace_t *)objspace_ptr, obj);
2224heap_slot_size(
unsigned char pool_id)
2226 GC_ASSERT(pool_id < HEAP_COUNT);
2228 size_t slot_size = (1 << pool_id) * BASE_SLOT_SIZE;
2230#if RGENGC_CHECK_MODE
2231 rb_objspace_t *
objspace = rb_gc_get_objspace();
2232 GC_ASSERT(heaps[pool_id].slot_size == (
short)slot_size);
2235 slot_size -= RVALUE_OVERHEAD;
2241rb_gc_impl_size_allocatable_p(
size_t size)
2243 return size <= heap_slot_size(HEAP_COUNT - 1);
2246static const size_t ALLOCATED_COUNT_STEP = 1024;
2248ractor_cache_flush_count(rb_objspace_t *
objspace, rb_ractor_newobj_cache_t *cache)
2250 for (
int heap_idx = 0; heap_idx < HEAP_COUNT; heap_idx++) {
2251 rb_ractor_newobj_heap_cache_t *heap_cache = &cache->heap_caches[heap_idx];
2253 rb_heap_t *heap = &heaps[heap_idx];
2255 heap_cache->allocated_objects_count = 0;
2260ractor_cache_allocate_slot(rb_objspace_t *
objspace, rb_ractor_newobj_cache_t *cache,
2263 rb_ractor_newobj_heap_cache_t *heap_cache = &cache->heap_caches[heap_idx];
2264 struct free_slot *p = heap_cache->freelist;
2266 if (RB_UNLIKELY(is_incremental_marking(
objspace))) {
2268 if (cache->incremental_mark_step_allocated_slots >= INCREMENTAL_MARK_STEP_ALLOCATIONS) {
2273 cache->incremental_mark_step_allocated_slots++;
2279 rb_asan_unpoison_object(obj,
true);
2280 heap_cache->freelist = p->next;
2282 heap_cache->allocated_objects_count++;
2283 rb_heap_t *heap = &heaps[heap_idx];
2284 if (heap_cache->allocated_objects_count >= ALLOCATED_COUNT_STEP) {
2286 heap_cache->allocated_objects_count = 0;
2289#if RGENGC_CHECK_MODE
2290 GC_ASSERT(rb_gc_impl_obj_slot_size(obj) == heap_slot_size(heap_idx));
2292 MEMZERO((
char *)obj,
char, heap_slot_size(heap_idx));
2302heap_next_free_page(rb_objspace_t *
objspace, rb_heap_t *heap)
2306 if (heap->free_pages == NULL) {
2310 page = heap->free_pages;
2311 heap->free_pages = page->free_next;
2313 GC_ASSERT(page->free_slots != 0);
2315 asan_unlock_freelist(page);
2321ractor_cache_set_page(rb_objspace_t *
objspace, rb_ractor_newobj_cache_t *cache,
size_t heap_idx,
2324 gc_report(3,
objspace,
"ractor_set_cache: Using page %p\n", (
void *)page->body);
2326 rb_ractor_newobj_heap_cache_t *heap_cache = &cache->heap_caches[heap_idx];
2328 GC_ASSERT(heap_cache->freelist == NULL);
2329 GC_ASSERT(page->free_slots != 0);
2330 GC_ASSERT(page->freelist != NULL);
2332 heap_cache->using_page = page;
2333 heap_cache->freelist = page->freelist;
2334 page->free_slots = 0;
2335 page->freelist = NULL;
2337 rb_asan_unpoison_object((
VALUE)heap_cache->freelist,
false);
2338 GC_ASSERT(RB_TYPE_P((
VALUE)heap_cache->freelist,
T_NONE));
2339 rb_asan_poison_object((
VALUE)heap_cache->freelist);
2343heap_idx_for_size(
size_t size)
2345 size += RVALUE_OVERHEAD;
2347 size_t slot_count = CEILDIV(size, BASE_SLOT_SIZE);
2350 size_t heap_idx = 64 - nlz_int64(slot_count - 1);
2352 if (heap_idx >= HEAP_COUNT) {
2353 rb_bug(
"heap_idx_for_size: allocation size too large "
2354 "(size=%"PRIuSIZE
"u, heap_idx=%"PRIuSIZE
"u)", size, heap_idx);
2357#if RGENGC_CHECK_MODE
2358 rb_objspace_t *
objspace = rb_gc_get_objspace();
2359 GC_ASSERT(size <= (
size_t)heaps[heap_idx].slot_size);
2360 if (heap_idx > 0) GC_ASSERT(size > (
size_t)heaps[heap_idx - 1].slot_size);
2367rb_gc_impl_heap_id_for_size(
void *objspace_ptr,
size_t size)
2369 return heap_idx_for_size(size);
2373static size_t heap_sizes[HEAP_COUNT + 1] = { 0 };
2376rb_gc_impl_heap_sizes(
void *objspace_ptr)
2378 if (heap_sizes[0] == 0) {
2379 for (
unsigned char i = 0; i < HEAP_COUNT; i++) {
2380 heap_sizes[i] = heap_slot_size(i);
2387NOINLINE(
static VALUE newobj_cache_miss(rb_objspace_t *
objspace, rb_ractor_newobj_cache_t *cache,
size_t heap_idx,
bool vm_locked));
2390newobj_cache_miss(rb_objspace_t *
objspace, rb_ractor_newobj_cache_t *cache,
size_t heap_idx,
bool vm_locked)
2392 rb_heap_t *heap = &heaps[heap_idx];
2395 unsigned int lev = 0;
2396 bool unlock_vm =
false;
2399 lev = RB_GC_CR_LOCK();
2404 if (is_incremental_marking(
objspace)) {
2406 cache->incremental_mark_step_allocated_slots = 0;
2409 obj = ractor_cache_allocate_slot(
objspace, cache, heap_idx);
2415 ractor_cache_set_page(
objspace, cache, heap_idx, page);
2418 obj = ractor_cache_allocate_slot(
objspace, cache, heap_idx);
2423 RB_GC_CR_UNLOCK(lev);
2426 if (RB_UNLIKELY(obj ==
Qfalse)) {
2433newobj_alloc(rb_objspace_t *
objspace, rb_ractor_newobj_cache_t *cache,
size_t heap_idx,
bool vm_locked)
2435 VALUE obj = ractor_cache_allocate_slot(
objspace, cache, heap_idx);
2437 if (RB_UNLIKELY(obj ==
Qfalse)) {
2438 obj = newobj_cache_miss(
objspace, cache, heap_idx, vm_locked);
2444ALWAYS_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));
2447newobj_slowpath(
VALUE klass,
VALUE flags, rb_objspace_t *
objspace, rb_ractor_newobj_cache_t *cache,
int wb_protected,
size_t heap_idx)
2452 lev = RB_GC_CR_LOCK();
2454 if (RB_UNLIKELY(during_gc || ruby_gc_stressful)) {
2458 if (rb_memerror_reentered()) {
2461 rb_bug(
"object allocation during garbage collection phase");
2464 if (ruby_gc_stressful) {
2465 if (!garbage_collect(
objspace, GPR_FLAG_NEWOBJ)) {
2471 obj = newobj_alloc(
objspace, cache, heap_idx,
true);
2472 newobj_init(klass, flags, wb_protected,
objspace, obj);
2474 RB_GC_CR_UNLOCK(lev);
2479NOINLINE(
static VALUE newobj_slowpath_wb_protected(
VALUE klass,
VALUE flags,
2480 rb_objspace_t *
objspace, rb_ractor_newobj_cache_t *cache,
size_t heap_idx));
2481NOINLINE(
static VALUE newobj_slowpath_wb_unprotected(
VALUE klass,
VALUE flags,
2482 rb_objspace_t *
objspace, rb_ractor_newobj_cache_t *cache,
size_t heap_idx));
2485newobj_slowpath_wb_protected(
VALUE klass,
VALUE flags, rb_objspace_t *
objspace, rb_ractor_newobj_cache_t *cache,
size_t heap_idx)
2487 return newobj_slowpath(klass, flags,
objspace, cache, TRUE, heap_idx);
2491newobj_slowpath_wb_unprotected(
VALUE klass,
VALUE flags, rb_objspace_t *
objspace, rb_ractor_newobj_cache_t *cache,
size_t heap_idx)
2493 return newobj_slowpath(klass, flags,
objspace, cache, FALSE, heap_idx);
2497rb_gc_impl_new_obj(
void *objspace_ptr,
void *cache_ptr,
VALUE klass,
VALUE flags,
bool wb_protected,
size_t alloc_size)
2500 rb_objspace_t *
objspace = objspace_ptr;
2502 RB_DEBUG_COUNTER_INC(obj_newobj);
2503 (void)RB_DEBUG_COUNTER_INC_IF(obj_newobj_wb_unprotected, !wb_protected);
2505 if (RB_UNLIKELY(stress_to_class)) {
2506 if (rb_hash_lookup2(stress_to_class, klass,
Qundef) !=
Qundef) {
2511 size_t heap_idx = heap_idx_for_size(alloc_size);
2513 rb_ractor_newobj_cache_t *cache = (rb_ractor_newobj_cache_t *)cache_ptr;
2515 if (!RB_UNLIKELY(during_gc || ruby_gc_stressful) &&
2517 obj = newobj_alloc(
objspace, cache, heap_idx,
false);
2518 newobj_init(klass, flags, wb_protected,
objspace, obj);
2521 RB_DEBUG_COUNTER_INC(obj_newobj_slowpath);
2523 obj = wb_protected ?
2524 newobj_slowpath_wb_protected(klass, flags,
objspace, cache, heap_idx) :
2525 newobj_slowpath_wb_unprotected(klass, flags,
objspace, cache, heap_idx);
2532ptr_in_page_body_p(
const void *
ptr,
const void *memb)
2535 uintptr_t p_body = (uintptr_t)page->body;
2537 if ((uintptr_t)
ptr >= p_body) {
2538 return (uintptr_t)
ptr < (p_body + HEAP_PAGE_SIZE) ? 0 : 1;
2545PUREFUNC(
static inline struct heap_page *heap_page_for_ptr(rb_objspace_t *
objspace, uintptr_t
ptr);)
2547heap_page_for_ptr(rb_objspace_t *
objspace, uintptr_t
ptr)
2551 if (
ptr < (uintptr_t)heap_pages_lomem ||
2552 ptr > (uintptr_t)heap_pages_himem) {
2556 res = bsearch((
void *)
ptr, rb_darray_ref(
objspace->heap_pages.sorted, 0),
2558 ptr_in_page_body_p);
2568PUREFUNC(
static inline bool is_pointer_to_heap(rb_objspace_t *
objspace,
const void *
ptr);)
2570is_pointer_to_heap(rb_objspace_t *
objspace,
const void *
ptr)
2572 register uintptr_t p = (uintptr_t)
ptr;
2575 RB_DEBUG_COUNTER_INC(gc_isptr_trial);
2577 if (p < heap_pages_lomem || p > heap_pages_himem)
return FALSE;
2578 RB_DEBUG_COUNTER_INC(gc_isptr_range);
2580 if (p % BASE_SLOT_SIZE != 0)
return FALSE;
2581 RB_DEBUG_COUNTER_INC(gc_isptr_align);
2583 page = heap_page_for_ptr(
objspace, (uintptr_t)
ptr);
2585 RB_DEBUG_COUNTER_INC(gc_isptr_maybe);
2586 if (heap_page_in_global_empty_pages_pool(
objspace, page)) {
2590 if (p < page->start)
return FALSE;
2591 if (p >= page->start + (page->total_slots * page->slot_size))
return FALSE;
2592 if ((NUM_IN_PAGE(p) * BASE_SLOT_SIZE) % page->slot_size != 0)
return FALSE;
2601rb_gc_impl_pointer_to_heap_p(
void *objspace_ptr,
const void *
ptr)
2603 return is_pointer_to_heap(objspace_ptr,
ptr);
2606#define ZOMBIE_OBJ_KEPT_FLAGS (FL_FINALIZE)
2609rb_gc_impl_make_zombie(
void *objspace_ptr,
VALUE obj,
void (*dfree)(
void *),
void *data)
2611 rb_objspace_t *
objspace = objspace_ptr;
2613 struct RZombie *zombie = RZOMBIE(obj);
2614 zombie->flags =
T_ZOMBIE | (zombie->flags & ZOMBIE_OBJ_KEPT_FLAGS);
2615 zombie->dfree = dfree;
2616 zombie->data = data;
2617 VALUE prev, next = heap_pages_deferred_final;
2619 zombie->next = prev = next;
2621 }
while (next != prev);
2623 struct heap_page *page = GET_HEAP_PAGE(obj);
2624 page->final_slots++;
2625 page->heap->final_slots_count++;
2628typedef int each_obj_callback(
void *,
void *,
size_t,
void *);
2629typedef int each_page_callback(
struct heap_page *,
void *);
2632 rb_objspace_t *objspace;
2633 bool reenable_incremental;
2635 each_obj_callback *each_obj_callback;
2636 each_page_callback *each_page_callback;
2640 size_t pages_counts[HEAP_COUNT];
2644objspace_each_objects_ensure(
VALUE arg)
2647 rb_objspace_t *
objspace = data->objspace;
2650 if (data->reenable_incremental) {
2651 objspace->flags.dont_incremental = FALSE;
2654 for (
int i = 0; i < HEAP_COUNT; i++) {
2655 struct heap_page **pages = data->pages[i];
2663objspace_each_objects_try(
VALUE arg)
2666 rb_objspace_t *
objspace = data->objspace;
2669 for (
int i = 0; i < HEAP_COUNT; i++) {
2670 rb_heap_t *heap = &heaps[i];
2671 size_t size = heap->total_pages *
sizeof(
struct heap_page *);
2673 struct heap_page **pages = malloc(size);
2674 if (!pages) rb_memerror();
2682 size_t pages_count = 0;
2683 ccan_list_for_each(&heap->pages, page, page_node) {
2684 pages[pages_count] = page;
2687 data->pages[i] = pages;
2688 data->pages_counts[i] = pages_count;
2689 GC_ASSERT(pages_count == heap->total_pages);
2692 for (
int i = 0; i < HEAP_COUNT; i++) {
2693 rb_heap_t *heap = &heaps[i];
2694 size_t pages_count = data->pages_counts[i];
2695 struct heap_page **pages = data->pages[i];
2698 for (
size_t i = 0; i < pages_count; i++) {
2701 if (page == NULL)
break;
2705 if (pages[i] != page)
continue;
2707 uintptr_t pstart = (uintptr_t)page->start;
2708 uintptr_t pend = pstart + (page->total_slots * heap->slot_size);
2710 if (data->each_obj_callback &&
2711 (*data->each_obj_callback)((
void *)pstart, (
void *)pend, heap->slot_size, data->data)) {
2714 if (data->each_page_callback &&
2715 (*data->each_page_callback)(page, data->data)) {
2719 page = ccan_list_next(&heap->pages, page, page_node);
2731 bool reenable_incremental = FALSE;
2733 reenable_incremental = !
objspace->flags.dont_incremental;
2736 objspace->flags.dont_incremental = TRUE;
2747objspace_each_objects(rb_objspace_t *
objspace, each_obj_callback *callback,
void *data,
bool protected)
2751 .each_obj_callback = callback,
2752 .each_page_callback = NULL,
2759rb_gc_impl_each_objects(
void *objspace_ptr, each_obj_callback *callback,
void *data)
2761 objspace_each_objects(objspace_ptr, callback, data, TRUE);
2764#if GC_CAN_COMPILE_COMPACTION
2766objspace_each_pages(rb_objspace_t *
objspace, each_page_callback *callback,
void *data,
bool protected)
2770 .each_obj_callback = NULL,
2771 .each_page_callback = callback,
2779rb_gc_impl_define_finalizer(
void *objspace_ptr,
VALUE obj,
VALUE block)
2781 rb_objspace_t *
objspace = objspace_ptr;
2789 unsigned int lev = RB_GC_VM_LOCK();
2791 if (st_lookup(finalizer_table, obj, &data)) {
2792 table = (
VALUE)data;
2795 RB_GC_VM_UNLOCK(lev);
2801 for (i = 0; i <
len; i++) {
2808 lev = RB_GC_VM_LOCK();
2816 st_add_direct(finalizer_table, obj, table);
2819 RB_GC_VM_UNLOCK(lev);
2825rb_gc_impl_undefine_finalizer(
void *objspace_ptr,
VALUE obj)
2827 rb_objspace_t *
objspace = objspace_ptr;
2831 st_data_t data = obj;
2833 int lev = RB_GC_VM_LOCK();
2834 st_delete(finalizer_table, &data, 0);
2835 RB_GC_VM_UNLOCK(lev);
2841rb_gc_impl_copy_finalizer(
void *objspace_ptr,
VALUE dest,
VALUE obj)
2843 rb_objspace_t *
objspace = objspace_ptr;
2849 int lev = RB_GC_VM_LOCK();
2850 if (RB_LIKELY(st_lookup(finalizer_table, obj, &data))) {
2852 RARRAY_ASET(table, 0, rb_obj_id(dest));
2853 st_insert(finalizer_table, dest, table);
2857 rb_bug(
"rb_gc_copy_finalizer: FL_FINALIZE set but not found in finalizer_table: %s", rb_obj_info(obj));
2859 RB_GC_VM_UNLOCK(lev);
2863get_final(
long i,
void *data)
2871run_final(rb_objspace_t *
objspace,
VALUE zombie,
unsigned int lev)
2873 if (RZOMBIE(zombie)->dfree) {
2874 RZOMBIE(zombie)->dfree(RZOMBIE(zombie)->data);
2877 st_data_t key = (st_data_t)zombie;
2881 if (st_delete(finalizer_table, &key, &table)) {
2882 RB_GC_VM_UNLOCK(lev);
2884 lev = RB_GC_VM_LOCK();
2887 rb_bug(
"FL_FINALIZE flag is set, but finalizers are not found");
2891 GC_ASSERT(!st_lookup(finalizer_table, key, NULL));
2902 rb_asan_unpoison_object(zombie,
false);
2903 next_zombie = RZOMBIE(zombie)->next;
2904 page = GET_HEAP_PAGE(zombie);
2906 unsigned int lev = RB_GC_VM_LOCK();
2908 lev = run_final(
objspace, zombie, lev);
2911 GC_ASSERT(page->heap->final_slots_count > 0);
2912 GC_ASSERT(page->final_slots > 0);
2914 page->heap->final_slots_count--;
2915 page->final_slots--;
2917 RVALUE_AGE_SET_BITMAP(zombie, 0);
2918 heap_page_add_freeobj(
objspace, page, zombie);
2919 page->heap->total_freed_objects++;
2921 RB_GC_VM_UNLOCK(lev);
2923 zombie = next_zombie;
2928finalize_deferred_heap_pages(rb_objspace_t *
objspace)
2937finalize_deferred(rb_objspace_t *
objspace)
2939 rb_gc_set_pending_interrupt();
2940 finalize_deferred_heap_pages(
objspace);
2941 rb_gc_unset_pending_interrupt();
2945gc_finalize_deferred(
void *dmy)
2955gc_finalize_deferred_register(rb_objspace_t *
objspace)
2961static int pop_mark_stack(mark_stack_t *stack,
VALUE *data);
2964gc_abort(
void *objspace_ptr)
2966 rb_objspace_t *
objspace = objspace_ptr;
2968 if (is_incremental_marking(
objspace)) {
2971 while (pop_mark_stack(&
objspace->mark_stack, &obj));
2973 objspace->flags.during_incremental_marking = FALSE;
2977 for (
int i = 0; i < HEAP_COUNT; i++) {
2978 rb_heap_t *heap = &heaps[i];
2980 heap->sweeping_page = NULL;
2983 ccan_list_for_each(&heap->pages, page, page_node) {
2984 page->flags.before_sweep =
false;
2989 for (
int i = 0; i < HEAP_COUNT; i++) {
2990 rb_heap_t *heap = &heaps[i];
2991 rgengc_mark_and_rememberset_clear(
objspace, heap);
2994 gc_mode_set(
objspace, gc_mode_none);
2998rb_gc_impl_shutdown_free_objects(
void *objspace_ptr)
3000 rb_objspace_t *
objspace = objspace_ptr;
3002 for (
size_t i = 0; i < rb_darray_size(
objspace->heap_pages.sorted); i++) {
3004 short stride = page->slot_size;
3006 uintptr_t p = (uintptr_t)page->start;
3007 uintptr_t pend = p + page->total_slots * stride;
3008 for (; p < pend; p += stride) {
3010 asan_unpoisoning_object(vp) {
3011 if (RB_BUILTIN_TYPE(vp) !=
T_NONE) {
3012 rb_gc_obj_free_vm_weak_references(vp);
3013 if (rb_gc_obj_free(
objspace, vp)) {
3023rb_gc_impl_shutdown_call_finalizer_i(st_data_t key, st_data_t val, st_data_t _data)
3029 GC_ASSERT(RB_BUILTIN_TYPE(val) ==
T_ARRAY);
3039rb_gc_impl_shutdown_call_finalizer(
void *objspace_ptr)
3041 rb_objspace_t *
objspace = objspace_ptr;
3043#if RGENGC_CHECK_MODE >= 2
3044 gc_verify_internal_consistency(
objspace);
3048 objspace->flags.dont_incremental = 1;
3057 while (finalizer_table->num_entries) {
3058 st_foreach(finalizer_table, rb_gc_impl_shutdown_call_finalizer_i, 0);
3063 GC_ASSERT(heap_pages_deferred_final == 0);
3072 unsigned int lock_lev;
3073 gc_enter(
objspace, gc_enter_event_finalizer, &lock_lev);
3076 for (
size_t i = 0; i < rb_darray_size(
objspace->heap_pages.sorted); i++) {
3078 short stride = page->slot_size;
3080 uintptr_t p = (uintptr_t)page->start;
3081 uintptr_t pend = p + page->total_slots * stride;
3082 for (; p < pend; p += stride) {
3084 asan_unpoisoning_object(vp) {
3085 if (rb_gc_shutdown_call_finalizer_p(vp)) {
3086 rb_gc_obj_free_vm_weak_references(vp);
3087 if (rb_gc_obj_free(
objspace, vp)) {
3095 gc_exit(
objspace, gc_enter_event_finalizer, &lock_lev);
3097 finalize_deferred_heap_pages(
objspace);
3099 st_free_table(finalizer_table);
3100 finalizer_table = 0;
3105rb_gc_impl_each_object(
void *objspace_ptr,
void (*func)(
VALUE obj,
void *data),
void *data)
3107 rb_objspace_t *
objspace = objspace_ptr;
3109 for (
size_t i = 0; i < rb_darray_size(
objspace->heap_pages.sorted); i++) {
3111 short stride = page->slot_size;
3113 uintptr_t p = (uintptr_t)page->start;
3114 uintptr_t pend = p + page->total_slots * stride;
3115 for (; p < pend; p += stride) {
3118 asan_unpoisoning_object(obj) {
3132objspace_available_slots(rb_objspace_t *
objspace)
3134 size_t total_slots = 0;
3135 for (
int i = 0; i < HEAP_COUNT; i++) {
3136 rb_heap_t *heap = &heaps[i];
3137 total_slots += heap->total_slots;
3143objspace_live_slots(rb_objspace_t *
objspace)
3149objspace_free_slots(rb_objspace_t *
objspace)
3155gc_setup_mark_bits(
struct heap_page *page)
3158 memcpy(&page->mark_bits[0], &page->uncollectible_bits[0], HEAP_PAGE_BITMAP_SIZE);
3161static int gc_is_moveable_obj(rb_objspace_t *
objspace,
VALUE obj);
3165enum {HEAP_PAGE_LOCK = PAGE_NOACCESS, HEAP_PAGE_UNLOCK = PAGE_READWRITE};
3171 return VirtualProtect(body, HEAP_PAGE_SIZE, protect, &old_protect) != 0;
3173#elif defined(__wasi__)
3175enum {HEAP_PAGE_LOCK, HEAP_PAGE_UNLOCK};
3176#define protect_page_body(body, protect) 1
3178enum {HEAP_PAGE_LOCK = PROT_NONE, HEAP_PAGE_UNLOCK = PROT_READ | PROT_WRITE};
3179#define protect_page_body(body, protect) !mprotect((body), HEAP_PAGE_SIZE, (protect))
3185 if (!protect_page_body(body, HEAP_PAGE_LOCK)) {
3186 rb_bug(
"Couldn't protect page %p, errno: %s", (
void *)body, strerror(
errno));
3189 gc_report(5,
objspace,
"Protecting page in move %p\n", (
void *)body);
3196 if (!protect_page_body(body, HEAP_PAGE_UNLOCK)) {
3197 rb_bug(
"Couldn't unprotect page %p, errno: %s", (
void *)body, strerror(
errno));
3200 gc_report(5,
objspace,
"Unprotecting page in move %p\n", (
void *)body);
3207 GC_ASSERT(gc_is_moveable_obj(
objspace, src));
3209 struct heap_page *src_page = GET_HEAP_PAGE(src);
3217 GC_ASSERT(RVALUE_MARKED(
objspace, src));
3219 asan_unlock_freelist(free_page);
3221 asan_lock_freelist(free_page);
3223 rb_asan_unpoison_object(dest,
false);
3230 asan_unlock_freelist(free_page);
3231 free_page->freelist = ((
struct free_slot *)dest)->next;
3232 asan_lock_freelist(free_page);
3234 GC_ASSERT(RB_BUILTIN_TYPE(dest) ==
T_NONE);
3236 if (src_page->slot_size > free_page->slot_size) {
3239 else if (free_page->slot_size > src_page->slot_size) {
3243 objspace->rcompactor.total_moved++;
3245 gc_move(
objspace, src, dest, src_page->slot_size, free_page->slot_size);
3247 free_page->free_slots--;
3253gc_unprotect_pages(rb_objspace_t *
objspace, rb_heap_t *heap)
3255 struct heap_page *cursor = heap->compact_cursor;
3258 unlock_page_body(
objspace, cursor->body);
3259 cursor = ccan_list_next(&heap->pages, cursor, page_node);
3263static void gc_update_references(rb_objspace_t *
objspace);
3264#if GC_CAN_COMPILE_COMPACTION
3265static void invalidate_moved_page(rb_objspace_t *
objspace,
struct heap_page *page);
3268#if defined(__MINGW32__) || defined(_WIN32)
3269# define GC_COMPACTION_SUPPORTED 1
3273# define GC_COMPACTION_SUPPORTED (GC_CAN_COMPILE_COMPACTION && HEAP_PAGE_ALLOC_USE_MMAP)
3276#if GC_CAN_COMPILE_COMPACTION
3278read_barrier_handler(uintptr_t address)
3280 rb_objspace_t *
objspace = (rb_objspace_t *)rb_gc_get_objspace();
3286 if (page_body == NULL) {
3287 rb_bug(
"read_barrier_handler: segmentation fault at %p", (
void *)address);
3290 int lev = RB_GC_VM_LOCK();
3292 unlock_page_body(
objspace, page_body);
3294 objspace->profile.read_barrier_faults++;
3296 invalidate_moved_page(
objspace, GET_HEAP_PAGE(address));
3298 RB_GC_VM_UNLOCK(lev);
3302#if !GC_CAN_COMPILE_COMPACTION
3304uninstall_handlers(
void)
3310install_handlers(
void)
3314#elif defined(_WIN32)
3315static LPTOP_LEVEL_EXCEPTION_FILTER old_handler;
3316typedef void (*signal_handler)(int);
3317static signal_handler old_sigsegv_handler;
3320read_barrier_signal(EXCEPTION_POINTERS *info)
3323 if (info->ExceptionRecord->ExceptionCode == EXCEPTION_ACCESS_VIOLATION) {
3328 read_barrier_handler((uintptr_t)info->ExceptionRecord->ExceptionInformation[1]);
3329 return EXCEPTION_CONTINUE_EXECUTION;
3332 return EXCEPTION_CONTINUE_SEARCH;
3337uninstall_handlers(
void)
3339 signal(SIGSEGV, old_sigsegv_handler);
3340 SetUnhandledExceptionFilter(old_handler);
3344install_handlers(
void)
3347 old_sigsegv_handler = signal(SIGSEGV, NULL);
3350 old_handler = SetUnhandledExceptionFilter(read_barrier_signal);
3353static struct sigaction old_sigbus_handler;
3354static struct sigaction old_sigsegv_handler;
3356#ifdef HAVE_MACH_TASK_EXCEPTION_PORTS
3357static exception_mask_t old_exception_masks[32];
3358static mach_port_t old_exception_ports[32];
3359static exception_behavior_t old_exception_behaviors[32];
3360static thread_state_flavor_t old_exception_flavors[32];
3361static mach_msg_type_number_t old_exception_count;
3364disable_mach_bad_access_exc(
void)
3366 old_exception_count =
sizeof(old_exception_masks) /
sizeof(old_exception_masks[0]);
3367 task_swap_exception_ports(
3368 mach_task_self(), EXC_MASK_BAD_ACCESS,
3369 MACH_PORT_NULL, EXCEPTION_DEFAULT, 0,
3370 old_exception_masks, &old_exception_count,
3371 old_exception_ports, old_exception_behaviors, old_exception_flavors
3376restore_mach_bad_access_exc(
void)
3378 for (mach_msg_type_number_t i = 0; i < old_exception_count; i++) {
3379 task_set_exception_ports(
3381 old_exception_masks[i], old_exception_ports[i],
3382 old_exception_behaviors[i], old_exception_flavors[i]
3389read_barrier_signal(
int sig, siginfo_t *info,
void *data)
3392 struct sigaction prev_sigbus, prev_sigsegv;
3393 sigaction(SIGBUS, &old_sigbus_handler, &prev_sigbus);
3394 sigaction(SIGSEGV, &old_sigsegv_handler, &prev_sigsegv);
3397 sigset_t set, prev_set;
3399 sigaddset(&set, SIGBUS);
3400 sigaddset(&set, SIGSEGV);
3401 sigprocmask(SIG_UNBLOCK, &set, &prev_set);
3402#ifdef HAVE_MACH_TASK_EXCEPTION_PORTS
3403 disable_mach_bad_access_exc();
3406 read_barrier_handler((uintptr_t)info->si_addr);
3409#ifdef HAVE_MACH_TASK_EXCEPTION_PORTS
3410 restore_mach_bad_access_exc();
3412 sigaction(SIGBUS, &prev_sigbus, NULL);
3413 sigaction(SIGSEGV, &prev_sigsegv, NULL);
3414 sigprocmask(SIG_SETMASK, &prev_set, NULL);
3418uninstall_handlers(
void)
3420#ifdef HAVE_MACH_TASK_EXCEPTION_PORTS
3421 restore_mach_bad_access_exc();
3423 sigaction(SIGBUS, &old_sigbus_handler, NULL);
3424 sigaction(SIGSEGV, &old_sigsegv_handler, NULL);
3428install_handlers(
void)
3430 struct sigaction action;
3431 memset(&action, 0,
sizeof(
struct sigaction));
3432 sigemptyset(&action.sa_mask);
3433 action.sa_sigaction = read_barrier_signal;
3434 action.sa_flags = SA_SIGINFO | SA_ONSTACK;
3436 sigaction(SIGBUS, &action, &old_sigbus_handler);
3437 sigaction(SIGSEGV, &action, &old_sigsegv_handler);
3438#ifdef HAVE_MACH_TASK_EXCEPTION_PORTS
3439 disable_mach_bad_access_exc();
3445gc_compact_finish(rb_objspace_t *
objspace)
3447 for (
int i = 0; i < HEAP_COUNT; i++) {
3448 rb_heap_t *heap = &heaps[i];
3449 gc_unprotect_pages(
objspace, heap);
3452 uninstall_handlers();
3457 for (
int i = 0; i < HEAP_COUNT; i++) {
3458 rb_heap_t *heap = &heaps[i];
3459 heap->compact_cursor = NULL;
3460 heap->free_pages = NULL;
3461 heap->compact_cursor_index = 0;
3466 record->moved_objects =
objspace->rcompactor.total_moved - record->moved_objects;
3468 objspace->flags.during_compacting = FALSE;
3481 struct heap_page *sweep_page = ctx->page;
3482 short slot_size = sweep_page->slot_size;
3483 short slot_bits = slot_size / BASE_SLOT_SIZE;
3484 GC_ASSERT(slot_bits > 0);
3488 GC_ASSERT(vp % BASE_SLOT_SIZE == 0);
3490 rb_asan_unpoison_object(vp,
false);
3494 gc_report(2,
objspace,
"page_sweep: free %p\n", (
void *)p);
3495#if RGENGC_CHECK_MODE
3497 if (RVALUE_OLD_P(
objspace, vp)) rb_bug(
"page_sweep: %p - old while minor GC.", (
void *)p);
3498 if (RVALUE_REMEMBERED(
objspace, vp)) rb_bug(
"page_sweep: %p - remembered.", (
void *)p);
3502 if (RVALUE_WB_UNPROTECTED(
objspace, vp)) CLEAR_IN_BITMAP(GET_HEAP_WB_UNPROTECTED_BITS(vp), vp);
3504#if RGENGC_CHECK_MODE
3505#define CHECK(x) if (x(objspace, vp) != FALSE) rb_bug("obj_free: " #x "(%s) != FALSE", rb_obj_info(vp))
3506 CHECK(RVALUE_WB_UNPROTECTED);
3507 CHECK(RVALUE_MARKED);
3508 CHECK(RVALUE_MARKING);
3509 CHECK(RVALUE_UNCOLLECTIBLE);
3515 rb_gc_obj_free_vm_weak_references(vp);
3516 if (rb_gc_obj_free(
objspace, vp)) {
3519 (void)VALGRIND_MAKE_MEM_UNDEFINED((
void*)p, BASE_SLOT_SIZE);
3520 RVALUE_AGE_SET_BITMAP(vp, 0);
3521 heap_page_add_freeobj(
objspace, sweep_page, vp);
3522 gc_report(3,
objspace,
"page_sweep: %s is added to freelist\n", rb_obj_info(vp));
3531 if (
objspace->flags.during_compacting) {
3537 rb_bug(
"T_MOVED shouldn't be seen until compaction is finished");
3539 gc_report(3,
objspace,
"page_sweep: %s is added to freelist\n", rb_obj_info(vp));
3541 RVALUE_AGE_SET_BITMAP(vp, 0);
3542 heap_page_add_freeobj(
objspace, sweep_page, vp);
3553 bitset >>= slot_bits;
3560 struct heap_page *sweep_page = ctx->page;
3561 GC_ASSERT(sweep_page->heap == heap);
3564 bits_t *bits, bitset;
3566 gc_report(2,
objspace,
"page_sweep: start.\n");
3568#if RGENGC_CHECK_MODE
3569 if (!
objspace->flags.immediate_sweep) {
3570 GC_ASSERT(sweep_page->flags.before_sweep == TRUE);
3573 sweep_page->flags.before_sweep = FALSE;
3574 sweep_page->free_slots = 0;
3576 p = (uintptr_t)sweep_page->start;
3577 bits = sweep_page->mark_bits;
3579 int page_rvalue_count = sweep_page->total_slots * (sweep_page->slot_size / BASE_SLOT_SIZE);
3580 int out_of_range_bits = (NUM_IN_PAGE(p) + page_rvalue_count) % BITS_BITLENGTH;
3581 if (out_of_range_bits != 0) {
3582 bits[BITMAP_INDEX(p) + page_rvalue_count / BITS_BITLENGTH] |= ~(((bits_t)1 << out_of_range_bits) - 1);
3588 int bitmap_plane_count = CEILDIV(NUM_IN_PAGE(p) + page_rvalue_count, BITS_BITLENGTH);
3589 GC_ASSERT(bitmap_plane_count == HEAP_PAGE_BITMAP_LIMIT - 1 ||
3590 bitmap_plane_count == HEAP_PAGE_BITMAP_LIMIT);
3592 bits_t slot_mask = heap->slot_bits_mask;
3596 bitset >>= NUM_IN_PAGE(p);
3597 bitset &= slot_mask;
3599 gc_sweep_plane(
objspace, heap, p, bitset, ctx);
3601 p += (BITS_BITLENGTH - NUM_IN_PAGE(p)) * BASE_SLOT_SIZE;
3603 for (
int i = 1; i < bitmap_plane_count; i++) {
3605 bitset &= slot_mask;
3607 gc_sweep_plane(
objspace, heap, p, bitset, ctx);
3609 p += BITS_BITLENGTH * BASE_SLOT_SIZE;
3612 if (!heap->compact_cursor) {
3613 gc_setup_mark_bits(sweep_page);
3616#if GC_PROFILE_MORE_DETAIL
3619 record->removing_objects += ctx->final_slots + ctx->freed_slots;
3620 record->empty_objects += ctx->empty_slots;
3623 if (0) fprintf(stderr,
"gc_sweep_page(%"PRIdSIZE
"): total_slots: %d, freed_slots: %d, empty_slots: %d, final_slots: %d\n",
3625 sweep_page->total_slots,
3626 ctx->freed_slots, ctx->empty_slots, ctx->final_slots);
3628 sweep_page->free_slots += ctx->freed_slots + ctx->empty_slots;
3629 sweep_page->heap->total_freed_objects += ctx->freed_slots;
3631 if (heap_pages_deferred_final && !finalizing) {
3632 gc_finalize_deferred_register(
objspace);
3635#if RGENGC_CHECK_MODE
3636 short freelist_len = 0;
3637 asan_unlock_freelist(sweep_page);
3641 rb_asan_unpoison_object((
VALUE)
ptr,
false);
3646 asan_lock_freelist(sweep_page);
3647 if (freelist_len != sweep_page->free_slots) {
3648 rb_bug(
"inconsistent freelist length: expected %d but was %d", sweep_page->free_slots, freelist_len);
3652 gc_report(2,
objspace,
"page_sweep: end.\n");
3656gc_mode_name(
enum gc_mode mode)
3659 case gc_mode_none:
return "none";
3660 case gc_mode_marking:
return "marking";
3661 case gc_mode_sweeping:
return "sweeping";
3662 case gc_mode_compacting:
return "compacting";
3663 default: rb_bug(
"gc_mode_name: unknown mode: %d", (
int)mode);
3668gc_mode_transition(rb_objspace_t *
objspace,
enum gc_mode mode)
3670#if RGENGC_CHECK_MODE
3671 enum gc_mode prev_mode = gc_mode(
objspace);
3672 switch (prev_mode) {
3673 case gc_mode_none: GC_ASSERT(mode == gc_mode_marking);
break;
3674 case gc_mode_marking: GC_ASSERT(mode == gc_mode_sweeping);
break;
3675 case gc_mode_sweeping: GC_ASSERT(mode == gc_mode_none || mode == gc_mode_compacting);
break;
3676 case gc_mode_compacting: GC_ASSERT(mode == gc_mode_none);
break;
3679 if (0) fprintf(stderr,
"gc_mode_transition: %s->%s\n", gc_mode_name(gc_mode(
objspace)), gc_mode_name(mode));
3687 asan_unlock_freelist(page);
3688 if (page->freelist) {
3690 rb_asan_unpoison_object((
VALUE)p,
false);
3694 rb_asan_poison_object((
VALUE)prev);
3695 rb_asan_unpoison_object((
VALUE)p,
false);
3698 rb_asan_poison_object((
VALUE)p);
3701 page->freelist = freelist;
3703 asan_lock_freelist(page);
3708gc_sweep_start_heap(rb_objspace_t *
objspace, rb_heap_t *heap)
3710 heap->sweeping_page = ccan_list_top(&heap->pages,
struct heap_page, page_node);
3711 heap->free_pages = NULL;
3712 heap->pooled_pages = NULL;
3713 if (!
objspace->flags.immediate_sweep) {
3716 ccan_list_for_each(&heap->pages, page, page_node) {
3717 page->flags.before_sweep = TRUE;
3722#if defined(__GNUC__) && __GNUC__ == 4 && __GNUC_MINOR__ == 4
3726#if GC_CAN_COMPILE_COMPACTION
3727static void gc_sort_heap_by_compare_func(rb_objspace_t *
objspace, gc_compact_compare_func compare_func);
3728static int compare_pinned_slots(
const void *left,
const void *right,
void *d);
3732gc_ractor_newobj_cache_clear(
void *c,
void *data)
3734 rb_objspace_t *
objspace = rb_gc_get_objspace();
3735 rb_ractor_newobj_cache_t *newobj_cache = c;
3737 newobj_cache->incremental_mark_step_allocated_slots = 0;
3739 for (
size_t heap_idx = 0; heap_idx < HEAP_COUNT; heap_idx++) {
3741 rb_ractor_newobj_heap_cache_t *cache = &newobj_cache->heap_caches[heap_idx];
3743 rb_heap_t *heap = &heaps[heap_idx];
3745 cache->allocated_objects_count = 0;
3747 struct heap_page *page = cache->using_page;
3748 struct free_slot *freelist = cache->freelist;
3749 RUBY_DEBUG_LOG(
"ractor using_page:%p freelist:%p", (
void *)page, (
void *)freelist);
3751 heap_page_freelist_append(page, freelist);
3753 cache->using_page = NULL;
3754 cache->freelist = NULL;
3759gc_sweep_start(rb_objspace_t *
objspace)
3761 gc_mode_transition(
objspace, gc_mode_sweeping);
3764#if GC_CAN_COMPILE_COMPACTION
3765 if (
objspace->flags.during_compacting) {
3766 gc_sort_heap_by_compare_func(
3768 objspace->rcompactor.compare_func ?
objspace->rcompactor.compare_func : compare_pinned_slots
3773 for (
int i = 0; i < HEAP_COUNT; i++) {
3774 rb_heap_t *heap = &heaps[i];
3775 gc_sweep_start_heap(
objspace, heap);
3778 if (heap->sweeping_page == NULL) {
3779 GC_ASSERT(heap->total_pages == 0);
3780 GC_ASSERT(heap->total_slots == 0);
3781 gc_sweep_finish_heap(
objspace, heap);
3785 rb_gc_ractor_newobj_cache_foreach(gc_ractor_newobj_cache_clear, NULL);
3789gc_sweep_finish_heap(rb_objspace_t *
objspace, rb_heap_t *heap)
3791 size_t total_slots = heap->total_slots;
3792 size_t swept_slots = heap->freed_slots + heap->empty_slots;
3794 size_t init_slots = gc_params.heap_init_slots[heap - heaps];
3795 size_t min_free_slots = (size_t)(MAX(total_slots, init_slots) * gc_params.heap_free_slots_min_ratio);
3797 if (swept_slots < min_free_slots &&
3799 ((heap->empty_slots == 0 && total_slots > 0) || heap->freed_slots > heap->empty_slots)) {
3805 while (swept_slots < min_free_slots &&
3806 (resurrected_page = heap_page_resurrect(
objspace))) {
3807 heap_add_page(
objspace, heap, resurrected_page);
3808 heap_add_freepage(heap, resurrected_page);
3810 swept_slots += resurrected_page->free_slots;
3813 if (swept_slots < min_free_slots) {
3817 objspace->profile.count -
objspace->rgengc.last_major_gc < RVALUE_OLD_AGE) {
3818 if (
objspace->heap_pages.allocatable_slots < min_free_slots) {
3819 heap_allocatable_slots_expand(
objspace, heap, swept_slots, heap->total_slots);
3822 else if (
objspace->heap_pages.allocatable_slots < (min_free_slots - swept_slots)) {
3823 gc_needs_major_flags |= GPR_FLAG_MAJOR_BY_NOFREE;
3824 heap->force_major_gc_count++;
3831gc_sweep_finish(rb_objspace_t *
objspace)
3833 gc_report(1,
objspace,
"gc_sweep_finish\n");
3836 heap_pages_free_unused_pages(
objspace);
3838 for (
int i = 0; i < HEAP_COUNT; i++) {
3839 rb_heap_t *heap = &heaps[i];
3841 heap->freed_slots = 0;
3842 heap->empty_slots = 0;
3844 if (!will_be_incremental_marking(
objspace)) {
3845 struct heap_page *end_page = heap->free_pages;
3847 while (end_page->free_next) end_page = end_page->free_next;
3848 end_page->free_next = heap->pooled_pages;
3851 heap->free_pages = heap->pooled_pages;
3853 heap->pooled_pages = NULL;
3859 gc_mode_transition(
objspace, gc_mode_none);
3861#if RGENGC_CHECK_MODE >= 2
3862 gc_verify_internal_consistency(
objspace);
3867gc_sweep_step(rb_objspace_t *
objspace, rb_heap_t *heap)
3869 struct heap_page *sweep_page = heap->sweeping_page;
3870 int swept_slots = 0;
3871 int pooled_slots = 0;
3873 if (sweep_page == NULL)
return FALSE;
3875#if GC_ENABLE_LAZY_SWEEP
3876 gc_prof_sweep_timer_start(
objspace);
3880 RUBY_DEBUG_LOG(
"sweep_page:%p", (
void *)sweep_page);
3888 gc_sweep_page(
objspace, heap, &ctx);
3889 int free_slots = ctx.freed_slots + ctx.empty_slots;
3891 heap->sweeping_page = ccan_list_next(&heap->pages, sweep_page, page_node);
3893 if (free_slots == sweep_page->total_slots) {
3895 heap_unlink_page(
objspace, heap, sweep_page);
3897 sweep_page->start = 0;
3898 sweep_page->total_slots = 0;
3899 sweep_page->slot_size = 0;
3900 sweep_page->heap = NULL;
3901 sweep_page->free_slots = 0;
3903 asan_unlock_freelist(sweep_page);
3904 sweep_page->freelist = NULL;
3905 asan_lock_freelist(sweep_page);
3907 asan_poison_memory_region(sweep_page->body, HEAP_PAGE_SIZE);
3910 sweep_page->free_next =
objspace->empty_pages;
3911 objspace->empty_pages = sweep_page;
3913 else if (free_slots > 0) {
3914 heap->freed_slots += ctx.freed_slots;
3915 heap->empty_slots += ctx.empty_slots;
3917 if (pooled_slots < GC_INCREMENTAL_SWEEP_POOL_SLOT_COUNT) {
3918 heap_add_poolpage(
objspace, heap, sweep_page);
3919 pooled_slots += free_slots;
3922 heap_add_freepage(heap, sweep_page);
3923 swept_slots += free_slots;
3924 if (swept_slots > GC_INCREMENTAL_SWEEP_SLOT_COUNT) {
3930 sweep_page->free_next = NULL;
3932 }
while ((sweep_page = heap->sweeping_page));
3934 if (!heap->sweeping_page) {
3935 gc_sweep_finish_heap(
objspace, heap);
3937 if (!has_sweeping_pages(
objspace)) {
3942#if GC_ENABLE_LAZY_SWEEP
3943 gc_prof_sweep_timer_stop(
objspace);
3946 return heap->free_pages != NULL;
3950gc_sweep_rest(rb_objspace_t *
objspace)
3952 for (
int i = 0; i < HEAP_COUNT; i++) {
3953 rb_heap_t *heap = &heaps[i];
3955 while (heap->sweeping_page) {
3962gc_sweep_continue(rb_objspace_t *
objspace, rb_heap_t *sweep_heap)
3964 GC_ASSERT(dont_gc_val() == FALSE ||
objspace->profile.latest_gc_info & GPR_FLAG_METHOD);
3965 if (!GC_ENABLE_LAZY_SWEEP)
return;
3969 for (
int i = 0; i < HEAP_COUNT; i++) {
3970 rb_heap_t *heap = &heaps[i];
3971 if (gc_sweep_step(
objspace, heap)) {
3972 GC_ASSERT(heap->free_pages != NULL);
3974 else if (heap == sweep_heap) {
3975 if (
objspace->empty_pages_count > 0 ||
objspace->heap_pages.allocatable_slots > 0) {
3986 heap_page_allocate_and_initialize(
objspace, heap);
3988 GC_ASSERT(heap->free_pages != NULL);
3993 GC_ASSERT(gc_mode(
objspace) == gc_mode_none);
4003rb_gc_impl_location(
void *objspace_ptr,
VALUE value)
4007 asan_unpoisoning_object(value) {
4009 destination = (
VALUE)RMOVED(value)->destination;
4013 destination = value;
4020#if GC_CAN_COMPILE_COMPACTION
4022invalidate_moved_plane(rb_objspace_t *
objspace,
struct heap_page *page, uintptr_t p, bits_t bitset)
4031 GC_ASSERT(RVALUE_PINNED(
objspace, forwarding_object));
4032 GC_ASSERT(!RVALUE_MARKED(
objspace, forwarding_object));
4034 CLEAR_IN_BITMAP(GET_HEAP_PINNED_BITS(forwarding_object), forwarding_object);
4036 object = rb_gc_impl_location(
objspace, forwarding_object);
4038 uint32_t original_shape_id = 0;
4040 original_shape_id = RMOVED(forwarding_object)->original_shape_id;
4043 gc_move(
objspace,
object, forwarding_object, GET_HEAP_PAGE(
object)->slot_size, page->slot_size);
4047 if (original_shape_id) {
4048 rb_gc_set_shape(forwarding_object, original_shape_id);
4051 struct heap_page *orig_page = GET_HEAP_PAGE(
object);
4052 orig_page->free_slots++;
4053 RVALUE_AGE_SET_BITMAP(
object, 0);
4054 heap_page_add_freeobj(
objspace, orig_page,
object);
4056 GC_ASSERT(RVALUE_MARKED(
objspace, forwarding_object));
4061 p += BASE_SLOT_SIZE;
4071 bits_t *mark_bits, *pin_bits;
4074 mark_bits = page->mark_bits;
4075 pin_bits = page->pinned_bits;
4077 uintptr_t p = page->start;
4080 bitset = pin_bits[0] & ~mark_bits[0];
4081 bitset >>= NUM_IN_PAGE(p);
4082 invalidate_moved_plane(
objspace, page, p, bitset);
4083 p += (BITS_BITLENGTH - NUM_IN_PAGE(p)) * BASE_SLOT_SIZE;
4085 for (i=1; i < HEAP_PAGE_BITMAP_LIMIT; i++) {
4088 bitset = pin_bits[i] & ~mark_bits[i];
4090 invalidate_moved_plane(
objspace, page, p, bitset);
4091 p += BITS_BITLENGTH * BASE_SLOT_SIZE;
4097gc_compact_start(rb_objspace_t *
objspace)
4100 gc_mode_transition(
objspace, gc_mode_compacting);
4102 for (
int i = 0; i < HEAP_COUNT; i++) {
4103 rb_heap_t *heap = &heaps[i];
4104 ccan_list_for_each(&heap->pages, page, page_node) {
4105 page->flags.before_sweep = TRUE;
4108 heap->compact_cursor = ccan_list_tail(&heap->pages,
struct heap_page, page_node);
4109 heap->compact_cursor_index = 0;
4114 record->moved_objects =
objspace->rcompactor.total_moved;
4117 memset(
objspace->rcompactor.considered_count_table, 0,
T_MASK *
sizeof(
size_t));
4118 memset(
objspace->rcompactor.moved_count_table, 0,
T_MASK *
sizeof(
size_t));
4119 memset(
objspace->rcompactor.moved_up_count_table, 0,
T_MASK *
sizeof(
size_t));
4120 memset(
objspace->rcompactor.moved_down_count_table, 0,
T_MASK *
sizeof(
size_t));
4126static void gc_sweep_compact(rb_objspace_t *
objspace);
4133 const unsigned int immediate_sweep =
objspace->flags.immediate_sweep;
4135 gc_report(1,
objspace,
"gc_sweep: immediate: %d\n", immediate_sweep);
4138 if (
objspace->flags.during_compacting) {
4142 if (immediate_sweep) {
4143#if !GC_ENABLE_LAZY_SWEEP
4144 gc_prof_sweep_timer_start(
objspace);
4147#if !GC_ENABLE_LAZY_SWEEP
4148 gc_prof_sweep_timer_stop(
objspace);
4154 for (
int i = 0; i < HEAP_COUNT; i++) {
4155 rb_heap_t *heap = &heaps[i];
4165static stack_chunk_t *
4166stack_chunk_alloc(
void)
4170 res = malloc(
sizeof(stack_chunk_t));
4178is_mark_stack_empty(mark_stack_t *stack)
4180 return stack->chunk == NULL;
4184mark_stack_size(mark_stack_t *stack)
4186 size_t size = stack->index;
4187 stack_chunk_t *chunk = stack->chunk ? stack->chunk->next : NULL;
4190 size += stack->limit;
4191 chunk = chunk->next;
4197add_stack_chunk_cache(mark_stack_t *stack, stack_chunk_t *chunk)
4199 chunk->next = stack->cache;
4200 stack->cache = chunk;
4201 stack->cache_size++;
4205shrink_stack_chunk_cache(mark_stack_t *stack)
4207 stack_chunk_t *chunk;
4209 if (stack->unused_cache_size > (stack->cache_size/2)) {
4210 chunk = stack->cache;
4211 stack->cache = stack->cache->next;
4212 stack->cache_size--;
4215 stack->unused_cache_size = stack->cache_size;
4219push_mark_stack_chunk(mark_stack_t *stack)
4221 stack_chunk_t *next;
4223 GC_ASSERT(stack->index == stack->limit);
4225 if (stack->cache_size > 0) {
4226 next = stack->cache;
4227 stack->cache = stack->cache->next;
4228 stack->cache_size--;
4229 if (stack->unused_cache_size > stack->cache_size)
4230 stack->unused_cache_size = stack->cache_size;
4233 next = stack_chunk_alloc();
4235 next->next = stack->chunk;
4236 stack->chunk = next;
4241pop_mark_stack_chunk(mark_stack_t *stack)
4243 stack_chunk_t *prev;
4245 prev = stack->chunk->next;
4246 GC_ASSERT(stack->index == 0);
4247 add_stack_chunk_cache(stack, stack->chunk);
4248 stack->chunk = prev;
4249 stack->index = stack->limit;
4253mark_stack_chunk_list_free(stack_chunk_t *chunk)
4255 stack_chunk_t *next = NULL;
4257 while (chunk != NULL) {
4265free_stack_chunks(mark_stack_t *stack)
4267 mark_stack_chunk_list_free(stack->chunk);
4271mark_stack_free_cache(mark_stack_t *stack)
4273 mark_stack_chunk_list_free(stack->cache);
4274 stack->cache_size = 0;
4275 stack->unused_cache_size = 0;
4279push_mark_stack(mark_stack_t *stack,
VALUE obj)
4302 if (stack->index == stack->limit) {
4303 push_mark_stack_chunk(stack);
4305 stack->chunk->data[stack->index++] = obj;
4315 rb_bug(
"push_mark_stack() called for broken object");
4319 rb_bug(
"push_mark_stack: unexpected T_NODE object");
4323 rb_bug(
"rb_gc_mark(): unknown data type 0x%x(%p) %s",
4325 is_pointer_to_heap((rb_objspace_t *)rb_gc_get_objspace(), (
void *)obj) ?
"corrupted object" :
"non object");
4329pop_mark_stack(mark_stack_t *stack,
VALUE *data)
4331 if (is_mark_stack_empty(stack)) {
4334 if (stack->index == 1) {
4335 *data = stack->chunk->data[--stack->index];
4336 pop_mark_stack_chunk(stack);
4339 *data = stack->chunk->data[--stack->index];
4345init_mark_stack(mark_stack_t *stack)
4349 MEMZERO(stack, mark_stack_t, 1);
4350 stack->index = stack->limit = STACK_CHUNK_SIZE;
4352 for (i=0; i < 4; i++) {
4353 add_stack_chunk_cache(stack, stack_chunk_alloc());
4355 stack->unused_cache_size = stack->cache_size;
4363 if (
objspace->rgengc.parent_object_old_p) {
4364 if (RVALUE_WB_UNPROTECTED(
objspace, obj) || !RVALUE_OLD_P(
objspace, obj)) {
4373 if (RVALUE_MARKED(
objspace, obj))
return 0;
4374 MARK_IN_BITMAP(GET_HEAP_MARK_BITS(obj), obj);
4388 if(!gc_config_full_mark_val)
4391 struct heap_page *page = GET_HEAP_PAGE(obj);
4393 GC_ASSERT(RVALUE_MARKING(
objspace, obj) == FALSE);
4394 check_rvalue_consistency(
objspace, obj);
4396 if (!RVALUE_PAGE_WB_UNPROTECTED(page, obj)) {
4397 if (!RVALUE_OLD_P(
objspace, obj)) {
4398 gc_report(3,
objspace,
"gc_aging: YOUNG: %s\n", rb_obj_info(obj));
4401 else if (is_full_marking(
objspace)) {
4402 GC_ASSERT(RVALUE_PAGE_UNCOLLECTIBLE(page, obj) == FALSE);
4403 RVALUE_PAGE_OLD_UNCOLLECTIBLE_SET(
objspace, page, obj);
4406 check_rvalue_consistency(
objspace, obj);
4414#if RGENGC_CHECK_MODE
4415 if (RVALUE_MARKED(
objspace, obj) == FALSE) rb_bug(
"gc_grey: %s is not marked.", rb_obj_info(obj));
4416 if (RVALUE_MARKING(
objspace, obj) == TRUE) rb_bug(
"gc_grey: %s is marking/remembered.", rb_obj_info(obj));
4419 if (is_incremental_marking(
objspace)) {
4420 MARK_IN_BITMAP(GET_HEAP_MARKING_BITS(obj), obj);
4423 push_mark_stack(&
objspace->mark_stack, obj);
4430 enum {info_size = 256};
4431 char obj_info_buf[info_size];
4432 rb_raw_obj_info(obj_info_buf, info_size, obj);
4434 char parent_obj_info_buf[info_size];
4435 rb_raw_obj_info(parent_obj_info_buf, info_size,
objspace->rgengc.parent_object);
4437 rb_bug(
"try to mark T_NONE object (obj: %s, parent: %s)", obj_info_buf, parent_obj_info_buf);
4444 GC_ASSERT(during_gc);
4445 GC_ASSERT(!
objspace->flags.during_reference_updating);
4447 rgengc_check_relation(
objspace, obj);
4448 if (!gc_mark_set(
objspace, obj))
return;
4451 RUBY_DEBUG_LOG(
"%p (%s) parent:%p (%s)",
4452 (
void *)obj, obj_type_name(obj),
4453 (
void *)
objspace->rgengc.parent_object, obj_type_name(
objspace->rgengc.parent_object));
4456 gc_mark_check_t_none(
objspace, obj);
4466 if (RB_UNLIKELY(
objspace->flags.during_compacting)) {
4467 if (RB_LIKELY(during_gc)) {
4468 if (!RVALUE_PINNED(
objspace, obj)) {
4469 GC_ASSERT(GET_HEAP_PAGE(obj)->pinned_slots <= GET_HEAP_PAGE(obj)->total_slots);
4470 GET_HEAP_PAGE(obj)->pinned_slots++;
4471 MARK_IN_BITMAP(GET_HEAP_PINNED_BITS(obj), obj);
4485rb_gc_impl_mark_and_move(
void *objspace_ptr,
VALUE *
ptr)
4487 rb_objspace_t *
objspace = objspace_ptr;
4489 if (RB_UNLIKELY(
objspace->flags.during_reference_updating)) {
4490 GC_ASSERT(
objspace->flags.during_compacting);
4491 GC_ASSERT(during_gc);
4494 if (destination != *
ptr) {
4504rb_gc_impl_mark(
void *objspace_ptr,
VALUE obj)
4506 rb_objspace_t *
objspace = objspace_ptr;
4512rb_gc_impl_mark_and_pin(
void *objspace_ptr,
VALUE obj)
4514 rb_objspace_t *
objspace = objspace_ptr;
4520rb_gc_impl_mark_maybe(
void *objspace_ptr,
VALUE obj)
4522 rb_objspace_t *
objspace = objspace_ptr;
4524 (void)VALGRIND_MAKE_MEM_DEFINED(&obj,
sizeof(obj));
4526 if (is_pointer_to_heap(
objspace, (
void *)obj)) {
4527 asan_unpoisoning_object(obj) {
4542rb_gc_impl_mark_weak(
void *objspace_ptr,
VALUE *
ptr)
4544 rb_objspace_t *
objspace = objspace_ptr;
4548 gc_mark_check_t_none(
objspace, obj);
4554 GC_ASSERT(RVALUE_MARKED(
objspace, obj));
4555 GC_ASSERT(!
objspace->flags.during_compacting);
4560 rgengc_check_relation(
objspace, obj);
4562 rb_darray_append_without_gc(&
objspace->weak_references,
ptr);
4564 objspace->profile.weak_references_count++;
4568rb_gc_impl_remove_weak(
void *objspace_ptr,
VALUE parent_obj,
VALUE *
ptr)
4570 rb_objspace_t *
objspace = objspace_ptr;
4574 if (!is_incremental_marking(
objspace))
return;
4577 if (!RVALUE_MARKED(
objspace, parent_obj))
return;
4580 rb_darray_foreach(
objspace->weak_references, i, ptr_ptr) {
4581 if (*ptr_ptr ==
ptr) {
4589pin_value(st_data_t key, st_data_t value, st_data_t data)
4591 rb_gc_impl_mark_and_pin((
void *)data, (
VALUE)value);
4597gc_mark_set_parent_raw(rb_objspace_t *
objspace,
VALUE obj,
bool old_p)
4599 asan_unpoison_memory_region(&
objspace->rgengc.parent_object,
sizeof(
objspace->rgengc.parent_object),
false);
4600 asan_unpoison_memory_region(&
objspace->rgengc.parent_object_old_p,
sizeof(
objspace->rgengc.parent_object_old_p),
false);
4601 objspace->rgengc.parent_object = obj;
4602 objspace->rgengc.parent_object_old_p = old_p;
4612gc_mark_set_parent_invalid(rb_objspace_t *
objspace)
4614 asan_poison_memory_region(&
objspace->rgengc.parent_object,
sizeof(
objspace->rgengc.parent_object));
4615 asan_poison_memory_region(&
objspace->rgengc.parent_object_old_p,
sizeof(
objspace->rgengc.parent_object_old_p));
4619mark_roots(rb_objspace_t *
objspace,
const char **categoryp)
4621#define MARK_CHECKPOINT(category) do { \
4622 if (categoryp) *categoryp = category; \
4625 MARK_CHECKPOINT(
"objspace");
4628 if (finalizer_table != NULL) {
4629 st_foreach(finalizer_table, pin_value, (st_data_t)
objspace);
4632 if (stress_to_class) rb_gc_mark(stress_to_class);
4634 rb_gc_save_machine_context();
4635 rb_gc_mark_roots(
objspace, categoryp);
4636 gc_mark_set_parent_invalid(
objspace);
4643 rb_gc_mark_children(
objspace, obj);
4644 gc_mark_set_parent_invalid(
objspace);
4652gc_mark_stacked_objects(rb_objspace_t *
objspace,
int incremental,
size_t count)
4654 mark_stack_t *mstack = &
objspace->mark_stack;
4656 size_t marked_slots_at_the_beginning =
objspace->marked_slots;
4657 size_t popped_count = 0;
4659 while (pop_mark_stack(mstack, &obj)) {
4660 if (obj ==
Qundef)
continue;
4662 if (RGENGC_CHECK_MODE && !RVALUE_MARKED(
objspace, obj)) {
4663 rb_bug(
"gc_mark_stacked_objects: %s is not marked.", rb_obj_info(obj));
4668 if (RGENGC_CHECK_MODE && !RVALUE_MARKING(
objspace, obj)) {
4669 rb_bug(
"gc_mark_stacked_objects: incremental, but marking bit is 0");
4671 CLEAR_IN_BITMAP(GET_HEAP_MARKING_BITS(obj), obj);
4674 if (popped_count + (
objspace->marked_slots - marked_slots_at_the_beginning) > count) {
4683 if (RGENGC_CHECK_MODE >= 3) gc_verify_internal_consistency(
objspace);
4685 if (is_mark_stack_empty(mstack)) {
4686 shrink_stack_chunk_cache(mstack);
4695gc_mark_stacked_objects_incremental(rb_objspace_t *
objspace,
size_t count)
4697 return gc_mark_stacked_objects(
objspace, TRUE, count);
4701gc_mark_stacked_objects_all(rb_objspace_t *
objspace)
4703 return gc_mark_stacked_objects(
objspace, FALSE, 0);
4706#if RGENGC_CHECK_MODE >= 4
4708#define MAKE_ROOTSIG(obj) (((VALUE)(obj) << 1) | 0x01)
4709#define IS_ROOTSIG(obj) ((VALUE)(obj) & 0x01)
4710#define GET_ROOTSIG(obj) ((const char *)((VALUE)(obj) >> 1))
4718static struct reflist *
4719reflist_create(
VALUE obj)
4721 struct reflist *refs =
xmalloc(
sizeof(
struct reflist));
4724 refs->list[0] = obj;
4730reflist_destruct(
struct reflist *refs)
4737reflist_add(
struct reflist *refs,
VALUE obj)
4739 if (refs->pos == refs->size) {
4741 SIZED_REALLOC_N(refs->list,
VALUE, refs->size, refs->size/2);
4744 refs->list[refs->pos++] = obj;
4748reflist_dump(
struct reflist *refs)
4751 for (i=0; i<refs->pos; i++) {
4752 VALUE obj = refs->list[i];
4753 if (IS_ROOTSIG(obj)) {
4754 fprintf(stderr,
"<root@%s>", GET_ROOTSIG(obj));
4757 fprintf(stderr,
"<%s>", rb_obj_info(obj));
4759 if (i+1 < refs->pos) fprintf(stderr,
", ");
4764reflist_referred_from_machine_context(
struct reflist *refs)
4767 for (i=0; i<refs->pos; i++) {
4768 VALUE obj = refs->list[i];
4769 if (IS_ROOTSIG(obj) && strcmp(GET_ROOTSIG(obj),
"machine_context") == 0)
return 1;
4775 rb_objspace_t *objspace;
4783 struct st_table *references;
4784 const char *category;
4786 mark_stack_t mark_stack;
4790allrefs_add(
struct allrefs *data,
VALUE obj)
4792 struct reflist *refs;
4795 if (st_lookup(data->references, obj, &r)) {
4796 refs = (
struct reflist *)r;
4797 reflist_add(refs, data->root_obj);
4801 refs = reflist_create(data->root_obj);
4802 st_insert(data->references, obj, (st_data_t)refs);
4810 struct allrefs *data = (
struct allrefs *)
ptr;
4812 if (allrefs_add(data, obj)) {
4813 push_mark_stack(&data->mark_stack, obj);
4818allrefs_roots_i(
VALUE obj,
void *
ptr)
4820 struct allrefs *data = (
struct allrefs *)
ptr;
4821 if (strlen(data->category) == 0) rb_bug(
"!!!");
4822 data->root_obj = MAKE_ROOTSIG(data->category);
4824 if (allrefs_add(data, obj)) {
4825 push_mark_stack(&data->mark_stack, obj);
4828#define PUSH_MARK_FUNC_DATA(v) do { \
4829 struct gc_mark_func_data_struct *prev_mark_func_data = GET_VM()->gc.mark_func_data; \
4830 GET_VM()->gc.mark_func_data = (v);
4832#define POP_MARK_FUNC_DATA() GET_VM()->gc.mark_func_data = prev_mark_func_data;} while (0)
4835objspace_allrefs(rb_objspace_t *
objspace)
4837 struct allrefs data;
4838 struct gc_mark_func_data_struct mfd;
4840 int prev_dont_gc = dont_gc_val();
4844 data.references = st_init_numtable();
4845 init_mark_stack(&data.mark_stack);
4847 mfd.mark_func = allrefs_roots_i;
4851 PUSH_MARK_FUNC_DATA(&mfd);
4852 GET_VM()->gc.mark_func_data = &mfd;
4853 mark_roots(
objspace, &data.category);
4854 POP_MARK_FUNC_DATA();
4857 while (pop_mark_stack(&data.mark_stack, &obj)) {
4858 rb_objspace_reachable_objects_from(data.root_obj = obj, allrefs_i, &data);
4860 free_stack_chunks(&data.mark_stack);
4862 dont_gc_set(prev_dont_gc);
4863 return data.references;
4867objspace_allrefs_destruct_i(st_data_t key, st_data_t value, st_data_t
ptr)
4869 struct reflist *refs = (
struct reflist *)value;
4870 reflist_destruct(refs);
4875objspace_allrefs_destruct(
struct st_table *refs)
4877 st_foreach(refs, objspace_allrefs_destruct_i, 0);
4878 st_free_table(refs);
4881#if RGENGC_CHECK_MODE >= 5
4883allrefs_dump_i(st_data_t k, st_data_t v, st_data_t
ptr)
4886 struct reflist *refs = (
struct reflist *)v;
4887 fprintf(stderr,
"[allrefs_dump_i] %s <- ", rb_obj_info(obj));
4889 fprintf(stderr,
"\n");
4894allrefs_dump(rb_objspace_t *
objspace)
4897 fprintf(stderr,
"[all refs] (size: %"PRIuVALUE
")\n", size);
4898 st_foreach(
objspace->rgengc.allrefs_table, allrefs_dump_i, 0);
4903gc_check_after_marks_i(st_data_t k, st_data_t v, st_data_t
ptr)
4906 struct reflist *refs = (
struct reflist *)v;
4910 if (!RVALUE_MARKED(
objspace, obj)) {
4911 fprintf(stderr,
"gc_check_after_marks_i: %s is not marked and not oldgen.\n", rb_obj_info(obj));
4912 fprintf(stderr,
"gc_check_after_marks_i: %p is referred from ", (
void *)obj);
4915 if (reflist_referred_from_machine_context(refs)) {
4916 fprintf(stderr,
" (marked from machine stack).\n");
4921 fprintf(stderr,
"\n");
4928gc_marks_check(rb_objspace_t *
objspace, st_foreach_callback_func *checker_func,
const char *checker_name)
4930 size_t saved_malloc_increase =
objspace->malloc_params.increase;
4931#if RGENGC_ESTIMATE_OLDMALLOC
4932 size_t saved_oldmalloc_increase =
objspace->malloc_counters.oldmalloc_increase;
4939 st_foreach(
objspace->rgengc.allrefs_table, checker_func, (st_data_t)
objspace);
4942 if (
objspace->rgengc.error_count > 0) {
4943#if RGENGC_CHECK_MODE >= 5
4946 if (checker_name) rb_bug(
"%s: GC has problem.", checker_name);
4949 objspace_allrefs_destruct(
objspace->rgengc.allrefs_table);
4950 objspace->rgengc.allrefs_table = 0;
4953 objspace->malloc_params.increase = saved_malloc_increase;
4954#if RGENGC_ESTIMATE_OLDMALLOC
4955 objspace->malloc_counters.oldmalloc_increase = saved_oldmalloc_increase;
4961 rb_objspace_t *objspace;
4963 size_t live_object_count;
4964 size_t zombie_object_count;
4967 size_t old_object_count;
4968 size_t remembered_shady_count;
4972check_generation_i(
const VALUE child,
void *
ptr)
4975 const VALUE parent = data->parent;
4977 if (RGENGC_CHECK_MODE) GC_ASSERT(RVALUE_OLD_P(data->objspace, parent));
4979 if (!RVALUE_OLD_P(data->objspace, child)) {
4980 if (!RVALUE_REMEMBERED(data->objspace, parent) &&
4981 !RVALUE_REMEMBERED(data->objspace, child) &&
4982 !RVALUE_UNCOLLECTIBLE(data->objspace, child)) {
4983 fprintf(stderr,
"verify_internal_consistency_reachable_i: WB miss (O->Y) %s -> %s\n", rb_obj_info(parent), rb_obj_info(child));
4990check_color_i(
const VALUE child,
void *
ptr)
4993 const VALUE parent = data->parent;
4995 if (!RVALUE_WB_UNPROTECTED(data->objspace, parent) && RVALUE_WHITE_P(data->objspace, child)) {
4996 fprintf(stderr,
"verify_internal_consistency_reachable_i: WB miss (B->W) - %s -> %s\n",
4997 rb_obj_info(parent), rb_obj_info(child));
5003check_children_i(
const VALUE child,
void *
ptr)
5006 if (check_rvalue_consistency_force(data->objspace, child, FALSE) != 0) {
5007 fprintf(stderr,
"check_children_i: %s has error (referenced from %s)",
5008 rb_obj_info(child), rb_obj_info(data->parent));
5015verify_internal_consistency_i(
void *page_start,
void *page_end,
size_t stride,
5019 rb_objspace_t *
objspace = data->objspace;
5021 for (obj = (
VALUE)page_start; obj != (
VALUE)page_end; obj += stride) {
5022 asan_unpoisoning_object(obj) {
5023 if (!rb_gc_impl_garbage_object_p(
objspace, obj)) {
5025 data->live_object_count++;
5030 if (!gc_object_moved_p(
objspace, obj)) {
5032 rb_objspace_reachable_objects_from(obj, check_children_i, (
void *)data);
5036 if (RVALUE_OLD_P(
objspace, obj)) data->old_object_count++;
5037 if (RVALUE_WB_UNPROTECTED(
objspace, obj) && RVALUE_UNCOLLECTIBLE(
objspace, obj)) data->remembered_shady_count++;
5042 rb_objspace_reachable_objects_from(obj, check_generation_i, (
void *)data);
5045 if (!is_marking(
objspace) && rb_gc_obj_shareable_p(obj)) {
5046 rb_gc_verify_shareable(obj);
5049 if (is_incremental_marking(
objspace)) {
5050 if (RVALUE_BLACK_P(
objspace, obj)) {
5053 rb_objspace_reachable_objects_from(obj, check_color_i, (
void *)data);
5059 data->zombie_object_count++;
5062 fprintf(stderr,
"verify_internal_consistency_i: T_ZOMBIE has extra flags set: %s\n",
5068 fprintf(stderr,
"verify_internal_consistency_i: FL_FINALIZE %s but %s finalizer_table: %s\n",
5069 FL_TEST(obj,
FL_FINALIZE) ?
"set" :
"not set", st_is_member(finalizer_table, obj) ?
"in" :
"not in",
5084 unsigned int has_remembered_shady = FALSE;
5085 unsigned int has_remembered_old = FALSE;
5086 int remembered_old_objects = 0;
5087 int free_objects = 0;
5088 int zombie_objects = 0;
5090 short slot_size = page->slot_size;
5091 uintptr_t start = (uintptr_t)page->start;
5092 uintptr_t end = start + page->total_slots * slot_size;
5094 for (uintptr_t
ptr = start;
ptr < end;
ptr += slot_size) {
5096 asan_unpoisoning_object(val) {
5101 if (RVALUE_PAGE_UNCOLLECTIBLE(page, val) && RVALUE_PAGE_WB_UNPROTECTED(page, val)) {
5102 has_remembered_shady = TRUE;
5104 if (RVALUE_PAGE_MARKING(page, val)) {
5105 has_remembered_old = TRUE;
5106 remembered_old_objects++;
5111 if (!is_incremental_marking(
objspace) &&
5112 page->flags.has_remembered_objects == FALSE && has_remembered_old == TRUE) {
5114 for (uintptr_t
ptr = start;
ptr < end;
ptr += slot_size) {
5116 if (RVALUE_PAGE_MARKING(page, val)) {
5117 fprintf(stderr,
"marking -> %s\n", rb_obj_info(val));
5120 rb_bug(
"page %p's has_remembered_objects should be false, but there are remembered old objects (%d). %s",
5121 (
void *)page, remembered_old_objects, obj ? rb_obj_info(obj) :
"");
5124 if (page->flags.has_uncollectible_wb_unprotected_objects == FALSE && has_remembered_shady == TRUE) {
5125 rb_bug(
"page %p's has_remembered_shady should be false, but there are remembered shady objects. %s",
5126 (
void *)page, obj ? rb_obj_info(obj) :
"");
5131 if (page->free_slots != free_objects) {
5132 rb_bug(
"page %p's free_slots should be %d, but %d", (
void *)page, page->free_slots, free_objects);
5135 if (page->final_slots != zombie_objects) {
5136 rb_bug(
"page %p's final_slots should be %d, but %d", (
void *)page, page->final_slots, zombie_objects);
5139 return remembered_old_objects;
5143gc_verify_heap_pages_(rb_objspace_t *
objspace,
struct ccan_list_head *head)
5145 int remembered_old_objects = 0;
5148 ccan_list_for_each(head, page, page_node) {
5149 asan_unlock_freelist(page);
5154 rb_asan_unpoison_object(vp,
false);
5156 fprintf(stderr,
"freelist slot expected to be T_NONE but was: %s\n", rb_obj_info(vp));
5159 rb_asan_poison_object(prev);
5161 asan_lock_freelist(page);
5163 if (page->flags.has_remembered_objects == FALSE) {
5164 remembered_old_objects += gc_verify_heap_page(
objspace, page,
Qfalse);
5168 return remembered_old_objects;
5172gc_verify_heap_pages(rb_objspace_t *
objspace)
5174 int remembered_old_objects = 0;
5175 for (
int i = 0; i < HEAP_COUNT; i++) {
5176 remembered_old_objects += gc_verify_heap_pages_(
objspace, &((&heaps[i])->pages));
5178 return remembered_old_objects;
5182gc_verify_internal_consistency_(rb_objspace_t *
objspace)
5187 gc_report(5,
objspace,
"gc_verify_internal_consistency: start\n");
5190 for (
size_t i = 0; i < rb_darray_size(
objspace->heap_pages.sorted); i++) {
5192 short slot_size = page->slot_size;
5194 uintptr_t start = (uintptr_t)page->start;
5195 uintptr_t end = start + page->total_slots * slot_size;
5197 verify_internal_consistency_i((
void *)start, (
void *)end, slot_size, &data);
5200 if (data.err_count != 0) {
5201#if RGENGC_CHECK_MODE >= 5
5202 objspace->rgengc.error_count = data.err_count;
5203 gc_marks_check(
objspace, NULL, NULL);
5206 rb_bug(
"gc_verify_internal_consistency: found internal inconsistency.");
5214 ractor_cache_flush_count(
objspace, rb_gc_get_ractor_newobj_cache());
5218 !rb_gc_multi_ractor_p()) {
5219 if (objspace_live_slots(
objspace) != data.live_object_count) {
5220 fprintf(stderr,
"heap_pages_final_slots: %"PRIdSIZE
", total_freed_objects: %"PRIdSIZE
"\n",
5222 rb_bug(
"inconsistent live slot number: expect %"PRIuSIZE
", but %"PRIuSIZE
".",
5223 objspace_live_slots(
objspace), data.live_object_count);
5228 if (
objspace->rgengc.old_objects != data.old_object_count) {
5229 rb_bug(
"inconsistent old slot number: expect %"PRIuSIZE
", but %"PRIuSIZE
".",
5230 objspace->rgengc.old_objects, data.old_object_count);
5232 if (
objspace->rgengc.uncollectible_wb_unprotected_objects != data.remembered_shady_count) {
5233 rb_bug(
"inconsistent number of wb unprotected objects: expect %"PRIuSIZE
", but %"PRIuSIZE
".",
5234 objspace->rgengc.uncollectible_wb_unprotected_objects, data.remembered_shady_count);
5239 size_t list_count = 0;
5242 VALUE z = heap_pages_deferred_final;
5245 z = RZOMBIE(z)->next;
5249 if (total_final_slots_count(
objspace) != data.zombie_object_count ||
5250 total_final_slots_count(
objspace) != list_count) {
5252 rb_bug(
"inconsistent finalizing object count:\n"
5253 " expect %"PRIuSIZE
"\n"
5254 " but %"PRIuSIZE
" zombies\n"
5255 " heap_pages_deferred_final list has %"PRIuSIZE
" items.",
5257 data.zombie_object_count,
5262 gc_report(5,
objspace,
"gc_verify_internal_consistency: OK\n");
5266gc_verify_internal_consistency(
void *objspace_ptr)
5268 rb_objspace_t *
objspace = objspace_ptr;
5270 unsigned int lev = RB_GC_VM_LOCK();
5274 unsigned int prev_during_gc = during_gc;
5277 gc_verify_internal_consistency_(
objspace);
5279 during_gc = prev_during_gc;
5281 RB_GC_VM_UNLOCK(lev);
5285heap_move_pooled_pages_to_free_pages(rb_heap_t *heap)
5287 if (heap->pooled_pages) {
5288 if (heap->free_pages) {
5289 struct heap_page *free_pages_tail = heap->free_pages;
5290 while (free_pages_tail->free_next) {
5291 free_pages_tail = free_pages_tail->free_next;
5293 free_pages_tail->free_next = heap->pooled_pages;
5296 heap->free_pages = heap->pooled_pages;
5299 heap->pooled_pages = NULL;
5306 struct heap_page *page = GET_HEAP_PAGE(obj);
5307 bits_t *uncollectible_bits = &page->uncollectible_bits[0];
5309 if (!MARKED_IN_BITMAP(uncollectible_bits, obj)) {
5310 page->flags.has_uncollectible_wb_unprotected_objects = TRUE;
5311 MARK_IN_BITMAP(uncollectible_bits, obj);
5312 objspace->rgengc.uncollectible_wb_unprotected_objects++;
5314#if RGENGC_PROFILE > 0
5315 objspace->profile.total_remembered_shady_object_count++;
5316#if RGENGC_PROFILE >= 2
5328gc_marks_wb_unprotected_objects_plane(rb_objspace_t *
objspace, uintptr_t p, bits_t bits)
5333 gc_report(2,
objspace,
"gc_marks_wb_unprotected_objects: marked shady: %s\n", rb_obj_info((
VALUE)p));
5338 p += BASE_SLOT_SIZE;
5345gc_marks_wb_unprotected_objects(rb_objspace_t *
objspace, rb_heap_t *heap)
5349 ccan_list_for_each(&heap->pages, page, page_node) {
5350 bits_t *mark_bits = page->mark_bits;
5351 bits_t *wbun_bits = page->wb_unprotected_bits;
5352 uintptr_t p = page->start;
5355 bits_t bits = mark_bits[0] & wbun_bits[0];
5356 bits >>= NUM_IN_PAGE(p);
5357 gc_marks_wb_unprotected_objects_plane(
objspace, p, bits);
5358 p += (BITS_BITLENGTH - NUM_IN_PAGE(p)) * BASE_SLOT_SIZE;
5360 for (j=1; j<HEAP_PAGE_BITMAP_LIMIT; j++) {
5361 bits_t bits = mark_bits[j] & wbun_bits[j];
5363 gc_marks_wb_unprotected_objects_plane(
objspace, p, bits);
5364 p += BITS_BITLENGTH * BASE_SLOT_SIZE;
5368 gc_mark_stacked_objects_all(
objspace);
5372gc_update_weak_references(rb_objspace_t *
objspace)
5374 size_t retained_weak_references_count = 0;
5376 rb_darray_foreach(
objspace->weak_references, i, ptr_ptr) {
5377 if (!*ptr_ptr)
continue;
5379 VALUE obj = **ptr_ptr;
5381 if (RB_SPECIAL_CONST_P(obj))
continue;
5383 if (!RVALUE_MARKED(
objspace, obj)) {
5387 retained_weak_references_count++;
5391 objspace->profile.retained_weak_references_count = retained_weak_references_count;
5393 rb_darray_clear(
objspace->weak_references);
5394 rb_darray_resize_capa_without_gc(&
objspace->weak_references, retained_weak_references_count);
5398gc_marks_finish(rb_objspace_t *
objspace)
5401 if (is_incremental_marking(
objspace)) {
5402 if (RGENGC_CHECK_MODE && is_mark_stack_empty(&
objspace->mark_stack) == 0) {
5403 rb_bug(
"gc_marks_finish: mark stack is not empty (%"PRIdSIZE
").",
5404 mark_stack_size(&
objspace->mark_stack));
5408 while (gc_mark_stacked_objects_incremental(
objspace, INT_MAX) ==
false);
5410#if RGENGC_CHECK_MODE >= 2
5411 if (gc_verify_heap_pages(
objspace) != 0) {
5412 rb_bug(
"gc_marks_finish (incremental): there are remembered old objects.");
5416 objspace->flags.during_incremental_marking = FALSE;
5418 for (
int i = 0; i < HEAP_COUNT; i++) {
5419 gc_marks_wb_unprotected_objects(
objspace, &heaps[i]);
5423 gc_update_weak_references(
objspace);
5425#if RGENGC_CHECK_MODE >= 2
5426 gc_verify_internal_consistency(
objspace);
5429#if RGENGC_CHECK_MODE >= 4
5431 gc_marks_check(
objspace, gc_check_after_marks_i,
"after_marks");
5436 const unsigned long r_mul =
objspace->live_ractor_cache_count > 8 ? 8 :
objspace->live_ractor_cache_count;
5438 size_t total_slots = objspace_available_slots(
objspace);
5439 size_t sweep_slots = total_slots -
objspace->marked_slots;
5440 size_t max_free_slots = (size_t)(total_slots * gc_params.heap_free_slots_max_ratio);
5441 size_t min_free_slots = (size_t)(total_slots * gc_params.heap_free_slots_min_ratio);
5442 if (min_free_slots < gc_params.heap_free_slots * r_mul) {
5443 min_free_slots = gc_params.heap_free_slots * r_mul;
5446 int full_marking = is_full_marking(
objspace);
5451 size_t total_init_slots = 0;
5452 for (
int i = 0; i < HEAP_COUNT; i++) {
5453 total_init_slots += gc_params.heap_init_slots[i] * r_mul;
5456 if (max_free_slots < total_init_slots) {
5457 max_free_slots = total_init_slots;
5460 if (sweep_slots > max_free_slots) {
5461 heap_pages_freeable_pages = (sweep_slots - max_free_slots) / HEAP_PAGE_OBJ_LIMIT;
5464 heap_pages_freeable_pages = 0;
5467 if (
objspace->heap_pages.allocatable_slots == 0 && sweep_slots < min_free_slots) {
5468 if (!full_marking) {
5469 if (
objspace->profile.count -
objspace->rgengc.last_major_gc < RVALUE_OLD_AGE) {
5470 full_marking = TRUE;
5473 gc_report(1,
objspace,
"gc_marks_finish: next is full GC!!)\n");
5474 gc_needs_major_flags |= GPR_FLAG_MAJOR_BY_NOFREE;
5479 heap_allocatable_slots_expand(
objspace, NULL, sweep_slots, total_slots);
5485 const double r = gc_params.oldobject_limit_factor;
5486 objspace->rgengc.uncollectible_wb_unprotected_objects_limit = MAX(
5487 (
size_t)(
objspace->rgengc.uncollectible_wb_unprotected_objects * r),
5488 (
size_t)(
objspace->rgengc.old_objects * gc_params.uncollectible_wb_unprotected_objects_limit_ratio)
5490 objspace->rgengc.old_objects_limit = (size_t)(
objspace->rgengc.old_objects * r);
5493 if (
objspace->rgengc.uncollectible_wb_unprotected_objects >
objspace->rgengc.uncollectible_wb_unprotected_objects_limit) {
5494 gc_needs_major_flags |= GPR_FLAG_MAJOR_BY_SHADY;
5497 gc_needs_major_flags |= GPR_FLAG_MAJOR_BY_OLDGEN;
5500 gc_report(1,
objspace,
"gc_marks_finish (marks %"PRIdSIZE
" objects, "
5501 "old %"PRIdSIZE
" objects, total %"PRIdSIZE
" slots, "
5502 "sweep %"PRIdSIZE
" slots, allocatable %"PRIdSIZE
" slots, next GC: %s)\n",
5504 gc_needs_major_flags ?
"major" :
"minor");
5508 rb_ractor_finish_marking();
5514gc_compact_heap_cursors_met_p(rb_heap_t *heap)
5516 return heap->sweeping_page == heap->compact_cursor;
5521gc_compact_destination_pool(rb_objspace_t *
objspace, rb_heap_t *src_pool,
VALUE obj)
5523 size_t obj_size = rb_gc_obj_optimal_size(obj);
5524 if (obj_size == 0) {
5528 GC_ASSERT(rb_gc_impl_size_allocatable_p(obj_size));
5530 size_t idx = heap_idx_for_size(obj_size);
5536gc_compact_move(rb_objspace_t *
objspace, rb_heap_t *heap,
VALUE src)
5539 GC_ASSERT(gc_is_moveable_obj(
objspace, src));
5541 rb_heap_t *dest_pool = gc_compact_destination_pool(
objspace, heap, src);
5542 uint32_t orig_shape = 0;
5543 uint32_t new_shape = 0;
5545 if (gc_compact_heap_cursors_met_p(dest_pool)) {
5546 return dest_pool != heap;
5550 orig_shape = rb_gc_get_shape(src);
5552 if (dest_pool != heap) {
5553 new_shape = rb_gc_rebuild_shape(src, dest_pool - heaps);
5555 if (new_shape == 0) {
5561 while (!try_move(
objspace, dest_pool, dest_pool->free_pages, src)) {
5563 .page = dest_pool->sweeping_page,
5572 lock_page_body(
objspace, GET_PAGE_BODY(src));
5573 gc_sweep_page(
objspace, dest_pool, &ctx);
5574 unlock_page_body(
objspace, GET_PAGE_BODY(src));
5576 if (dest_pool->sweeping_page->free_slots > 0) {
5577 heap_add_freepage(dest_pool, dest_pool->sweeping_page);
5580 dest_pool->sweeping_page = ccan_list_next(&dest_pool->pages, dest_pool->sweeping_page, page_node);
5581 if (gc_compact_heap_cursors_met_p(dest_pool)) {
5582 return dest_pool != heap;
5586 if (orig_shape != 0) {
5587 if (new_shape != 0) {
5589 rb_gc_set_shape(dest, new_shape);
5591 RMOVED(src)->original_shape_id = orig_shape;
5598gc_compact_plane(rb_objspace_t *
objspace, rb_heap_t *heap, uintptr_t p, bits_t bitset,
struct heap_page *page)
5600 short slot_size = page->slot_size;
5601 short slot_bits = slot_size / BASE_SLOT_SIZE;
5602 GC_ASSERT(slot_bits > 0);
5606 GC_ASSERT(vp % BASE_SLOT_SIZE == 0);
5611 if (gc_is_moveable_obj(
objspace, vp)) {
5612 if (!gc_compact_move(
objspace, heap, vp)) {
5619 bitset >>= slot_bits;
5627gc_compact_page(rb_objspace_t *
objspace, rb_heap_t *heap,
struct heap_page *page)
5629 GC_ASSERT(page == heap->compact_cursor);
5631 bits_t *mark_bits, *pin_bits;
5633 uintptr_t p = page->start;
5635 mark_bits = page->mark_bits;
5636 pin_bits = page->pinned_bits;
5639 bitset = (mark_bits[0] & ~pin_bits[0]);
5640 bitset >>= NUM_IN_PAGE(p);
5642 if (!gc_compact_plane(
objspace, heap, (uintptr_t)p, bitset, page))
5645 p += (BITS_BITLENGTH - NUM_IN_PAGE(p)) * BASE_SLOT_SIZE;
5647 for (
int j = 1; j < HEAP_PAGE_BITMAP_LIMIT; j++) {
5648 bitset = (mark_bits[j] & ~pin_bits[j]);
5650 if (!gc_compact_plane(
objspace, heap, (uintptr_t)p, bitset, page))
5653 p += BITS_BITLENGTH * BASE_SLOT_SIZE;
5660gc_compact_all_compacted_p(rb_objspace_t *
objspace)
5662 for (
int i = 0; i < HEAP_COUNT; i++) {
5663 rb_heap_t *heap = &heaps[i];
5665 if (heap->total_pages > 0 &&
5666 !gc_compact_heap_cursors_met_p(heap)) {
5675gc_sweep_compact(rb_objspace_t *
objspace)
5678#if RGENGC_CHECK_MODE >= 2
5679 gc_verify_internal_consistency(
objspace);
5682 while (!gc_compact_all_compacted_p(
objspace)) {
5683 for (
int i = 0; i < HEAP_COUNT; i++) {
5684 rb_heap_t *heap = &heaps[i];
5686 if (gc_compact_heap_cursors_met_p(heap)) {
5690 struct heap_page *start_page = heap->compact_cursor;
5692 if (!gc_compact_page(
objspace, heap, start_page)) {
5693 lock_page_body(
objspace, start_page->body);
5700 lock_page_body(
objspace, start_page->body);
5701 heap->compact_cursor = ccan_list_prev(&heap->pages, heap->compact_cursor, page_node);
5707#if RGENGC_CHECK_MODE >= 2
5708 gc_verify_internal_consistency(
objspace);
5713gc_marks_rest(rb_objspace_t *
objspace)
5715 gc_report(1,
objspace,
"gc_marks_rest\n");
5717 for (
int i = 0; i < HEAP_COUNT; i++) {
5718 (&heaps[i])->pooled_pages = NULL;
5721 if (is_incremental_marking(
objspace)) {
5722 while (gc_mark_stacked_objects_incremental(
objspace, INT_MAX) == FALSE);
5725 gc_mark_stacked_objects_all(
objspace);
5732gc_marks_step(rb_objspace_t *
objspace,
size_t slots)
5734 bool marking_finished =
false;
5737 if (gc_mark_stacked_objects_incremental(
objspace, slots)) {
5740 marking_finished =
true;
5743 return marking_finished;
5747gc_marks_continue(rb_objspace_t *
objspace, rb_heap_t *heap)
5749 GC_ASSERT(dont_gc_val() == FALSE ||
objspace->profile.latest_gc_info & GPR_FLAG_METHOD);
5750 bool marking_finished =
true;
5754 if (heap->free_pages) {
5755 gc_report(2,
objspace,
"gc_marks_continue: has pooled pages");
5760 gc_report(2,
objspace,
"gc_marks_continue: no more pooled pages (stack depth: %"PRIdSIZE
").\n",
5761 mark_stack_size(&
objspace->mark_stack));
5762 heap->force_incremental_marking_finish_count++;
5768 return marking_finished;
5772gc_marks_start(rb_objspace_t *
objspace,
int full_mark)
5775 gc_report(1,
objspace,
"gc_marks_start: (%s)\n", full_mark ?
"full" :
"minor");
5776 gc_mode_transition(
objspace, gc_mode_marking);
5779 size_t incremental_marking_steps = (
objspace->rincgc.pooled_slots / INCREMENTAL_MARK_STEP_ALLOCATIONS) + 1;
5780 objspace->rincgc.step_slots = (
objspace->marked_slots * 2) / incremental_marking_steps;
5782 if (0) fprintf(stderr,
"objspace->marked_slots: %"PRIdSIZE
", "
5783 "objspace->rincgc.pooled_page_num: %"PRIdSIZE
", "
5784 "objspace->rincgc.step_slots: %"PRIdSIZE
", \n",
5786 objspace->flags.during_minor_gc = FALSE;
5787 if (ruby_enable_autocompact) {
5788 objspace->flags.during_compacting |= TRUE;
5790 objspace->profile.major_gc_count++;
5791 objspace->rgengc.uncollectible_wb_unprotected_objects = 0;
5796 for (
int i = 0; i < HEAP_COUNT; i++) {
5797 rb_heap_t *heap = &heaps[i];
5798 rgengc_mark_and_rememberset_clear(
objspace, heap);
5799 heap_move_pooled_pages_to_free_pages(heap);
5801 if (
objspace->flags.during_compacting) {
5804 ccan_list_for_each(&heap->pages, page, page_node) {
5805 page->pinned_slots = 0;
5811 objspace->flags.during_minor_gc = TRUE;
5813 objspace->rgengc.old_objects +
objspace->rgengc.uncollectible_wb_unprotected_objects;
5814 objspace->profile.minor_gc_count++;
5816 for (
int i = 0; i < HEAP_COUNT; i++) {
5817 rgengc_rememberset_mark(
objspace, &heaps[i]);
5823 gc_report(1,
objspace,
"gc_marks_start: (%s) end, stack in %"PRIdSIZE
"\n",
5824 full_mark ?
"full" :
"minor", mark_stack_size(&
objspace->mark_stack));
5828gc_marks(rb_objspace_t *
objspace,
int full_mark)
5830 gc_prof_mark_timer_start(
objspace);
5833 bool marking_finished =
false;
5837 gc_marks_start(
objspace, full_mark);
5838 if (!is_incremental_marking(
objspace)) {
5840 marking_finished =
true;
5843#if RGENGC_PROFILE > 0
5846 record->old_objects =
objspace->rgengc.old_objects;
5853 return marking_finished;
5859gc_report_body(
int level, rb_objspace_t *
objspace,
const char *fmt, ...)
5861 if (level <= RGENGC_DEBUG) {
5865 const char *status =
" ";
5868 status = is_full_marking(
objspace) ?
"+" :
"-";
5874 if (is_incremental_marking(
objspace)) {
5879 va_start(args, fmt);
5880 vsnprintf(buf, 1024, fmt, args);
5883 fprintf(out,
"%s|", status);
5891rgengc_remembersetbits_set(rb_objspace_t *
objspace,
VALUE obj)
5893 struct heap_page *page = GET_HEAP_PAGE(obj);
5894 bits_t *bits = &page->remembered_bits[0];
5896 if (MARKED_IN_BITMAP(bits, obj)) {
5900 page->flags.has_remembered_objects = TRUE;
5901 MARK_IN_BITMAP(bits, obj);
5912 gc_report(6,
objspace,
"rgengc_remember: %s %s\n", rb_obj_info(obj),
5913 RVALUE_REMEMBERED(
objspace, obj) ?
"was already remembered" :
"is remembered now");
5915 check_rvalue_consistency(
objspace, obj);
5917 if (RGENGC_CHECK_MODE) {
5918 if (RVALUE_WB_UNPROTECTED(
objspace, obj)) rb_bug(
"rgengc_remember: %s is not wb protected.", rb_obj_info(obj));
5921#if RGENGC_PROFILE > 0
5922 if (!RVALUE_REMEMBERED(
objspace, obj)) {
5923 if (RVALUE_WB_UNPROTECTED(
objspace, obj) == 0) {
5924 objspace->profile.total_remembered_normal_object_count++;
5925#if RGENGC_PROFILE >= 2
5932 return rgengc_remembersetbits_set(
objspace, obj);
5935#ifndef PROFILE_REMEMBERSET_MARK
5936#define PROFILE_REMEMBERSET_MARK 0
5940rgengc_rememberset_mark_plane(rb_objspace_t *
objspace, uintptr_t p, bits_t bitset)
5946 gc_report(2,
objspace,
"rgengc_rememberset_mark: mark %s\n", rb_obj_info(obj));
5947 GC_ASSERT(RVALUE_UNCOLLECTIBLE(
objspace, obj));
5948 GC_ASSERT(RVALUE_OLD_P(
objspace, obj) || RVALUE_WB_UNPROTECTED(
objspace, obj));
5952 p += BASE_SLOT_SIZE;
5959rgengc_rememberset_mark(rb_objspace_t *
objspace, rb_heap_t *heap)
5963#if PROFILE_REMEMBERSET_MARK
5964 int has_old = 0, has_shady = 0, has_both = 0, skip = 0;
5966 gc_report(1,
objspace,
"rgengc_rememberset_mark: start\n");
5968 ccan_list_for_each(&heap->pages, page, page_node) {
5969 if (page->flags.has_remembered_objects | page->flags.has_uncollectible_wb_unprotected_objects) {
5970 uintptr_t p = page->start;
5971 bits_t bitset, bits[HEAP_PAGE_BITMAP_LIMIT];
5972 bits_t *remembered_bits = page->remembered_bits;
5973 bits_t *uncollectible_bits = page->uncollectible_bits;
5974 bits_t *wb_unprotected_bits = page->wb_unprotected_bits;
5975#if PROFILE_REMEMBERSET_MARK
5976 if (page->flags.has_remembered_objects && page->flags.has_uncollectible_wb_unprotected_objects) has_both++;
5977 else if (page->flags.has_remembered_objects) has_old++;
5978 else if (page->flags.has_uncollectible_wb_unprotected_objects) has_shady++;
5980 for (j=0; j<HEAP_PAGE_BITMAP_LIMIT; j++) {
5981 bits[j] = remembered_bits[j] | (uncollectible_bits[j] & wb_unprotected_bits[j]);
5982 remembered_bits[j] = 0;
5984 page->flags.has_remembered_objects = FALSE;
5987 bitset >>= NUM_IN_PAGE(p);
5988 rgengc_rememberset_mark_plane(
objspace, p, bitset);
5989 p += (BITS_BITLENGTH - NUM_IN_PAGE(p)) * BASE_SLOT_SIZE;
5991 for (j=1; j < HEAP_PAGE_BITMAP_LIMIT; j++) {
5993 rgengc_rememberset_mark_plane(
objspace, p, bitset);
5994 p += BITS_BITLENGTH * BASE_SLOT_SIZE;
5997#if PROFILE_REMEMBERSET_MARK
6004#if PROFILE_REMEMBERSET_MARK
6005 fprintf(stderr,
"%d\t%d\t%d\t%d\n", has_both, has_old, has_shady, skip);
6007 gc_report(1,
objspace,
"rgengc_rememberset_mark: finished\n");
6011rgengc_mark_and_rememberset_clear(rb_objspace_t *
objspace, rb_heap_t *heap)
6015 ccan_list_for_each(&heap->pages, page, page_node) {
6016 memset(&page->mark_bits[0], 0, HEAP_PAGE_BITMAP_SIZE);
6017 memset(&page->uncollectible_bits[0], 0, HEAP_PAGE_BITMAP_SIZE);
6018 memset(&page->marking_bits[0], 0, HEAP_PAGE_BITMAP_SIZE);
6019 memset(&page->remembered_bits[0], 0, HEAP_PAGE_BITMAP_SIZE);
6020 memset(&page->pinned_bits[0], 0, HEAP_PAGE_BITMAP_SIZE);
6021 page->flags.has_uncollectible_wb_unprotected_objects = FALSE;
6022 page->flags.has_remembered_objects = FALSE;
6028NOINLINE(
static void gc_writebarrier_generational(
VALUE a,
VALUE b, rb_objspace_t *
objspace));
6033 if (RGENGC_CHECK_MODE) {
6034 if (!RVALUE_OLD_P(
objspace, a)) rb_bug(
"gc_writebarrier_generational: %s is not an old object.", rb_obj_info(a));
6035 if ( RVALUE_OLD_P(
objspace, b)) rb_bug(
"gc_writebarrier_generational: %s is an old object.", rb_obj_info(b));
6036 if (is_incremental_marking(
objspace)) rb_bug(
"gc_writebarrier_generational: called while incremental marking: %s -> %s", rb_obj_info(a), rb_obj_info(b));
6040 if (!RVALUE_REMEMBERED(
objspace, a)) {
6041 int lev = RB_GC_VM_LOCK_NO_BARRIER();
6045 RB_GC_VM_UNLOCK_NO_BARRIER(lev);
6047 gc_report(1,
objspace,
"gc_writebarrier_generational: %s (remembered) -> %s\n", rb_obj_info(a), rb_obj_info(b));
6050 check_rvalue_consistency(
objspace, a);
6051 check_rvalue_consistency(
objspace, b);
6057 gc_mark_set_parent(
objspace, parent);
6058 rgengc_check_relation(
objspace, obj);
6059 if (gc_mark_set(
objspace, obj) != FALSE) {
6063 gc_mark_set_parent_invalid(
objspace);
6066NOINLINE(
static void gc_writebarrier_incremental(
VALUE a,
VALUE b, rb_objspace_t *
objspace));
6071 gc_report(2,
objspace,
"gc_writebarrier_incremental: [LG] %p -> %s\n", (
void *)a, rb_obj_info(b));
6075 if (!RVALUE_WB_UNPROTECTED(
objspace, a)) {
6076 gc_report(2,
objspace,
"gc_writebarrier_incremental: [IN] %p -> %s\n", (
void *)a, rb_obj_info(b));
6084 if (RB_UNLIKELY(
objspace->flags.during_compacting)) {
6085 MARK_IN_BITMAP(GET_HEAP_PINNED_BITS(b), b);
6091rb_gc_impl_writebarrier(
void *objspace_ptr,
VALUE a,
VALUE b)
6093 rb_objspace_t *
objspace = objspace_ptr;
6095#if RGENGC_CHECK_MODE
6096 if (
SPECIAL_CONST_P(a)) rb_bug(
"rb_gc_writebarrier: a is special const: %"PRIxVALUE, a);
6097 if (
SPECIAL_CONST_P(b)) rb_bug(
"rb_gc_writebarrier: b is special const: %"PRIxVALUE, b);
6103 GC_ASSERT(!during_gc);
6104 GC_ASSERT(RB_BUILTIN_TYPE(a) !=
T_NONE);
6105 GC_ASSERT(RB_BUILTIN_TYPE(a) !=
T_MOVED);
6106 GC_ASSERT(RB_BUILTIN_TYPE(a) !=
T_ZOMBIE);
6107 GC_ASSERT(RB_BUILTIN_TYPE(b) !=
T_NONE);
6108 GC_ASSERT(RB_BUILTIN_TYPE(b) !=
T_MOVED);
6109 GC_ASSERT(RB_BUILTIN_TYPE(b) !=
T_ZOMBIE);
6112 if (!is_incremental_marking(
objspace)) {
6117 gc_writebarrier_generational(a, b,
objspace);
6123 int lev = RB_GC_VM_LOCK_NO_BARRIER();
6125 if (is_incremental_marking(
objspace)) {
6126 gc_writebarrier_incremental(a, b,
objspace);
6132 RB_GC_VM_UNLOCK_NO_BARRIER(lev);
6134 if (retry)
goto retry;
6140rb_gc_impl_writebarrier_unprotect(
void *objspace_ptr,
VALUE obj)
6142 rb_objspace_t *
objspace = objspace_ptr;
6144 if (RVALUE_WB_UNPROTECTED(
objspace, obj)) {
6148 gc_report(2,
objspace,
"rb_gc_writebarrier_unprotect: %s %s\n", rb_obj_info(obj),
6149 RVALUE_REMEMBERED(
objspace, obj) ?
" (already remembered)" :
"");
6151 unsigned int lev = RB_GC_VM_LOCK_NO_BARRIER();
6154 gc_report(1,
objspace,
"rb_gc_writebarrier_unprotect: %s\n", rb_obj_info(obj));
6157 gc_remember_unprotected(
objspace, obj);
6160 objspace->profile.total_shade_operation_count++;
6161#if RGENGC_PROFILE >= 2
6167 RVALUE_AGE_RESET(obj);
6170 RB_DEBUG_COUNTER_INC(obj_wb_unprotect);
6171 MARK_IN_BITMAP(GET_HEAP_WB_UNPROTECTED_BITS(obj), obj);
6173 RB_GC_VM_UNLOCK_NO_BARRIER(lev);
6178rb_gc_impl_copy_attributes(
void *objspace_ptr,
VALUE dest,
VALUE obj)
6180 rb_objspace_t *
objspace = objspace_ptr;
6182 if (RVALUE_WB_UNPROTECTED(
objspace, obj)) {
6183 rb_gc_impl_writebarrier_unprotect(
objspace, dest);
6185 rb_gc_impl_copy_finalizer(
objspace, dest, obj);
6189rb_gc_impl_active_gc_name(
void)
6195rb_gc_impl_writebarrier_remember(
void *objspace_ptr,
VALUE obj)
6197 rb_objspace_t *
objspace = objspace_ptr;
6199 gc_report(1,
objspace,
"rb_gc_writebarrier_remember: %s\n", rb_obj_info(obj));
6202 int lev = RB_GC_VM_LOCK_NO_BARRIER();
6204 if (is_incremental_marking(
objspace)) {
6205 if (RVALUE_BLACK_P(
objspace, obj)) {
6209 else if (RVALUE_OLD_P(
objspace, obj)) {
6213 RB_GC_VM_UNLOCK_NO_BARRIER(lev);
6219 ID ID_wb_protected, ID_age, ID_old, ID_uncollectible, ID_marking,
6220 ID_marked, ID_pinned, ID_remembered, ID_object_id, ID_shareable;
6223#define RB_GC_OBJECT_METADATA_ENTRY_COUNT (sizeof(struct rb_gc_object_metadata_names) / sizeof(ID))
6227rb_gc_impl_object_metadata(
void *objspace_ptr,
VALUE obj)
6229 rb_objspace_t *
objspace = objspace_ptr;
6233 if (!names.ID_marked) {
6234#define I(s) names.ID_##s = rb_intern(#s)
6248#define SET_ENTRY(na, v) do { \
6249 GC_ASSERT(n <= RB_GC_OBJECT_METADATA_ENTRY_COUNT); \
6250 object_metadata_entries[n].name = names.ID_##na; \
6251 object_metadata_entries[n].val = v; \
6255 if (!RVALUE_WB_UNPROTECTED(
objspace, obj)) SET_ENTRY(wb_protected,
Qtrue);
6256 SET_ENTRY(age,
INT2FIX(RVALUE_AGE_GET(obj)));
6258 if (RVALUE_UNCOLLECTIBLE(
objspace, obj)) SET_ENTRY(uncollectible,
Qtrue);
6259 if (RVALUE_MARKING(
objspace, obj)) SET_ENTRY(marking,
Qtrue);
6262 if (RVALUE_REMEMBERED(
objspace, obj)) SET_ENTRY(remembered,
Qtrue);
6263 if (rb_obj_id_p(obj)) SET_ENTRY(object_id, rb_obj_id(obj));
6266 object_metadata_entries[n].name = 0;
6267 object_metadata_entries[n].val = 0;
6270 return object_metadata_entries;
6274rb_gc_impl_ractor_cache_alloc(
void *objspace_ptr,
void *ractor)
6276 rb_objspace_t *
objspace = objspace_ptr;
6278 objspace->live_ractor_cache_count++;
6280 return calloc1(
sizeof(rb_ractor_newobj_cache_t));
6284rb_gc_impl_ractor_cache_free(
void *objspace_ptr,
void *cache)
6286 rb_objspace_t *
objspace = objspace_ptr;
6288 objspace->live_ractor_cache_count--;
6289 gc_ractor_newobj_cache_clear(cache, NULL);
6294heap_ready_to_gc(rb_objspace_t *
objspace, rb_heap_t *heap)
6296 if (!heap->free_pages) {
6297 if (!heap_page_allocate_and_initialize(
objspace, heap)) {
6298 objspace->heap_pages.allocatable_slots = 1;
6299 heap_page_allocate_and_initialize(
objspace, heap);
6305ready_to_gc(rb_objspace_t *
objspace)
6307 if (dont_gc_val() || during_gc) {
6308 for (
int i = 0; i < HEAP_COUNT; i++) {
6309 rb_heap_t *heap = &heaps[i];
6320gc_reset_malloc_info(rb_objspace_t *
objspace,
bool full_mark)
6325 size_t old_limit = malloc_limit;
6327 if (inc > malloc_limit) {
6328 malloc_limit = (size_t)(inc * gc_params.malloc_limit_growth_factor);
6329 if (malloc_limit > gc_params.malloc_limit_max) {
6330 malloc_limit = gc_params.malloc_limit_max;
6334 malloc_limit = (size_t)(malloc_limit * 0.98);
6335 if (malloc_limit < gc_params.malloc_limit_min) {
6336 malloc_limit = gc_params.malloc_limit_min;
6341 if (old_limit != malloc_limit) {
6342 fprintf(stderr,
"[%"PRIuSIZE
"] malloc_limit: %"PRIuSIZE
" -> %"PRIuSIZE
"\n",
6343 rb_gc_count(), old_limit, malloc_limit);
6346 fprintf(stderr,
"[%"PRIuSIZE
"] malloc_limit: not changed (%"PRIuSIZE
")\n",
6347 rb_gc_count(), malloc_limit);
6353#if RGENGC_ESTIMATE_OLDMALLOC
6355 if (
objspace->malloc_counters.oldmalloc_increase >
objspace->rgengc.oldmalloc_increase_limit) {
6356 gc_needs_major_flags |= GPR_FLAG_MAJOR_BY_OLDMALLOC;
6357 objspace->rgengc.oldmalloc_increase_limit =
6358 (size_t)(
objspace->rgengc.oldmalloc_increase_limit * gc_params.oldmalloc_limit_growth_factor);
6360 if (
objspace->rgengc.oldmalloc_increase_limit > gc_params.oldmalloc_limit_max) {
6361 objspace->rgengc.oldmalloc_increase_limit = gc_params.oldmalloc_limit_max;
6365 if (0) fprintf(stderr,
"%"PRIdSIZE
"\t%d\t%"PRIuSIZE
"\t%"PRIuSIZE
"\t%"PRIdSIZE
"\n",
6367 gc_needs_major_flags,
6368 objspace->malloc_counters.oldmalloc_increase,
6369 objspace->rgengc.oldmalloc_increase_limit,
6370 gc_params.oldmalloc_limit_max);
6374 objspace->malloc_counters.oldmalloc_increase = 0;
6376 if ((
objspace->profile.latest_gc_info & GPR_FLAG_MAJOR_BY_OLDMALLOC) == 0) {
6377 objspace->rgengc.oldmalloc_increase_limit =
6378 (size_t)(
objspace->rgengc.oldmalloc_increase_limit / ((gc_params.oldmalloc_limit_growth_factor - 1)/10 + 1));
6379 if (
objspace->rgengc.oldmalloc_increase_limit < gc_params.oldmalloc_limit_min) {
6380 objspace->rgengc.oldmalloc_increase_limit = gc_params.oldmalloc_limit_min;
6388garbage_collect(rb_objspace_t *
objspace,
unsigned int reason)
6392 int lev = RB_GC_VM_LOCK();
6394#if GC_PROFILE_MORE_DETAIL
6395 objspace->profile.prepare_time = getrusage_time();
6400#if GC_PROFILE_MORE_DETAIL
6401 objspace->profile.prepare_time = getrusage_time() -
objspace->profile.prepare_time;
6406 RB_GC_VM_UNLOCK(lev);
6412gc_start(rb_objspace_t *
objspace,
unsigned int reason)
6414 unsigned int do_full_mark = !!(reason & GPR_FLAG_FULL_MARK);
6416 if (!rb_darray_size(
objspace->heap_pages.sorted))
return TRUE;
6417 if (!(reason & GPR_FLAG_METHOD) && !ready_to_gc(
objspace))
return TRUE;
6419 GC_ASSERT(gc_mode(
objspace) == gc_mode_none,
"gc_mode is %s\n", gc_mode_name(gc_mode(
objspace)));
6420 GC_ASSERT(!is_lazy_sweeping(
objspace));
6421 GC_ASSERT(!is_incremental_marking(
objspace));
6423 unsigned int lock_lev;
6424 gc_enter(
objspace, gc_enter_event_start, &lock_lev);
6427 objspace->flags.immediate_sweep = !!(reason & GPR_FLAG_IMMEDIATE_SWEEP);
6429#if RGENGC_CHECK_MODE >= 2
6430 gc_verify_internal_consistency(
objspace);
6433 if (ruby_gc_stressful) {
6434 int flag =
FIXNUM_P(ruby_gc_stress_mode) ?
FIX2INT(ruby_gc_stress_mode) : 0;
6436 if ((flag & (1 << gc_stress_no_major)) == 0) {
6437 do_full_mark = TRUE;
6440 objspace->flags.immediate_sweep = !(flag & (1<<gc_stress_no_immediate_sweep));
6443 if (gc_needs_major_flags) {
6444 reason |= gc_needs_major_flags;
6445 do_full_mark = TRUE;
6449 if (!gc_config_full_mark_val) {
6450 do_full_mark = FALSE;
6452 gc_needs_major_flags = GPR_FLAG_NONE;
6454 if (do_full_mark && (reason & GPR_FLAG_MAJOR_MASK) == 0) {
6455 reason |= GPR_FLAG_MAJOR_BY_FORCE;
6458 if (
objspace->flags.dont_incremental ||
6459 reason & GPR_FLAG_IMMEDIATE_MARK ||
6460 ruby_gc_stressful) {
6461 objspace->flags.during_incremental_marking = FALSE;
6464 objspace->flags.during_incremental_marking = do_full_mark;
6468 if (do_full_mark && ruby_enable_autocompact) {
6469 objspace->flags.during_compacting = TRUE;
6470#if RGENGC_CHECK_MODE
6471 objspace->rcompactor.compare_func = ruby_autocompact_compare_func;
6475 objspace->flags.during_compacting = !!(reason & GPR_FLAG_COMPACT);
6478 if (!GC_ENABLE_LAZY_SWEEP ||
objspace->flags.dont_incremental) {
6479 objspace->flags.immediate_sweep = TRUE;
6482 if (
objspace->flags.immediate_sweep) reason |= GPR_FLAG_IMMEDIATE_SWEEP;
6484 gc_report(1,
objspace,
"gc_start(reason: %x) => %u, %d, %d\n",
6486 do_full_mark, !is_incremental_marking(
objspace),
objspace->flags.immediate_sweep);
6488 RB_DEBUG_COUNTER_INC(gc_count);
6490 if (reason & GPR_FLAG_MAJOR_MASK) {
6491 (void)RB_DEBUG_COUNTER_INC_IF(gc_major_nofree, reason & GPR_FLAG_MAJOR_BY_NOFREE);
6492 (void)RB_DEBUG_COUNTER_INC_IF(gc_major_oldgen, reason & GPR_FLAG_MAJOR_BY_OLDGEN);
6493 (void)RB_DEBUG_COUNTER_INC_IF(gc_major_shady, reason & GPR_FLAG_MAJOR_BY_SHADY);
6494 (void)RB_DEBUG_COUNTER_INC_IF(gc_major_force, reason & GPR_FLAG_MAJOR_BY_FORCE);
6495#if RGENGC_ESTIMATE_OLDMALLOC
6496 (void)RB_DEBUG_COUNTER_INC_IF(gc_major_oldmalloc, reason & GPR_FLAG_MAJOR_BY_OLDMALLOC);
6500 (void)RB_DEBUG_COUNTER_INC_IF(gc_minor_newobj, reason & GPR_FLAG_NEWOBJ);
6501 (void)RB_DEBUG_COUNTER_INC_IF(gc_minor_malloc, reason & GPR_FLAG_MALLOC);
6502 (void)RB_DEBUG_COUNTER_INC_IF(gc_minor_method, reason & GPR_FLAG_METHOD);
6503 (void)RB_DEBUG_COUNTER_INC_IF(gc_minor_capi, reason & GPR_FLAG_CAPI);
6504 (void)RB_DEBUG_COUNTER_INC_IF(gc_minor_stress, reason & GPR_FLAG_STRESS);
6508 objspace->profile.latest_gc_info = reason;
6509 objspace->profile.total_allocated_objects_at_gc_start = total_allocated_objects(
objspace);
6510 objspace->profile.heap_used_at_gc_start = rb_darray_size(
objspace->heap_pages.sorted);
6511 objspace->profile.weak_references_count = 0;
6512 objspace->profile.retained_weak_references_count = 0;
6513 gc_prof_setup_new_record(
objspace, reason);
6514 gc_reset_malloc_info(
objspace, do_full_mark);
6518 GC_ASSERT(during_gc);
6522 if (gc_marks(
objspace, do_full_mark)) {
6528 gc_exit(
objspace, gc_enter_event_start, &lock_lev);
6536 unsigned int lock_lev;
6537 gc_enter(
objspace, gc_enter_event_rest, &lock_lev);
6539 if (RGENGC_CHECK_MODE >= 2) gc_verify_internal_consistency(
objspace);
6541 if (is_incremental_marking(
objspace)) {
6555 gc_exit(
objspace, gc_enter_event_rest, &lock_lev);
6560 rb_objspace_t *objspace;
6561 unsigned int reason;
6565gc_current_status_fill(rb_objspace_t *
objspace,
char *buff)
6570 if (is_full_marking(
objspace)) buff[i++] =
'F';
6571 if (is_incremental_marking(
objspace)) buff[i++] =
'I';
6575 if (is_lazy_sweeping(
objspace)) buff[i++] =
'L';
6584gc_current_status(rb_objspace_t *
objspace)
6586 static char buff[0x10];
6587 gc_current_status_fill(
objspace, buff);
6591#if PRINT_ENTER_EXIT_TICK
6593static tick_t last_exit_tick;
6594static tick_t enter_tick;
6595static int enter_count = 0;
6596static char last_gc_status[0x10];
6599gc_record(rb_objspace_t *
objspace,
int direction,
const char *event)
6601 if (direction == 0) {
6603 enter_tick = tick();
6604 gc_current_status_fill(
objspace, last_gc_status);
6607 tick_t exit_tick = tick();
6608 char current_gc_status[0x10];
6609 gc_current_status_fill(
objspace, current_gc_status);
6612 fprintf(stderr,
"%"PRItick
"\t%"PRItick
"\t%s\t[%s->%s|%c]\n",
6613 enter_tick - last_exit_tick,
6614 exit_tick - enter_tick,
6616 last_gc_status, current_gc_status,
6617 (
objspace->profile.latest_gc_info & GPR_FLAG_MAJOR_MASK) ?
'+' :
'-');
6618 last_exit_tick = exit_tick;
6621 fprintf(stderr,
"%"PRItick
"\t%"PRItick
"\t%s\t[%s->%s|%c]\n",
6623 exit_tick - enter_tick,
6625 last_gc_status, current_gc_status,
6626 (
objspace->profile.latest_gc_info & GPR_FLAG_MAJOR_MASK) ?
'+' :
'-');
6632gc_record(rb_objspace_t *
objspace,
int direction,
const char *event)
6639gc_enter_event_cstr(
enum gc_enter_event event)
6642 case gc_enter_event_start:
return "start";
6643 case gc_enter_event_continue:
return "continue";
6644 case gc_enter_event_rest:
return "rest";
6645 case gc_enter_event_finalizer:
return "finalizer";
6651gc_enter_count(
enum gc_enter_event event)
6654 case gc_enter_event_start: RB_DEBUG_COUNTER_INC(gc_enter_start);
break;
6655 case gc_enter_event_continue: RB_DEBUG_COUNTER_INC(gc_enter_continue);
break;
6656 case gc_enter_event_rest: RB_DEBUG_COUNTER_INC(gc_enter_rest);
break;
6657 case gc_enter_event_finalizer: RB_DEBUG_COUNTER_INC(gc_enter_finalizer);
break;
6661static bool current_process_time(
struct timespec *ts);
6666 if (!current_process_time(ts)) {
6672static unsigned long long
6677 if ((ts->tv_sec > 0 || ts->tv_nsec > 0) &&
6678 current_process_time(&end_time) &&
6679 end_time.tv_sec >= ts->tv_sec) {
6680 return (
unsigned long long)(end_time.tv_sec - ts->tv_sec) * (1000 * 1000 * 1000) +
6681 (end_time.tv_nsec - ts->tv_nsec);
6688gc_enter(rb_objspace_t *
objspace,
enum gc_enter_event event,
unsigned int *lock_lev)
6690 *lock_lev = RB_GC_VM_LOCK();
6693 case gc_enter_event_rest:
6694 case gc_enter_event_start:
6695 case gc_enter_event_continue:
6703 gc_enter_count(event);
6704 if (RB_UNLIKELY(during_gc != 0)) rb_bug(
"during_gc != 0");
6705 if (RGENGC_CHECK_MODE >= 3) gc_verify_internal_consistency(
objspace);
6708 RUBY_DEBUG_LOG(
"%s (%s)",gc_enter_event_cstr(event), gc_current_status(
objspace));
6709 gc_report(1,
objspace,
"gc_enter: %s [%s]\n", gc_enter_event_cstr(event), gc_current_status(
objspace));
6710 gc_record(
objspace, 0, gc_enter_event_cstr(event));
6716gc_exit(rb_objspace_t *
objspace,
enum gc_enter_event event,
unsigned int *lock_lev)
6718 GC_ASSERT(during_gc != 0);
6722 gc_record(
objspace, 1, gc_enter_event_cstr(event));
6723 RUBY_DEBUG_LOG(
"%s (%s)", gc_enter_event_cstr(event), gc_current_status(
objspace));
6724 gc_report(1,
objspace,
"gc_exit: %s [%s]\n", gc_enter_event_cstr(event), gc_current_status(
objspace));
6727 RB_GC_VM_UNLOCK(*lock_lev);
6731#define MEASURE_GC (objspace->flags.measure_gc)
6735gc_marking_enter(rb_objspace_t *
objspace)
6737 GC_ASSERT(during_gc != 0);
6740 gc_clock_start(&
objspace->profile.marking_start_time);
6745gc_marking_exit(rb_objspace_t *
objspace)
6747 GC_ASSERT(during_gc != 0);
6750 objspace->profile.marking_time_ns += gc_clock_end(&
objspace->profile.marking_start_time);
6755gc_sweeping_enter(rb_objspace_t *
objspace)
6757 GC_ASSERT(during_gc != 0);
6760 gc_clock_start(&
objspace->profile.sweeping_start_time);
6765gc_sweeping_exit(rb_objspace_t *
objspace)
6767 GC_ASSERT(during_gc != 0);
6770 objspace->profile.sweeping_time_ns += gc_clock_end(&
objspace->profile.sweeping_start_time);
6775gc_with_gvl(
void *
ptr)
6778 return (
void *)(
VALUE)garbage_collect(oar->objspace, oar->reason);
6781int ruby_thread_has_gvl_p(
void);
6784garbage_collect_with_gvl(rb_objspace_t *
objspace,
unsigned int reason)
6786 if (dont_gc_val()) {
6792 else if (!ruby_thread_has_gvl_p()) {
6796 oar.reason = reason;
6802 return garbage_collect(
objspace, reason);
6807gc_set_candidate_object_i(
void *vstart,
void *vend,
size_t stride,
void *data)
6809 rb_objspace_t *
objspace = (rb_objspace_t *)data;
6812 for (; v != (
VALUE)vend; v += stride) {
6813 asan_unpoisoning_object(v) {
6819 rb_gc_prepare_heap_process_object(v);
6821 RVALUE_AGE_SET_CANDIDATE(
objspace, v);
6831rb_gc_impl_start(
void *objspace_ptr,
bool full_mark,
bool immediate_mark,
bool immediate_sweep,
bool compact)
6833 rb_objspace_t *
objspace = objspace_ptr;
6834 unsigned int reason = (GPR_FLAG_FULL_MARK |
6835 GPR_FLAG_IMMEDIATE_MARK |
6836 GPR_FLAG_IMMEDIATE_SWEEP |
6839 int full_marking_p = gc_config_full_mark_val;
6840 gc_config_full_mark_set(TRUE);
6844 GC_ASSERT(GC_COMPACTION_SUPPORTED);
6846 reason |= GPR_FLAG_COMPACT;
6849 if (!full_mark) reason &= ~GPR_FLAG_FULL_MARK;
6850 if (!immediate_mark) reason &= ~GPR_FLAG_IMMEDIATE_MARK;
6851 if (!immediate_sweep) reason &= ~GPR_FLAG_IMMEDIATE_SWEEP;
6857 gc_config_full_mark_set(full_marking_p);
6861rb_gc_impl_prepare_heap(
void *objspace_ptr)
6863 rb_objspace_t *
objspace = objspace_ptr;
6865 size_t orig_total_slots = objspace_available_slots(
objspace);
6866 size_t orig_allocatable_slots =
objspace->heap_pages.allocatable_slots;
6868 rb_gc_impl_each_objects(
objspace, gc_set_candidate_object_i, objspace_ptr);
6870 double orig_max_free_slots = gc_params.heap_free_slots_max_ratio;
6872 gc_params.heap_free_slots_max_ratio = 0.0;
6873 rb_gc_impl_start(
objspace,
true,
true,
true,
true);
6874 gc_params.heap_free_slots_max_ratio = orig_max_free_slots;
6876 objspace->heap_pages.allocatable_slots = 0;
6877 heap_pages_freeable_pages =
objspace->empty_pages_count;
6878 heap_pages_free_unused_pages(objspace_ptr);
6879 GC_ASSERT(heap_pages_freeable_pages == 0);
6880 GC_ASSERT(
objspace->empty_pages_count == 0);
6881 objspace->heap_pages.allocatable_slots = orig_allocatable_slots;
6883 size_t total_slots = objspace_available_slots(
objspace);
6884 if (orig_total_slots > total_slots) {
6885 objspace->heap_pages.allocatable_slots += orig_total_slots - total_slots;
6888#if defined(HAVE_MALLOC_TRIM) && !defined(RUBY_ALTERNATIVE_MALLOC_HEADER)
6934 GC_ASSERT(st_is_member(finalizer_table, obj));
6938 GC_ASSERT(RVALUE_MARKED(
objspace, obj));
6939 GC_ASSERT(!RVALUE_PINNED(
objspace, obj));
6944 rb_bug(
"gc_is_moveable_obj: unreachable (%d)", (
int)
BUILTIN_TYPE(obj));
6951void rb_mv_generic_ivar(
VALUE src,
VALUE dst);
6954gc_move(rb_objspace_t *
objspace,
VALUE src,
VALUE dest,
size_t src_slot_size,
size_t slot_size)
6961 gc_report(4,
objspace,
"Moving object: %p -> %p\n", (
void *)src, (
void *)dest);
6964 GC_ASSERT(!MARKED_IN_BITMAP(GET_HEAP_MARK_BITS(dest), dest));
6966 GC_ASSERT(!RVALUE_MARKING(
objspace, src));
6969 marked = RVALUE_MARKED(
objspace, src);
6970 wb_unprotected = RVALUE_WB_UNPROTECTED(
objspace, src);
6971 uncollectible = RVALUE_UNCOLLECTIBLE(
objspace, src);
6972 bool remembered = RVALUE_REMEMBERED(
objspace, src);
6973 age = RVALUE_AGE_GET(src);
6976 CLEAR_IN_BITMAP(GET_HEAP_MARK_BITS(src), src);
6977 CLEAR_IN_BITMAP(GET_HEAP_WB_UNPROTECTED_BITS(src), src);
6978 CLEAR_IN_BITMAP(GET_HEAP_UNCOLLECTIBLE_BITS(src), src);
6979 CLEAR_IN_BITMAP(GET_HEAP_PAGE(src)->remembered_bits, src);
6982 memcpy((
void *)dest, (
void *)src, MIN(src_slot_size, slot_size));
6984 if (RVALUE_OVERHEAD > 0) {
6985 void *dest_overhead = (
void *)(((uintptr_t)dest) + slot_size - RVALUE_OVERHEAD);
6986 void *src_overhead = (
void *)(((uintptr_t)src) + src_slot_size - RVALUE_OVERHEAD);
6988 memcpy(dest_overhead, src_overhead, RVALUE_OVERHEAD);
6991 memset((
void *)src, 0, src_slot_size);
6992 RVALUE_AGE_SET_BITMAP(src, 0);
6996 MARK_IN_BITMAP(GET_HEAP_PAGE(dest)->remembered_bits, dest);
6999 CLEAR_IN_BITMAP(GET_HEAP_PAGE(dest)->remembered_bits, dest);
7003 MARK_IN_BITMAP(GET_HEAP_MARK_BITS(dest), dest);
7006 CLEAR_IN_BITMAP(GET_HEAP_MARK_BITS(dest), dest);
7009 if (wb_unprotected) {
7010 MARK_IN_BITMAP(GET_HEAP_WB_UNPROTECTED_BITS(dest), dest);
7013 CLEAR_IN_BITMAP(GET_HEAP_WB_UNPROTECTED_BITS(dest), dest);
7016 if (uncollectible) {
7017 MARK_IN_BITMAP(GET_HEAP_UNCOLLECTIBLE_BITS(dest), dest);
7020 CLEAR_IN_BITMAP(GET_HEAP_UNCOLLECTIBLE_BITS(dest), dest);
7023 RVALUE_AGE_SET(dest, age);
7026 RMOVED(src)->dummy =
Qundef;
7027 RMOVED(src)->destination = dest;
7030 GET_HEAP_PAGE(src)->heap->total_freed_objects++;
7031 GET_HEAP_PAGE(dest)->heap->total_allocated_objects++;
7036#if GC_CAN_COMPILE_COMPACTION
7038compare_pinned_slots(
const void *left,
const void *right,
void *dummy)
7043 left_page = *(
struct heap_page *
const *)left;
7044 right_page = *(
struct heap_page *
const *)right;
7046 return left_page->pinned_slots - right_page->pinned_slots;
7050compare_free_slots(
const void *left,
const void *right,
void *dummy)
7055 left_page = *(
struct heap_page *
const *)left;
7056 right_page = *(
struct heap_page *
const *)right;
7058 return left_page->free_slots - right_page->free_slots;
7062gc_sort_heap_by_compare_func(rb_objspace_t *
objspace, gc_compact_compare_func compare_func)
7064 for (
int j = 0; j < HEAP_COUNT; j++) {
7065 rb_heap_t *heap = &heaps[j];
7067 size_t total_pages = heap->total_pages;
7069 struct heap_page *page = 0, **page_list = malloc(size);
7072 heap->free_pages = NULL;
7073 ccan_list_for_each(&heap->pages, page, page_node) {
7074 page_list[i++] = page;
7078 GC_ASSERT((
size_t)i == total_pages);
7085 ccan_list_head_init(&heap->pages);
7087 for (i = 0; i < total_pages; i++) {
7088 ccan_list_add(&heap->pages, &page_list[i]->page_node);
7089 if (page_list[i]->free_slots != 0) {
7090 heap_add_freepage(heap, page_list[i]);
7100rb_gc_impl_object_moved_p(
void *objspace_ptr,
VALUE obj)
7102 return gc_object_moved_p(objspace_ptr, obj);
7106gc_ref_update(
void *vstart,
void *vend,
size_t stride, rb_objspace_t *
objspace,
struct heap_page *page)
7110 page->flags.has_uncollectible_wb_unprotected_objects = FALSE;
7111 page->flags.has_remembered_objects = FALSE;
7114 for (; v != (
VALUE)vend; v += stride) {
7115 asan_unpoisoning_object(v) {
7122 if (RVALUE_WB_UNPROTECTED(
objspace, v)) {
7123 page->flags.has_uncollectible_wb_unprotected_objects = TRUE;
7125 if (RVALUE_REMEMBERED(
objspace, v)) {
7126 page->flags.has_remembered_objects = TRUE;
7128 if (page->flags.before_sweep) {
7130 rb_gc_update_object_references(
objspace, v);
7134 rb_gc_update_object_references(
objspace, v);
7144gc_update_references_weak_table_i(
VALUE obj,
void *data)
7147 asan_unpoisoning_object(obj) {
7154gc_update_references_weak_table_replace_i(
VALUE *obj,
void *data)
7156 *obj = rb_gc_location(*obj);
7162gc_update_references(rb_objspace_t *
objspace)
7164 objspace->flags.during_reference_updating =
true;
7166 rb_gc_before_updating_jit_code();
7170 for (
int i = 0; i < HEAP_COUNT; i++) {
7171 bool should_set_mark_bits = TRUE;
7172 rb_heap_t *heap = &heaps[i];
7174 ccan_list_for_each(&heap->pages, page, page_node) {
7175 uintptr_t start = (uintptr_t)page->start;
7176 uintptr_t end = start + (page->total_slots * heap->slot_size);
7178 gc_ref_update((
void *)start, (
void *)end, heap->slot_size,
objspace, page);
7179 if (page == heap->sweeping_page) {
7180 should_set_mark_bits = FALSE;
7182 if (should_set_mark_bits) {
7183 gc_setup_mark_bits(page);
7188 gc_update_table_refs(finalizer_table);
7190 rb_gc_update_vm_references((
void *)
objspace);
7192 for (
int table = 0; table < RB_GC_VM_WEAK_TABLE_COUNT; table++) {
7193 rb_gc_vm_weak_table_foreach(
7194 gc_update_references_weak_table_i,
7195 gc_update_references_weak_table_replace_i,
7202 rb_gc_after_updating_jit_code();
7204 objspace->flags.during_reference_updating =
false;
7207#if GC_CAN_COMPILE_COMPACTION
7209root_obj_check_moved_i(
const char *category,
VALUE obj,
void *data)
7213 if (gc_object_moved_p(
objspace, obj)) {
7214 rb_bug(
"ROOT %s points to MOVED: %p -> %s", category, (
void *)obj, rb_obj_info(rb_gc_impl_location(
objspace, obj)));
7219reachable_object_check_moved_i(
VALUE ref,
void *data)
7222 if (gc_object_moved_p(rb_gc_get_objspace(), ref)) {
7223 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)));
7228heap_check_moved_i(
void *vstart,
void *vend,
size_t stride,
void *data)
7233 for (; v != (
VALUE)vend; v += stride) {
7234 if (gc_object_moved_p(
objspace, v)) {
7238 asan_unpoisoning_object(v) {
7244 if (!rb_gc_impl_garbage_object_p(
objspace, v)) {
7245 rb_objspace_reachable_objects_from(v, reachable_object_check_moved_i, (
void *)v);
7257rb_gc_impl_during_gc_p(
void *objspace_ptr)
7259 rb_objspace_t *
objspace = objspace_ptr;
7264#if RGENGC_PROFILE >= 2
7297 default:
return "unknown";
7302gc_count_add_each_types(
VALUE hash,
const char *name,
const size_t *types)
7306 for (i=0; i<
T_MASK; i++) {
7307 const char *
type = type_name(i, 0);
7310 rb_hash_aset(hash,
ID2SYM(rb_intern(name)), result);
7315rb_gc_impl_gc_count(
void *objspace_ptr)
7317 rb_objspace_t *
objspace = objspace_ptr;
7323gc_info_decode(rb_objspace_t *
objspace,
const VALUE hash_or_key,
const unsigned int orig_flags)
7325 static VALUE sym_major_by =
Qnil, sym_gc_by, sym_immediate_sweep, sym_have_finalizer, sym_state, sym_need_major_by;
7326 static VALUE sym_nofree, sym_oldgen, sym_shady, sym_force, sym_stress;
7327#if RGENGC_ESTIMATE_OLDMALLOC
7328 static VALUE sym_oldmalloc;
7330 static VALUE sym_newobj, sym_malloc, sym_method, sym_capi;
7331 static VALUE sym_none, sym_marking, sym_sweeping;
7332 static VALUE sym_weak_references_count, sym_retained_weak_references_count;
7334 VALUE major_by, need_major_by;
7335 unsigned int flags = orig_flags ? orig_flags :
objspace->profile.latest_gc_info;
7340 else if (RB_TYPE_P(hash_or_key,
T_HASH)) {
7344 rb_bug(
"gc_info_decode: non-hash or symbol given");
7347 if (
NIL_P(sym_major_by)) {
7348#define S(s) sym_##s = ID2SYM(rb_intern_const(#s))
7361#if RGENGC_ESTIMATE_OLDMALLOC
7373 S(weak_references_count);
7374 S(retained_weak_references_count);
7378#define SET(name, attr) \
7379 if (key == sym_##name) \
7381 else if (hash != Qnil) \
7382 rb_hash_aset(hash, sym_##name, (attr));
7385 (flags & GPR_FLAG_MAJOR_BY_NOFREE) ? sym_nofree :
7386 (flags & GPR_FLAG_MAJOR_BY_OLDGEN) ? sym_oldgen :
7387 (flags & GPR_FLAG_MAJOR_BY_SHADY) ? sym_shady :
7388 (flags & GPR_FLAG_MAJOR_BY_FORCE) ? sym_force :
7389#if RGENGC_ESTIMATE_OLDMALLOC
7390 (flags & GPR_FLAG_MAJOR_BY_OLDMALLOC) ? sym_oldmalloc :
7393 SET(major_by, major_by);
7395 if (orig_flags == 0) {
7396 unsigned int need_major_flags = gc_needs_major_flags;
7398 (need_major_flags & GPR_FLAG_MAJOR_BY_NOFREE) ? sym_nofree :
7399 (need_major_flags & GPR_FLAG_MAJOR_BY_OLDGEN) ? sym_oldgen :
7400 (need_major_flags & GPR_FLAG_MAJOR_BY_SHADY) ? sym_shady :
7401 (need_major_flags & GPR_FLAG_MAJOR_BY_FORCE) ? sym_force :
7402#if RGENGC_ESTIMATE_OLDMALLOC
7403 (need_major_flags & GPR_FLAG_MAJOR_BY_OLDMALLOC) ? sym_oldmalloc :
7406 SET(need_major_by, need_major_by);
7410 (flags & GPR_FLAG_NEWOBJ) ? sym_newobj :
7411 (flags & GPR_FLAG_MALLOC) ? sym_malloc :
7412 (flags & GPR_FLAG_METHOD) ? sym_method :
7413 (flags & GPR_FLAG_CAPI) ? sym_capi :
7414 (flags & GPR_FLAG_STRESS) ? sym_stress :
7418 SET(have_finalizer, (flags & GPR_FLAG_HAVE_FINALIZE) ?
Qtrue :
Qfalse);
7419 SET(immediate_sweep, (flags & GPR_FLAG_IMMEDIATE_SWEEP) ?
Qtrue :
Qfalse);
7421 if (orig_flags == 0) {
7422 SET(state, gc_mode(
objspace) == gc_mode_none ? sym_none :
7423 gc_mode(
objspace) == gc_mode_marking ? sym_marking : sym_sweeping);
7426 SET(weak_references_count,
LONG2FIX(
objspace->profile.weak_references_count));
7427 SET(retained_weak_references_count,
LONG2FIX(
objspace->profile.retained_weak_references_count));
7439rb_gc_impl_latest_gc_info(
void *objspace_ptr,
VALUE key)
7441 rb_objspace_t *
objspace = objspace_ptr;
7443 return gc_info_decode(
objspace, key, 0);
7450 gc_stat_sym_marking_time,
7451 gc_stat_sym_sweeping_time,
7452 gc_stat_sym_heap_allocated_pages,
7453 gc_stat_sym_heap_empty_pages,
7454 gc_stat_sym_heap_allocatable_slots,
7455 gc_stat_sym_heap_available_slots,
7456 gc_stat_sym_heap_live_slots,
7457 gc_stat_sym_heap_free_slots,
7458 gc_stat_sym_heap_final_slots,
7459 gc_stat_sym_heap_marked_slots,
7460 gc_stat_sym_heap_eden_pages,
7461 gc_stat_sym_total_allocated_pages,
7462 gc_stat_sym_total_freed_pages,
7463 gc_stat_sym_total_allocated_objects,
7464 gc_stat_sym_total_freed_objects,
7465 gc_stat_sym_malloc_increase_bytes,
7466 gc_stat_sym_malloc_increase_bytes_limit,
7467 gc_stat_sym_minor_gc_count,
7468 gc_stat_sym_major_gc_count,
7469 gc_stat_sym_compact_count,
7470 gc_stat_sym_read_barrier_faults,
7471 gc_stat_sym_total_moved_objects,
7472 gc_stat_sym_remembered_wb_unprotected_objects,
7473 gc_stat_sym_remembered_wb_unprotected_objects_limit,
7474 gc_stat_sym_old_objects,
7475 gc_stat_sym_old_objects_limit,
7476#if RGENGC_ESTIMATE_OLDMALLOC
7477 gc_stat_sym_oldmalloc_increase_bytes,
7478 gc_stat_sym_oldmalloc_increase_bytes_limit,
7480 gc_stat_sym_weak_references_count,
7482 gc_stat_sym_total_generated_normal_object_count,
7483 gc_stat_sym_total_generated_shady_object_count,
7484 gc_stat_sym_total_shade_operation_count,
7485 gc_stat_sym_total_promoted_count,
7486 gc_stat_sym_total_remembered_normal_object_count,
7487 gc_stat_sym_total_remembered_shady_object_count,
7492static VALUE gc_stat_symbols[gc_stat_sym_last];
7495setup_gc_stat_symbols(
void)
7497 if (gc_stat_symbols[0] == 0) {
7498#define S(s) gc_stat_symbols[gc_stat_sym_##s] = ID2SYM(rb_intern_const(#s))
7503 S(heap_allocated_pages);
7504 S(heap_empty_pages);
7505 S(heap_allocatable_slots);
7506 S(heap_available_slots);
7509 S(heap_final_slots);
7510 S(heap_marked_slots);
7512 S(total_allocated_pages);
7513 S(total_freed_pages);
7514 S(total_allocated_objects);
7515 S(total_freed_objects);
7516 S(malloc_increase_bytes);
7517 S(malloc_increase_bytes_limit);
7521 S(read_barrier_faults);
7522 S(total_moved_objects);
7523 S(remembered_wb_unprotected_objects);
7524 S(remembered_wb_unprotected_objects_limit);
7526 S(old_objects_limit);
7527#if RGENGC_ESTIMATE_OLDMALLOC
7528 S(oldmalloc_increase_bytes);
7529 S(oldmalloc_increase_bytes_limit);
7531 S(weak_references_count);
7533 S(total_generated_normal_object_count);
7534 S(total_generated_shady_object_count);
7535 S(total_shade_operation_count);
7536 S(total_promoted_count);
7537 S(total_remembered_normal_object_count);
7538 S(total_remembered_shady_object_count);
7545ns_to_ms(uint64_t ns)
7547 return ns / (1000 * 1000);
7550static void malloc_increase_local_flush(rb_objspace_t *
objspace);
7553rb_gc_impl_stat(
void *objspace_ptr,
VALUE hash_or_sym)
7555 rb_objspace_t *
objspace = objspace_ptr;
7558 setup_gc_stat_symbols();
7560 ractor_cache_flush_count(
objspace, rb_gc_get_ractor_newobj_cache());
7561 malloc_increase_local_flush(
objspace);
7563 if (RB_TYPE_P(hash_or_sym,
T_HASH)) {
7570 rb_bug(
"non-hash or symbol given");
7573#define SET(name, attr) \
7574 if (key == gc_stat_symbols[gc_stat_sym_##name]) \
7575 return SIZET2NUM(attr); \
7576 else if (hash != Qnil) \
7577 rb_hash_aset(hash, gc_stat_symbols[gc_stat_sym_##name], SIZET2NUM(attr));
7579 SET(count,
objspace->profile.count);
7580 SET(time, (
size_t)ns_to_ms(
objspace->profile.marking_time_ns +
objspace->profile.sweeping_time_ns));
7581 SET(marking_time, (
size_t)ns_to_ms(
objspace->profile.marking_time_ns));
7582 SET(sweeping_time, (
size_t)ns_to_ms(
objspace->profile.sweeping_time_ns));
7585 SET(heap_allocated_pages, rb_darray_size(
objspace->heap_pages.sorted));
7586 SET(heap_empty_pages,
objspace->empty_pages_count)
7587 SET(heap_allocatable_slots,
objspace->heap_pages.allocatable_slots);
7588 SET(heap_available_slots, objspace_available_slots(
objspace));
7589 SET(heap_live_slots, objspace_live_slots(
objspace));
7590 SET(heap_free_slots, objspace_free_slots(
objspace));
7591 SET(heap_final_slots, total_final_slots_count(
objspace));
7592 SET(heap_marked_slots,
objspace->marked_slots);
7593 SET(heap_eden_pages, heap_eden_total_pages(
objspace));
7594 SET(total_allocated_pages,
objspace->heap_pages.allocated_pages);
7595 SET(total_freed_pages,
objspace->heap_pages.freed_pages);
7596 SET(total_allocated_objects, total_allocated_objects(
objspace));
7597 SET(total_freed_objects, total_freed_objects(
objspace));
7598 SET(malloc_increase_bytes, malloc_increase);
7599 SET(malloc_increase_bytes_limit, malloc_limit);
7600 SET(minor_gc_count,
objspace->profile.minor_gc_count);
7601 SET(major_gc_count,
objspace->profile.major_gc_count);
7602 SET(compact_count,
objspace->profile.compact_count);
7603 SET(read_barrier_faults,
objspace->profile.read_barrier_faults);
7604 SET(total_moved_objects,
objspace->rcompactor.total_moved);
7605 SET(remembered_wb_unprotected_objects,
objspace->rgengc.uncollectible_wb_unprotected_objects);
7606 SET(remembered_wb_unprotected_objects_limit,
objspace->rgengc.uncollectible_wb_unprotected_objects_limit);
7607 SET(old_objects,
objspace->rgengc.old_objects);
7608 SET(old_objects_limit,
objspace->rgengc.old_objects_limit);
7609#if RGENGC_ESTIMATE_OLDMALLOC
7610 SET(oldmalloc_increase_bytes,
objspace->malloc_counters.oldmalloc_increase);
7611 SET(oldmalloc_increase_bytes_limit,
objspace->rgengc.oldmalloc_increase_limit);
7615 SET(total_generated_normal_object_count,
objspace->profile.total_generated_normal_object_count);
7616 SET(total_generated_shady_object_count,
objspace->profile.total_generated_shady_object_count);
7617 SET(total_shade_operation_count,
objspace->profile.total_shade_operation_count);
7618 SET(total_promoted_count,
objspace->profile.total_promoted_count);
7619 SET(total_remembered_normal_object_count,
objspace->profile.total_remembered_normal_object_count);
7620 SET(total_remembered_shady_object_count,
objspace->profile.total_remembered_shady_object_count);
7629#if defined(RGENGC_PROFILE) && RGENGC_PROFILE >= 2
7631 gc_count_add_each_types(hash,
"generated_normal_object_count_types",
objspace->profile.generated_normal_object_count_types);
7632 gc_count_add_each_types(hash,
"generated_shady_object_count_types",
objspace->profile.generated_shady_object_count_types);
7633 gc_count_add_each_types(hash,
"shade_operation_count_types",
objspace->profile.shade_operation_count_types);
7634 gc_count_add_each_types(hash,
"promoted_types",
objspace->profile.promoted_types);
7635 gc_count_add_each_types(hash,
"remembered_normal_object_count_types",
objspace->profile.remembered_normal_object_count_types);
7636 gc_count_add_each_types(hash,
"remembered_shady_object_count_types",
objspace->profile.remembered_shady_object_count_types);
7643enum gc_stat_heap_sym {
7644 gc_stat_heap_sym_slot_size,
7645 gc_stat_heap_sym_heap_live_slots,
7646 gc_stat_heap_sym_heap_free_slots,
7647 gc_stat_heap_sym_heap_final_slots,
7648 gc_stat_heap_sym_heap_eden_pages,
7649 gc_stat_heap_sym_heap_eden_slots,
7650 gc_stat_heap_sym_total_allocated_pages,
7651 gc_stat_heap_sym_force_major_gc_count,
7652 gc_stat_heap_sym_force_incremental_marking_finish_count,
7653 gc_stat_heap_sym_total_allocated_objects,
7654 gc_stat_heap_sym_total_freed_objects,
7655 gc_stat_heap_sym_last
7658static VALUE gc_stat_heap_symbols[gc_stat_heap_sym_last];
7661setup_gc_stat_heap_symbols(
void)
7663 if (gc_stat_heap_symbols[0] == 0) {
7664#define S(s) gc_stat_heap_symbols[gc_stat_heap_sym_##s] = ID2SYM(rb_intern_const(#s))
7668 S(heap_final_slots);
7671 S(total_allocated_pages);
7672 S(force_major_gc_count);
7673 S(force_incremental_marking_finish_count);
7674 S(total_allocated_objects);
7675 S(total_freed_objects);
7681stat_one_heap(rb_heap_t *heap,
VALUE hash,
VALUE key)
7683#define SET(name, attr) \
7684 if (key == gc_stat_heap_symbols[gc_stat_heap_sym_##name]) \
7685 return SIZET2NUM(attr); \
7686 else if (hash != Qnil) \
7687 rb_hash_aset(hash, gc_stat_heap_symbols[gc_stat_heap_sym_##name], SIZET2NUM(attr));
7689 SET(slot_size, heap->slot_size);
7690 SET(heap_live_slots, heap->total_allocated_objects - heap->total_freed_objects - heap->final_slots_count);
7691 SET(heap_free_slots, heap->total_slots - (heap->total_allocated_objects - heap->total_freed_objects));
7692 SET(heap_final_slots, heap->final_slots_count);
7693 SET(heap_eden_pages, heap->total_pages);
7694 SET(heap_eden_slots, heap->total_slots);
7695 SET(total_allocated_pages, heap->total_allocated_pages);
7696 SET(force_major_gc_count, heap->force_major_gc_count);
7697 SET(force_incremental_marking_finish_count, heap->force_incremental_marking_finish_count);
7698 SET(total_allocated_objects, heap->total_allocated_objects);
7699 SET(total_freed_objects, heap->total_freed_objects);
7711rb_gc_impl_stat_heap(
void *objspace_ptr,
VALUE heap_name,
VALUE hash_or_sym)
7713 rb_objspace_t *
objspace = objspace_ptr;
7715 ractor_cache_flush_count(
objspace, rb_gc_get_ractor_newobj_cache());
7717 setup_gc_stat_heap_symbols();
7719 if (
NIL_P(heap_name)) {
7720 if (!RB_TYPE_P(hash_or_sym,
T_HASH)) {
7721 rb_bug(
"non-hash given");
7724 for (
int i = 0; i < HEAP_COUNT; i++) {
7727 hash = rb_hash_new();
7728 rb_hash_aset(hash_or_sym,
INT2FIX(i), hash);
7731 stat_one_heap(&heaps[i], hash,
Qnil);
7735 int heap_idx =
FIX2INT(heap_name);
7737 if (heap_idx < 0 || heap_idx >= HEAP_COUNT) {
7738 rb_raise(rb_eArgError,
"size pool index out of range");
7742 return stat_one_heap(&heaps[heap_idx],
Qnil, hash_or_sym);
7744 else if (RB_TYPE_P(hash_or_sym,
T_HASH)) {
7745 return stat_one_heap(&heaps[heap_idx], hash_or_sym,
Qnil);
7748 rb_bug(
"non-hash or symbol given");
7752 rb_bug(
"heap_name must be nil or an Integer");
7764#define RBOOL(v) (v ? Qtrue : Qfalse)
7768rb_gc_impl_config_get(
void *objspace_ptr)
7770#define sym(name) ID2SYM(rb_intern_const(name))
7771 rb_objspace_t *
objspace = objspace_ptr;
7772 VALUE hash = rb_hash_new();
7774 rb_hash_aset(hash, sym(
"rgengc_allow_full_mark"), RBOOL(gc_config_full_mark_val));
7782 rb_objspace_t *
objspace = (rb_objspace_t *)data;
7783 if (
rb_sym2id(key) == rb_intern(
"rgengc_allow_full_mark")) {
7785 gc_config_full_mark_set(
RTEST(value));
7791rb_gc_impl_config_set(
void *objspace_ptr,
VALUE hash)
7793 rb_objspace_t *
objspace = objspace_ptr;
7795 if (!RB_TYPE_P(hash,
T_HASH)) {
7796 rb_raise(rb_eArgError,
"expected keyword arguments");
7799 rb_hash_foreach(hash, gc_config_set_key, (st_data_t)
objspace);
7803rb_gc_impl_stress_get(
void *objspace_ptr)
7805 rb_objspace_t *
objspace = objspace_ptr;
7806 return ruby_gc_stress_mode;
7810rb_gc_impl_stress_set(
void *objspace_ptr,
VALUE flag)
7812 rb_objspace_t *
objspace = objspace_ptr;
7819get_envparam_size(
const char *name,
size_t *default_value,
size_t lower_bound)
7821 const char *
ptr = getenv(name);
7824 if (
ptr != NULL && *
ptr) {
7827#if SIZEOF_SIZE_T == SIZEOF_LONG_LONG
7828 val = strtoll(
ptr, &end, 0);
7830 val = strtol(
ptr, &end, 0);
7842 unit = 1024*1024*1024;
7846 while (*end && isspace((
unsigned char)*end)) end++;
7852 if (val < -(ssize_t)(SIZE_MAX / 2 / unit) || (ssize_t)(SIZE_MAX / 2 / unit) < val) {
7853 if (
RTEST(
ruby_verbose)) fprintf(stderr,
"%s=%s is ignored because it overflows\n", name,
ptr);
7858 if (val > 0 && (
size_t)val > lower_bound) {
7860 fprintf(stderr,
"%s=%"PRIdSIZE
" (default value: %"PRIuSIZE
")\n", name, val, *default_value);
7862 *default_value = (size_t)val;
7867 fprintf(stderr,
"%s=%"PRIdSIZE
" (default value: %"PRIuSIZE
") is ignored because it must be greater than %"PRIuSIZE
".\n",
7868 name, val, *default_value, lower_bound);
7877get_envparam_double(
const char *name,
double *default_value,
double lower_bound,
double upper_bound,
int accept_zero)
7879 const char *
ptr = getenv(name);
7882 if (
ptr != NULL && *
ptr) {
7885 if (!*
ptr || *end) {
7890 if (accept_zero && val == 0.0) {
7893 else if (val <= lower_bound) {
7895 fprintf(stderr,
"%s=%f (default value: %f) is ignored because it must be greater than %f.\n",
7896 name, val, *default_value, lower_bound);
7899 else if (upper_bound != 0.0 &&
7900 val > upper_bound) {
7902 fprintf(stderr,
"%s=%f (default value: %f) is ignored because it must be lower than %f.\n",
7903 name, val, *default_value, upper_bound);
7913 if (
RTEST(
ruby_verbose)) fprintf(stderr,
"%s=%f (default value: %f)\n", name, val, *default_value);
7914 *default_value = val;
7959rb_gc_impl_set_params(
void *objspace_ptr)
7961 rb_objspace_t *
objspace = objspace_ptr;
7963 if (get_envparam_size(
"RUBY_GC_HEAP_FREE_SLOTS", &gc_params.heap_free_slots, 0)) {
7967 for (
int i = 0; i < HEAP_COUNT; i++) {
7968 char env_key[
sizeof(
"RUBY_GC_HEAP_" "_INIT_SLOTS") +
DECIMAL_SIZE_OF_BITS(
sizeof(
int) * CHAR_BIT)];
7969 snprintf(env_key,
sizeof(env_key),
"RUBY_GC_HEAP_%d_INIT_SLOTS", i);
7971 get_envparam_size(env_key, &gc_params.heap_init_slots[i], 0);
7974 get_envparam_double(
"RUBY_GC_HEAP_GROWTH_FACTOR", &gc_params.growth_factor, 1.0, 0.0, FALSE);
7975 get_envparam_size (
"RUBY_GC_HEAP_GROWTH_MAX_SLOTS", &gc_params.growth_max_slots, 0);
7976 get_envparam_double(
"RUBY_GC_HEAP_FREE_SLOTS_MIN_RATIO", &gc_params.heap_free_slots_min_ratio,
7978 get_envparam_double(
"RUBY_GC_HEAP_FREE_SLOTS_MAX_RATIO", &gc_params.heap_free_slots_max_ratio,
7979 gc_params.heap_free_slots_min_ratio, 1.0, FALSE);
7980 get_envparam_double(
"RUBY_GC_HEAP_FREE_SLOTS_GOAL_RATIO", &gc_params.heap_free_slots_goal_ratio,
7981 gc_params.heap_free_slots_min_ratio, gc_params.heap_free_slots_max_ratio, TRUE);
7982 get_envparam_double(
"RUBY_GC_HEAP_OLDOBJECT_LIMIT_FACTOR", &gc_params.oldobject_limit_factor, 0.0, 0.0, TRUE);
7983 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);
7985 if (get_envparam_size(
"RUBY_GC_MALLOC_LIMIT", &gc_params.malloc_limit_min, 0)) {
7986 malloc_limit = gc_params.malloc_limit_min;
7988 get_envparam_size (
"RUBY_GC_MALLOC_LIMIT_MAX", &gc_params.malloc_limit_max, 0);
7989 if (!gc_params.malloc_limit_max) {
7990 gc_params.malloc_limit_max = SIZE_MAX;
7992 get_envparam_double(
"RUBY_GC_MALLOC_LIMIT_GROWTH_FACTOR", &gc_params.malloc_limit_growth_factor, 1.0, 0.0, FALSE);
7994#if RGENGC_ESTIMATE_OLDMALLOC
7995 if (get_envparam_size(
"RUBY_GC_OLDMALLOC_LIMIT", &gc_params.oldmalloc_limit_min, 0)) {
7996 objspace->rgengc.oldmalloc_increase_limit = gc_params.oldmalloc_limit_min;
7998 get_envparam_size (
"RUBY_GC_OLDMALLOC_LIMIT_MAX", &gc_params.oldmalloc_limit_max, 0);
7999 get_envparam_double(
"RUBY_GC_OLDMALLOC_LIMIT_GROWTH_FACTOR", &gc_params.oldmalloc_limit_growth_factor, 1.0, 0.0, FALSE);
8004objspace_malloc_size(rb_objspace_t *
objspace,
void *
ptr,
size_t hint)
8006#ifdef HAVE_MALLOC_USABLE_SIZE
8008 hint = malloc_usable_size(
ptr);
8015 MEMOP_TYPE_MALLOC = 0,
8021atomic_sub_nounderflow(
size_t *var,
size_t sub)
8023 if (sub == 0)
return;
8027 if (val < sub) sub = val;
8032#define gc_stress_full_mark_after_malloc_p() \
8033 (FIXNUM_P(ruby_gc_stress_mode) && (FIX2LONG(ruby_gc_stress_mode) & (1<<gc_stress_full_mark_after_malloc)))
8036objspace_malloc_gc_stress(rb_objspace_t *
objspace)
8039 unsigned int reason = (GPR_FLAG_IMMEDIATE_MARK | GPR_FLAG_IMMEDIATE_SWEEP |
8040 GPR_FLAG_STRESS | GPR_FLAG_MALLOC);
8042 if (gc_stress_full_mark_after_malloc_p()) {
8043 reason |= GPR_FLAG_FULL_MARK;
8045 garbage_collect_with_gvl(
objspace, reason);
8050malloc_increase_commit(rb_objspace_t *
objspace,
size_t new_size,
size_t old_size)
8052 if (new_size > old_size) {
8054#if RGENGC_ESTIMATE_OLDMALLOC
8059 atomic_sub_nounderflow(&malloc_increase, old_size - new_size);
8060#if RGENGC_ESTIMATE_OLDMALLOC
8061 atomic_sub_nounderflow(&
objspace->malloc_counters.oldmalloc_increase, old_size - new_size);
8066#if USE_MALLOC_INCREASE_LOCAL
8068malloc_increase_local_flush(rb_objspace_t *
objspace)
8070 int delta = malloc_increase_local;
8071 if (delta == 0)
return;
8073 malloc_increase_local = 0;
8075 malloc_increase_commit(
objspace, (
size_t)delta, 0);
8078 malloc_increase_commit(
objspace, 0, (
size_t)(-delta));
8083malloc_increase_local_flush(rb_objspace_t *
objspace)
8089objspace_malloc_increase_report(rb_objspace_t *
objspace,
void *mem,
size_t new_size,
size_t old_size,
enum memop_type
type,
bool gc_allowed)
8091 if (0) fprintf(stderr,
"increase - ptr: %p, type: %s, new_size: %"PRIdSIZE
", old_size: %"PRIdSIZE
"\n",
8093 type == MEMOP_TYPE_MALLOC ?
"malloc" :
8094 type == MEMOP_TYPE_FREE ?
"free " :
8095 type == MEMOP_TYPE_REALLOC ?
"realloc":
"error",
8096 new_size, old_size);
8101objspace_malloc_increase_body(rb_objspace_t *
objspace,
void *mem,
size_t new_size,
size_t old_size,
enum memop_type
type,
bool gc_allowed)
8103#if USE_MALLOC_INCREASE_LOCAL
8104 if (new_size < GC_MALLOC_INCREASE_LOCAL_THRESHOLD &&
8105 old_size < GC_MALLOC_INCREASE_LOCAL_THRESHOLD) {
8106 malloc_increase_local += (int)new_size - (
int)old_size;
8108 if (malloc_increase_local >= GC_MALLOC_INCREASE_LOCAL_THRESHOLD ||
8109 malloc_increase_local <= -GC_MALLOC_INCREASE_LOCAL_THRESHOLD) {
8110 malloc_increase_local_flush(
objspace);
8114 malloc_increase_local_flush(
objspace);
8115 malloc_increase_commit(
objspace, new_size, old_size);
8118 malloc_increase_commit(
objspace, new_size, old_size);
8121 if (
type == MEMOP_TYPE_MALLOC && gc_allowed) {
8124 if (ruby_thread_has_gvl_p() && is_lazy_sweeping(
objspace)) {
8128 garbage_collect_with_gvl(
objspace, GPR_FLAG_MALLOC);
8132#if MALLOC_ALLOCATED_SIZE
8133 if (new_size >= old_size) {
8137 size_t dec_size = old_size - new_size;
8139#if MALLOC_ALLOCATED_SIZE_CHECK
8140 size_t allocated_size =
objspace->malloc_params.allocated_size;
8141 if (allocated_size < dec_size) {
8142 rb_bug(
"objspace_malloc_increase: underflow malloc_params.allocated_size.");
8145 atomic_sub_nounderflow(&
objspace->malloc_params.allocated_size, dec_size);
8149 case MEMOP_TYPE_MALLOC:
8152 case MEMOP_TYPE_FREE:
8154 size_t allocations =
objspace->malloc_params.allocations;
8155 if (allocations > 0) {
8156 atomic_sub_nounderflow(&
objspace->malloc_params.allocations, 1);
8158#if MALLOC_ALLOCATED_SIZE_CHECK
8160 GC_ASSERT(
objspace->malloc_params.allocations > 0);
8165 case MEMOP_TYPE_REALLOC:
break;
8171#define objspace_malloc_increase(...) \
8172 for (bool malloc_increase_done = objspace_malloc_increase_report(__VA_ARGS__); \
8173 !malloc_increase_done; \
8174 malloc_increase_done = objspace_malloc_increase_body(__VA_ARGS__))
8181objspace_malloc_prepare(rb_objspace_t *
objspace,
size_t size)
8183 if (size == 0) size = 1;
8185#if CALC_EXACT_MALLOC_SIZE
8193malloc_during_gc_p(rb_objspace_t *
objspace)
8199 return during_gc && !dont_gc_val() && !rb_gc_multi_ractor_p() && ruby_thread_has_gvl_p();
8203objspace_malloc_fixup(rb_objspace_t *
objspace,
void *mem,
size_t size,
bool gc_allowed)
8205 size = objspace_malloc_size(
objspace, mem, size);
8206 objspace_malloc_increase(
objspace, mem, size, 0, MEMOP_TYPE_MALLOC, gc_allowed) {}
8208#if CALC_EXACT_MALLOC_SIZE
8219#if defined(__GNUC__) && RUBY_DEBUG
8220#define RB_BUG_INSTEAD_OF_RB_MEMERROR 1
8223#ifndef RB_BUG_INSTEAD_OF_RB_MEMERROR
8224# define RB_BUG_INSTEAD_OF_RB_MEMERROR 0
8227#define GC_MEMERROR(...) \
8228 ((RB_BUG_INSTEAD_OF_RB_MEMERROR+0) ? rb_bug("" __VA_ARGS__) : (void)0)
8230#define TRY_WITH_GC(siz, expr) do { \
8231 const gc_profile_record_flag gpr = \
8232 GPR_FLAG_FULL_MARK | \
8233 GPR_FLAG_IMMEDIATE_MARK | \
8234 GPR_FLAG_IMMEDIATE_SWEEP | \
8236 objspace_malloc_gc_stress(objspace); \
8238 if (RB_LIKELY((expr))) { \
8241 else if (gc_allowed && !garbage_collect_with_gvl(objspace, gpr)) { \
8243 GC_MEMERROR("TRY_WITH_GC: could not GC"); \
8245 else if ((expr)) { \
8249 GC_MEMERROR("TRY_WITH_GC: could not allocate:" \
8250 "%"PRIdSIZE" bytes for %s", \
8256check_malloc_not_in_gc(rb_objspace_t *
objspace,
const char *msg)
8258 if (RB_UNLIKELY(malloc_during_gc_p(
objspace))) {
8261 rb_bug(
"Cannot %s during GC", msg);
8266rb_gc_impl_free(
void *objspace_ptr,
void *
ptr,
size_t old_size)
8268 rb_objspace_t *
objspace = objspace_ptr;
8277#if CALC_EXACT_MALLOC_SIZE
8280 old_size = info->size;
8282 old_size = objspace_malloc_size(
objspace,
ptr, old_size);
8284 objspace_malloc_increase(
objspace,
ptr, 0, old_size, MEMOP_TYPE_FREE,
true) {
8287 RB_DEBUG_COUNTER_INC(heap_xfree);
8292rb_gc_impl_malloc(
void *objspace_ptr,
size_t size,
bool gc_allowed)
8294 rb_objspace_t *
objspace = objspace_ptr;
8295 check_malloc_not_in_gc(
objspace,
"malloc");
8299 size = objspace_malloc_prepare(
objspace, size);
8300 TRY_WITH_GC(size, mem = malloc(size));
8301 RB_DEBUG_COUNTER_INC(heap_xmalloc);
8302 if (!mem)
return mem;
8303 return objspace_malloc_fixup(
objspace, mem, size, gc_allowed);
8307rb_gc_impl_calloc(
void *objspace_ptr,
size_t size,
bool gc_allowed)
8309 rb_objspace_t *
objspace = objspace_ptr;
8311 if (RB_UNLIKELY(malloc_during_gc_p(
objspace))) {
8312 rb_warn(
"calloc during GC detected, this could cause crashes if it triggers another GC");
8313#if RGENGC_CHECK_MODE || RUBY_DEBUG
8314 rb_bug(
"Cannot calloc during GC");
8320 size = objspace_malloc_prepare(
objspace, size);
8321 TRY_WITH_GC(size, mem = calloc1(size));
8322 if (!mem)
return mem;
8323 return objspace_malloc_fixup(
objspace, mem, size, gc_allowed);
8327rb_gc_impl_realloc(
void *objspace_ptr,
void *
ptr,
size_t new_size,
size_t old_size,
bool gc_allowed)
8329 rb_objspace_t *
objspace = objspace_ptr;
8331 check_malloc_not_in_gc(
objspace,
"realloc");
8335 if (!
ptr)
return rb_gc_impl_malloc(
objspace, new_size, gc_allowed);
8342 if (new_size == 0) {
8343 if ((mem = rb_gc_impl_malloc(
objspace, 0, gc_allowed)) != NULL) {
8380#if CALC_EXACT_MALLOC_SIZE
8385 old_size = info->size;
8389 old_size = objspace_malloc_size(
objspace,
ptr, old_size);
8391 if (!mem)
return mem;
8392 new_size = objspace_malloc_size(
objspace, mem, new_size);
8394#if CALC_EXACT_MALLOC_SIZE
8397 info->size = new_size;
8402 objspace_malloc_increase(
objspace, mem, new_size, old_size, MEMOP_TYPE_REALLOC, gc_allowed);
8404 RB_DEBUG_COUNTER_INC(heap_xrealloc);
8409rb_gc_impl_adjust_memory_usage(
void *objspace_ptr, ssize_t diff)
8411 rb_objspace_t *
objspace = objspace_ptr;
8414 objspace_malloc_increase(
objspace, 0, diff, 0, MEMOP_TYPE_REALLOC,
true);
8416 else if (diff < 0) {
8417 objspace_malloc_increase(
objspace, 0, 0, -diff, MEMOP_TYPE_REALLOC,
true);
8426#define GC_PROFILE_RECORD_DEFAULT_SIZE 100
8429current_process_time(
struct timespec *ts)
8431#if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_PROCESS_CPUTIME_ID)
8433 static int try_clock_gettime = 1;
8434 if (try_clock_gettime && clock_gettime(CLOCK_PROCESS_CPUTIME_ID, ts) == 0) {
8438 try_clock_gettime = 0;
8445 struct rusage usage;
8447 if (getrusage(RUSAGE_SELF, &usage) == 0) {
8448 time = usage.ru_utime;
8449 ts->tv_sec = time.tv_sec;
8450 ts->tv_nsec = (int32_t)time.tv_usec * 1000;
8458 FILETIME creation_time, exit_time, kernel_time, user_time;
8461 if (GetProcessTimes(GetCurrentProcess(),
8462 &creation_time, &exit_time, &kernel_time, &user_time) != 0) {
8463 memcpy(&ui, &user_time,
sizeof(FILETIME));
8464#define PER100NSEC (uint64_t)(1000 * 1000 * 10)
8465 ts->tv_nsec = (long)(ui.QuadPart % PER100NSEC);
8466 ts->tv_sec = (time_t)(ui.QuadPart / PER100NSEC);
8479 if (current_process_time(&ts)) {
8480 return ts.tv_sec + ts.tv_nsec * 1e-9;
8489gc_prof_setup_new_record(rb_objspace_t *
objspace,
unsigned int reason)
8492 size_t index =
objspace->profile.next_index;
8499 objspace->profile.size = GC_PROFILE_RECORD_DEFAULT_SIZE;
8502 if (index >=
objspace->profile.size) {
8506 if (!
ptr) rb_memerror();
8510 rb_bug(
"gc_profile malloc or realloc miss");
8516 record->flags = reason | (ruby_gc_stressful ? GPR_FLAG_STRESS : 0);
8517#if MALLOC_ALLOCATED_SIZE
8518 record->allocated_size = malloc_allocated_size;
8520#if GC_PROFILE_MORE_DETAIL && GC_PROFILE_DETAIL_MEMORY
8523 struct rusage usage;
8524 if (getrusage(RUSAGE_SELF, &usage) == 0) {
8525 record->maxrss = usage.ru_maxrss;
8526 record->minflt = usage.ru_minflt;
8527 record->majflt = usage.ru_majflt;
8536gc_prof_timer_start(rb_objspace_t *
objspace)
8540#if GC_PROFILE_MORE_DETAIL
8541 record->prepare_time =
objspace->profile.prepare_time;
8543 record->gc_time = 0;
8544 record->gc_invoke_time = getrusage_time();
8549elapsed_time_from(
double time)
8551 double now = getrusage_time();
8561gc_prof_timer_stop(rb_objspace_t *
objspace)
8565 record->gc_time = elapsed_time_from(record->gc_invoke_time);
8566 record->gc_invoke_time -=
objspace->profile.invoke_time;
8570#ifdef BUILDING_MODULAR_GC
8571# define RUBY_DTRACE_GC_HOOK(name)
8573# define RUBY_DTRACE_GC_HOOK(name) \
8574 do {if (RUBY_DTRACE_GC_##name##_ENABLED()) RUBY_DTRACE_GC_##name();} while (0)
8578gc_prof_mark_timer_start(rb_objspace_t *
objspace)
8580 RUBY_DTRACE_GC_HOOK(MARK_BEGIN);
8581#if GC_PROFILE_MORE_DETAIL
8583 gc_prof_record(
objspace)->gc_mark_time = getrusage_time();
8589gc_prof_mark_timer_stop(rb_objspace_t *
objspace)
8591 RUBY_DTRACE_GC_HOOK(MARK_END);
8592#if GC_PROFILE_MORE_DETAIL
8595 record->gc_mark_time = elapsed_time_from(record->gc_mark_time);
8601gc_prof_sweep_timer_start(rb_objspace_t *
objspace)
8603 RUBY_DTRACE_GC_HOOK(SWEEP_BEGIN);
8607 if (record->gc_time > 0 || GC_PROFILE_MORE_DETAIL) {
8608 objspace->profile.gc_sweep_start_time = getrusage_time();
8614gc_prof_sweep_timer_stop(rb_objspace_t *
objspace)
8616 RUBY_DTRACE_GC_HOOK(SWEEP_END);
8622 if (record->gc_time > 0) {
8623 sweep_time = elapsed_time_from(
objspace->profile.gc_sweep_start_time);
8625 record->gc_time += sweep_time;
8627 else if (GC_PROFILE_MORE_DETAIL) {
8628 sweep_time = elapsed_time_from(
objspace->profile.gc_sweep_start_time);
8631#if GC_PROFILE_MORE_DETAIL
8632 record->gc_sweep_time += sweep_time;
8633 if (heap_pages_deferred_final) record->flags |= GPR_FLAG_HAVE_FINALIZE;
8635 if (heap_pages_deferred_final)
objspace->profile.latest_gc_info |= GPR_FLAG_HAVE_FINALIZE;
8640gc_prof_set_malloc_info(rb_objspace_t *
objspace)
8642#if GC_PROFILE_MORE_DETAIL
8645 record->allocate_increase = malloc_increase;
8646 record->allocate_limit = malloc_limit;
8652gc_prof_set_heap_info(rb_objspace_t *
objspace)
8656 size_t live =
objspace->profile.total_allocated_objects_at_gc_start - total_freed_objects(
objspace);
8657 size_t total =
objspace->profile.heap_used_at_gc_start * HEAP_PAGE_OBJ_LIMIT;
8659#if GC_PROFILE_MORE_DETAIL
8660 record->heap_use_pages =
objspace->profile.heap_used_at_gc_start;
8661 record->heap_live_objects = live;
8662 record->heap_free_objects = total - live;
8665 record->heap_total_objects = total;
8666 record->heap_use_size = live * BASE_SLOT_SIZE;
8667 record->heap_total_size = total * BASE_SLOT_SIZE;
8682 rb_objspace_t *
objspace = rb_gc_get_objspace();
8683 void *p =
objspace->profile.records;
8687 objspace->profile.current_record = 0;
8743gc_profile_record_get(
VALUE _)
8748 rb_objspace_t *
objspace = rb_gc_get_objspace();
8754 for (i =0; i <
objspace->profile.next_index; i++) {
8757 prof = rb_hash_new();
8758 rb_hash_aset(prof,
ID2SYM(rb_intern(
"GC_FLAGS")), gc_info_decode(
objspace, rb_hash_new(), record->flags));
8759 rb_hash_aset(prof,
ID2SYM(rb_intern(
"GC_TIME")),
DBL2NUM(record->gc_time));
8760 rb_hash_aset(prof,
ID2SYM(rb_intern(
"GC_INVOKE_TIME")),
DBL2NUM(record->gc_invoke_time));
8761 rb_hash_aset(prof,
ID2SYM(rb_intern(
"HEAP_USE_SIZE")),
SIZET2NUM(record->heap_use_size));
8762 rb_hash_aset(prof,
ID2SYM(rb_intern(
"HEAP_TOTAL_SIZE")),
SIZET2NUM(record->heap_total_size));
8763 rb_hash_aset(prof,
ID2SYM(rb_intern(
"HEAP_TOTAL_OBJECTS")),
SIZET2NUM(record->heap_total_objects));
8764 rb_hash_aset(prof,
ID2SYM(rb_intern(
"MOVED_OBJECTS")),
SIZET2NUM(record->moved_objects));
8765 rb_hash_aset(prof,
ID2SYM(rb_intern(
"GC_IS_MARKED")),
Qtrue);
8766#if GC_PROFILE_MORE_DETAIL
8767 rb_hash_aset(prof,
ID2SYM(rb_intern(
"GC_MARK_TIME")),
DBL2NUM(record->gc_mark_time));
8768 rb_hash_aset(prof,
ID2SYM(rb_intern(
"GC_SWEEP_TIME")),
DBL2NUM(record->gc_sweep_time));
8769 rb_hash_aset(prof,
ID2SYM(rb_intern(
"ALLOCATE_INCREASE")),
SIZET2NUM(record->allocate_increase));
8770 rb_hash_aset(prof,
ID2SYM(rb_intern(
"ALLOCATE_LIMIT")),
SIZET2NUM(record->allocate_limit));
8771 rb_hash_aset(prof,
ID2SYM(rb_intern(
"HEAP_USE_PAGES")),
SIZET2NUM(record->heap_use_pages));
8772 rb_hash_aset(prof,
ID2SYM(rb_intern(
"HEAP_LIVE_OBJECTS")),
SIZET2NUM(record->heap_live_objects));
8773 rb_hash_aset(prof,
ID2SYM(rb_intern(
"HEAP_FREE_OBJECTS")),
SIZET2NUM(record->heap_free_objects));
8775 rb_hash_aset(prof,
ID2SYM(rb_intern(
"REMOVING_OBJECTS")),
SIZET2NUM(record->removing_objects));
8776 rb_hash_aset(prof,
ID2SYM(rb_intern(
"EMPTY_OBJECTS")),
SIZET2NUM(record->empty_objects));
8778 rb_hash_aset(prof,
ID2SYM(rb_intern(
"HAVE_FINALIZE")), (record->flags & GPR_FLAG_HAVE_FINALIZE) ?
Qtrue :
Qfalse);
8781#if RGENGC_PROFILE > 0
8782 rb_hash_aset(prof,
ID2SYM(rb_intern(
"OLD_OBJECTS")),
SIZET2NUM(record->old_objects));
8783 rb_hash_aset(prof,
ID2SYM(rb_intern(
"REMEMBERED_NORMAL_OBJECTS")),
SIZET2NUM(record->remembered_normal_objects));
8784 rb_hash_aset(prof,
ID2SYM(rb_intern(
"REMEMBERED_SHADY_OBJECTS")),
SIZET2NUM(record->remembered_shady_objects));
8792#if GC_PROFILE_MORE_DETAIL
8793#define MAJOR_REASON_MAX 0x10
8796gc_profile_dump_major_reason(
unsigned int flags,
char *buff)
8798 unsigned int reason = flags & GPR_FLAG_MAJOR_MASK;
8801 if (reason == GPR_FLAG_NONE) {
8807 if (reason & GPR_FLAG_MAJOR_BY_##x) { \
8808 buff[i++] = #x[0]; \
8809 if (i >= MAJOR_REASON_MAX) rb_bug("gc_profile_dump_major_reason: overflow"); \
8815#if RGENGC_ESTIMATE_OLDMALLOC
8829 rb_objspace_t *
objspace = rb_gc_get_objspace();
8830 size_t count =
objspace->profile.next_index;
8831#ifdef MAJOR_REASON_MAX
8832 char reason_str[MAJOR_REASON_MAX];
8835 if (
objspace->profile.run && count ) {
8839 append(out, rb_sprintf(
"GC %"PRIuSIZE
" invokes.\n",
objspace->profile.count));
8840 append(out,
rb_str_new_cstr(
"Index Invoke Time(sec) Use Size(byte) Total Size(byte) Total Object GC Time(ms)\n"));
8842 for (i = 0; i < count; i++) {
8843 record = &
objspace->profile.records[i];
8844 append(out, rb_sprintf(
"%5"PRIuSIZE
" %19.3f %20"PRIuSIZE
" %20"PRIuSIZE
" %20"PRIuSIZE
" %30.20f\n",
8845 i+1, record->gc_invoke_time, record->heap_use_size,
8846 record->heap_total_size, record->heap_total_objects, record->gc_time*1000));
8849#if GC_PROFILE_MORE_DETAIL
8850 const char *str =
"\n\n" \
8852 "Prepare Time = Previously GC's rest sweep time\n"
8853 "Index Flags Allocate Inc. Allocate Limit"
8854#if CALC_EXACT_MALLOC_SIZE
8857 " Use Page Mark Time(ms) Sweep Time(ms) Prepare Time(ms) LivingObj FreeObj RemovedObj EmptyObj"
8859 " OldgenObj RemNormObj RemShadObj"
8861#if GC_PROFILE_DETAIL_MEMORY
8862 " MaxRSS(KB) MinorFLT MajorFLT"
8867 for (i = 0; i < count; i++) {
8868 record = &
objspace->profile.records[i];
8869 append(out, rb_sprintf(
"%5"PRIuSIZE
" %4s/%c/%6s%c %13"PRIuSIZE
" %15"PRIuSIZE
8870#
if CALC_EXACT_MALLOC_SIZE
8873 " %9"PRIuSIZE
" %17.12f %17.12f %17.12f %10"PRIuSIZE
" %10"PRIuSIZE
" %10"PRIuSIZE
" %10"PRIuSIZE
8875 "%10"PRIuSIZE
" %10"PRIuSIZE
" %10"PRIuSIZE
8877#
if GC_PROFILE_DETAIL_MEMORY
8883 gc_profile_dump_major_reason(record->flags, reason_str),
8884 (record->flags & GPR_FLAG_HAVE_FINALIZE) ?
'F' :
'.',
8885 (record->flags & GPR_FLAG_NEWOBJ) ?
"NEWOBJ" :
8886 (record->flags & GPR_FLAG_MALLOC) ?
"MALLOC" :
8887 (record->flags & GPR_FLAG_METHOD) ?
"METHOD" :
8888 (record->flags & GPR_FLAG_CAPI) ?
"CAPI__" :
"??????",
8889 (record->flags & GPR_FLAG_STRESS) ?
'!' :
' ',
8890 record->allocate_increase, record->allocate_limit,
8891#
if CALC_EXACT_MALLOC_SIZE
8892 record->allocated_size,
8894 record->heap_use_pages,
8895 record->gc_mark_time*1000,
8896 record->gc_sweep_time*1000,
8897 record->prepare_time*1000,
8899 record->heap_live_objects,
8900 record->heap_free_objects,
8901 record->removing_objects,
8902 record->empty_objects
8905 record->old_objects,
8906 record->remembered_normal_objects,
8907 record->remembered_shady_objects
8909#
if GC_PROFILE_DETAIL_MEMORY
8911 record->maxrss / 1024,
8934gc_profile_result(
VALUE _)
8951gc_profile_report(
int argc,
VALUE *argv,
VALUE self)
8955 out = (!rb_check_arity(argc, 0, 1) ?
rb_stdout : argv[0]);
8956 gc_profile_dump_on(out, rb_io_write);
8969gc_profile_total_time(
VALUE self)
8972 rb_objspace_t *
objspace = rb_gc_get_objspace();
8976 size_t count =
objspace->profile.next_index;
8978 for (i = 0; i < count; i++) {
8979 time +=
objspace->profile.records[i].gc_time;
8993gc_profile_enable_get(
VALUE self)
8995 rb_objspace_t *
objspace = rb_gc_get_objspace();
9008gc_profile_enable(
VALUE _)
9010 rb_objspace_t *
objspace = rb_gc_get_objspace();
9012 objspace->profile.current_record = 0;
9025gc_profile_disable(
VALUE _)
9027 rb_objspace_t *
objspace = rb_gc_get_objspace();
9030 objspace->profile.current_record = 0;
9035rb_gc_verify_internal_consistency(
void)
9037 gc_verify_internal_consistency(rb_gc_get_objspace());
9051gc_verify_internal_consistency_m(
VALUE dummy)
9053 rb_gc_verify_internal_consistency();
9057#if GC_CAN_COMPILE_COMPACTION
9071 GC_ASSERT(GC_COMPACTION_SUPPORTED);
9073 ruby_enable_autocompact =
RTEST(v);
9075#if RGENGC_CHECK_MODE
9076 ruby_autocompact_compare_func = NULL;
9080 if (
id == rb_intern(
"empty")) {
9081 ruby_autocompact_compare_func = compare_free_slots;
9089# define gc_set_auto_compact rb_f_notimplement
9092#if GC_CAN_COMPILE_COMPACTION
9100gc_get_auto_compact(
VALUE _)
9105# define gc_get_auto_compact rb_f_notimplement
9108#if GC_CAN_COMPILE_COMPACTION
9134gc_compact_stats(
VALUE self)
9136 rb_objspace_t *
objspace = rb_gc_get_objspace();
9137 VALUE h = rb_hash_new();
9138 VALUE considered = rb_hash_new();
9139 VALUE moved = rb_hash_new();
9140 VALUE moved_up = rb_hash_new();
9141 VALUE moved_down = rb_hash_new();
9143 for (
size_t i = 0; i <
T_MASK; i++) {
9144 if (
objspace->rcompactor.considered_count_table[i]) {
9145 rb_hash_aset(considered, type_sym(i),
SIZET2NUM(
objspace->rcompactor.considered_count_table[i]));
9148 if (
objspace->rcompactor.moved_count_table[i]) {
9149 rb_hash_aset(moved, type_sym(i),
SIZET2NUM(
objspace->rcompactor.moved_count_table[i]));
9152 if (
objspace->rcompactor.moved_up_count_table[i]) {
9153 rb_hash_aset(moved_up, type_sym(i),
SIZET2NUM(
objspace->rcompactor.moved_up_count_table[i]));
9156 if (
objspace->rcompactor.moved_down_count_table[i]) {
9157 rb_hash_aset(moved_down, type_sym(i),
SIZET2NUM(
objspace->rcompactor.moved_down_count_table[i]));
9161 rb_hash_aset(h,
ID2SYM(rb_intern(
"considered")), considered);
9162 rb_hash_aset(h,
ID2SYM(rb_intern(
"moved")), moved);
9163 rb_hash_aset(h,
ID2SYM(rb_intern(
"moved_up")), moved_up);
9164 rb_hash_aset(h,
ID2SYM(rb_intern(
"moved_down")), moved_down);
9169# define gc_compact_stats rb_f_notimplement
9172#if GC_CAN_COMPILE_COMPACTION
9191gc_compact(
VALUE self)
9193 rb_objspace_t *
objspace = rb_gc_get_objspace();
9194 int full_marking_p = gc_config_full_mark_val;
9195 gc_config_full_mark_set(TRUE);
9198 rb_gc_impl_start(rb_gc_get_objspace(),
true,
true,
true,
true);
9199 gc_config_full_mark_set(full_marking_p);
9201 return gc_compact_stats(self);
9204# define gc_compact rb_f_notimplement
9207#if GC_CAN_COMPILE_COMPACTION
9208struct desired_compaction_pages_i_data {
9209 rb_objspace_t *objspace;
9210 size_t required_slots[HEAP_COUNT];
9214desired_compaction_pages_i(
struct heap_page *page,
void *data)
9216 struct desired_compaction_pages_i_data *tdata = data;
9217 rb_objspace_t *
objspace = tdata->objspace;
9219 VALUE vend = vstart + (
VALUE)(page->total_slots * page->heap->slot_size);
9222 for (
VALUE v = vstart; v != vend; v += page->heap->slot_size) {
9223 asan_unpoisoning_object(v) {
9226 rb_heap_t *dest_pool = gc_compact_destination_pool(
objspace, page->heap, v);
9227 size_t dest_pool_idx = dest_pool - heaps;
9228 tdata->required_slots[dest_pool_idx]++;
9252gc_verify_compaction_references(
int argc,
VALUE* argv,
VALUE self)
9254 static ID keywords[3] = {0};
9256 keywords[0] = rb_intern(
"toward");
9257 keywords[1] = rb_intern(
"double_heap");
9258 keywords[2] = rb_intern(
"expand_heap");
9265 int kwarg_count =
rb_get_kwargs(options, keywords, 0, 3, arguments);
9266 bool toward_empty = kwarg_count > 0 &&
SYMBOL_P(arguments[0]) &&
SYM2ID(arguments[0]) == rb_intern(
"empty");
9267 bool expand_heap = (kwarg_count > 1 &&
RTEST(arguments[1])) || (kwarg_count > 2 &&
RTEST(arguments[2]));
9269 rb_objspace_t *
objspace = rb_gc_get_objspace();
9272 rb_gc_impl_start(
objspace,
true,
true,
true,
false);
9274 unsigned int lev = RB_GC_VM_LOCK();
9280 struct desired_compaction_pages_i_data desired_compaction = {
9282 .required_slots = {0},
9285 objspace_each_pages(
objspace, desired_compaction_pages_i, &desired_compaction, TRUE);
9288 size_t max_existing_pages = 0;
9289 for (
int i = 0; i < HEAP_COUNT; i++) {
9290 rb_heap_t *heap = &heaps[i];
9291 max_existing_pages = MAX(max_existing_pages, heap->total_pages);
9295 for (
int i = 0; i < HEAP_COUNT; i++) {
9296 rb_heap_t *heap = &heaps[i];
9298 size_t pages_to_add = 0;
9305 pages_to_add += max_existing_pages - heap->total_pages;
9310 objspace->heap_pages.allocatable_slots = desired_compaction.required_slots[i];
9311 while (
objspace->heap_pages.allocatable_slots > 0) {
9312 heap_page_allocate_and_initialize(
objspace, heap);
9320 for (; pages_to_add > 0; pages_to_add--) {
9321 heap_page_allocate_and_initialize_force(
objspace, heap);
9327 objspace->rcompactor.compare_func = compare_free_slots;
9330 RB_GC_VM_UNLOCK(lev);
9332 rb_gc_impl_start(rb_gc_get_objspace(),
true,
true,
true,
true);
9334 rb_objspace_reachable_objects_from_root(root_obj_check_moved_i,
objspace);
9337 objspace->rcompactor.compare_func = NULL;
9339 return gc_compact_stats(self);
9342# define gc_verify_compaction_references rb_f_notimplement
9346rb_gc_impl_objspace_free(
void *objspace_ptr)
9348 rb_objspace_t *
objspace = objspace_ptr;
9351 rb_bug(
"lazy sweeping underway when freeing object space");
9356 for (
size_t i = 0; i < rb_darray_size(
objspace->heap_pages.sorted); i++) {
9359 rb_darray_free_without_gc(
objspace->heap_pages.sorted);
9360 heap_pages_lomem = 0;
9361 heap_pages_himem = 0;
9363 for (
int i = 0; i < HEAP_COUNT; i++) {
9364 rb_heap_t *heap = &heaps[i];
9365 heap->total_pages = 0;
9366 heap->total_slots = 0;
9369 free_stack_chunks(&
objspace->mark_stack);
9370 mark_stack_free_cache(&
objspace->mark_stack);
9372 rb_darray_free_without_gc(
objspace->weak_references);
9377#if MALLOC_ALLOCATED_SIZE
9388gc_malloc_allocated_size(
VALUE self)
9390 rb_objspace_t *
objspace = (rb_objspace_t *)rb_gc_get_objspace();
9404gc_malloc_allocations(
VALUE self)
9406 rb_objspace_t *
objspace = (rb_objspace_t *)rb_gc_get_objspace();
9412rb_gc_impl_before_fork(
void *objspace_ptr)
9414 rb_objspace_t *
objspace = objspace_ptr;
9416 objspace->fork_vm_lock_lev = RB_GC_VM_LOCK();
9421rb_gc_impl_after_fork(
void *objspace_ptr, rb_pid_t pid)
9423 rb_objspace_t *
objspace = objspace_ptr;
9425 RB_GC_VM_UNLOCK(
objspace->fork_vm_lock_lev);
9429 rb_gc_ractor_newobj_cache_foreach(gc_ractor_newobj_cache_clear, NULL);
9433VALUE rb_ident_hash_new_with_size(st_index_t size);
9435#if GC_DEBUG_STRESS_TO_CLASS
9444rb_gcdebug_add_stress_to_class(
int argc,
VALUE *argv,
VALUE self)
9446 rb_objspace_t *
objspace = rb_gc_get_objspace();
9448 if (!stress_to_class) {
9449 set_stress_to_class(rb_ident_hash_new_with_size(argc));
9452 for (
int i = 0; i < argc; i++) {
9453 VALUE klass = argv[i];
9454 rb_hash_aset(stress_to_class, klass,
Qtrue);
9469rb_gcdebug_remove_stress_to_class(
int argc,
VALUE *argv,
VALUE self)
9471 rb_objspace_t *
objspace = rb_gc_get_objspace();
9473 if (stress_to_class) {
9474 for (
int i = 0; i < argc; ++i) {
9475 rb_hash_delete(stress_to_class, argv[i]);
9478 if (rb_hash_size(stress_to_class) == 0) {
9479 stress_to_class = 0;
9488rb_gc_impl_objspace_alloc(
void)
9490 rb_objspace_t *
objspace = calloc1(
sizeof(rb_objspace_t));
9496rb_gc_impl_objspace_init(
void *objspace_ptr)
9498 rb_objspace_t *
objspace = objspace_ptr;
9500 gc_config_full_mark_set(TRUE);
9503 malloc_limit = gc_params.malloc_limit_min;
9505 if (
objspace->finalize_deferred_pjob == POSTPONED_JOB_HANDLE_INVALID) {
9506 rb_bug(
"Could not preregister postponed job for GC");
9509 for (
int i = 0; i < HEAP_COUNT; i++) {
9510 rb_heap_t *heap = &heaps[i];
9512 heap->slot_size = (1 << i) * BASE_SLOT_SIZE;
9515 static const bits_t slot_bits_masks[] = {
9517 (bits_t)0x5555555555555555ULL,
9518 (bits_t)0x1111111111111111ULL,
9519 (bits_t)0x0101010101010101ULL,
9520 (bits_t)0x0001000100010001ULL,
9522 GC_ASSERT(HEAP_COUNT ==
sizeof(slot_bits_masks) /
sizeof(slot_bits_masks[0]));
9523 heap->slot_bits_mask = slot_bits_masks[i];
9525 ccan_list_head_init(&heap->pages);
9528 rb_darray_make_without_gc(&
objspace->heap_pages.sorted, 0);
9529 rb_darray_make_without_gc(&
objspace->weak_references, 0);
9536#if defined(INIT_HEAP_PAGE_ALLOC_USE_MMAP)
9538 heap_page_alloc_use_mmap = INIT_HEAP_PAGE_ALLOC_USE_MMAP;
9540#if RGENGC_ESTIMATE_OLDMALLOC
9541 objspace->rgengc.oldmalloc_increase_limit = gc_params.oldmalloc_limit_min;
9544 for (
int i = 0; i < HEAP_COUNT; i++) {
9546 gc_params.heap_init_slots[i] = GC_HEAP_INIT_SLOTS;
9549 init_mark_stack(&
objspace->mark_stack);
9551 objspace->profile.invoke_time = getrusage_time();
9552 finalizer_table = st_init_numtable();
9556rb_gc_impl_init(
void)
9558 VALUE gc_constants = rb_hash_new();
9559 rb_hash_aset(gc_constants,
ID2SYM(rb_intern(
"DEBUG")), GC_DEBUG ?
Qtrue :
Qfalse);
9560 rb_hash_aset(gc_constants,
ID2SYM(rb_intern(
"BASE_SLOT_SIZE")),
SIZET2NUM(BASE_SLOT_SIZE - RVALUE_OVERHEAD));
9562 rb_hash_aset(gc_constants,
ID2SYM(rb_intern(
"RVALUE_OVERHEAD")),
SIZET2NUM(RVALUE_OVERHEAD));
9563 rb_hash_aset(gc_constants,
ID2SYM(rb_intern(
"HEAP_PAGE_OBJ_LIMIT")),
SIZET2NUM(HEAP_PAGE_OBJ_LIMIT));
9564 rb_hash_aset(gc_constants,
ID2SYM(rb_intern(
"HEAP_PAGE_BITMAP_SIZE")),
SIZET2NUM(HEAP_PAGE_BITMAP_SIZE));
9565 rb_hash_aset(gc_constants,
ID2SYM(rb_intern(
"HEAP_PAGE_SIZE")),
SIZET2NUM(HEAP_PAGE_SIZE));
9566 rb_hash_aset(gc_constants,
ID2SYM(rb_intern(
"HEAP_COUNT")),
LONG2FIX(HEAP_COUNT));
9567 rb_hash_aset(gc_constants,
ID2SYM(rb_intern(
"RVARGC_MAX_ALLOCATE_SIZE")),
LONG2FIX(heap_slot_size(HEAP_COUNT - 1)));
9568 rb_hash_aset(gc_constants,
ID2SYM(rb_intern(
"RVALUE_OLD_AGE")),
LONG2FIX(RVALUE_OLD_AGE));
9569 if (RB_BUG_INSTEAD_OF_RB_MEMERROR+0) {
9570 rb_hash_aset(gc_constants,
ID2SYM(rb_intern(
"RB_BUG_INSTEAD_OF_RB_MEMERROR")),
Qtrue);
9574 rb_define_const(
rb_mGC,
"INTERNAL_CONSTANTS", gc_constants);
9576 if (GC_COMPACTION_SUPPORTED) {
9591#if GC_DEBUG_STRESS_TO_CLASS
9599#if MALLOC_ALLOCATED_SIZE
9618#define OPT(o) if (o) rb_ary_push(opts, rb_interned_str(#o, sizeof(#o) - 1))
9622 OPT(RGENGC_CHECK_MODE);
9623 OPT(RGENGC_PROFILE);
9624 OPT(RGENGC_ESTIMATE_OLDMALLOC);
9625 OPT(GC_PROFILE_MORE_DETAIL);
9626 OPT(GC_ENABLE_LAZY_SWEEP);
9627 OPT(CALC_EXACT_MALLOC_SIZE);
9628 OPT(MALLOC_ALLOCATED_SIZE);
9629 OPT(MALLOC_ALLOCATED_SIZE_CHECK);
9630 OPT(GC_PROFILE_DETAIL_MEMORY);
9631 OPT(GC_COMPACTION_SUPPORTED);
#define RBIMPL_ASSERT_OR_ASSUME(...)
This is either RUBY_ASSERT or RBIMPL_ASSUME, depending on RUBY_DEBUG.
#define RUBY_ASSERT(...)
Asserts that the given expression is truthy if and only if RUBY_DEBUG is truthy.
#define RUBY_ATOMIC_VALUE_CAS(var, oldval, newval)
Identical to RUBY_ATOMIC_CAS, except it expects its arguments are VALUE.
#define RUBY_ATOMIC_SIZE_EXCHANGE(var, val)
Identical to RUBY_ATOMIC_EXCHANGE, except it expects its arguments are size_t.
#define RUBY_ATOMIC_SIZE_INC(var)
Identical to RUBY_ATOMIC_INC, except it expects its argument is size_t.
#define RUBY_ATOMIC_SIZE_CAS(var, oldval, newval)
Identical to RUBY_ATOMIC_CAS, except it expects its arguments are size_t.
std::atomic< unsigned > rb_atomic_t
Type that is eligible for atomic operations.
#define RUBY_ATOMIC_SIZE_ADD(var, val)
Identical to RUBY_ATOMIC_ADD, except it expects its arguments are size_t.
#define RUBY_ATOMIC_VALUE_EXCHANGE(var, val)
Identical to RUBY_ATOMIC_EXCHANGE, except it expects its arguments are VALUE.
#define RUBY_ATOMIC_SET(var, val)
Identical to RUBY_ATOMIC_EXCHANGE, except for the return type.
#define RUBY_ATOMIC_EXCHANGE(var, val)
Atomically replaces the value pointed by var with val.
#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...
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...
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 ...
#define RUBY_INTERNAL_EVENT_GC_EXIT
gc_exit() is called.
#define RUBY_INTERNAL_EVENT_GC_ENTER
gc_enter() is called.
#define RUBY_INTERNAL_EVENT_GC_END_SWEEP
GC ended sweep phase.
#define RUBY_INTERNAL_EVENT_GC_END_MARK
GC ended mark phase.
#define RUBY_INTERNAL_EVENT_OBJSPACE_MASK
Bitmask of GC events.
#define RUBY_INTERNAL_EVENT_FREEOBJ
Object swept.
#define RUBY_INTERNAL_EVENT_GC_START
GC started.
uint32_t rb_event_flag_t
Represents event(s).
#define RUBY_INTERNAL_EVENT_NEWOBJ
Object allocated.
@ RUBY_FL_PROMOTED
Ruby objects are "generational".
VALUE rb_define_module_under(VALUE outer, const char *name)
Defines a module under the namespace of outer.
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.
int rb_keyword_given_p(void)
Determines if the current method is given a keyword argument.
int rb_get_kwargs(VALUE keyword_hash, const ID *table, int required, int optional, VALUE *values)
Keyword argument deconstructor.
#define T_COMPLEX
Old name of RUBY_T_COMPLEX.
#define T_FILE
Old name of RUBY_T_FILE.
#define T_STRING
Old name of RUBY_T_STRING.
#define xfree
Old name of ruby_xfree.
#define T_MASK
Old name of RUBY_T_MASK.
#define Qundef
Old name of RUBY_Qundef.
#define INT2FIX
Old name of RB_INT2FIX.
#define OBJ_FROZEN
Old name of RB_OBJ_FROZEN.
#define T_NIL
Old name of RUBY_T_NIL.
#define T_FLOAT
Old name of RUBY_T_FLOAT.
#define T_IMEMO
Old name of RUBY_T_IMEMO.
#define ID2SYM
Old name of RB_ID2SYM.
#define T_BIGNUM
Old name of RUBY_T_BIGNUM.
#define SPECIAL_CONST_P
Old name of RB_SPECIAL_CONST_P.
#define T_STRUCT
Old name of RUBY_T_STRUCT.
#define OBJ_FREEZE
Old name of RB_OBJ_FREEZE.
#define T_FIXNUM
Old name of RUBY_T_FIXNUM.
#define SYM2ID
Old name of RB_SYM2ID.
#define T_DATA
Old name of RUBY_T_DATA.
#define FL_SHAREABLE
Old name of RUBY_FL_SHAREABLE.
#define T_NONE
Old name of RUBY_T_NONE.
#define T_NODE
Old name of RUBY_T_NODE.
#define SIZET2NUM
Old name of RB_SIZE2NUM.
#define xmalloc
Old name of ruby_xmalloc.
#define LONG2FIX
Old name of RB_INT2FIX.
#define FIX2INT
Old name of RB_FIX2INT.
#define FL_FINALIZE
Old name of RUBY_FL_FINALIZE.
#define T_MODULE
Old name of RUBY_T_MODULE.
#define T_TRUE
Old name of RUBY_T_TRUE.
#define T_RATIONAL
Old name of RUBY_T_RATIONAL.
#define T_ICLASS
Old name of RUBY_T_ICLASS.
#define T_HASH
Old name of RUBY_T_HASH.
#define ALLOC_N
Old name of RB_ALLOC_N.
#define FL_TEST_RAW
Old name of RB_FL_TEST_RAW.
#define FL_SET
Old name of RB_FL_SET.
#define rb_ary_new3
Old name of rb_ary_new_from_args.
#define T_FALSE
Old name of RUBY_T_FALSE.
#define ULL2NUM
Old name of RB_ULL2NUM.
#define T_UNDEF
Old name of RUBY_T_UNDEF.
#define Qtrue
Old name of RUBY_Qtrue.
#define T_ZOMBIE
Old name of RUBY_T_ZOMBIE.
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#define T_ARRAY
Old name of RUBY_T_ARRAY.
#define T_OBJECT
Old name of RUBY_T_OBJECT.
#define NIL_P
Old name of RB_NIL_P.
#define FL_WB_PROTECTED
Old name of RUBY_FL_WB_PROTECTED.
#define T_SYMBOL
Old name of RUBY_T_SYMBOL.
#define DBL2NUM
Old name of rb_float_new.
#define T_MATCH
Old name of RUBY_T_MATCH.
#define T_CLASS
Old name of RUBY_T_CLASS.
#define BUILTIN_TYPE
Old name of RB_BUILTIN_TYPE.
#define T_MOVED
Old name of RUBY_T_MOVED.
#define FL_TEST
Old name of RB_FL_TEST.
#define FL_UNSET
Old name of RB_FL_UNSET.
#define FIXNUM_P
Old name of RB_FIXNUM_P.
#define SYMBOL_P
Old name of RB_SYMBOL_P.
#define T_REGEXP
Old name of RUBY_T_REGEXP.
#define ruby_verbose
This variable controls whether the interpreter is in debug mode.
VALUE rb_eRuntimeError
RuntimeError exception.
void rb_warn(const char *fmt,...)
Identical to rb_warning(), except it reports unless $VERBOSE is nil.
VALUE rb_ensure(VALUE(*b_proc)(VALUE), VALUE data1, VALUE(*e_proc)(VALUE), VALUE data2)
An equivalent to ensure clause.
VALUE rb_obj_hide(VALUE obj)
Make the object invisible from Ruby code.
VALUE rb_equal(VALUE lhs, VALUE rhs)
This function is an optimised version of calling #==.
VALUE rb_stdout
STDOUT constant.
#define RB_GNUC_EXTENSION_BLOCK(x)
This is expanded to the passed token for non-GCC compilers.
Routines to manipulate encodings of strings.
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.
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.
VALUE rb_str_buf_new(long capa)
Allocates a "string buffer".
#define rb_str_new_cstr(str)
Identical to rb_str_new, except it assumes the passed pointer is a pointer to a C string.
const char * rb_sourcefile(void)
Resembles __FILE__.
VALUE rb_f_notimplement(int argc, const VALUE *argv, VALUE obj, VALUE marker)
Raises rb_eNotImpError.
int rb_sourceline(void)
Resembles __LINE__.
#define RB_SYM2ID
Just another name of rb_sym2id.
ID rb_sym2id(VALUE obj)
Converts an instance of rb_cSymbol into an ID.
char * ptr
Pointer to the underlying memory region, of at least capa bytes.
int len
Length of the buffer.
void * rb_thread_call_with_gvl(void *(*func)(void *), void *data1)
(Re-)acquires the GVL.
#define strtod(s, e)
Just another name of ruby_strtod.
void ruby_qsort(void *, const size_t, const size_t, int(*)(const void *, const void *, void *), void *)
Reentrant implementation of quick sort.
#define DECIMAL_SIZE_OF_BITS(n)
an approximation of ceil(n * log10(2)), up to 1,048,576 (1<<20) without overflow within 32-bit calcul...
#define MEMZERO(p, type, n)
Handy macro to erase a region of memory.
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
VALUE type(ANYARGS)
ANYARGS-ed function type.
#define RARRAY_LEN
Just another name of rb_array_len.
#define RARRAY_AREF(a, i)
#define RBASIC(obj)
Convenient casting macro.
#define errno
Ractor-aware version of errno.
int ruby_native_thread_p(void)
Queries if the thread which calls this function is a ruby's thread.
#define RTEST
This is an old name of RB_TEST.
#define _(args)
This was a transition path from K&R to ANSI.
Ruby object's base components.
uintptr_t ID
Type that represents a Ruby identifier such as a variable name.
uintptr_t VALUE
Type that represents a Ruby object.
ruby_value_type
C-level type of an object.
@ RUBY_T_ICLASS
Hidden classes known as IClasses.
@ RUBY_T_FIXNUM
Integers formerly known as Fixnums.
@ RUBY_T_MASK
Bitmask of ruby_value_type.
@ RUBY_T_NONE
Non-object (swept etc.).