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;
528 rb_darray(
struct heap_page *) sorted;
530 size_t allocated_pages;
533 size_t freeable_pages;
535 size_t allocatable_slots;
538 VALUE deferred_final;
541 st_table *finalizer_table;
545 unsigned int latest_gc_info;
546 gc_profile_record *records;
547 gc_profile_record *current_record;
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;
586 struct timespec marking_start_time;
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
613 struct st_table *allrefs_table;
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);
1064static inline void gc_mark(rb_objspace_t *
objspace,
VALUE ptr);
1065static inline void gc_pin(rb_objspace_t *
objspace,
VALUE ptr);
1066static inline void gc_mark_and_pin(rb_objspace_t *
objspace,
VALUE ptr);
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) {
1390 check_rvalue_consistency(
objspace, 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;
2218heap_slot_size(
unsigned char pool_id)
2220 GC_ASSERT(pool_id < HEAP_COUNT);
2222 size_t slot_size = (1 << pool_id) * BASE_SLOT_SIZE;
2224#if RGENGC_CHECK_MODE
2225 rb_objspace_t *
objspace = rb_gc_get_objspace();
2226 GC_ASSERT(heaps[pool_id].slot_size == (
short)slot_size);
2229 slot_size -= RVALUE_OVERHEAD;
2235rb_gc_impl_size_allocatable_p(
size_t size)
2237 return size <= heap_slot_size(HEAP_COUNT - 1);
2240static const size_t ALLOCATED_COUNT_STEP = 1024;
2242ractor_cache_flush_count(rb_objspace_t *
objspace, rb_ractor_newobj_cache_t *cache)
2244 for (
int heap_idx = 0; heap_idx < HEAP_COUNT; heap_idx++) {
2245 rb_ractor_newobj_heap_cache_t *heap_cache = &cache->heap_caches[heap_idx];
2247 rb_heap_t *heap = &heaps[heap_idx];
2249 heap_cache->allocated_objects_count = 0;
2254ractor_cache_allocate_slot(rb_objspace_t *
objspace, rb_ractor_newobj_cache_t *cache,
2257 rb_ractor_newobj_heap_cache_t *heap_cache = &cache->heap_caches[heap_idx];
2258 struct free_slot *p = heap_cache->freelist;
2260 if (RB_UNLIKELY(is_incremental_marking(
objspace))) {
2262 if (cache->incremental_mark_step_allocated_slots >= INCREMENTAL_MARK_STEP_ALLOCATIONS) {
2267 cache->incremental_mark_step_allocated_slots++;
2273 rb_asan_unpoison_object(obj,
true);
2274 heap_cache->freelist = p->next;
2276 heap_cache->allocated_objects_count++;
2277 rb_heap_t *heap = &heaps[heap_idx];
2278 if (heap_cache->allocated_objects_count >= ALLOCATED_COUNT_STEP) {
2280 heap_cache->allocated_objects_count = 0;
2283#if RGENGC_CHECK_MODE
2284 GC_ASSERT(rb_gc_impl_obj_slot_size(obj) == heap_slot_size(heap_idx));
2286 MEMZERO((
char *)obj,
char, heap_slot_size(heap_idx));
2296heap_next_free_page(rb_objspace_t *
objspace, rb_heap_t *heap)
2300 if (heap->free_pages == NULL) {
2304 page = heap->free_pages;
2305 heap->free_pages = page->free_next;
2307 GC_ASSERT(page->free_slots != 0);
2309 asan_unlock_freelist(page);
2315ractor_cache_set_page(rb_objspace_t *
objspace, rb_ractor_newobj_cache_t *cache,
size_t heap_idx,
2318 gc_report(3,
objspace,
"ractor_set_cache: Using page %p\n", (
void *)page->body);
2320 rb_ractor_newobj_heap_cache_t *heap_cache = &cache->heap_caches[heap_idx];
2322 GC_ASSERT(heap_cache->freelist == NULL);
2323 GC_ASSERT(page->free_slots != 0);
2324 GC_ASSERT(page->freelist != NULL);
2326 heap_cache->using_page = page;
2327 heap_cache->freelist = page->freelist;
2328 page->free_slots = 0;
2329 page->freelist = NULL;
2331 rb_asan_unpoison_object((
VALUE)heap_cache->freelist,
false);
2333 rb_asan_poison_object((
VALUE)heap_cache->freelist);
2337heap_idx_for_size(
size_t size)
2339 size += RVALUE_OVERHEAD;
2341 size_t slot_count = CEILDIV(size, BASE_SLOT_SIZE);
2344 size_t heap_idx = 64 - nlz_int64(slot_count - 1);
2346 if (heap_idx >= HEAP_COUNT) {
2347 rb_bug(
"heap_idx_for_size: allocation size too large "
2348 "(size=%"PRIuSIZE
"u, heap_idx=%"PRIuSIZE
"u)", size, heap_idx);
2351#if RGENGC_CHECK_MODE
2352 rb_objspace_t *
objspace = rb_gc_get_objspace();
2353 GC_ASSERT(size <= (
size_t)heaps[heap_idx].slot_size);
2354 if (heap_idx > 0) GC_ASSERT(size > (
size_t)heaps[heap_idx - 1].slot_size);
2361rb_gc_impl_heap_id_for_size(
void *objspace_ptr,
size_t size)
2363 return heap_idx_for_size(size);
2367static size_t heap_sizes[HEAP_COUNT + 1] = { 0 };
2370rb_gc_impl_heap_sizes(
void *objspace_ptr)
2372 if (heap_sizes[0] == 0) {
2373 for (
unsigned char i = 0; i < HEAP_COUNT; i++) {
2374 heap_sizes[i] = heap_slot_size(i);
2381NOINLINE(
static VALUE newobj_cache_miss(rb_objspace_t *
objspace, rb_ractor_newobj_cache_t *cache,
size_t heap_idx,
bool vm_locked));
2384newobj_cache_miss(rb_objspace_t *
objspace, rb_ractor_newobj_cache_t *cache,
size_t heap_idx,
bool vm_locked)
2386 rb_heap_t *heap = &heaps[heap_idx];
2389 unsigned int lev = 0;
2390 bool unlock_vm =
false;
2393 lev = RB_GC_CR_LOCK();
2398 if (is_incremental_marking(
objspace)) {
2400 cache->incremental_mark_step_allocated_slots = 0;
2403 obj = ractor_cache_allocate_slot(
objspace, cache, heap_idx);
2409 ractor_cache_set_page(
objspace, cache, heap_idx, page);
2412 obj = ractor_cache_allocate_slot(
objspace, cache, heap_idx);
2417 RB_GC_CR_UNLOCK(lev);
2420 if (RB_UNLIKELY(obj ==
Qfalse)) {
2427newobj_alloc(rb_objspace_t *
objspace, rb_ractor_newobj_cache_t *cache,
size_t heap_idx,
bool vm_locked)
2429 VALUE obj = ractor_cache_allocate_slot(
objspace, cache, heap_idx);
2431 if (RB_UNLIKELY(obj ==
Qfalse)) {
2432 obj = newobj_cache_miss(
objspace, cache, heap_idx, vm_locked);
2438ALWAYS_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));
2441newobj_slowpath(
VALUE klass,
VALUE flags, rb_objspace_t *
objspace, rb_ractor_newobj_cache_t *cache,
int wb_protected,
size_t heap_idx)
2446 lev = RB_GC_CR_LOCK();
2448 if (RB_UNLIKELY(during_gc || ruby_gc_stressful)) {
2452 if (rb_memerror_reentered()) {
2455 rb_bug(
"object allocation during garbage collection phase");
2458 if (ruby_gc_stressful) {
2459 if (!garbage_collect(
objspace, GPR_FLAG_NEWOBJ)) {
2465 obj = newobj_alloc(
objspace, cache, heap_idx,
true);
2466 newobj_init(klass, flags, wb_protected,
objspace, obj);
2468 RB_GC_CR_UNLOCK(lev);
2473NOINLINE(
static VALUE newobj_slowpath_wb_protected(
VALUE klass,
VALUE flags,
2474 rb_objspace_t *
objspace, rb_ractor_newobj_cache_t *cache,
size_t heap_idx));
2475NOINLINE(
static VALUE newobj_slowpath_wb_unprotected(
VALUE klass,
VALUE flags,
2476 rb_objspace_t *
objspace, rb_ractor_newobj_cache_t *cache,
size_t heap_idx));
2479newobj_slowpath_wb_protected(
VALUE klass,
VALUE flags, rb_objspace_t *
objspace, rb_ractor_newobj_cache_t *cache,
size_t heap_idx)
2481 return newobj_slowpath(klass, flags,
objspace, cache, TRUE, heap_idx);
2485newobj_slowpath_wb_unprotected(
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, FALSE, heap_idx);
2491rb_gc_impl_new_obj(
void *objspace_ptr,
void *cache_ptr,
VALUE klass,
VALUE flags,
bool wb_protected,
size_t alloc_size)
2494 rb_objspace_t *
objspace = objspace_ptr;
2496 RB_DEBUG_COUNTER_INC(obj_newobj);
2497 (void)RB_DEBUG_COUNTER_INC_IF(obj_newobj_wb_unprotected, !wb_protected);
2499 if (RB_UNLIKELY(stress_to_class)) {
2500 if (rb_hash_lookup2(stress_to_class, klass,
Qundef) !=
Qundef) {
2505 size_t heap_idx = heap_idx_for_size(alloc_size);
2507 rb_ractor_newobj_cache_t *cache = (rb_ractor_newobj_cache_t *)cache_ptr;
2509 if (!RB_UNLIKELY(during_gc || ruby_gc_stressful) &&
2511 obj = newobj_alloc(
objspace, cache, heap_idx,
false);
2512 newobj_init(klass, flags, wb_protected,
objspace, obj);
2515 RB_DEBUG_COUNTER_INC(obj_newobj_slowpath);
2517 obj = wb_protected ?
2518 newobj_slowpath_wb_protected(klass, flags,
objspace, cache, heap_idx) :
2519 newobj_slowpath_wb_unprotected(klass, flags,
objspace, cache, heap_idx);
2526ptr_in_page_body_p(
const void *ptr,
const void *memb)
2529 uintptr_t p_body = (uintptr_t)page->body;
2531 if ((uintptr_t)ptr >= p_body) {
2532 return (uintptr_t)ptr < (p_body + HEAP_PAGE_SIZE) ? 0 : 1;
2539PUREFUNC(
static inline struct heap_page *heap_page_for_ptr(rb_objspace_t *
objspace, uintptr_t ptr);)
2541heap_page_for_ptr(rb_objspace_t *
objspace, uintptr_t ptr)
2545 if (ptr < (uintptr_t)heap_pages_lomem ||
2546 ptr > (uintptr_t)heap_pages_himem) {
2550 res = bsearch((
void *)ptr, rb_darray_ref(
objspace->heap_pages.sorted, 0),
2552 ptr_in_page_body_p);
2562PUREFUNC(
static inline bool is_pointer_to_heap(rb_objspace_t *
objspace,
const void *ptr);)
2564is_pointer_to_heap(rb_objspace_t *
objspace,
const void *ptr)
2566 register uintptr_t p = (uintptr_t)ptr;
2569 RB_DEBUG_COUNTER_INC(gc_isptr_trial);
2571 if (p < heap_pages_lomem || p > heap_pages_himem)
return FALSE;
2572 RB_DEBUG_COUNTER_INC(gc_isptr_range);
2574 if (p % BASE_SLOT_SIZE != 0)
return FALSE;
2575 RB_DEBUG_COUNTER_INC(gc_isptr_align);
2577 page = heap_page_for_ptr(
objspace, (uintptr_t)ptr);
2579 RB_DEBUG_COUNTER_INC(gc_isptr_maybe);
2580 if (heap_page_in_global_empty_pages_pool(
objspace, page)) {
2584 if (p < page->start)
return FALSE;
2585 if (p >= page->start + (page->total_slots * page->slot_size))
return FALSE;
2586 if ((NUM_IN_PAGE(p) * BASE_SLOT_SIZE) % page->slot_size != 0)
return FALSE;
2595rb_gc_impl_pointer_to_heap_p(
void *objspace_ptr,
const void *ptr)
2597 return is_pointer_to_heap(objspace_ptr, ptr);
2600#define ZOMBIE_OBJ_KEPT_FLAGS (FL_FINALIZE)
2603rb_gc_impl_make_zombie(
void *objspace_ptr,
VALUE obj,
void (*dfree)(
void *),
void *data)
2605 rb_objspace_t *
objspace = objspace_ptr;
2607 struct RZombie *zombie = RZOMBIE(obj);
2608 zombie->flags =
T_ZOMBIE | (zombie->flags & ZOMBIE_OBJ_KEPT_FLAGS);
2609 zombie->dfree = dfree;
2610 zombie->data = data;
2611 VALUE prev, next = heap_pages_deferred_final;
2613 zombie->next = prev = next;
2615 }
while (next != prev);
2617 struct heap_page *page = GET_HEAP_PAGE(obj);
2618 page->final_slots++;
2619 page->heap->final_slots_count++;
2622typedef int each_obj_callback(
void *,
void *,
size_t,
void *);
2623typedef int each_page_callback(
struct heap_page *,
void *);
2626 rb_objspace_t *objspace;
2627 bool reenable_incremental;
2629 each_obj_callback *each_obj_callback;
2630 each_page_callback *each_page_callback;
2634 size_t pages_counts[HEAP_COUNT];
2638objspace_each_objects_ensure(
VALUE arg)
2641 rb_objspace_t *
objspace = data->objspace;
2644 if (data->reenable_incremental) {
2645 objspace->flags.dont_incremental = FALSE;
2648 for (
int i = 0; i < HEAP_COUNT; i++) {
2649 struct heap_page **pages = data->pages[i];
2657objspace_each_objects_try(
VALUE arg)
2660 rb_objspace_t *
objspace = data->objspace;
2663 for (
int i = 0; i < HEAP_COUNT; i++) {
2664 rb_heap_t *heap = &heaps[i];
2665 size_t size = heap->total_pages *
sizeof(
struct heap_page *);
2667 struct heap_page **pages = malloc(size);
2676 size_t pages_count = 0;
2677 ccan_list_for_each(&heap->pages, page, page_node) {
2678 pages[pages_count] = page;
2681 data->pages[i] = pages;
2682 data->pages_counts[i] = pages_count;
2683 GC_ASSERT(pages_count == heap->total_pages);
2686 for (
int i = 0; i < HEAP_COUNT; i++) {
2687 rb_heap_t *heap = &heaps[i];
2688 size_t pages_count = data->pages_counts[i];
2689 struct heap_page **pages = data->pages[i];
2692 for (
size_t i = 0; i < pages_count; i++) {
2695 if (page == NULL)
break;
2699 if (pages[i] != page)
continue;
2701 uintptr_t pstart = (uintptr_t)page->start;
2702 uintptr_t pend = pstart + (page->total_slots * heap->slot_size);
2704 if (data->each_obj_callback &&
2705 (*data->each_obj_callback)((
void *)pstart, (
void *)pend, heap->slot_size, data->data)) {
2708 if (data->each_page_callback &&
2709 (*data->each_page_callback)(page, data->data)) {
2713 page = ccan_list_next(&heap->pages, page, page_node);
2725 bool reenable_incremental = FALSE;
2727 reenable_incremental = !
objspace->flags.dont_incremental;
2730 objspace->flags.dont_incremental = TRUE;
2741objspace_each_objects(rb_objspace_t *
objspace, each_obj_callback *callback,
void *data,
bool protected)
2745 .each_obj_callback = callback,
2746 .each_page_callback = NULL,
2753rb_gc_impl_each_objects(
void *objspace_ptr, each_obj_callback *callback,
void *data)
2755 objspace_each_objects(objspace_ptr, callback, data, TRUE);
2758#if GC_CAN_COMPILE_COMPACTION
2760objspace_each_pages(rb_objspace_t *
objspace, each_page_callback *callback,
void *data,
bool protected)
2764 .each_obj_callback = NULL,
2765 .each_page_callback = callback,
2773rb_gc_impl_define_finalizer(
void *objspace_ptr,
VALUE obj,
VALUE block)
2775 rb_objspace_t *
objspace = objspace_ptr;
2783 unsigned int lev = RB_GC_VM_LOCK();
2785 if (st_lookup(finalizer_table, obj, &data)) {
2786 table = (
VALUE)data;
2789 RB_GC_VM_UNLOCK(lev);
2795 for (i = 0; i <
len; i++) {
2802 lev = RB_GC_VM_LOCK();
2810 st_add_direct(finalizer_table, obj, table);
2813 RB_GC_VM_UNLOCK(lev);
2819rb_gc_impl_undefine_finalizer(
void *objspace_ptr,
VALUE obj)
2821 rb_objspace_t *
objspace = objspace_ptr;
2825 st_data_t data = obj;
2827 int lev = RB_GC_VM_LOCK();
2828 st_delete(finalizer_table, &data, 0);
2829 RB_GC_VM_UNLOCK(lev);
2835rb_gc_impl_copy_finalizer(
void *objspace_ptr,
VALUE dest,
VALUE obj)
2837 rb_objspace_t *
objspace = objspace_ptr;
2843 int lev = RB_GC_VM_LOCK();
2844 if (RB_LIKELY(st_lookup(finalizer_table, obj, &data))) {
2847 st_insert(finalizer_table, dest, table);
2851 rb_bug(
"rb_gc_copy_finalizer: FL_FINALIZE set but not found in finalizer_table: %s", rb_obj_info(obj));
2853 RB_GC_VM_UNLOCK(lev);
2857get_final(
long i,
void *data)
2865run_final(rb_objspace_t *
objspace,
VALUE zombie,
unsigned int lev)
2867 if (RZOMBIE(zombie)->dfree) {
2868 RZOMBIE(zombie)->dfree(RZOMBIE(zombie)->data);
2871 st_data_t key = (st_data_t)zombie;
2875 if (st_delete(finalizer_table, &key, &table)) {
2876 RB_GC_VM_UNLOCK(lev);
2878 lev = RB_GC_VM_LOCK();
2881 rb_bug(
"FL_FINALIZE flag is set, but finalizers are not found");
2885 GC_ASSERT(!st_lookup(finalizer_table, key, NULL));
2896 rb_asan_unpoison_object(zombie,
false);
2897 next_zombie = RZOMBIE(zombie)->next;
2898 page = GET_HEAP_PAGE(zombie);
2900 unsigned int lev = RB_GC_VM_LOCK();
2902 lev = run_final(
objspace, zombie, lev);
2905 GC_ASSERT(page->heap->final_slots_count > 0);
2906 GC_ASSERT(page->final_slots > 0);
2908 page->heap->final_slots_count--;
2909 page->final_slots--;
2911 RVALUE_AGE_SET_BITMAP(zombie, 0);
2912 heap_page_add_freeobj(
objspace, page, zombie);
2913 page->heap->total_freed_objects++;
2915 RB_GC_VM_UNLOCK(lev);
2917 zombie = next_zombie;
2922finalize_deferred_heap_pages(rb_objspace_t *
objspace)
2931finalize_deferred(rb_objspace_t *
objspace)
2933 rb_gc_set_pending_interrupt();
2934 finalize_deferred_heap_pages(
objspace);
2935 rb_gc_unset_pending_interrupt();
2939gc_finalize_deferred(
void *dmy)
2949gc_finalize_deferred_register(rb_objspace_t *
objspace)
2955static int pop_mark_stack(mark_stack_t *stack,
VALUE *data);
2958gc_abort(
void *objspace_ptr)
2960 rb_objspace_t *
objspace = objspace_ptr;
2962 if (is_incremental_marking(
objspace)) {
2965 while (pop_mark_stack(&
objspace->mark_stack, &obj));
2967 objspace->flags.during_incremental_marking = FALSE;
2971 for (
int i = 0; i < HEAP_COUNT; i++) {
2972 rb_heap_t *heap = &heaps[i];
2974 heap->sweeping_page = NULL;
2977 ccan_list_for_each(&heap->pages, page, page_node) {
2978 page->flags.before_sweep =
false;
2983 for (
int i = 0; i < HEAP_COUNT; i++) {
2984 rb_heap_t *heap = &heaps[i];
2985 rgengc_mark_and_rememberset_clear(
objspace, heap);
2988 gc_mode_set(
objspace, gc_mode_none);
2992rb_gc_impl_shutdown_free_objects(
void *objspace_ptr)
2994 rb_objspace_t *
objspace = objspace_ptr;
2996 for (
size_t i = 0; i < rb_darray_size(
objspace->heap_pages.sorted); i++) {
2998 short stride = page->slot_size;
3000 uintptr_t p = (uintptr_t)page->start;
3001 uintptr_t pend = p + page->total_slots * stride;
3002 for (; p < pend; p += stride) {
3004 asan_unpoisoning_object(vp) {
3006 rb_gc_obj_free_vm_weak_references(vp);
3007 if (rb_gc_obj_free(
objspace, vp)) {
3017rb_gc_impl_shutdown_call_finalizer_i(st_data_t key, st_data_t val, st_data_t _data)
3033rb_gc_impl_shutdown_call_finalizer(
void *objspace_ptr)
3035 rb_objspace_t *
objspace = objspace_ptr;
3037#if RGENGC_CHECK_MODE >= 2
3038 gc_verify_internal_consistency(
objspace);
3042 objspace->flags.dont_incremental = 1;
3051 while (finalizer_table->num_entries) {
3052 st_foreach(finalizer_table, rb_gc_impl_shutdown_call_finalizer_i, 0);
3057 GC_ASSERT(heap_pages_deferred_final == 0);
3066 unsigned int lock_lev;
3067 gc_enter(
objspace, gc_enter_event_finalizer, &lock_lev);
3070 for (
size_t i = 0; i < rb_darray_size(
objspace->heap_pages.sorted); i++) {
3072 short stride = page->slot_size;
3074 uintptr_t p = (uintptr_t)page->start;
3075 uintptr_t pend = p + page->total_slots * stride;
3076 for (; p < pend; p += stride) {
3078 asan_unpoisoning_object(vp) {
3079 if (rb_gc_shutdown_call_finalizer_p(vp)) {
3080 rb_gc_obj_free_vm_weak_references(vp);
3081 if (rb_gc_obj_free(
objspace, vp)) {
3089 gc_exit(
objspace, gc_enter_event_finalizer, &lock_lev);
3091 finalize_deferred_heap_pages(
objspace);
3093 st_free_table(finalizer_table);
3094 finalizer_table = 0;
3099rb_gc_impl_each_object(
void *objspace_ptr,
void (*func)(
VALUE obj,
void *data),
void *data)
3101 rb_objspace_t *
objspace = objspace_ptr;
3103 for (
size_t i = 0; i < rb_darray_size(
objspace->heap_pages.sorted); i++) {
3105 short stride = page->slot_size;
3107 uintptr_t p = (uintptr_t)page->start;
3108 uintptr_t pend = p + page->total_slots * stride;
3109 for (; p < pend; p += stride) {
3112 asan_unpoisoning_object(obj) {
3126objspace_available_slots(rb_objspace_t *
objspace)
3128 size_t total_slots = 0;
3129 for (
int i = 0; i < HEAP_COUNT; i++) {
3130 rb_heap_t *heap = &heaps[i];
3131 total_slots += heap->total_slots;
3137objspace_live_slots(rb_objspace_t *
objspace)
3143objspace_free_slots(rb_objspace_t *
objspace)
3149gc_setup_mark_bits(
struct heap_page *page)
3152 memcpy(&page->mark_bits[0], &page->uncollectible_bits[0], HEAP_PAGE_BITMAP_SIZE);
3155static int gc_is_moveable_obj(rb_objspace_t *
objspace,
VALUE obj);
3159enum {HEAP_PAGE_LOCK = PAGE_NOACCESS, HEAP_PAGE_UNLOCK = PAGE_READWRITE};
3165 return VirtualProtect(body, HEAP_PAGE_SIZE, protect, &old_protect) != 0;
3167#elif defined(__wasi__)
3169enum {HEAP_PAGE_LOCK, HEAP_PAGE_UNLOCK};
3170#define protect_page_body(body, protect) 1
3172enum {HEAP_PAGE_LOCK = PROT_NONE, HEAP_PAGE_UNLOCK = PROT_READ | PROT_WRITE};
3173#define protect_page_body(body, protect) !mprotect((body), HEAP_PAGE_SIZE, (protect))
3179 if (!protect_page_body(body, HEAP_PAGE_LOCK)) {
3180 rb_bug(
"Couldn't protect page %p, errno: %s", (
void *)body, strerror(
errno));
3183 gc_report(5,
objspace,
"Protecting page in move %p\n", (
void *)body);
3190 if (!protect_page_body(body, HEAP_PAGE_UNLOCK)) {
3191 rb_bug(
"Couldn't unprotect page %p, errno: %s", (
void *)body, strerror(
errno));
3194 gc_report(5,
objspace,
"Unprotecting page in move %p\n", (
void *)body);
3201 GC_ASSERT(gc_is_moveable_obj(
objspace, src));
3203 struct heap_page *src_page = GET_HEAP_PAGE(src);
3211 GC_ASSERT(RVALUE_MARKED(
objspace, src));
3213 asan_unlock_freelist(free_page);
3215 asan_lock_freelist(free_page);
3217 rb_asan_unpoison_object(dest,
false);
3224 asan_unlock_freelist(free_page);
3225 free_page->freelist = ((
struct free_slot *)dest)->next;
3226 asan_lock_freelist(free_page);
3230 if (src_page->slot_size > free_page->slot_size) {
3233 else if (free_page->slot_size > src_page->slot_size) {
3237 objspace->rcompactor.total_moved++;
3239 gc_move(
objspace, src, dest, src_page->slot_size, free_page->slot_size);
3241 free_page->free_slots--;
3247gc_unprotect_pages(rb_objspace_t *
objspace, rb_heap_t *heap)
3249 struct heap_page *cursor = heap->compact_cursor;
3252 unlock_page_body(
objspace, cursor->body);
3253 cursor = ccan_list_next(&heap->pages, cursor, page_node);
3257static void gc_update_references(rb_objspace_t *
objspace);
3258#if GC_CAN_COMPILE_COMPACTION
3259static void invalidate_moved_page(rb_objspace_t *
objspace,
struct heap_page *page);
3262#if defined(__MINGW32__) || defined(_WIN32)
3263# define GC_COMPACTION_SUPPORTED 1
3267# define GC_COMPACTION_SUPPORTED (GC_CAN_COMPILE_COMPACTION && HEAP_PAGE_ALLOC_USE_MMAP)
3270#if GC_CAN_COMPILE_COMPACTION
3272read_barrier_handler(uintptr_t address)
3274 rb_objspace_t *
objspace = (rb_objspace_t *)rb_gc_get_objspace();
3280 if (page_body == NULL) {
3281 rb_bug(
"read_barrier_handler: segmentation fault at %p", (
void *)address);
3284 int lev = RB_GC_VM_LOCK();
3286 unlock_page_body(
objspace, page_body);
3288 objspace->profile.read_barrier_faults++;
3290 invalidate_moved_page(
objspace, GET_HEAP_PAGE(address));
3292 RB_GC_VM_UNLOCK(lev);
3296#if !GC_CAN_COMPILE_COMPACTION
3298uninstall_handlers(
void)
3304install_handlers(
void)
3308#elif defined(_WIN32)
3309static LPTOP_LEVEL_EXCEPTION_FILTER old_handler;
3310typedef void (*signal_handler)(int);
3311static signal_handler old_sigsegv_handler;
3314read_barrier_signal(EXCEPTION_POINTERS *info)
3317 if (info->ExceptionRecord->ExceptionCode == EXCEPTION_ACCESS_VIOLATION) {
3322 read_barrier_handler((uintptr_t)info->ExceptionRecord->ExceptionInformation[1]);
3323 return EXCEPTION_CONTINUE_EXECUTION;
3326 return EXCEPTION_CONTINUE_SEARCH;
3331uninstall_handlers(
void)
3333 signal(SIGSEGV, old_sigsegv_handler);
3334 SetUnhandledExceptionFilter(old_handler);
3338install_handlers(
void)
3341 old_sigsegv_handler = signal(SIGSEGV, NULL);
3344 old_handler = SetUnhandledExceptionFilter(read_barrier_signal);
3347static struct sigaction old_sigbus_handler;
3348static struct sigaction old_sigsegv_handler;
3350#ifdef HAVE_MACH_TASK_EXCEPTION_PORTS
3351static exception_mask_t old_exception_masks[32];
3352static mach_port_t old_exception_ports[32];
3353static exception_behavior_t old_exception_behaviors[32];
3354static thread_state_flavor_t old_exception_flavors[32];
3355static mach_msg_type_number_t old_exception_count;
3358disable_mach_bad_access_exc(
void)
3360 old_exception_count =
sizeof(old_exception_masks) /
sizeof(old_exception_masks[0]);
3361 task_swap_exception_ports(
3362 mach_task_self(), EXC_MASK_BAD_ACCESS,
3363 MACH_PORT_NULL, EXCEPTION_DEFAULT, 0,
3364 old_exception_masks, &old_exception_count,
3365 old_exception_ports, old_exception_behaviors, old_exception_flavors
3370restore_mach_bad_access_exc(
void)
3372 for (mach_msg_type_number_t i = 0; i < old_exception_count; i++) {
3373 task_set_exception_ports(
3375 old_exception_masks[i], old_exception_ports[i],
3376 old_exception_behaviors[i], old_exception_flavors[i]
3383read_barrier_signal(
int sig, siginfo_t *info,
void *data)
3386 struct sigaction prev_sigbus, prev_sigsegv;
3387 sigaction(SIGBUS, &old_sigbus_handler, &prev_sigbus);
3388 sigaction(SIGSEGV, &old_sigsegv_handler, &prev_sigsegv);
3391 sigset_t set, prev_set;
3393 sigaddset(&set, SIGBUS);
3394 sigaddset(&set, SIGSEGV);
3395 sigprocmask(SIG_UNBLOCK, &set, &prev_set);
3396#ifdef HAVE_MACH_TASK_EXCEPTION_PORTS
3397 disable_mach_bad_access_exc();
3400 read_barrier_handler((uintptr_t)info->si_addr);
3403#ifdef HAVE_MACH_TASK_EXCEPTION_PORTS
3404 restore_mach_bad_access_exc();
3406 sigaction(SIGBUS, &prev_sigbus, NULL);
3407 sigaction(SIGSEGV, &prev_sigsegv, NULL);
3408 sigprocmask(SIG_SETMASK, &prev_set, NULL);
3412uninstall_handlers(
void)
3414#ifdef HAVE_MACH_TASK_EXCEPTION_PORTS
3415 restore_mach_bad_access_exc();
3417 sigaction(SIGBUS, &old_sigbus_handler, NULL);
3418 sigaction(SIGSEGV, &old_sigsegv_handler, NULL);
3422install_handlers(
void)
3424 struct sigaction action;
3425 memset(&action, 0,
sizeof(
struct sigaction));
3426 sigemptyset(&action.sa_mask);
3427 action.sa_sigaction = read_barrier_signal;
3428 action.sa_flags = SA_SIGINFO | SA_ONSTACK;
3430 sigaction(SIGBUS, &action, &old_sigbus_handler);
3431 sigaction(SIGSEGV, &action, &old_sigsegv_handler);
3432#ifdef HAVE_MACH_TASK_EXCEPTION_PORTS
3433 disable_mach_bad_access_exc();
3439gc_compact_finish(rb_objspace_t *
objspace)
3441 for (
int i = 0; i < HEAP_COUNT; i++) {
3442 rb_heap_t *heap = &heaps[i];
3443 gc_unprotect_pages(
objspace, heap);
3446 uninstall_handlers();
3451 for (
int i = 0; i < HEAP_COUNT; i++) {
3452 rb_heap_t *heap = &heaps[i];
3453 heap->compact_cursor = NULL;
3454 heap->free_pages = NULL;
3455 heap->compact_cursor_index = 0;
3460 record->moved_objects =
objspace->rcompactor.total_moved - record->moved_objects;
3462 objspace->flags.during_compacting = FALSE;
3475 struct heap_page *sweep_page = ctx->page;
3476 short slot_size = sweep_page->slot_size;
3477 short slot_bits = slot_size / BASE_SLOT_SIZE;
3478 GC_ASSERT(slot_bits > 0);
3482 GC_ASSERT(vp % BASE_SLOT_SIZE == 0);
3484 rb_asan_unpoison_object(vp,
false);
3488 gc_report(2,
objspace,
"page_sweep: free %p\n", (
void *)p);
3489#if RGENGC_CHECK_MODE
3491 if (RVALUE_OLD_P(
objspace, vp)) rb_bug(
"page_sweep: %p - old while minor GC.", (
void *)p);
3492 if (RVALUE_REMEMBERED(
objspace, vp)) rb_bug(
"page_sweep: %p - remembered.", (
void *)p);
3496 if (RVALUE_WB_UNPROTECTED(
objspace, vp)) CLEAR_IN_BITMAP(GET_HEAP_WB_UNPROTECTED_BITS(vp), vp);
3498#if RGENGC_CHECK_MODE
3499#define CHECK(x) if (x(objspace, vp) != FALSE) rb_bug("obj_free: " #x "(%s) != FALSE", rb_obj_info(vp))
3500 CHECK(RVALUE_WB_UNPROTECTED);
3501 CHECK(RVALUE_MARKED);
3502 CHECK(RVALUE_MARKING);
3503 CHECK(RVALUE_UNCOLLECTIBLE);
3509 rb_gc_obj_free_vm_weak_references(vp);
3510 if (rb_gc_obj_free(
objspace, vp)) {
3513 (void)VALGRIND_MAKE_MEM_UNDEFINED((
void*)p, BASE_SLOT_SIZE);
3514 RVALUE_AGE_SET_BITMAP(vp, 0);
3515 heap_page_add_freeobj(
objspace, sweep_page, vp);
3516 gc_report(3,
objspace,
"page_sweep: %s is added to freelist\n", rb_obj_info(vp));
3525 if (
objspace->flags.during_compacting) {
3531 rb_bug(
"T_MOVED shouldn't be seen until compaction is finished");
3533 gc_report(3,
objspace,
"page_sweep: %s is added to freelist\n", rb_obj_info(vp));
3535 RVALUE_AGE_SET_BITMAP(vp, 0);
3536 heap_page_add_freeobj(
objspace, sweep_page, vp);
3547 bitset >>= slot_bits;
3554 struct heap_page *sweep_page = ctx->page;
3555 GC_ASSERT(sweep_page->heap == heap);
3558 bits_t *bits, bitset;
3560 gc_report(2,
objspace,
"page_sweep: start.\n");
3562#if RGENGC_CHECK_MODE
3563 if (!
objspace->flags.immediate_sweep) {
3564 GC_ASSERT(sweep_page->flags.before_sweep == TRUE);
3567 sweep_page->flags.before_sweep = FALSE;
3568 sweep_page->free_slots = 0;
3570 p = (uintptr_t)sweep_page->start;
3571 bits = sweep_page->mark_bits;
3573 int page_rvalue_count = sweep_page->total_slots * (sweep_page->slot_size / BASE_SLOT_SIZE);
3574 int out_of_range_bits = (NUM_IN_PAGE(p) + page_rvalue_count) % BITS_BITLENGTH;
3575 if (out_of_range_bits != 0) {
3576 bits[BITMAP_INDEX(p) + page_rvalue_count / BITS_BITLENGTH] |= ~(((bits_t)1 << out_of_range_bits) - 1);
3582 int bitmap_plane_count = CEILDIV(NUM_IN_PAGE(p) + page_rvalue_count, BITS_BITLENGTH);
3583 GC_ASSERT(bitmap_plane_count == HEAP_PAGE_BITMAP_LIMIT - 1 ||
3584 bitmap_plane_count == HEAP_PAGE_BITMAP_LIMIT);
3586 bits_t slot_mask = heap->slot_bits_mask;
3590 bitset >>= NUM_IN_PAGE(p);
3591 bitset &= slot_mask;
3593 gc_sweep_plane(
objspace, heap, p, bitset, ctx);
3595 p += (BITS_BITLENGTH - NUM_IN_PAGE(p)) * BASE_SLOT_SIZE;
3597 for (
int i = 1; i < bitmap_plane_count; i++) {
3599 bitset &= slot_mask;
3601 gc_sweep_plane(
objspace, heap, p, bitset, ctx);
3603 p += BITS_BITLENGTH * BASE_SLOT_SIZE;
3606 if (!heap->compact_cursor) {
3607 gc_setup_mark_bits(sweep_page);
3610#if GC_PROFILE_MORE_DETAIL
3613 record->removing_objects += ctx->final_slots + ctx->freed_slots;
3614 record->empty_objects += ctx->empty_slots;
3617 if (0) fprintf(stderr,
"gc_sweep_page(%"PRIdSIZE
"): total_slots: %d, freed_slots: %d, empty_slots: %d, final_slots: %d\n",
3619 sweep_page->total_slots,
3620 ctx->freed_slots, ctx->empty_slots, ctx->final_slots);
3622 sweep_page->free_slots += ctx->freed_slots + ctx->empty_slots;
3623 sweep_page->heap->total_freed_objects += ctx->freed_slots;
3625 if (heap_pages_deferred_final && !finalizing) {
3626 gc_finalize_deferred_register(
objspace);
3629#if RGENGC_CHECK_MODE
3630 short freelist_len = 0;
3631 asan_unlock_freelist(sweep_page);
3632 struct free_slot *ptr = sweep_page->freelist;
3635 rb_asan_unpoison_object((
VALUE)ptr,
false);
3637 rb_asan_poison_object((
VALUE)ptr);
3640 asan_lock_freelist(sweep_page);
3641 if (freelist_len != sweep_page->free_slots) {
3642 rb_bug(
"inconsistent freelist length: expected %d but was %d", sweep_page->free_slots, freelist_len);
3646 gc_report(2,
objspace,
"page_sweep: end.\n");
3650gc_mode_name(
enum gc_mode mode)
3653 case gc_mode_none:
return "none";
3654 case gc_mode_marking:
return "marking";
3655 case gc_mode_sweeping:
return "sweeping";
3656 case gc_mode_compacting:
return "compacting";
3657 default: rb_bug(
"gc_mode_name: unknown mode: %d", (
int)mode);
3662gc_mode_transition(rb_objspace_t *
objspace,
enum gc_mode mode)
3664#if RGENGC_CHECK_MODE
3665 enum gc_mode prev_mode = gc_mode(
objspace);
3666 switch (prev_mode) {
3667 case gc_mode_none: GC_ASSERT(mode == gc_mode_marking);
break;
3668 case gc_mode_marking: GC_ASSERT(mode == gc_mode_sweeping);
break;
3669 case gc_mode_sweeping: GC_ASSERT(mode == gc_mode_none || mode == gc_mode_compacting);
break;
3670 case gc_mode_compacting: GC_ASSERT(mode == gc_mode_none);
break;
3673 if (0) fprintf(stderr,
"gc_mode_transition: %s->%s\n", gc_mode_name(gc_mode(
objspace)), gc_mode_name(mode));
3681 asan_unlock_freelist(page);
3682 if (page->freelist) {
3684 rb_asan_unpoison_object((
VALUE)p,
false);
3688 rb_asan_poison_object((
VALUE)prev);
3689 rb_asan_unpoison_object((
VALUE)p,
false);
3692 rb_asan_poison_object((
VALUE)p);
3695 page->freelist = freelist;
3697 asan_lock_freelist(page);
3702gc_sweep_start_heap(rb_objspace_t *
objspace, rb_heap_t *heap)
3704 heap->sweeping_page = ccan_list_top(&heap->pages,
struct heap_page, page_node);
3705 heap->free_pages = NULL;
3706 heap->pooled_pages = NULL;
3707 if (!
objspace->flags.immediate_sweep) {
3710 ccan_list_for_each(&heap->pages, page, page_node) {
3711 page->flags.before_sweep = TRUE;
3716#if defined(__GNUC__) && __GNUC__ == 4 && __GNUC_MINOR__ == 4
3720#if GC_CAN_COMPILE_COMPACTION
3721static void gc_sort_heap_by_compare_func(rb_objspace_t *
objspace, gc_compact_compare_func compare_func);
3722static int compare_pinned_slots(
const void *left,
const void *right,
void *d);
3726gc_ractor_newobj_cache_clear(
void *c,
void *data)
3728 rb_objspace_t *
objspace = rb_gc_get_objspace();
3729 rb_ractor_newobj_cache_t *newobj_cache = c;
3731 newobj_cache->incremental_mark_step_allocated_slots = 0;
3733 for (
size_t heap_idx = 0; heap_idx < HEAP_COUNT; heap_idx++) {
3735 rb_ractor_newobj_heap_cache_t *cache = &newobj_cache->heap_caches[heap_idx];
3737 rb_heap_t *heap = &heaps[heap_idx];
3739 cache->allocated_objects_count = 0;
3741 struct heap_page *page = cache->using_page;
3742 struct free_slot *freelist = cache->freelist;
3743 RUBY_DEBUG_LOG(
"ractor using_page:%p freelist:%p", (
void *)page, (
void *)freelist);
3745 heap_page_freelist_append(page, freelist);
3747 cache->using_page = NULL;
3748 cache->freelist = NULL;
3753gc_sweep_start(rb_objspace_t *
objspace)
3755 gc_mode_transition(
objspace, gc_mode_sweeping);
3758#if GC_CAN_COMPILE_COMPACTION
3759 if (
objspace->flags.during_compacting) {
3760 gc_sort_heap_by_compare_func(
3762 objspace->rcompactor.compare_func ?
objspace->rcompactor.compare_func : compare_pinned_slots
3767 for (
int i = 0; i < HEAP_COUNT; i++) {
3768 rb_heap_t *heap = &heaps[i];
3769 gc_sweep_start_heap(
objspace, heap);
3772 if (heap->sweeping_page == NULL) {
3773 GC_ASSERT(heap->total_pages == 0);
3774 GC_ASSERT(heap->total_slots == 0);
3775 gc_sweep_finish_heap(
objspace, heap);
3779 rb_gc_ractor_newobj_cache_foreach(gc_ractor_newobj_cache_clear, NULL);
3783gc_sweep_finish_heap(rb_objspace_t *
objspace, rb_heap_t *heap)
3785 size_t total_slots = heap->total_slots;
3786 size_t swept_slots = heap->freed_slots + heap->empty_slots;
3788 size_t init_slots = gc_params.heap_init_slots[heap - heaps];
3789 size_t min_free_slots = (size_t)(MAX(total_slots, init_slots) * gc_params.heap_free_slots_min_ratio);
3791 if (swept_slots < min_free_slots &&
3793 ((heap->empty_slots == 0 && total_slots > 0) || heap->freed_slots > heap->empty_slots)) {
3799 while (swept_slots < min_free_slots &&
3800 (resurrected_page = heap_page_resurrect(
objspace))) {
3801 heap_add_page(
objspace, heap, resurrected_page);
3802 heap_add_freepage(heap, resurrected_page);
3804 swept_slots += resurrected_page->free_slots;
3807 if (swept_slots < min_free_slots) {
3811 objspace->profile.count -
objspace->rgengc.last_major_gc < RVALUE_OLD_AGE) {
3812 if (
objspace->heap_pages.allocatable_slots < min_free_slots) {
3813 heap_allocatable_slots_expand(
objspace, heap, swept_slots, heap->total_slots);
3816 else if (
objspace->heap_pages.allocatable_slots < (min_free_slots - swept_slots)) {
3817 gc_needs_major_flags |= GPR_FLAG_MAJOR_BY_NOFREE;
3818 heap->force_major_gc_count++;
3825gc_sweep_finish(rb_objspace_t *
objspace)
3827 gc_report(1,
objspace,
"gc_sweep_finish\n");
3830 heap_pages_free_unused_pages(
objspace);
3832 for (
int i = 0; i < HEAP_COUNT; i++) {
3833 rb_heap_t *heap = &heaps[i];
3835 heap->freed_slots = 0;
3836 heap->empty_slots = 0;
3838 if (!will_be_incremental_marking(
objspace)) {
3839 struct heap_page *end_page = heap->free_pages;
3841 while (end_page->free_next) end_page = end_page->free_next;
3842 end_page->free_next = heap->pooled_pages;
3845 heap->free_pages = heap->pooled_pages;
3847 heap->pooled_pages = NULL;
3853 gc_mode_transition(
objspace, gc_mode_none);
3855#if RGENGC_CHECK_MODE >= 2
3856 gc_verify_internal_consistency(
objspace);
3861gc_sweep_step(rb_objspace_t *
objspace, rb_heap_t *heap)
3863 struct heap_page *sweep_page = heap->sweeping_page;
3864 int swept_slots = 0;
3865 int pooled_slots = 0;
3867 if (sweep_page == NULL)
return FALSE;
3869#if GC_ENABLE_LAZY_SWEEP
3870 gc_prof_sweep_timer_start(
objspace);
3874 RUBY_DEBUG_LOG(
"sweep_page:%p", (
void *)sweep_page);
3882 gc_sweep_page(
objspace, heap, &ctx);
3883 int free_slots = ctx.freed_slots + ctx.empty_slots;
3885 heap->sweeping_page = ccan_list_next(&heap->pages, sweep_page, page_node);
3887 if (free_slots == sweep_page->total_slots) {
3889 heap_unlink_page(
objspace, heap, sweep_page);
3891 sweep_page->start = 0;
3892 sweep_page->total_slots = 0;
3893 sweep_page->slot_size = 0;
3894 sweep_page->heap = NULL;
3895 sweep_page->free_slots = 0;
3897 asan_unlock_freelist(sweep_page);
3898 sweep_page->freelist = NULL;
3899 asan_lock_freelist(sweep_page);
3901 asan_poison_memory_region(sweep_page->body, HEAP_PAGE_SIZE);
3904 sweep_page->free_next =
objspace->empty_pages;
3905 objspace->empty_pages = sweep_page;
3907 else if (free_slots > 0) {
3908 heap->freed_slots += ctx.freed_slots;
3909 heap->empty_slots += ctx.empty_slots;
3911 if (pooled_slots < GC_INCREMENTAL_SWEEP_POOL_SLOT_COUNT) {
3912 heap_add_poolpage(
objspace, heap, sweep_page);
3913 pooled_slots += free_slots;
3916 heap_add_freepage(heap, sweep_page);
3917 swept_slots += free_slots;
3918 if (swept_slots > GC_INCREMENTAL_SWEEP_SLOT_COUNT) {
3924 sweep_page->free_next = NULL;
3926 }
while ((sweep_page = heap->sweeping_page));
3928 if (!heap->sweeping_page) {
3929 gc_sweep_finish_heap(
objspace, heap);
3931 if (!has_sweeping_pages(
objspace)) {
3936#if GC_ENABLE_LAZY_SWEEP
3937 gc_prof_sweep_timer_stop(
objspace);
3940 return heap->free_pages != NULL;
3944gc_sweep_rest(rb_objspace_t *
objspace)
3946 for (
int i = 0; i < HEAP_COUNT; i++) {
3947 rb_heap_t *heap = &heaps[i];
3949 while (heap->sweeping_page) {
3956gc_sweep_continue(rb_objspace_t *
objspace, rb_heap_t *sweep_heap)
3958 GC_ASSERT(dont_gc_val() == FALSE ||
objspace->profile.latest_gc_info & GPR_FLAG_METHOD);
3959 if (!GC_ENABLE_LAZY_SWEEP)
return;
3963 for (
int i = 0; i < HEAP_COUNT; i++) {
3964 rb_heap_t *heap = &heaps[i];
3965 if (gc_sweep_step(
objspace, heap)) {
3966 GC_ASSERT(heap->free_pages != NULL);
3968 else if (heap == sweep_heap) {
3969 if (
objspace->empty_pages_count > 0 ||
objspace->heap_pages.allocatable_slots > 0) {
3980 heap_page_allocate_and_initialize(
objspace, heap);
3982 GC_ASSERT(heap->free_pages != NULL);
3987 GC_ASSERT(gc_mode(
objspace) == gc_mode_none);
3997rb_gc_impl_location(
void *objspace_ptr,
VALUE value)
4001 asan_unpoisoning_object(value) {
4003 destination = (
VALUE)RMOVED(value)->destination;
4007 destination = value;
4014#if GC_CAN_COMPILE_COMPACTION
4016invalidate_moved_plane(rb_objspace_t *
objspace,
struct heap_page *page, uintptr_t p, bits_t bitset)
4025 GC_ASSERT(RVALUE_PINNED(
objspace, forwarding_object));
4026 GC_ASSERT(!RVALUE_MARKED(
objspace, forwarding_object));
4028 CLEAR_IN_BITMAP(GET_HEAP_PINNED_BITS(forwarding_object), forwarding_object);
4030 object = rb_gc_impl_location(
objspace, forwarding_object);
4032 uint32_t original_shape_id = 0;
4034 original_shape_id = RMOVED(forwarding_object)->original_shape_id;
4037 gc_move(
objspace,
object, forwarding_object, GET_HEAP_PAGE(
object)->slot_size, page->slot_size);
4041 if (original_shape_id) {
4042 rb_gc_set_shape(forwarding_object, original_shape_id);
4045 struct heap_page *orig_page = GET_HEAP_PAGE(
object);
4046 orig_page->free_slots++;
4047 RVALUE_AGE_SET_BITMAP(
object, 0);
4048 heap_page_add_freeobj(
objspace, orig_page,
object);
4050 GC_ASSERT(RVALUE_MARKED(
objspace, forwarding_object));
4055 p += BASE_SLOT_SIZE;
4065 bits_t *mark_bits, *pin_bits;
4068 mark_bits = page->mark_bits;
4069 pin_bits = page->pinned_bits;
4071 uintptr_t p = page->start;
4074 bitset = pin_bits[0] & ~mark_bits[0];
4075 bitset >>= NUM_IN_PAGE(p);
4076 invalidate_moved_plane(
objspace, page, p, bitset);
4077 p += (BITS_BITLENGTH - NUM_IN_PAGE(p)) * BASE_SLOT_SIZE;
4079 for (i=1; i < HEAP_PAGE_BITMAP_LIMIT; i++) {
4082 bitset = pin_bits[i] & ~mark_bits[i];
4084 invalidate_moved_plane(
objspace, page, p, bitset);
4085 p += BITS_BITLENGTH * BASE_SLOT_SIZE;
4091gc_compact_start(rb_objspace_t *
objspace)
4094 gc_mode_transition(
objspace, gc_mode_compacting);
4096 for (
int i = 0; i < HEAP_COUNT; i++) {
4097 rb_heap_t *heap = &heaps[i];
4098 ccan_list_for_each(&heap->pages, page, page_node) {
4099 page->flags.before_sweep = TRUE;
4102 heap->compact_cursor = ccan_list_tail(&heap->pages,
struct heap_page, page_node);
4103 heap->compact_cursor_index = 0;
4108 record->moved_objects =
objspace->rcompactor.total_moved;
4111 memset(
objspace->rcompactor.considered_count_table, 0,
T_MASK *
sizeof(
size_t));
4112 memset(
objspace->rcompactor.moved_count_table, 0,
T_MASK *
sizeof(
size_t));
4113 memset(
objspace->rcompactor.moved_up_count_table, 0,
T_MASK *
sizeof(
size_t));
4114 memset(
objspace->rcompactor.moved_down_count_table, 0,
T_MASK *
sizeof(
size_t));
4120static void gc_sweep_compact(rb_objspace_t *
objspace);
4127 const unsigned int immediate_sweep =
objspace->flags.immediate_sweep;
4129 gc_report(1,
objspace,
"gc_sweep: immediate: %d\n", immediate_sweep);
4132 if (
objspace->flags.during_compacting) {
4136 if (immediate_sweep) {
4137#if !GC_ENABLE_LAZY_SWEEP
4138 gc_prof_sweep_timer_start(
objspace);
4141#if !GC_ENABLE_LAZY_SWEEP
4142 gc_prof_sweep_timer_stop(
objspace);
4148 for (
int i = 0; i < HEAP_COUNT; i++) {
4149 rb_heap_t *heap = &heaps[i];
4159static stack_chunk_t *
4160stack_chunk_alloc(
void)
4164 res = malloc(
sizeof(stack_chunk_t));
4172is_mark_stack_empty(mark_stack_t *stack)
4174 return stack->chunk == NULL;
4178mark_stack_size(mark_stack_t *stack)
4180 size_t size = stack->index;
4181 stack_chunk_t *chunk = stack->chunk ? stack->chunk->next : NULL;
4184 size += stack->limit;
4185 chunk = chunk->next;
4191add_stack_chunk_cache(mark_stack_t *stack, stack_chunk_t *chunk)
4193 chunk->next = stack->cache;
4194 stack->cache = chunk;
4195 stack->cache_size++;
4199shrink_stack_chunk_cache(mark_stack_t *stack)
4201 stack_chunk_t *chunk;
4203 if (stack->unused_cache_size > (stack->cache_size/2)) {
4204 chunk = stack->cache;
4205 stack->cache = stack->cache->next;
4206 stack->cache_size--;
4209 stack->unused_cache_size = stack->cache_size;
4213push_mark_stack_chunk(mark_stack_t *stack)
4215 stack_chunk_t *next;
4217 GC_ASSERT(stack->index == stack->limit);
4219 if (stack->cache_size > 0) {
4220 next = stack->cache;
4221 stack->cache = stack->cache->next;
4222 stack->cache_size--;
4223 if (stack->unused_cache_size > stack->cache_size)
4224 stack->unused_cache_size = stack->cache_size;
4227 next = stack_chunk_alloc();
4229 next->next = stack->chunk;
4230 stack->chunk = next;
4235pop_mark_stack_chunk(mark_stack_t *stack)
4237 stack_chunk_t *prev;
4239 prev = stack->chunk->next;
4240 GC_ASSERT(stack->index == 0);
4241 add_stack_chunk_cache(stack, stack->chunk);
4242 stack->chunk = prev;
4243 stack->index = stack->limit;
4247mark_stack_chunk_list_free(stack_chunk_t *chunk)
4249 stack_chunk_t *next = NULL;
4251 while (chunk != NULL) {
4259free_stack_chunks(mark_stack_t *stack)
4261 mark_stack_chunk_list_free(stack->chunk);
4265mark_stack_free_cache(mark_stack_t *stack)
4267 mark_stack_chunk_list_free(stack->cache);
4268 stack->cache_size = 0;
4269 stack->unused_cache_size = 0;
4273push_mark_stack(mark_stack_t *stack,
VALUE obj)
4296 if (stack->index == stack->limit) {
4297 push_mark_stack_chunk(stack);
4299 stack->chunk->data[stack->index++] = obj;
4309 rb_bug(
"push_mark_stack() called for broken object");
4313 rb_bug(
"push_mark_stack: unexpected T_NODE object");
4317 rb_bug(
"rb_gc_mark(): unknown data type 0x%x(%p) %s",
4319 is_pointer_to_heap((rb_objspace_t *)rb_gc_get_objspace(), (
void *)obj) ?
"corrupted object" :
"non object");
4323pop_mark_stack(mark_stack_t *stack,
VALUE *data)
4325 if (is_mark_stack_empty(stack)) {
4328 if (stack->index == 1) {
4329 *data = stack->chunk->data[--stack->index];
4330 pop_mark_stack_chunk(stack);
4333 *data = stack->chunk->data[--stack->index];
4339init_mark_stack(mark_stack_t *stack)
4343 MEMZERO(stack, mark_stack_t, 1);
4344 stack->index = stack->limit = STACK_CHUNK_SIZE;
4346 for (i=0; i < 4; i++) {
4347 add_stack_chunk_cache(stack, stack_chunk_alloc());
4349 stack->unused_cache_size = stack->cache_size;
4357 if (
objspace->rgengc.parent_object_old_p) {
4358 if (RVALUE_WB_UNPROTECTED(
objspace, obj) || !RVALUE_OLD_P(
objspace, obj)) {
4367 if (RVALUE_MARKED(
objspace, obj))
return 0;
4368 MARK_IN_BITMAP(GET_HEAP_MARK_BITS(obj), obj);
4382 if(!gc_config_full_mark_val)
4385 struct heap_page *page = GET_HEAP_PAGE(obj);
4387 GC_ASSERT(RVALUE_MARKING(
objspace, obj) == FALSE);
4388 check_rvalue_consistency(
objspace, obj);
4390 if (!RVALUE_PAGE_WB_UNPROTECTED(page, obj)) {
4391 if (!RVALUE_OLD_P(
objspace, obj)) {
4392 gc_report(3,
objspace,
"gc_aging: YOUNG: %s\n", rb_obj_info(obj));
4395 else if (is_full_marking(
objspace)) {
4396 GC_ASSERT(RVALUE_PAGE_UNCOLLECTIBLE(page, obj) == FALSE);
4397 RVALUE_PAGE_OLD_UNCOLLECTIBLE_SET(
objspace, page, obj);
4400 check_rvalue_consistency(
objspace, obj);
4408#if RGENGC_CHECK_MODE
4409 if (RVALUE_MARKED(
objspace, obj) == FALSE) rb_bug(
"gc_grey: %s is not marked.", rb_obj_info(obj));
4410 if (RVALUE_MARKING(
objspace, obj) == TRUE) rb_bug(
"gc_grey: %s is marking/remembered.", rb_obj_info(obj));
4413 if (is_incremental_marking(
objspace)) {
4414 MARK_IN_BITMAP(GET_HEAP_MARKING_BITS(obj), obj);
4417 push_mark_stack(&
objspace->mark_stack, obj);
4424 enum {info_size = 256};
4425 char obj_info_buf[info_size];
4426 rb_raw_obj_info(obj_info_buf, info_size, obj);
4428 char parent_obj_info_buf[info_size];
4429 rb_raw_obj_info(parent_obj_info_buf, info_size,
objspace->rgengc.parent_object);
4431 rb_bug(
"try to mark T_NONE object (obj: %s, parent: %s)", obj_info_buf, parent_obj_info_buf);
4438 GC_ASSERT(during_gc);
4439 GC_ASSERT(!
objspace->flags.during_reference_updating);
4441 rgengc_check_relation(
objspace, obj);
4442 if (!gc_mark_set(
objspace, obj))
return;
4445 RUBY_DEBUG_LOG(
"%p (%s) parent:%p (%s)",
4446 (
void *)obj, obj_type_name(obj),
4447 (
void *)
objspace->rgengc.parent_object, obj_type_name(
objspace->rgengc.parent_object));
4450 gc_mark_check_t_none(
objspace, obj);
4460 if (RB_UNLIKELY(
objspace->flags.during_compacting)) {
4461 if (RB_LIKELY(during_gc)) {
4462 if (!RVALUE_PINNED(
objspace, obj)) {
4463 GC_ASSERT(GET_HEAP_PAGE(obj)->pinned_slots <= GET_HEAP_PAGE(obj)->total_slots);
4464 GET_HEAP_PAGE(obj)->pinned_slots++;
4465 MARK_IN_BITMAP(GET_HEAP_PINNED_BITS(obj), obj);
4479rb_gc_impl_mark_and_move(
void *objspace_ptr,
VALUE *ptr)
4481 rb_objspace_t *
objspace = objspace_ptr;
4483 if (RB_UNLIKELY(
objspace->flags.during_reference_updating)) {
4484 GC_ASSERT(
objspace->flags.during_compacting);
4485 GC_ASSERT(during_gc);
4488 if (destination != *ptr) {
4498rb_gc_impl_mark(
void *objspace_ptr,
VALUE obj)
4500 rb_objspace_t *
objspace = objspace_ptr;
4506rb_gc_impl_mark_and_pin(
void *objspace_ptr,
VALUE obj)
4508 rb_objspace_t *
objspace = objspace_ptr;
4514rb_gc_impl_mark_maybe(
void *objspace_ptr,
VALUE obj)
4516 rb_objspace_t *
objspace = objspace_ptr;
4518 (void)VALGRIND_MAKE_MEM_DEFINED(&obj,
sizeof(obj));
4520 if (is_pointer_to_heap(
objspace, (
void *)obj)) {
4521 asan_unpoisoning_object(obj) {
4536rb_gc_impl_mark_weak(
void *objspace_ptr,
VALUE *ptr)
4538 rb_objspace_t *
objspace = objspace_ptr;
4542 gc_mark_check_t_none(
objspace, obj);
4548 GC_ASSERT(RVALUE_MARKED(
objspace, obj));
4549 GC_ASSERT(!
objspace->flags.during_compacting);
4554 rgengc_check_relation(
objspace, obj);
4556 rb_darray_append_without_gc(&
objspace->weak_references, ptr);
4558 objspace->profile.weak_references_count++;
4562rb_gc_impl_remove_weak(
void *objspace_ptr,
VALUE parent_obj,
VALUE *ptr)
4564 rb_objspace_t *
objspace = objspace_ptr;
4568 if (!is_incremental_marking(
objspace))
return;
4571 if (!RVALUE_MARKED(
objspace, parent_obj))
return;
4574 rb_darray_foreach(
objspace->weak_references, i, ptr_ptr) {
4575 if (*ptr_ptr == ptr) {
4583pin_value(st_data_t key, st_data_t value, st_data_t data)
4585 rb_gc_impl_mark_and_pin((
void *)data, (
VALUE)value);
4591gc_mark_set_parent_raw(rb_objspace_t *
objspace,
VALUE obj,
bool old_p)
4593 asan_unpoison_memory_region(&
objspace->rgengc.parent_object,
sizeof(
objspace->rgengc.parent_object),
false);
4594 asan_unpoison_memory_region(&
objspace->rgengc.parent_object_old_p,
sizeof(
objspace->rgengc.parent_object_old_p),
false);
4595 objspace->rgengc.parent_object = obj;
4596 objspace->rgengc.parent_object_old_p = old_p;
4606gc_mark_set_parent_invalid(rb_objspace_t *
objspace)
4608 asan_poison_memory_region(&
objspace->rgengc.parent_object,
sizeof(
objspace->rgengc.parent_object));
4609 asan_poison_memory_region(&
objspace->rgengc.parent_object_old_p,
sizeof(
objspace->rgengc.parent_object_old_p));
4613mark_roots(rb_objspace_t *
objspace,
const char **categoryp)
4615#define MARK_CHECKPOINT(category) do { \
4616 if (categoryp) *categoryp = category; \
4619 MARK_CHECKPOINT(
"objspace");
4622 if (finalizer_table != NULL) {
4626 if (stress_to_class) rb_gc_mark(stress_to_class);
4628 rb_gc_save_machine_context();
4629 rb_gc_mark_roots(
objspace, categoryp);
4630 gc_mark_set_parent_invalid(
objspace);
4637 rb_gc_mark_children(
objspace, obj);
4638 gc_mark_set_parent_invalid(
objspace);
4646gc_mark_stacked_objects(rb_objspace_t *
objspace,
int incremental,
size_t count)
4648 mark_stack_t *mstack = &
objspace->mark_stack;
4650 size_t marked_slots_at_the_beginning =
objspace->marked_slots;
4651 size_t popped_count = 0;
4653 while (pop_mark_stack(mstack, &obj)) {
4654 if (obj ==
Qundef)
continue;
4656 if (RGENGC_CHECK_MODE && !RVALUE_MARKED(
objspace, obj)) {
4657 rb_bug(
"gc_mark_stacked_objects: %s is not marked.", rb_obj_info(obj));
4662 if (RGENGC_CHECK_MODE && !RVALUE_MARKING(
objspace, obj)) {
4663 rb_bug(
"gc_mark_stacked_objects: incremental, but marking bit is 0");
4665 CLEAR_IN_BITMAP(GET_HEAP_MARKING_BITS(obj), obj);
4668 if (popped_count + (
objspace->marked_slots - marked_slots_at_the_beginning) > count) {
4677 if (RGENGC_CHECK_MODE >= 3) gc_verify_internal_consistency(
objspace);
4679 if (is_mark_stack_empty(mstack)) {
4680 shrink_stack_chunk_cache(mstack);
4689gc_mark_stacked_objects_incremental(rb_objspace_t *
objspace,
size_t count)
4691 return gc_mark_stacked_objects(
objspace, TRUE, count);
4695gc_mark_stacked_objects_all(rb_objspace_t *
objspace)
4697 return gc_mark_stacked_objects(
objspace, FALSE, 0);
4700#if RGENGC_CHECK_MODE >= 4
4702#define MAKE_ROOTSIG(obj) (((VALUE)(obj) << 1) | 0x01)
4703#define IS_ROOTSIG(obj) ((VALUE)(obj) & 0x01)
4704#define GET_ROOTSIG(obj) ((const char *)((VALUE)(obj) >> 1))
4712static struct reflist *
4713reflist_create(
VALUE obj)
4715 struct reflist *refs =
xmalloc(
sizeof(
struct reflist));
4718 refs->list[0] = obj;
4724reflist_destruct(
struct reflist *refs)
4731reflist_add(
struct reflist *refs,
VALUE obj)
4733 if (refs->pos == refs->size) {
4735 SIZED_REALLOC_N(refs->list,
VALUE, refs->size, refs->size/2);
4738 refs->list[refs->pos++] = obj;
4742reflist_dump(
struct reflist *refs)
4745 for (i=0; i<refs->pos; i++) {
4746 VALUE obj = refs->list[i];
4747 if (IS_ROOTSIG(obj)) {
4748 fprintf(stderr,
"<root@%s>", GET_ROOTSIG(obj));
4751 fprintf(stderr,
"<%s>", rb_obj_info(obj));
4753 if (i+1 < refs->pos) fprintf(stderr,
", ");
4758reflist_referred_from_machine_context(
struct reflist *refs)
4761 for (i=0; i<refs->pos; i++) {
4762 VALUE obj = refs->list[i];
4763 if (IS_ROOTSIG(obj) && strcmp(GET_ROOTSIG(obj),
"machine_context") == 0)
return 1;
4769 rb_objspace_t *objspace;
4777 struct st_table *references;
4778 const char *category;
4780 mark_stack_t mark_stack;
4784allrefs_add(
struct allrefs *data,
VALUE obj)
4786 struct reflist *refs;
4789 if (st_lookup(data->references, obj, &r)) {
4790 refs = (
struct reflist *)r;
4791 reflist_add(refs, data->root_obj);
4795 refs = reflist_create(data->root_obj);
4796 st_insert(data->references, obj, (st_data_t)refs);
4802allrefs_i(
VALUE obj,
void *ptr)
4804 struct allrefs *data = (
struct allrefs *)ptr;
4806 if (allrefs_add(data, obj)) {
4807 push_mark_stack(&data->mark_stack, obj);
4812allrefs_roots_i(
VALUE obj,
void *ptr)
4814 struct allrefs *data = (
struct allrefs *)ptr;
4815 if (strlen(data->category) == 0) rb_bug(
"!!!");
4816 data->root_obj = MAKE_ROOTSIG(data->category);
4818 if (allrefs_add(data, obj)) {
4819 push_mark_stack(&data->mark_stack, obj);
4822#define PUSH_MARK_FUNC_DATA(v) do { \
4823 struct gc_mark_func_data_struct *prev_mark_func_data = GET_VM()->gc.mark_func_data; \
4824 GET_VM()->gc.mark_func_data = (v);
4826#define POP_MARK_FUNC_DATA() GET_VM()->gc.mark_func_data = prev_mark_func_data;} while (0)
4829objspace_allrefs(rb_objspace_t *
objspace)
4831 struct allrefs data;
4832 struct gc_mark_func_data_struct mfd;
4834 int prev_dont_gc = dont_gc_val();
4838 data.references = st_init_numtable();
4839 init_mark_stack(&data.mark_stack);
4841 mfd.mark_func = allrefs_roots_i;
4845 PUSH_MARK_FUNC_DATA(&mfd);
4846 GET_VM()->gc.mark_func_data = &mfd;
4847 mark_roots(
objspace, &data.category);
4848 POP_MARK_FUNC_DATA();
4851 while (pop_mark_stack(&data.mark_stack, &obj)) {
4852 rb_objspace_reachable_objects_from(data.root_obj = obj, allrefs_i, &data);
4854 free_stack_chunks(&data.mark_stack);
4856 dont_gc_set(prev_dont_gc);
4857 return data.references;
4861objspace_allrefs_destruct_i(st_data_t key, st_data_t value, st_data_t ptr)
4863 struct reflist *refs = (
struct reflist *)value;
4864 reflist_destruct(refs);
4869objspace_allrefs_destruct(
struct st_table *refs)
4871 st_foreach(refs, objspace_allrefs_destruct_i, 0);
4872 st_free_table(refs);
4875#if RGENGC_CHECK_MODE >= 5
4877allrefs_dump_i(st_data_t k, st_data_t v, st_data_t ptr)
4880 struct reflist *refs = (
struct reflist *)v;
4881 fprintf(stderr,
"[allrefs_dump_i] %s <- ", rb_obj_info(obj));
4883 fprintf(stderr,
"\n");
4888allrefs_dump(rb_objspace_t *
objspace)
4891 fprintf(stderr,
"[all refs] (size: %"PRIuVALUE
")\n", size);
4897gc_check_after_marks_i(st_data_t k, st_data_t v, st_data_t ptr)
4900 struct reflist *refs = (
struct reflist *)v;
4901 rb_objspace_t *
objspace = (rb_objspace_t *)ptr;
4904 if (!RVALUE_MARKED(
objspace, obj)) {
4905 fprintf(stderr,
"gc_check_after_marks_i: %s is not marked and not oldgen.\n", rb_obj_info(obj));
4906 fprintf(stderr,
"gc_check_after_marks_i: %p is referred from ", (
void *)obj);
4909 if (reflist_referred_from_machine_context(refs)) {
4910 fprintf(stderr,
" (marked from machine stack).\n");
4915 fprintf(stderr,
"\n");
4922gc_marks_check(rb_objspace_t *
objspace, st_foreach_callback_func *checker_func,
const char *checker_name)
4924 size_t saved_malloc_increase =
objspace->malloc_params.increase;
4925#if RGENGC_ESTIMATE_OLDMALLOC
4926 size_t saved_oldmalloc_increase =
objspace->malloc_counters.oldmalloc_increase;
4936 if (
objspace->rgengc.error_count > 0) {
4937#if RGENGC_CHECK_MODE >= 5
4940 if (checker_name) rb_bug(
"%s: GC has problem.", checker_name);
4943 objspace_allrefs_destruct(
objspace->rgengc.allrefs_table);
4944 objspace->rgengc.allrefs_table = 0;
4947 objspace->malloc_params.increase = saved_malloc_increase;
4948#if RGENGC_ESTIMATE_OLDMALLOC
4949 objspace->malloc_counters.oldmalloc_increase = saved_oldmalloc_increase;
4955 rb_objspace_t *objspace;
4957 size_t live_object_count;
4958 size_t zombie_object_count;
4961 size_t old_object_count;
4962 size_t remembered_shady_count;
4966check_generation_i(
const VALUE child,
void *ptr)
4969 const VALUE parent = data->parent;
4971 if (RGENGC_CHECK_MODE) GC_ASSERT(RVALUE_OLD_P(data->objspace, parent));
4973 if (!RVALUE_OLD_P(data->objspace, child)) {
4974 if (!RVALUE_REMEMBERED(data->objspace, parent) &&
4975 !RVALUE_REMEMBERED(data->objspace, child) &&
4976 !RVALUE_UNCOLLECTIBLE(data->objspace, child)) {
4977 fprintf(stderr,
"verify_internal_consistency_reachable_i: WB miss (O->Y) %s -> %s\n", rb_obj_info(parent), rb_obj_info(child));
4984check_color_i(
const VALUE child,
void *ptr)
4987 const VALUE parent = data->parent;
4989 if (!RVALUE_WB_UNPROTECTED(data->objspace, parent) && RVALUE_WHITE_P(data->objspace, child)) {
4990 fprintf(stderr,
"verify_internal_consistency_reachable_i: WB miss (B->W) - %s -> %s\n",
4991 rb_obj_info(parent), rb_obj_info(child));
4997check_children_i(
const VALUE child,
void *ptr)
5000 if (check_rvalue_consistency_force(data->objspace, child, FALSE) != 0) {
5001 fprintf(stderr,
"check_children_i: %s has error (referenced from %s)",
5002 rb_obj_info(child), rb_obj_info(data->parent));
5009verify_internal_consistency_i(
void *page_start,
void *page_end,
size_t stride,
5013 rb_objspace_t *
objspace = data->objspace;
5015 for (obj = (
VALUE)page_start; obj != (
VALUE)page_end; obj += stride) {
5016 asan_unpoisoning_object(obj) {
5017 if (!rb_gc_impl_garbage_object_p(
objspace, obj)) {
5019 data->live_object_count++;
5024 if (!gc_object_moved_p(
objspace, obj)) {
5026 rb_objspace_reachable_objects_from(obj, check_children_i, (
void *)data);
5030 if (RVALUE_OLD_P(
objspace, obj)) data->old_object_count++;
5031 if (RVALUE_WB_UNPROTECTED(
objspace, obj) && RVALUE_UNCOLLECTIBLE(
objspace, obj)) data->remembered_shady_count++;
5036 rb_objspace_reachable_objects_from(obj, check_generation_i, (
void *)data);
5039 if (!is_marking(
objspace) && rb_gc_obj_shareable_p(obj)) {
5040 rb_gc_verify_shareable(obj);
5043 if (is_incremental_marking(
objspace)) {
5044 if (RVALUE_BLACK_P(
objspace, obj)) {
5047 rb_objspace_reachable_objects_from(obj, check_color_i, (
void *)data);
5053 data->zombie_object_count++;
5056 fprintf(stderr,
"verify_internal_consistency_i: T_ZOMBIE has extra flags set: %s\n",
5062 fprintf(stderr,
"verify_internal_consistency_i: FL_FINALIZE %s but %s finalizer_table: %s\n",
5063 FL_TEST(obj,
FL_FINALIZE) ?
"set" :
"not set", st_is_member(finalizer_table, obj) ?
"in" :
"not in",
5078 unsigned int has_remembered_shady = FALSE;
5079 unsigned int has_remembered_old = FALSE;
5080 int remembered_old_objects = 0;
5081 int free_objects = 0;
5082 int zombie_objects = 0;
5084 short slot_size = page->slot_size;
5085 uintptr_t start = (uintptr_t)page->start;
5086 uintptr_t end = start + page->total_slots * slot_size;
5088 for (uintptr_t ptr = start; ptr < end; ptr += slot_size) {
5090 asan_unpoisoning_object(val) {
5095 if (RVALUE_PAGE_UNCOLLECTIBLE(page, val) && RVALUE_PAGE_WB_UNPROTECTED(page, val)) {
5096 has_remembered_shady = TRUE;
5098 if (RVALUE_PAGE_MARKING(page, val)) {
5099 has_remembered_old = TRUE;
5100 remembered_old_objects++;
5105 if (!is_incremental_marking(
objspace) &&
5106 page->flags.has_remembered_objects == FALSE && has_remembered_old == TRUE) {
5108 for (uintptr_t ptr = start; ptr < end; ptr += slot_size) {
5110 if (RVALUE_PAGE_MARKING(page, val)) {
5111 fprintf(stderr,
"marking -> %s\n", rb_obj_info(val));
5114 rb_bug(
"page %p's has_remembered_objects should be false, but there are remembered old objects (%d). %s",
5115 (
void *)page, remembered_old_objects, obj ? rb_obj_info(obj) :
"");
5118 if (page->flags.has_uncollectible_wb_unprotected_objects == FALSE && has_remembered_shady == TRUE) {
5119 rb_bug(
"page %p's has_remembered_shady should be false, but there are remembered shady objects. %s",
5120 (
void *)page, obj ? rb_obj_info(obj) :
"");
5125 if (page->free_slots != free_objects) {
5126 rb_bug(
"page %p's free_slots should be %d, but %d", (
void *)page, page->free_slots, free_objects);
5129 if (page->final_slots != zombie_objects) {
5130 rb_bug(
"page %p's final_slots should be %d, but %d", (
void *)page, page->final_slots, zombie_objects);
5133 return remembered_old_objects;
5137gc_verify_heap_pages_(rb_objspace_t *
objspace,
struct ccan_list_head *head)
5139 int remembered_old_objects = 0;
5142 ccan_list_for_each(head, page, page_node) {
5143 asan_unlock_freelist(page);
5148 rb_asan_unpoison_object(vp,
false);
5150 fprintf(stderr,
"freelist slot expected to be T_NONE but was: %s\n", rb_obj_info(vp));
5153 rb_asan_poison_object(prev);
5155 asan_lock_freelist(page);
5157 if (page->flags.has_remembered_objects == FALSE) {
5158 remembered_old_objects += gc_verify_heap_page(
objspace, page,
Qfalse);
5162 return remembered_old_objects;
5166gc_verify_heap_pages(rb_objspace_t *
objspace)
5168 int remembered_old_objects = 0;
5169 for (
int i = 0; i < HEAP_COUNT; i++) {
5170 remembered_old_objects += gc_verify_heap_pages_(
objspace, &((&heaps[i])->pages));
5172 return remembered_old_objects;
5176gc_verify_internal_consistency_(rb_objspace_t *
objspace)
5181 gc_report(5,
objspace,
"gc_verify_internal_consistency: start\n");
5184 for (
size_t i = 0; i < rb_darray_size(
objspace->heap_pages.sorted); i++) {
5186 short slot_size = page->slot_size;
5188 uintptr_t start = (uintptr_t)page->start;
5189 uintptr_t end = start + page->total_slots * slot_size;
5191 verify_internal_consistency_i((
void *)start, (
void *)end, slot_size, &data);
5194 if (data.err_count != 0) {
5195#if RGENGC_CHECK_MODE >= 5
5196 objspace->rgengc.error_count = data.err_count;
5197 gc_marks_check(
objspace, NULL, NULL);
5200 rb_bug(
"gc_verify_internal_consistency: found internal inconsistency.");
5208 ractor_cache_flush_count(
objspace, rb_gc_get_ractor_newobj_cache());
5212 !rb_gc_multi_ractor_p()) {
5213 if (objspace_live_slots(
objspace) != data.live_object_count) {
5214 fprintf(stderr,
"heap_pages_final_slots: %"PRIdSIZE
", total_freed_objects: %"PRIdSIZE
"\n",
5216 rb_bug(
"inconsistent live slot number: expect %"PRIuSIZE
", but %"PRIuSIZE
".",
5217 objspace_live_slots(
objspace), data.live_object_count);
5222 if (
objspace->rgengc.old_objects != data.old_object_count) {
5223 rb_bug(
"inconsistent old slot number: expect %"PRIuSIZE
", but %"PRIuSIZE
".",
5224 objspace->rgengc.old_objects, data.old_object_count);
5226 if (
objspace->rgengc.uncollectible_wb_unprotected_objects != data.remembered_shady_count) {
5227 rb_bug(
"inconsistent number of wb unprotected objects: expect %"PRIuSIZE
", but %"PRIuSIZE
".",
5228 objspace->rgengc.uncollectible_wb_unprotected_objects, data.remembered_shady_count);
5233 size_t list_count = 0;
5236 VALUE z = heap_pages_deferred_final;
5239 z = RZOMBIE(z)->next;
5243 if (total_final_slots_count(
objspace) != data.zombie_object_count ||
5244 total_final_slots_count(
objspace) != list_count) {
5246 rb_bug(
"inconsistent finalizing object count:\n"
5247 " expect %"PRIuSIZE
"\n"
5248 " but %"PRIuSIZE
" zombies\n"
5249 " heap_pages_deferred_final list has %"PRIuSIZE
" items.",
5251 data.zombie_object_count,
5256 gc_report(5,
objspace,
"gc_verify_internal_consistency: OK\n");
5260gc_verify_internal_consistency(
void *objspace_ptr)
5262 rb_objspace_t *
objspace = objspace_ptr;
5264 unsigned int lev = RB_GC_VM_LOCK();
5268 unsigned int prev_during_gc = during_gc;
5271 gc_verify_internal_consistency_(
objspace);
5273 during_gc = prev_during_gc;
5275 RB_GC_VM_UNLOCK(lev);
5279heap_move_pooled_pages_to_free_pages(rb_heap_t *heap)
5281 if (heap->pooled_pages) {
5282 if (heap->free_pages) {
5283 struct heap_page *free_pages_tail = heap->free_pages;
5284 while (free_pages_tail->free_next) {
5285 free_pages_tail = free_pages_tail->free_next;
5287 free_pages_tail->free_next = heap->pooled_pages;
5290 heap->free_pages = heap->pooled_pages;
5293 heap->pooled_pages = NULL;
5300 struct heap_page *page = GET_HEAP_PAGE(obj);
5301 bits_t *uncollectible_bits = &page->uncollectible_bits[0];
5303 if (!MARKED_IN_BITMAP(uncollectible_bits, obj)) {
5304 page->flags.has_uncollectible_wb_unprotected_objects = TRUE;
5305 MARK_IN_BITMAP(uncollectible_bits, obj);
5306 objspace->rgengc.uncollectible_wb_unprotected_objects++;
5308#if RGENGC_PROFILE > 0
5309 objspace->profile.total_remembered_shady_object_count++;
5310#if RGENGC_PROFILE >= 2
5322gc_marks_wb_unprotected_objects_plane(rb_objspace_t *
objspace, uintptr_t p, bits_t bits)
5327 gc_report(2,
objspace,
"gc_marks_wb_unprotected_objects: marked shady: %s\n", rb_obj_info((
VALUE)p));
5332 p += BASE_SLOT_SIZE;
5339gc_marks_wb_unprotected_objects(rb_objspace_t *
objspace, rb_heap_t *heap)
5343 ccan_list_for_each(&heap->pages, page, page_node) {
5344 bits_t *mark_bits = page->mark_bits;
5345 bits_t *wbun_bits = page->wb_unprotected_bits;
5346 uintptr_t p = page->start;
5349 bits_t bits = mark_bits[0] & wbun_bits[0];
5350 bits >>= NUM_IN_PAGE(p);
5351 gc_marks_wb_unprotected_objects_plane(
objspace, p, bits);
5352 p += (BITS_BITLENGTH - NUM_IN_PAGE(p)) * BASE_SLOT_SIZE;
5354 for (j=1; j<HEAP_PAGE_BITMAP_LIMIT; j++) {
5355 bits_t bits = mark_bits[j] & wbun_bits[j];
5357 gc_marks_wb_unprotected_objects_plane(
objspace, p, bits);
5358 p += BITS_BITLENGTH * BASE_SLOT_SIZE;
5362 gc_mark_stacked_objects_all(
objspace);
5366gc_update_weak_references(rb_objspace_t *
objspace)
5368 size_t retained_weak_references_count = 0;
5370 rb_darray_foreach(
objspace->weak_references, i, ptr_ptr) {
5371 if (!*ptr_ptr)
continue;
5373 VALUE obj = **ptr_ptr;
5377 if (!RVALUE_MARKED(
objspace, obj)) {
5381 retained_weak_references_count++;
5385 objspace->profile.retained_weak_references_count = retained_weak_references_count;
5387 rb_darray_clear(
objspace->weak_references);
5388 rb_darray_resize_capa_without_gc(&
objspace->weak_references, retained_weak_references_count);
5392gc_marks_finish(rb_objspace_t *
objspace)
5395 if (is_incremental_marking(
objspace)) {
5396 if (RGENGC_CHECK_MODE && is_mark_stack_empty(&
objspace->mark_stack) == 0) {
5397 rb_bug(
"gc_marks_finish: mark stack is not empty (%"PRIdSIZE
").",
5398 mark_stack_size(&
objspace->mark_stack));
5402 while (gc_mark_stacked_objects_incremental(
objspace, INT_MAX) ==
false);
5404#if RGENGC_CHECK_MODE >= 2
5405 if (gc_verify_heap_pages(
objspace) != 0) {
5406 rb_bug(
"gc_marks_finish (incremental): there are remembered old objects.");
5410 objspace->flags.during_incremental_marking = FALSE;
5412 for (
int i = 0; i < HEAP_COUNT; i++) {
5413 gc_marks_wb_unprotected_objects(
objspace, &heaps[i]);
5417 gc_update_weak_references(
objspace);
5419#if RGENGC_CHECK_MODE >= 2
5420 gc_verify_internal_consistency(
objspace);
5423#if RGENGC_CHECK_MODE >= 4
5425 gc_marks_check(
objspace, gc_check_after_marks_i,
"after_marks");
5430 const unsigned long r_mul =
objspace->live_ractor_cache_count > 8 ? 8 :
objspace->live_ractor_cache_count;
5432 size_t total_slots = objspace_available_slots(
objspace);
5433 size_t sweep_slots = total_slots -
objspace->marked_slots;
5434 size_t max_free_slots = (size_t)(total_slots * gc_params.heap_free_slots_max_ratio);
5435 size_t min_free_slots = (size_t)(total_slots * gc_params.heap_free_slots_min_ratio);
5436 if (min_free_slots < gc_params.heap_free_slots * r_mul) {
5437 min_free_slots = gc_params.heap_free_slots * r_mul;
5440 int full_marking = is_full_marking(
objspace);
5445 size_t total_init_slots = 0;
5446 for (
int i = 0; i < HEAP_COUNT; i++) {
5447 total_init_slots += gc_params.heap_init_slots[i] * r_mul;
5450 if (max_free_slots < total_init_slots) {
5451 max_free_slots = total_init_slots;
5454 if (sweep_slots > max_free_slots) {
5455 heap_pages_freeable_pages = (sweep_slots - max_free_slots) / HEAP_PAGE_OBJ_LIMIT;
5458 heap_pages_freeable_pages = 0;
5461 if (
objspace->heap_pages.allocatable_slots == 0 && sweep_slots < min_free_slots) {
5462 if (!full_marking) {
5463 if (
objspace->profile.count -
objspace->rgengc.last_major_gc < RVALUE_OLD_AGE) {
5464 full_marking = TRUE;
5467 gc_report(1,
objspace,
"gc_marks_finish: next is full GC!!)\n");
5468 gc_needs_major_flags |= GPR_FLAG_MAJOR_BY_NOFREE;
5473 heap_allocatable_slots_expand(
objspace, NULL, sweep_slots, total_slots);
5479 const double r = gc_params.oldobject_limit_factor;
5480 objspace->rgengc.uncollectible_wb_unprotected_objects_limit = MAX(
5481 (
size_t)(
objspace->rgengc.uncollectible_wb_unprotected_objects * r),
5482 (
size_t)(
objspace->rgengc.old_objects * gc_params.uncollectible_wb_unprotected_objects_limit_ratio)
5484 objspace->rgengc.old_objects_limit = (size_t)(
objspace->rgengc.old_objects * r);
5487 if (
objspace->rgengc.uncollectible_wb_unprotected_objects >
objspace->rgengc.uncollectible_wb_unprotected_objects_limit) {
5488 gc_needs_major_flags |= GPR_FLAG_MAJOR_BY_SHADY;
5491 gc_needs_major_flags |= GPR_FLAG_MAJOR_BY_OLDGEN;
5494 gc_report(1,
objspace,
"gc_marks_finish (marks %"PRIdSIZE
" objects, "
5495 "old %"PRIdSIZE
" objects, total %"PRIdSIZE
" slots, "
5496 "sweep %"PRIdSIZE
" slots, allocatable %"PRIdSIZE
" slots, next GC: %s)\n",
5498 gc_needs_major_flags ?
"major" :
"minor");
5502 rb_ractor_finish_marking();
5508gc_compact_heap_cursors_met_p(rb_heap_t *heap)
5510 return heap->sweeping_page == heap->compact_cursor;
5515gc_compact_destination_pool(rb_objspace_t *
objspace, rb_heap_t *src_pool,
VALUE obj)
5517 size_t obj_size = rb_gc_obj_optimal_size(obj);
5518 if (obj_size == 0) {
5522 GC_ASSERT(rb_gc_impl_size_allocatable_p(obj_size));
5524 size_t idx = heap_idx_for_size(obj_size);
5530gc_compact_move(rb_objspace_t *
objspace, rb_heap_t *heap,
VALUE src)
5533 GC_ASSERT(gc_is_moveable_obj(
objspace, src));
5535 rb_heap_t *dest_pool = gc_compact_destination_pool(
objspace, heap, src);
5536 uint32_t orig_shape = 0;
5537 uint32_t new_shape = 0;
5539 if (gc_compact_heap_cursors_met_p(dest_pool)) {
5540 return dest_pool != heap;
5544 orig_shape = rb_gc_get_shape(src);
5546 if (dest_pool != heap) {
5547 new_shape = rb_gc_rebuild_shape(src, dest_pool - heaps);
5549 if (new_shape == 0) {
5555 while (!try_move(
objspace, dest_pool, dest_pool->free_pages, src)) {
5557 .page = dest_pool->sweeping_page,
5566 lock_page_body(
objspace, GET_PAGE_BODY(src));
5567 gc_sweep_page(
objspace, dest_pool, &ctx);
5568 unlock_page_body(
objspace, GET_PAGE_BODY(src));
5570 if (dest_pool->sweeping_page->free_slots > 0) {
5571 heap_add_freepage(dest_pool, dest_pool->sweeping_page);
5574 dest_pool->sweeping_page = ccan_list_next(&dest_pool->pages, dest_pool->sweeping_page, page_node);
5575 if (gc_compact_heap_cursors_met_p(dest_pool)) {
5576 return dest_pool != heap;
5580 if (orig_shape != 0) {
5581 if (new_shape != 0) {
5583 rb_gc_set_shape(dest, new_shape);
5585 RMOVED(src)->original_shape_id = orig_shape;
5592gc_compact_plane(rb_objspace_t *
objspace, rb_heap_t *heap, uintptr_t p, bits_t bitset,
struct heap_page *page)
5594 short slot_size = page->slot_size;
5595 short slot_bits = slot_size / BASE_SLOT_SIZE;
5596 GC_ASSERT(slot_bits > 0);
5600 GC_ASSERT(vp % BASE_SLOT_SIZE == 0);
5605 if (gc_is_moveable_obj(
objspace, vp)) {
5606 if (!gc_compact_move(
objspace, heap, vp)) {
5613 bitset >>= slot_bits;
5621gc_compact_page(rb_objspace_t *
objspace, rb_heap_t *heap,
struct heap_page *page)
5623 GC_ASSERT(page == heap->compact_cursor);
5625 bits_t *mark_bits, *pin_bits;
5627 uintptr_t p = page->start;
5629 mark_bits = page->mark_bits;
5630 pin_bits = page->pinned_bits;
5633 bitset = (mark_bits[0] & ~pin_bits[0]);
5634 bitset >>= NUM_IN_PAGE(p);
5636 if (!gc_compact_plane(
objspace, heap, (uintptr_t)p, bitset, page))
5639 p += (BITS_BITLENGTH - NUM_IN_PAGE(p)) * BASE_SLOT_SIZE;
5641 for (
int j = 1; j < HEAP_PAGE_BITMAP_LIMIT; j++) {
5642 bitset = (mark_bits[j] & ~pin_bits[j]);
5644 if (!gc_compact_plane(
objspace, heap, (uintptr_t)p, bitset, page))
5647 p += BITS_BITLENGTH * BASE_SLOT_SIZE;
5654gc_compact_all_compacted_p(rb_objspace_t *
objspace)
5656 for (
int i = 0; i < HEAP_COUNT; i++) {
5657 rb_heap_t *heap = &heaps[i];
5659 if (heap->total_pages > 0 &&
5660 !gc_compact_heap_cursors_met_p(heap)) {
5669gc_sweep_compact(rb_objspace_t *
objspace)
5672#if RGENGC_CHECK_MODE >= 2
5673 gc_verify_internal_consistency(
objspace);
5676 while (!gc_compact_all_compacted_p(
objspace)) {
5677 for (
int i = 0; i < HEAP_COUNT; i++) {
5678 rb_heap_t *heap = &heaps[i];
5680 if (gc_compact_heap_cursors_met_p(heap)) {
5684 struct heap_page *start_page = heap->compact_cursor;
5686 if (!gc_compact_page(
objspace, heap, start_page)) {
5687 lock_page_body(
objspace, start_page->body);
5694 lock_page_body(
objspace, start_page->body);
5695 heap->compact_cursor = ccan_list_prev(&heap->pages, heap->compact_cursor, page_node);
5701#if RGENGC_CHECK_MODE >= 2
5702 gc_verify_internal_consistency(
objspace);
5707gc_marks_rest(rb_objspace_t *
objspace)
5709 gc_report(1,
objspace,
"gc_marks_rest\n");
5711 for (
int i = 0; i < HEAP_COUNT; i++) {
5712 (&heaps[i])->pooled_pages = NULL;
5715 if (is_incremental_marking(
objspace)) {
5716 while (gc_mark_stacked_objects_incremental(
objspace, INT_MAX) == FALSE);
5719 gc_mark_stacked_objects_all(
objspace);
5726gc_marks_step(rb_objspace_t *
objspace,
size_t slots)
5728 bool marking_finished =
false;
5731 if (gc_mark_stacked_objects_incremental(
objspace, slots)) {
5734 marking_finished =
true;
5737 return marking_finished;
5741gc_marks_continue(rb_objspace_t *
objspace, rb_heap_t *heap)
5743 GC_ASSERT(dont_gc_val() == FALSE ||
objspace->profile.latest_gc_info & GPR_FLAG_METHOD);
5744 bool marking_finished =
true;
5748 if (heap->free_pages) {
5749 gc_report(2,
objspace,
"gc_marks_continue: has pooled pages");
5754 gc_report(2,
objspace,
"gc_marks_continue: no more pooled pages (stack depth: %"PRIdSIZE
").\n",
5755 mark_stack_size(&
objspace->mark_stack));
5756 heap->force_incremental_marking_finish_count++;
5762 return marking_finished;
5766gc_marks_start(rb_objspace_t *
objspace,
int full_mark)
5769 gc_report(1,
objspace,
"gc_marks_start: (%s)\n", full_mark ?
"full" :
"minor");
5770 gc_mode_transition(
objspace, gc_mode_marking);
5773 size_t incremental_marking_steps = (
objspace->rincgc.pooled_slots / INCREMENTAL_MARK_STEP_ALLOCATIONS) + 1;
5774 objspace->rincgc.step_slots = (
objspace->marked_slots * 2) / incremental_marking_steps;
5776 if (0) fprintf(stderr,
"objspace->marked_slots: %"PRIdSIZE
", "
5777 "objspace->rincgc.pooled_page_num: %"PRIdSIZE
", "
5778 "objspace->rincgc.step_slots: %"PRIdSIZE
", \n",
5780 objspace->flags.during_minor_gc = FALSE;
5781 if (ruby_enable_autocompact) {
5782 objspace->flags.during_compacting |= TRUE;
5784 objspace->profile.major_gc_count++;
5785 objspace->rgengc.uncollectible_wb_unprotected_objects = 0;
5790 for (
int i = 0; i < HEAP_COUNT; i++) {
5791 rb_heap_t *heap = &heaps[i];
5792 rgengc_mark_and_rememberset_clear(
objspace, heap);
5793 heap_move_pooled_pages_to_free_pages(heap);
5795 if (
objspace->flags.during_compacting) {
5798 ccan_list_for_each(&heap->pages, page, page_node) {
5799 page->pinned_slots = 0;
5805 objspace->flags.during_minor_gc = TRUE;
5807 objspace->rgengc.old_objects +
objspace->rgengc.uncollectible_wb_unprotected_objects;
5808 objspace->profile.minor_gc_count++;
5810 for (
int i = 0; i < HEAP_COUNT; i++) {
5811 rgengc_rememberset_mark(
objspace, &heaps[i]);
5817 gc_report(1,
objspace,
"gc_marks_start: (%s) end, stack in %"PRIdSIZE
"\n",
5818 full_mark ?
"full" :
"minor", mark_stack_size(&
objspace->mark_stack));
5822gc_marks(rb_objspace_t *
objspace,
int full_mark)
5824 gc_prof_mark_timer_start(
objspace);
5827 bool marking_finished =
false;
5831 gc_marks_start(
objspace, full_mark);
5832 if (!is_incremental_marking(
objspace)) {
5834 marking_finished =
true;
5837#if RGENGC_PROFILE > 0
5840 record->old_objects =
objspace->rgengc.old_objects;
5847 return marking_finished;
5853gc_report_body(
int level, rb_objspace_t *
objspace,
const char *fmt, ...)
5855 if (level <= RGENGC_DEBUG) {
5859 const char *status =
" ";
5862 status = is_full_marking(
objspace) ?
"+" :
"-";
5868 if (is_incremental_marking(
objspace)) {
5873 va_start(args, fmt);
5874 vsnprintf(buf, 1024, fmt, args);
5877 fprintf(out,
"%s|", status);
5885rgengc_remembersetbits_set(rb_objspace_t *
objspace,
VALUE obj)
5887 struct heap_page *page = GET_HEAP_PAGE(obj);
5888 bits_t *bits = &page->remembered_bits[0];
5890 if (MARKED_IN_BITMAP(bits, obj)) {
5894 page->flags.has_remembered_objects = TRUE;
5895 MARK_IN_BITMAP(bits, obj);
5906 gc_report(6,
objspace,
"rgengc_remember: %s %s\n", rb_obj_info(obj),
5907 RVALUE_REMEMBERED(
objspace, obj) ?
"was already remembered" :
"is remembered now");
5909 check_rvalue_consistency(
objspace, obj);
5911 if (RGENGC_CHECK_MODE) {
5912 if (RVALUE_WB_UNPROTECTED(
objspace, obj)) rb_bug(
"rgengc_remember: %s is not wb protected.", rb_obj_info(obj));
5915#if RGENGC_PROFILE > 0
5916 if (!RVALUE_REMEMBERED(
objspace, obj)) {
5917 if (RVALUE_WB_UNPROTECTED(
objspace, obj) == 0) {
5918 objspace->profile.total_remembered_normal_object_count++;
5919#if RGENGC_PROFILE >= 2
5926 return rgengc_remembersetbits_set(
objspace, obj);
5929#ifndef PROFILE_REMEMBERSET_MARK
5930#define PROFILE_REMEMBERSET_MARK 0
5934rgengc_rememberset_mark_plane(rb_objspace_t *
objspace, uintptr_t p, bits_t bitset)
5940 gc_report(2,
objspace,
"rgengc_rememberset_mark: mark %s\n", rb_obj_info(obj));
5941 GC_ASSERT(RVALUE_UNCOLLECTIBLE(
objspace, obj));
5942 GC_ASSERT(RVALUE_OLD_P(
objspace, obj) || RVALUE_WB_UNPROTECTED(
objspace, obj));
5946 p += BASE_SLOT_SIZE;
5953rgengc_rememberset_mark(rb_objspace_t *
objspace, rb_heap_t *heap)
5957#if PROFILE_REMEMBERSET_MARK
5958 int has_old = 0, has_shady = 0, has_both = 0, skip = 0;
5960 gc_report(1,
objspace,
"rgengc_rememberset_mark: start\n");
5962 ccan_list_for_each(&heap->pages, page, page_node) {
5963 if (page->flags.has_remembered_objects | page->flags.has_uncollectible_wb_unprotected_objects) {
5964 uintptr_t p = page->start;
5965 bits_t bitset, bits[HEAP_PAGE_BITMAP_LIMIT];
5966 bits_t *remembered_bits = page->remembered_bits;
5967 bits_t *uncollectible_bits = page->uncollectible_bits;
5968 bits_t *wb_unprotected_bits = page->wb_unprotected_bits;
5969#if PROFILE_REMEMBERSET_MARK
5970 if (page->flags.has_remembered_objects && page->flags.has_uncollectible_wb_unprotected_objects) has_both++;
5971 else if (page->flags.has_remembered_objects) has_old++;
5972 else if (page->flags.has_uncollectible_wb_unprotected_objects) has_shady++;
5974 for (j=0; j<HEAP_PAGE_BITMAP_LIMIT; j++) {
5975 bits[j] = remembered_bits[j] | (uncollectible_bits[j] & wb_unprotected_bits[j]);
5976 remembered_bits[j] = 0;
5978 page->flags.has_remembered_objects = FALSE;
5981 bitset >>= NUM_IN_PAGE(p);
5982 rgengc_rememberset_mark_plane(
objspace, p, bitset);
5983 p += (BITS_BITLENGTH - NUM_IN_PAGE(p)) * BASE_SLOT_SIZE;
5985 for (j=1; j < HEAP_PAGE_BITMAP_LIMIT; j++) {
5987 rgengc_rememberset_mark_plane(
objspace, p, bitset);
5988 p += BITS_BITLENGTH * BASE_SLOT_SIZE;
5991#if PROFILE_REMEMBERSET_MARK
5998#if PROFILE_REMEMBERSET_MARK
5999 fprintf(stderr,
"%d\t%d\t%d\t%d\n", has_both, has_old, has_shady, skip);
6001 gc_report(1,
objspace,
"rgengc_rememberset_mark: finished\n");
6005rgengc_mark_and_rememberset_clear(rb_objspace_t *
objspace, rb_heap_t *heap)
6009 ccan_list_for_each(&heap->pages, page, page_node) {
6010 memset(&page->mark_bits[0], 0, HEAP_PAGE_BITMAP_SIZE);
6011 memset(&page->uncollectible_bits[0], 0, HEAP_PAGE_BITMAP_SIZE);
6012 memset(&page->marking_bits[0], 0, HEAP_PAGE_BITMAP_SIZE);
6013 memset(&page->remembered_bits[0], 0, HEAP_PAGE_BITMAP_SIZE);
6014 memset(&page->pinned_bits[0], 0, HEAP_PAGE_BITMAP_SIZE);
6015 page->flags.has_uncollectible_wb_unprotected_objects = FALSE;
6016 page->flags.has_remembered_objects = FALSE;
6022NOINLINE(
static void gc_writebarrier_generational(
VALUE a,
VALUE b, rb_objspace_t *
objspace));
6027 if (RGENGC_CHECK_MODE) {
6028 if (!RVALUE_OLD_P(
objspace, a)) rb_bug(
"gc_writebarrier_generational: %s is not an old object.", rb_obj_info(a));
6029 if ( RVALUE_OLD_P(
objspace, b)) rb_bug(
"gc_writebarrier_generational: %s is an old object.", rb_obj_info(b));
6030 if (is_incremental_marking(
objspace)) rb_bug(
"gc_writebarrier_generational: called while incremental marking: %s -> %s", rb_obj_info(a), rb_obj_info(b));
6034 if (!RVALUE_REMEMBERED(
objspace, a)) {
6035 int lev = RB_GC_VM_LOCK_NO_BARRIER();
6039 RB_GC_VM_UNLOCK_NO_BARRIER(lev);
6041 gc_report(1,
objspace,
"gc_writebarrier_generational: %s (remembered) -> %s\n", rb_obj_info(a), rb_obj_info(b));
6044 check_rvalue_consistency(
objspace, a);
6045 check_rvalue_consistency(
objspace, b);
6051 gc_mark_set_parent(
objspace, parent);
6052 rgengc_check_relation(
objspace, obj);
6053 if (gc_mark_set(
objspace, obj) != FALSE) {
6057 gc_mark_set_parent_invalid(
objspace);
6060NOINLINE(
static void gc_writebarrier_incremental(
VALUE a,
VALUE b, rb_objspace_t *
objspace));
6065 gc_report(2,
objspace,
"gc_writebarrier_incremental: [LG] %p -> %s\n", (
void *)a, rb_obj_info(b));
6069 if (!RVALUE_WB_UNPROTECTED(
objspace, a)) {
6070 gc_report(2,
objspace,
"gc_writebarrier_incremental: [IN] %p -> %s\n", (
void *)a, rb_obj_info(b));
6078 if (RB_UNLIKELY(
objspace->flags.during_compacting)) {
6079 MARK_IN_BITMAP(GET_HEAP_PINNED_BITS(b), b);
6085rb_gc_impl_writebarrier(
void *objspace_ptr,
VALUE a,
VALUE b)
6087 rb_objspace_t *
objspace = objspace_ptr;
6089#if RGENGC_CHECK_MODE
6090 if (
SPECIAL_CONST_P(a)) rb_bug(
"rb_gc_writebarrier: a is special const: %"PRIxVALUE, a);
6091 if (
SPECIAL_CONST_P(b)) rb_bug(
"rb_gc_writebarrier: b is special const: %"PRIxVALUE, b);
6097 GC_ASSERT(!during_gc);
6106 if (!is_incremental_marking(
objspace)) {
6111 gc_writebarrier_generational(a, b,
objspace);
6117 int lev = RB_GC_VM_LOCK_NO_BARRIER();
6119 if (is_incremental_marking(
objspace)) {
6120 gc_writebarrier_incremental(a, b,
objspace);
6126 RB_GC_VM_UNLOCK_NO_BARRIER(lev);
6128 if (retry)
goto retry;
6134rb_gc_impl_writebarrier_unprotect(
void *objspace_ptr,
VALUE obj)
6136 rb_objspace_t *
objspace = objspace_ptr;
6138 if (RVALUE_WB_UNPROTECTED(
objspace, obj)) {
6142 gc_report(2,
objspace,
"rb_gc_writebarrier_unprotect: %s %s\n", rb_obj_info(obj),
6143 RVALUE_REMEMBERED(
objspace, obj) ?
" (already remembered)" :
"");
6145 unsigned int lev = RB_GC_VM_LOCK_NO_BARRIER();
6148 gc_report(1,
objspace,
"rb_gc_writebarrier_unprotect: %s\n", rb_obj_info(obj));
6151 gc_remember_unprotected(
objspace, obj);
6154 objspace->profile.total_shade_operation_count++;
6155#if RGENGC_PROFILE >= 2
6161 RVALUE_AGE_RESET(obj);
6164 RB_DEBUG_COUNTER_INC(obj_wb_unprotect);
6165 MARK_IN_BITMAP(GET_HEAP_WB_UNPROTECTED_BITS(obj), obj);
6167 RB_GC_VM_UNLOCK_NO_BARRIER(lev);
6172rb_gc_impl_copy_attributes(
void *objspace_ptr,
VALUE dest,
VALUE obj)
6174 rb_objspace_t *
objspace = objspace_ptr;
6176 if (RVALUE_WB_UNPROTECTED(
objspace, obj)) {
6177 rb_gc_impl_writebarrier_unprotect(
objspace, dest);
6179 rb_gc_impl_copy_finalizer(
objspace, dest, obj);
6183rb_gc_impl_active_gc_name(
void)
6189rb_gc_impl_writebarrier_remember(
void *objspace_ptr,
VALUE obj)
6191 rb_objspace_t *
objspace = objspace_ptr;
6193 gc_report(1,
objspace,
"rb_gc_writebarrier_remember: %s\n", rb_obj_info(obj));
6196 int lev = RB_GC_VM_LOCK_NO_BARRIER();
6198 if (is_incremental_marking(
objspace)) {
6199 if (RVALUE_BLACK_P(
objspace, obj)) {
6203 else if (RVALUE_OLD_P(
objspace, obj)) {
6207 RB_GC_VM_UNLOCK_NO_BARRIER(lev);
6213 ID ID_wb_protected, ID_age, ID_old, ID_uncollectible, ID_marking,
6214 ID_marked, ID_pinned, ID_remembered, ID_object_id, ID_shareable;
6217#define RB_GC_OBJECT_METADATA_ENTRY_COUNT (sizeof(struct rb_gc_object_metadata_names) / sizeof(ID))
6221rb_gc_impl_object_metadata(
void *objspace_ptr,
VALUE obj)
6223 rb_objspace_t *
objspace = objspace_ptr;
6227 if (!names.ID_marked) {
6228#define I(s) names.ID_##s = rb_intern(#s)
6242#define SET_ENTRY(na, v) do { \
6243 GC_ASSERT(n <= RB_GC_OBJECT_METADATA_ENTRY_COUNT); \
6244 object_metadata_entries[n].name = names.ID_##na; \
6245 object_metadata_entries[n].val = v; \
6249 if (!RVALUE_WB_UNPROTECTED(
objspace, obj)) SET_ENTRY(wb_protected,
Qtrue);
6250 SET_ENTRY(age,
INT2FIX(RVALUE_AGE_GET(obj)));
6252 if (RVALUE_UNCOLLECTIBLE(
objspace, obj)) SET_ENTRY(uncollectible,
Qtrue);
6253 if (RVALUE_MARKING(
objspace, obj)) SET_ENTRY(marking,
Qtrue);
6256 if (RVALUE_REMEMBERED(
objspace, obj)) SET_ENTRY(remembered,
Qtrue);
6257 if (rb_obj_id_p(obj)) SET_ENTRY(object_id, rb_obj_id(obj));
6260 object_metadata_entries[n].name = 0;
6261 object_metadata_entries[n].val = 0;
6264 return object_metadata_entries;
6268rb_gc_impl_ractor_cache_alloc(
void *objspace_ptr,
void *ractor)
6270 rb_objspace_t *
objspace = objspace_ptr;
6272 objspace->live_ractor_cache_count++;
6274 return calloc1(
sizeof(rb_ractor_newobj_cache_t));
6278rb_gc_impl_ractor_cache_free(
void *objspace_ptr,
void *cache)
6280 rb_objspace_t *
objspace = objspace_ptr;
6282 objspace->live_ractor_cache_count--;
6283 gc_ractor_newobj_cache_clear(cache, NULL);
6288heap_ready_to_gc(rb_objspace_t *
objspace, rb_heap_t *heap)
6290 if (!heap->free_pages) {
6291 if (!heap_page_allocate_and_initialize(
objspace, heap)) {
6292 objspace->heap_pages.allocatable_slots = 1;
6293 heap_page_allocate_and_initialize(
objspace, heap);
6299ready_to_gc(rb_objspace_t *
objspace)
6301 if (dont_gc_val() || during_gc) {
6302 for (
int i = 0; i < HEAP_COUNT; i++) {
6303 rb_heap_t *heap = &heaps[i];
6314gc_reset_malloc_info(rb_objspace_t *
objspace,
bool full_mark)
6319 size_t old_limit = malloc_limit;
6321 if (inc > malloc_limit) {
6322 malloc_limit = (size_t)(inc * gc_params.malloc_limit_growth_factor);
6323 if (malloc_limit > gc_params.malloc_limit_max) {
6324 malloc_limit = gc_params.malloc_limit_max;
6328 malloc_limit = (size_t)(malloc_limit * 0.98);
6329 if (malloc_limit < gc_params.malloc_limit_min) {
6330 malloc_limit = gc_params.malloc_limit_min;
6335 if (old_limit != malloc_limit) {
6336 fprintf(stderr,
"[%"PRIuSIZE
"] malloc_limit: %"PRIuSIZE
" -> %"PRIuSIZE
"\n",
6340 fprintf(stderr,
"[%"PRIuSIZE
"] malloc_limit: not changed (%"PRIuSIZE
")\n",
6347#if RGENGC_ESTIMATE_OLDMALLOC
6349 if (
objspace->malloc_counters.oldmalloc_increase >
objspace->rgengc.oldmalloc_increase_limit) {
6350 gc_needs_major_flags |= GPR_FLAG_MAJOR_BY_OLDMALLOC;
6351 objspace->rgengc.oldmalloc_increase_limit =
6352 (size_t)(
objspace->rgengc.oldmalloc_increase_limit * gc_params.oldmalloc_limit_growth_factor);
6354 if (
objspace->rgengc.oldmalloc_increase_limit > gc_params.oldmalloc_limit_max) {
6355 objspace->rgengc.oldmalloc_increase_limit = gc_params.oldmalloc_limit_max;
6359 if (0) fprintf(stderr,
"%"PRIdSIZE
"\t%d\t%"PRIuSIZE
"\t%"PRIuSIZE
"\t%"PRIdSIZE
"\n",
6361 gc_needs_major_flags,
6362 objspace->malloc_counters.oldmalloc_increase,
6363 objspace->rgengc.oldmalloc_increase_limit,
6364 gc_params.oldmalloc_limit_max);
6368 objspace->malloc_counters.oldmalloc_increase = 0;
6370 if ((
objspace->profile.latest_gc_info & GPR_FLAG_MAJOR_BY_OLDMALLOC) == 0) {
6371 objspace->rgengc.oldmalloc_increase_limit =
6372 (size_t)(
objspace->rgengc.oldmalloc_increase_limit / ((gc_params.oldmalloc_limit_growth_factor - 1)/10 + 1));
6373 if (
objspace->rgengc.oldmalloc_increase_limit < gc_params.oldmalloc_limit_min) {
6374 objspace->rgengc.oldmalloc_increase_limit = gc_params.oldmalloc_limit_min;
6382garbage_collect(rb_objspace_t *
objspace,
unsigned int reason)
6386 int lev = RB_GC_VM_LOCK();
6388#if GC_PROFILE_MORE_DETAIL
6389 objspace->profile.prepare_time = getrusage_time();
6394#if GC_PROFILE_MORE_DETAIL
6395 objspace->profile.prepare_time = getrusage_time() -
objspace->profile.prepare_time;
6400 RB_GC_VM_UNLOCK(lev);
6406gc_start(rb_objspace_t *
objspace,
unsigned int reason)
6408 unsigned int do_full_mark = !!(reason & GPR_FLAG_FULL_MARK);
6410 if (!rb_darray_size(
objspace->heap_pages.sorted))
return TRUE;
6411 if (!(reason & GPR_FLAG_METHOD) && !ready_to_gc(
objspace))
return TRUE;
6413 GC_ASSERT(gc_mode(
objspace) == gc_mode_none,
"gc_mode is %s\n", gc_mode_name(gc_mode(
objspace)));
6414 GC_ASSERT(!is_lazy_sweeping(
objspace));
6415 GC_ASSERT(!is_incremental_marking(
objspace));
6417 unsigned int lock_lev;
6418 gc_enter(
objspace, gc_enter_event_start, &lock_lev);
6421 objspace->flags.immediate_sweep = !!(reason & GPR_FLAG_IMMEDIATE_SWEEP);
6423#if RGENGC_CHECK_MODE >= 2
6424 gc_verify_internal_consistency(
objspace);
6427 if (ruby_gc_stressful) {
6428 int flag =
FIXNUM_P(ruby_gc_stress_mode) ?
FIX2INT(ruby_gc_stress_mode) : 0;
6430 if ((flag & (1 << gc_stress_no_major)) == 0) {
6431 do_full_mark = TRUE;
6434 objspace->flags.immediate_sweep = !(flag & (1<<gc_stress_no_immediate_sweep));
6437 if (gc_needs_major_flags) {
6438 reason |= gc_needs_major_flags;
6439 do_full_mark = TRUE;
6443 if (!gc_config_full_mark_val) {
6444 do_full_mark = FALSE;
6446 gc_needs_major_flags = GPR_FLAG_NONE;
6448 if (do_full_mark && (reason & GPR_FLAG_MAJOR_MASK) == 0) {
6449 reason |= GPR_FLAG_MAJOR_BY_FORCE;
6452 if (
objspace->flags.dont_incremental ||
6453 reason & GPR_FLAG_IMMEDIATE_MARK ||
6454 ruby_gc_stressful) {
6455 objspace->flags.during_incremental_marking = FALSE;
6458 objspace->flags.during_incremental_marking = do_full_mark;
6462 if (do_full_mark && ruby_enable_autocompact) {
6463 objspace->flags.during_compacting = TRUE;
6464#if RGENGC_CHECK_MODE
6465 objspace->rcompactor.compare_func = ruby_autocompact_compare_func;
6469 objspace->flags.during_compacting = !!(reason & GPR_FLAG_COMPACT);
6472 if (!GC_ENABLE_LAZY_SWEEP ||
objspace->flags.dont_incremental) {
6473 objspace->flags.immediate_sweep = TRUE;
6476 if (
objspace->flags.immediate_sweep) reason |= GPR_FLAG_IMMEDIATE_SWEEP;
6478 gc_report(1,
objspace,
"gc_start(reason: %x) => %u, %d, %d\n",
6480 do_full_mark, !is_incremental_marking(
objspace),
objspace->flags.immediate_sweep);
6482 RB_DEBUG_COUNTER_INC(gc_count);
6484 if (reason & GPR_FLAG_MAJOR_MASK) {
6485 (void)RB_DEBUG_COUNTER_INC_IF(gc_major_nofree, reason & GPR_FLAG_MAJOR_BY_NOFREE);
6486 (void)RB_DEBUG_COUNTER_INC_IF(gc_major_oldgen, reason & GPR_FLAG_MAJOR_BY_OLDGEN);
6487 (void)RB_DEBUG_COUNTER_INC_IF(gc_major_shady, reason & GPR_FLAG_MAJOR_BY_SHADY);
6488 (void)RB_DEBUG_COUNTER_INC_IF(gc_major_force, reason & GPR_FLAG_MAJOR_BY_FORCE);
6489#if RGENGC_ESTIMATE_OLDMALLOC
6490 (void)RB_DEBUG_COUNTER_INC_IF(gc_major_oldmalloc, reason & GPR_FLAG_MAJOR_BY_OLDMALLOC);
6494 (void)RB_DEBUG_COUNTER_INC_IF(gc_minor_newobj, reason & GPR_FLAG_NEWOBJ);
6495 (void)RB_DEBUG_COUNTER_INC_IF(gc_minor_malloc, reason & GPR_FLAG_MALLOC);
6496 (void)RB_DEBUG_COUNTER_INC_IF(gc_minor_method, reason & GPR_FLAG_METHOD);
6497 (void)RB_DEBUG_COUNTER_INC_IF(gc_minor_capi, reason & GPR_FLAG_CAPI);
6498 (void)RB_DEBUG_COUNTER_INC_IF(gc_minor_stress, reason & GPR_FLAG_STRESS);
6502 objspace->profile.latest_gc_info = reason;
6503 objspace->profile.total_allocated_objects_at_gc_start = total_allocated_objects(
objspace);
6504 objspace->profile.heap_used_at_gc_start = rb_darray_size(
objspace->heap_pages.sorted);
6505 objspace->profile.weak_references_count = 0;
6506 objspace->profile.retained_weak_references_count = 0;
6507 gc_prof_setup_new_record(
objspace, reason);
6508 gc_reset_malloc_info(
objspace, do_full_mark);
6512 GC_ASSERT(during_gc);
6516 if (gc_marks(
objspace, do_full_mark)) {
6522 gc_exit(
objspace, gc_enter_event_start, &lock_lev);
6530 unsigned int lock_lev;
6531 gc_enter(
objspace, gc_enter_event_rest, &lock_lev);
6533 if (RGENGC_CHECK_MODE >= 2) gc_verify_internal_consistency(
objspace);
6535 if (is_incremental_marking(
objspace)) {
6549 gc_exit(
objspace, gc_enter_event_rest, &lock_lev);
6554 rb_objspace_t *objspace;
6555 unsigned int reason;
6559gc_current_status_fill(rb_objspace_t *
objspace,
char *buff)
6564 if (is_full_marking(
objspace)) buff[i++] =
'F';
6565 if (is_incremental_marking(
objspace)) buff[i++] =
'I';
6569 if (is_lazy_sweeping(
objspace)) buff[i++] =
'L';
6578gc_current_status(rb_objspace_t *
objspace)
6580 static char buff[0x10];
6581 gc_current_status_fill(
objspace, buff);
6585#if PRINT_ENTER_EXIT_TICK
6587static tick_t last_exit_tick;
6588static tick_t enter_tick;
6589static int enter_count = 0;
6590static char last_gc_status[0x10];
6593gc_record(rb_objspace_t *
objspace,
int direction,
const char *event)
6595 if (direction == 0) {
6597 enter_tick = tick();
6598 gc_current_status_fill(
objspace, last_gc_status);
6601 tick_t exit_tick = tick();
6602 char current_gc_status[0x10];
6603 gc_current_status_fill(
objspace, current_gc_status);
6606 fprintf(stderr,
"%"PRItick
"\t%"PRItick
"\t%s\t[%s->%s|%c]\n",
6607 enter_tick - last_exit_tick,
6608 exit_tick - enter_tick,
6610 last_gc_status, current_gc_status,
6611 (
objspace->profile.latest_gc_info & GPR_FLAG_MAJOR_MASK) ?
'+' :
'-');
6612 last_exit_tick = exit_tick;
6615 fprintf(stderr,
"%"PRItick
"\t%"PRItick
"\t%s\t[%s->%s|%c]\n",
6617 exit_tick - enter_tick,
6619 last_gc_status, current_gc_status,
6620 (
objspace->profile.latest_gc_info & GPR_FLAG_MAJOR_MASK) ?
'+' :
'-');
6626gc_record(rb_objspace_t *
objspace,
int direction,
const char *event)
6633gc_enter_event_cstr(
enum gc_enter_event event)
6636 case gc_enter_event_start:
return "start";
6637 case gc_enter_event_continue:
return "continue";
6638 case gc_enter_event_rest:
return "rest";
6639 case gc_enter_event_finalizer:
return "finalizer";
6645gc_enter_count(
enum gc_enter_event event)
6648 case gc_enter_event_start: RB_DEBUG_COUNTER_INC(gc_enter_start);
break;
6649 case gc_enter_event_continue: RB_DEBUG_COUNTER_INC(gc_enter_continue);
break;
6650 case gc_enter_event_rest: RB_DEBUG_COUNTER_INC(gc_enter_rest);
break;
6651 case gc_enter_event_finalizer: RB_DEBUG_COUNTER_INC(gc_enter_finalizer);
break;
6655static bool current_process_time(
struct timespec *ts);
6660 if (!current_process_time(ts)) {
6666static unsigned long long
6671 if ((ts->tv_sec > 0 || ts->tv_nsec > 0) &&
6672 current_process_time(&end_time) &&
6673 end_time.tv_sec >= ts->tv_sec) {
6674 return (
unsigned long long)(end_time.tv_sec - ts->tv_sec) * (1000 * 1000 * 1000) +
6675 (end_time.tv_nsec - ts->tv_nsec);
6682gc_enter(rb_objspace_t *
objspace,
enum gc_enter_event event,
unsigned int *lock_lev)
6684 *lock_lev = RB_GC_VM_LOCK();
6687 case gc_enter_event_rest:
6688 case gc_enter_event_start:
6689 case gc_enter_event_continue:
6697 gc_enter_count(event);
6698 if (RB_UNLIKELY(during_gc != 0)) rb_bug(
"during_gc != 0");
6699 if (RGENGC_CHECK_MODE >= 3) gc_verify_internal_consistency(
objspace);
6702 RUBY_DEBUG_LOG(
"%s (%s)",gc_enter_event_cstr(event), gc_current_status(
objspace));
6703 gc_report(1,
objspace,
"gc_enter: %s [%s]\n", gc_enter_event_cstr(event), gc_current_status(
objspace));
6704 gc_record(
objspace, 0, gc_enter_event_cstr(event));
6710gc_exit(rb_objspace_t *
objspace,
enum gc_enter_event event,
unsigned int *lock_lev)
6712 GC_ASSERT(during_gc != 0);
6716 gc_record(
objspace, 1, gc_enter_event_cstr(event));
6717 RUBY_DEBUG_LOG(
"%s (%s)", gc_enter_event_cstr(event), gc_current_status(
objspace));
6718 gc_report(1,
objspace,
"gc_exit: %s [%s]\n", gc_enter_event_cstr(event), gc_current_status(
objspace));
6721 RB_GC_VM_UNLOCK(*lock_lev);
6725#define MEASURE_GC (objspace->flags.measure_gc)
6729gc_marking_enter(rb_objspace_t *
objspace)
6731 GC_ASSERT(during_gc != 0);
6734 gc_clock_start(&
objspace->profile.marking_start_time);
6739gc_marking_exit(rb_objspace_t *
objspace)
6741 GC_ASSERT(during_gc != 0);
6744 objspace->profile.marking_time_ns += gc_clock_end(&
objspace->profile.marking_start_time);
6749gc_sweeping_enter(rb_objspace_t *
objspace)
6751 GC_ASSERT(during_gc != 0);
6754 gc_clock_start(&
objspace->profile.sweeping_start_time);
6759gc_sweeping_exit(rb_objspace_t *
objspace)
6761 GC_ASSERT(during_gc != 0);
6764 objspace->profile.sweeping_time_ns += gc_clock_end(&
objspace->profile.sweeping_start_time);
6769gc_with_gvl(
void *ptr)
6772 return (
void *)(
VALUE)garbage_collect(oar->objspace, oar->reason);
6778garbage_collect_with_gvl(rb_objspace_t *
objspace,
unsigned int reason)
6780 if (dont_gc_val()) {
6790 oar.reason = reason;
6796 return garbage_collect(
objspace, reason);
6801gc_set_candidate_object_i(
void *vstart,
void *vend,
size_t stride,
void *data)
6803 rb_objspace_t *
objspace = (rb_objspace_t *)data;
6806 for (; v != (
VALUE)vend; v += stride) {
6807 asan_unpoisoning_object(v) {
6813 rb_gc_prepare_heap_process_object(v);
6815 RVALUE_AGE_SET_CANDIDATE(
objspace, v);
6825rb_gc_impl_start(
void *objspace_ptr,
bool full_mark,
bool immediate_mark,
bool immediate_sweep,
bool compact)
6827 rb_objspace_t *
objspace = objspace_ptr;
6828 unsigned int reason = (GPR_FLAG_FULL_MARK |
6829 GPR_FLAG_IMMEDIATE_MARK |
6830 GPR_FLAG_IMMEDIATE_SWEEP |
6833 int full_marking_p = gc_config_full_mark_val;
6834 gc_config_full_mark_set(TRUE);
6838 GC_ASSERT(GC_COMPACTION_SUPPORTED);
6840 reason |= GPR_FLAG_COMPACT;
6843 if (!full_mark) reason &= ~GPR_FLAG_FULL_MARK;
6844 if (!immediate_mark) reason &= ~GPR_FLAG_IMMEDIATE_MARK;
6845 if (!immediate_sweep) reason &= ~GPR_FLAG_IMMEDIATE_SWEEP;
6851 gc_config_full_mark_set(full_marking_p);
6855rb_gc_impl_prepare_heap(
void *objspace_ptr)
6857 rb_objspace_t *
objspace = objspace_ptr;
6859 size_t orig_total_slots = objspace_available_slots(
objspace);
6860 size_t orig_allocatable_slots =
objspace->heap_pages.allocatable_slots;
6862 rb_gc_impl_each_objects(
objspace, gc_set_candidate_object_i, objspace_ptr);
6864 double orig_max_free_slots = gc_params.heap_free_slots_max_ratio;
6866 gc_params.heap_free_slots_max_ratio = 0.0;
6867 rb_gc_impl_start(
objspace,
true,
true,
true,
true);
6868 gc_params.heap_free_slots_max_ratio = orig_max_free_slots;
6870 objspace->heap_pages.allocatable_slots = 0;
6871 heap_pages_freeable_pages =
objspace->empty_pages_count;
6872 heap_pages_free_unused_pages(objspace_ptr);
6873 GC_ASSERT(heap_pages_freeable_pages == 0);
6874 GC_ASSERT(
objspace->empty_pages_count == 0);
6875 objspace->heap_pages.allocatable_slots = orig_allocatable_slots;
6877 size_t total_slots = objspace_available_slots(
objspace);
6878 if (orig_total_slots > total_slots) {
6879 objspace->heap_pages.allocatable_slots += orig_total_slots - total_slots;
6882#if defined(HAVE_MALLOC_TRIM) && !defined(RUBY_ALTERNATIVE_MALLOC_HEADER)
6928 GC_ASSERT(st_is_member(finalizer_table, obj));
6932 GC_ASSERT(RVALUE_MARKED(
objspace, obj));
6933 GC_ASSERT(!RVALUE_PINNED(
objspace, obj));
6938 rb_bug(
"gc_is_moveable_obj: unreachable (%d)", (
int)
BUILTIN_TYPE(obj));
6945void rb_mv_generic_ivar(
VALUE src,
VALUE dst);
6948gc_move(rb_objspace_t *
objspace,
VALUE src,
VALUE dest,
size_t src_slot_size,
size_t slot_size)
6955 gc_report(4,
objspace,
"Moving object: %p -> %p\n", (
void *)src, (
void *)dest);
6958 GC_ASSERT(!MARKED_IN_BITMAP(GET_HEAP_MARK_BITS(dest), dest));
6960 GC_ASSERT(!RVALUE_MARKING(
objspace, src));
6963 marked = RVALUE_MARKED(
objspace, src);
6964 wb_unprotected = RVALUE_WB_UNPROTECTED(
objspace, src);
6965 uncollectible = RVALUE_UNCOLLECTIBLE(
objspace, src);
6966 bool remembered = RVALUE_REMEMBERED(
objspace, src);
6967 age = RVALUE_AGE_GET(src);
6970 CLEAR_IN_BITMAP(GET_HEAP_MARK_BITS(src), src);
6971 CLEAR_IN_BITMAP(GET_HEAP_WB_UNPROTECTED_BITS(src), src);
6972 CLEAR_IN_BITMAP(GET_HEAP_UNCOLLECTIBLE_BITS(src), src);
6973 CLEAR_IN_BITMAP(GET_HEAP_PAGE(src)->remembered_bits, src);
6976 memcpy((
void *)dest, (
void *)src, MIN(src_slot_size, slot_size));
6978 if (RVALUE_OVERHEAD > 0) {
6979 void *dest_overhead = (
void *)(((uintptr_t)dest) + slot_size - RVALUE_OVERHEAD);
6980 void *src_overhead = (
void *)(((uintptr_t)src) + src_slot_size - RVALUE_OVERHEAD);
6982 memcpy(dest_overhead, src_overhead, RVALUE_OVERHEAD);
6985 memset((
void *)src, 0, src_slot_size);
6986 RVALUE_AGE_SET_BITMAP(src, 0);
6990 MARK_IN_BITMAP(GET_HEAP_PAGE(dest)->remembered_bits, dest);
6993 CLEAR_IN_BITMAP(GET_HEAP_PAGE(dest)->remembered_bits, dest);
6997 MARK_IN_BITMAP(GET_HEAP_MARK_BITS(dest), dest);
7000 CLEAR_IN_BITMAP(GET_HEAP_MARK_BITS(dest), dest);
7003 if (wb_unprotected) {
7004 MARK_IN_BITMAP(GET_HEAP_WB_UNPROTECTED_BITS(dest), dest);
7007 CLEAR_IN_BITMAP(GET_HEAP_WB_UNPROTECTED_BITS(dest), dest);
7010 if (uncollectible) {
7011 MARK_IN_BITMAP(GET_HEAP_UNCOLLECTIBLE_BITS(dest), dest);
7014 CLEAR_IN_BITMAP(GET_HEAP_UNCOLLECTIBLE_BITS(dest), dest);
7017 RVALUE_AGE_SET(dest, age);
7020 RMOVED(src)->dummy =
Qundef;
7021 RMOVED(src)->destination = dest;
7024 GET_HEAP_PAGE(src)->heap->total_freed_objects++;
7025 GET_HEAP_PAGE(dest)->heap->total_allocated_objects++;
7030#if GC_CAN_COMPILE_COMPACTION
7032compare_pinned_slots(
const void *left,
const void *right,
void *dummy)
7037 left_page = *(
struct heap_page *
const *)left;
7038 right_page = *(
struct heap_page *
const *)right;
7040 return left_page->pinned_slots - right_page->pinned_slots;
7044compare_free_slots(
const void *left,
const void *right,
void *dummy)
7049 left_page = *(
struct heap_page *
const *)left;
7050 right_page = *(
struct heap_page *
const *)right;
7052 return left_page->free_slots - right_page->free_slots;
7056gc_sort_heap_by_compare_func(rb_objspace_t *
objspace, gc_compact_compare_func compare_func)
7058 for (
int j = 0; j < HEAP_COUNT; j++) {
7059 rb_heap_t *heap = &heaps[j];
7061 size_t total_pages = heap->total_pages;
7063 struct heap_page *page = 0, **page_list = malloc(size);
7066 heap->free_pages = NULL;
7067 ccan_list_for_each(&heap->pages, page, page_node) {
7068 page_list[i++] = page;
7072 GC_ASSERT((
size_t)i == total_pages);
7079 ccan_list_head_init(&heap->pages);
7081 for (i = 0; i < total_pages; i++) {
7082 ccan_list_add(&heap->pages, &page_list[i]->page_node);
7083 if (page_list[i]->free_slots != 0) {
7084 heap_add_freepage(heap, page_list[i]);
7094rb_gc_impl_object_moved_p(
void *objspace_ptr,
VALUE obj)
7096 return gc_object_moved_p(objspace_ptr, obj);
7100gc_ref_update(
void *vstart,
void *vend,
size_t stride, rb_objspace_t *
objspace,
struct heap_page *page)
7104 page->flags.has_uncollectible_wb_unprotected_objects = FALSE;
7105 page->flags.has_remembered_objects = FALSE;
7108 for (; v != (
VALUE)vend; v += stride) {
7109 asan_unpoisoning_object(v) {
7116 if (RVALUE_WB_UNPROTECTED(
objspace, v)) {
7117 page->flags.has_uncollectible_wb_unprotected_objects = TRUE;
7119 if (RVALUE_REMEMBERED(
objspace, v)) {
7120 page->flags.has_remembered_objects = TRUE;
7122 if (page->flags.before_sweep) {
7124 rb_gc_update_object_references(
objspace, v);
7128 rb_gc_update_object_references(
objspace, v);
7138gc_update_references_weak_table_i(
VALUE obj,
void *data)
7141 asan_unpoisoning_object(obj) {
7148gc_update_references_weak_table_replace_i(
VALUE *obj,
void *data)
7150 *obj = rb_gc_location(*obj);
7156gc_update_references(rb_objspace_t *
objspace)
7158 objspace->flags.during_reference_updating =
true;
7160 rb_gc_before_updating_jit_code();
7164 for (
int i = 0; i < HEAP_COUNT; i++) {
7165 bool should_set_mark_bits = TRUE;
7166 rb_heap_t *heap = &heaps[i];
7168 ccan_list_for_each(&heap->pages, page, page_node) {
7169 uintptr_t start = (uintptr_t)page->start;
7170 uintptr_t end = start + (page->total_slots * heap->slot_size);
7172 gc_ref_update((
void *)start, (
void *)end, heap->slot_size,
objspace, page);
7173 if (page == heap->sweeping_page) {
7174 should_set_mark_bits = FALSE;
7176 if (should_set_mark_bits) {
7177 gc_setup_mark_bits(page);
7182 gc_update_table_refs(finalizer_table);
7184 rb_gc_update_vm_references((
void *)
objspace);
7186 for (
int table = 0; table < RB_GC_VM_WEAK_TABLE_COUNT; table++) {
7187 rb_gc_vm_weak_table_foreach(
7188 gc_update_references_weak_table_i,
7189 gc_update_references_weak_table_replace_i,
7196 rb_gc_after_updating_jit_code();
7198 objspace->flags.during_reference_updating =
false;
7201#if GC_CAN_COMPILE_COMPACTION
7203root_obj_check_moved_i(
const char *category,
VALUE obj,
void *data)
7207 if (gc_object_moved_p(
objspace, obj)) {
7208 rb_bug(
"ROOT %s points to MOVED: %p -> %s", category, (
void *)obj, rb_obj_info(rb_gc_impl_location(
objspace, obj)));
7213reachable_object_check_moved_i(
VALUE ref,
void *data)
7216 if (gc_object_moved_p(rb_gc_get_objspace(), ref)) {
7217 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)));
7222heap_check_moved_i(
void *vstart,
void *vend,
size_t stride,
void *data)
7227 for (; v != (
VALUE)vend; v += stride) {
7228 if (gc_object_moved_p(
objspace, v)) {
7232 asan_unpoisoning_object(v) {
7238 if (!rb_gc_impl_garbage_object_p(
objspace, v)) {
7239 rb_objspace_reachable_objects_from(v, reachable_object_check_moved_i, (
void *)v);
7251rb_gc_impl_during_gc_p(
void *objspace_ptr)
7253 rb_objspace_t *
objspace = objspace_ptr;
7258#if RGENGC_PROFILE >= 2
7291 default:
return "unknown";
7296gc_count_add_each_types(
VALUE hash,
const char *name,
const size_t *types)
7300 for (i=0; i<
T_MASK; i++) {
7301 const char *
type = type_name(i, 0);
7304 rb_hash_aset(hash,
ID2SYM(rb_intern(name)), result);
7309rb_gc_impl_gc_count(
void *objspace_ptr)
7311 rb_objspace_t *
objspace = objspace_ptr;
7317gc_info_decode(rb_objspace_t *
objspace,
const VALUE hash_or_key,
const unsigned int orig_flags)
7319 static VALUE sym_major_by =
Qnil, sym_gc_by, sym_immediate_sweep, sym_have_finalizer, sym_state, sym_need_major_by;
7320 static VALUE sym_nofree, sym_oldgen, sym_shady, sym_force, sym_stress;
7321#if RGENGC_ESTIMATE_OLDMALLOC
7322 static VALUE sym_oldmalloc;
7324 static VALUE sym_newobj, sym_malloc, sym_method, sym_capi;
7325 static VALUE sym_none, sym_marking, sym_sweeping;
7326 static VALUE sym_weak_references_count, sym_retained_weak_references_count;
7328 VALUE major_by, need_major_by;
7329 unsigned int flags = orig_flags ? orig_flags :
objspace->profile.latest_gc_info;
7338 rb_bug(
"gc_info_decode: non-hash or symbol given");
7341 if (
NIL_P(sym_major_by)) {
7342#define S(s) sym_##s = ID2SYM(rb_intern_const(#s))
7355#if RGENGC_ESTIMATE_OLDMALLOC
7367 S(weak_references_count);
7368 S(retained_weak_references_count);
7372#define SET(name, attr) \
7373 if (key == sym_##name) \
7375 else if (hash != Qnil) \
7376 rb_hash_aset(hash, sym_##name, (attr));
7379 (flags & GPR_FLAG_MAJOR_BY_NOFREE) ? sym_nofree :
7380 (flags & GPR_FLAG_MAJOR_BY_OLDGEN) ? sym_oldgen :
7381 (flags & GPR_FLAG_MAJOR_BY_SHADY) ? sym_shady :
7382 (flags & GPR_FLAG_MAJOR_BY_FORCE) ? sym_force :
7383#if RGENGC_ESTIMATE_OLDMALLOC
7384 (flags & GPR_FLAG_MAJOR_BY_OLDMALLOC) ? sym_oldmalloc :
7387 SET(major_by, major_by);
7389 if (orig_flags == 0) {
7390 unsigned int need_major_flags = gc_needs_major_flags;
7392 (need_major_flags & GPR_FLAG_MAJOR_BY_NOFREE) ? sym_nofree :
7393 (need_major_flags & GPR_FLAG_MAJOR_BY_OLDGEN) ? sym_oldgen :
7394 (need_major_flags & GPR_FLAG_MAJOR_BY_SHADY) ? sym_shady :
7395 (need_major_flags & GPR_FLAG_MAJOR_BY_FORCE) ? sym_force :
7396#if RGENGC_ESTIMATE_OLDMALLOC
7397 (need_major_flags & GPR_FLAG_MAJOR_BY_OLDMALLOC) ? sym_oldmalloc :
7400 SET(need_major_by, need_major_by);
7404 (flags & GPR_FLAG_NEWOBJ) ? sym_newobj :
7405 (flags & GPR_FLAG_MALLOC) ? sym_malloc :
7406 (flags & GPR_FLAG_METHOD) ? sym_method :
7407 (flags & GPR_FLAG_CAPI) ? sym_capi :
7408 (flags & GPR_FLAG_STRESS) ? sym_stress :
7412 SET(have_finalizer, (flags & GPR_FLAG_HAVE_FINALIZE) ?
Qtrue :
Qfalse);
7413 SET(immediate_sweep, (flags & GPR_FLAG_IMMEDIATE_SWEEP) ?
Qtrue :
Qfalse);
7415 if (orig_flags == 0) {
7416 SET(state, gc_mode(
objspace) == gc_mode_none ? sym_none :
7417 gc_mode(
objspace) == gc_mode_marking ? sym_marking : sym_sweeping);
7420 SET(weak_references_count,
LONG2FIX(
objspace->profile.weak_references_count));
7421 SET(retained_weak_references_count,
LONG2FIX(
objspace->profile.retained_weak_references_count));
7433rb_gc_impl_latest_gc_info(
void *objspace_ptr,
VALUE key)
7435 rb_objspace_t *
objspace = objspace_ptr;
7437 return gc_info_decode(
objspace, key, 0);
7444 gc_stat_sym_marking_time,
7445 gc_stat_sym_sweeping_time,
7446 gc_stat_sym_heap_allocated_pages,
7447 gc_stat_sym_heap_empty_pages,
7448 gc_stat_sym_heap_allocatable_slots,
7449 gc_stat_sym_heap_available_slots,
7450 gc_stat_sym_heap_live_slots,
7451 gc_stat_sym_heap_free_slots,
7452 gc_stat_sym_heap_final_slots,
7453 gc_stat_sym_heap_marked_slots,
7454 gc_stat_sym_heap_eden_pages,
7455 gc_stat_sym_total_allocated_pages,
7456 gc_stat_sym_total_freed_pages,
7457 gc_stat_sym_total_allocated_objects,
7458 gc_stat_sym_total_freed_objects,
7459 gc_stat_sym_malloc_increase_bytes,
7460 gc_stat_sym_malloc_increase_bytes_limit,
7461 gc_stat_sym_minor_gc_count,
7462 gc_stat_sym_major_gc_count,
7463 gc_stat_sym_compact_count,
7464 gc_stat_sym_read_barrier_faults,
7465 gc_stat_sym_total_moved_objects,
7466 gc_stat_sym_remembered_wb_unprotected_objects,
7467 gc_stat_sym_remembered_wb_unprotected_objects_limit,
7468 gc_stat_sym_old_objects,
7469 gc_stat_sym_old_objects_limit,
7470#if RGENGC_ESTIMATE_OLDMALLOC
7471 gc_stat_sym_oldmalloc_increase_bytes,
7472 gc_stat_sym_oldmalloc_increase_bytes_limit,
7474 gc_stat_sym_weak_references_count,
7476 gc_stat_sym_total_generated_normal_object_count,
7477 gc_stat_sym_total_generated_shady_object_count,
7478 gc_stat_sym_total_shade_operation_count,
7479 gc_stat_sym_total_promoted_count,
7480 gc_stat_sym_total_remembered_normal_object_count,
7481 gc_stat_sym_total_remembered_shady_object_count,
7486static VALUE gc_stat_symbols[gc_stat_sym_last];
7489setup_gc_stat_symbols(
void)
7491 if (gc_stat_symbols[0] == 0) {
7492#define S(s) gc_stat_symbols[gc_stat_sym_##s] = ID2SYM(rb_intern_const(#s))
7497 S(heap_allocated_pages);
7498 S(heap_empty_pages);
7499 S(heap_allocatable_slots);
7500 S(heap_available_slots);
7503 S(heap_final_slots);
7504 S(heap_marked_slots);
7506 S(total_allocated_pages);
7507 S(total_freed_pages);
7508 S(total_allocated_objects);
7509 S(total_freed_objects);
7510 S(malloc_increase_bytes);
7511 S(malloc_increase_bytes_limit);
7515 S(read_barrier_faults);
7516 S(total_moved_objects);
7517 S(remembered_wb_unprotected_objects);
7518 S(remembered_wb_unprotected_objects_limit);
7520 S(old_objects_limit);
7521#if RGENGC_ESTIMATE_OLDMALLOC
7522 S(oldmalloc_increase_bytes);
7523 S(oldmalloc_increase_bytes_limit);
7525 S(weak_references_count);
7527 S(total_generated_normal_object_count);
7528 S(total_generated_shady_object_count);
7529 S(total_shade_operation_count);
7530 S(total_promoted_count);
7531 S(total_remembered_normal_object_count);
7532 S(total_remembered_shady_object_count);
7539ns_to_ms(uint64_t ns)
7541 return ns / (1000 * 1000);
7544static void malloc_increase_local_flush(rb_objspace_t *
objspace);
7547rb_gc_impl_stat(
void *objspace_ptr,
VALUE hash_or_sym)
7549 rb_objspace_t *
objspace = objspace_ptr;
7552 setup_gc_stat_symbols();
7554 ractor_cache_flush_count(
objspace, rb_gc_get_ractor_newobj_cache());
7555 malloc_increase_local_flush(
objspace);
7564 rb_bug(
"non-hash or symbol given");
7567#define SET(name, attr) \
7568 if (key == gc_stat_symbols[gc_stat_sym_##name]) \
7569 return SIZET2NUM(attr); \
7570 else if (hash != Qnil) \
7571 rb_hash_aset(hash, gc_stat_symbols[gc_stat_sym_##name], SIZET2NUM(attr));
7573 SET(count,
objspace->profile.count);
7574 SET(time, (
size_t)ns_to_ms(
objspace->profile.marking_time_ns +
objspace->profile.sweeping_time_ns));
7575 SET(marking_time, (
size_t)ns_to_ms(
objspace->profile.marking_time_ns));
7576 SET(sweeping_time, (
size_t)ns_to_ms(
objspace->profile.sweeping_time_ns));
7579 SET(heap_allocated_pages, rb_darray_size(
objspace->heap_pages.sorted));
7580 SET(heap_empty_pages,
objspace->empty_pages_count)
7581 SET(heap_allocatable_slots,
objspace->heap_pages.allocatable_slots);
7582 SET(heap_available_slots, objspace_available_slots(
objspace));
7583 SET(heap_live_slots, objspace_live_slots(
objspace));
7584 SET(heap_free_slots, objspace_free_slots(
objspace));
7585 SET(heap_final_slots, total_final_slots_count(
objspace));
7586 SET(heap_marked_slots,
objspace->marked_slots);
7587 SET(heap_eden_pages, heap_eden_total_pages(
objspace));
7588 SET(total_allocated_pages,
objspace->heap_pages.allocated_pages);
7589 SET(total_freed_pages,
objspace->heap_pages.freed_pages);
7590 SET(total_allocated_objects, total_allocated_objects(
objspace));
7591 SET(total_freed_objects, total_freed_objects(
objspace));
7592 SET(malloc_increase_bytes, malloc_increase);
7593 SET(malloc_increase_bytes_limit, malloc_limit);
7594 SET(minor_gc_count,
objspace->profile.minor_gc_count);
7595 SET(major_gc_count,
objspace->profile.major_gc_count);
7596 SET(compact_count,
objspace->profile.compact_count);
7597 SET(read_barrier_faults,
objspace->profile.read_barrier_faults);
7598 SET(total_moved_objects,
objspace->rcompactor.total_moved);
7599 SET(remembered_wb_unprotected_objects,
objspace->rgengc.uncollectible_wb_unprotected_objects);
7600 SET(remembered_wb_unprotected_objects_limit,
objspace->rgengc.uncollectible_wb_unprotected_objects_limit);
7601 SET(old_objects,
objspace->rgengc.old_objects);
7602 SET(old_objects_limit,
objspace->rgengc.old_objects_limit);
7603#if RGENGC_ESTIMATE_OLDMALLOC
7604 SET(oldmalloc_increase_bytes,
objspace->malloc_counters.oldmalloc_increase);
7605 SET(oldmalloc_increase_bytes_limit,
objspace->rgengc.oldmalloc_increase_limit);
7609 SET(total_generated_normal_object_count,
objspace->profile.total_generated_normal_object_count);
7610 SET(total_generated_shady_object_count,
objspace->profile.total_generated_shady_object_count);
7611 SET(total_shade_operation_count,
objspace->profile.total_shade_operation_count);
7612 SET(total_promoted_count,
objspace->profile.total_promoted_count);
7613 SET(total_remembered_normal_object_count,
objspace->profile.total_remembered_normal_object_count);
7614 SET(total_remembered_shady_object_count,
objspace->profile.total_remembered_shady_object_count);
7623#if defined(RGENGC_PROFILE) && RGENGC_PROFILE >= 2
7625 gc_count_add_each_types(hash,
"generated_normal_object_count_types",
objspace->profile.generated_normal_object_count_types);
7626 gc_count_add_each_types(hash,
"generated_shady_object_count_types",
objspace->profile.generated_shady_object_count_types);
7627 gc_count_add_each_types(hash,
"shade_operation_count_types",
objspace->profile.shade_operation_count_types);
7628 gc_count_add_each_types(hash,
"promoted_types",
objspace->profile.promoted_types);
7629 gc_count_add_each_types(hash,
"remembered_normal_object_count_types",
objspace->profile.remembered_normal_object_count_types);
7630 gc_count_add_each_types(hash,
"remembered_shady_object_count_types",
objspace->profile.remembered_shady_object_count_types);
7637enum gc_stat_heap_sym {
7638 gc_stat_heap_sym_slot_size,
7639 gc_stat_heap_sym_heap_live_slots,
7640 gc_stat_heap_sym_heap_free_slots,
7641 gc_stat_heap_sym_heap_final_slots,
7642 gc_stat_heap_sym_heap_eden_pages,
7643 gc_stat_heap_sym_heap_eden_slots,
7644 gc_stat_heap_sym_total_allocated_pages,
7645 gc_stat_heap_sym_force_major_gc_count,
7646 gc_stat_heap_sym_force_incremental_marking_finish_count,
7647 gc_stat_heap_sym_total_allocated_objects,
7648 gc_stat_heap_sym_total_freed_objects,
7649 gc_stat_heap_sym_last
7652static VALUE gc_stat_heap_symbols[gc_stat_heap_sym_last];
7655setup_gc_stat_heap_symbols(
void)
7657 if (gc_stat_heap_symbols[0] == 0) {
7658#define S(s) gc_stat_heap_symbols[gc_stat_heap_sym_##s] = ID2SYM(rb_intern_const(#s))
7662 S(heap_final_slots);
7665 S(total_allocated_pages);
7666 S(force_major_gc_count);
7667 S(force_incremental_marking_finish_count);
7668 S(total_allocated_objects);
7669 S(total_freed_objects);
7675stat_one_heap(rb_heap_t *heap,
VALUE hash,
VALUE key)
7677#define SET(name, attr) \
7678 if (key == gc_stat_heap_symbols[gc_stat_heap_sym_##name]) \
7679 return SIZET2NUM(attr); \
7680 else if (hash != Qnil) \
7681 rb_hash_aset(hash, gc_stat_heap_symbols[gc_stat_heap_sym_##name], SIZET2NUM(attr));
7683 SET(slot_size, heap->slot_size);
7684 SET(heap_live_slots, heap->total_allocated_objects - heap->total_freed_objects - heap->final_slots_count);
7685 SET(heap_free_slots, heap->total_slots - (heap->total_allocated_objects - heap->total_freed_objects));
7686 SET(heap_final_slots, heap->final_slots_count);
7687 SET(heap_eden_pages, heap->total_pages);
7688 SET(heap_eden_slots, heap->total_slots);
7689 SET(total_allocated_pages, heap->total_allocated_pages);
7690 SET(force_major_gc_count, heap->force_major_gc_count);
7691 SET(force_incremental_marking_finish_count, heap->force_incremental_marking_finish_count);
7692 SET(total_allocated_objects, heap->total_allocated_objects);
7693 SET(total_freed_objects, heap->total_freed_objects);
7705rb_gc_impl_stat_heap(
void *objspace_ptr,
VALUE heap_name,
VALUE hash_or_sym)
7707 rb_objspace_t *
objspace = objspace_ptr;
7709 ractor_cache_flush_count(
objspace, rb_gc_get_ractor_newobj_cache());
7711 setup_gc_stat_heap_symbols();
7713 if (
NIL_P(heap_name)) {
7715 rb_bug(
"non-hash given");
7718 for (
int i = 0; i < HEAP_COUNT; i++) {
7722 rb_hash_aset(hash_or_sym,
INT2FIX(i), hash);
7725 stat_one_heap(&heaps[i], hash,
Qnil);
7729 int heap_idx =
FIX2INT(heap_name);
7731 if (heap_idx < 0 || heap_idx >= HEAP_COUNT) {
7732 rb_raise(rb_eArgError,
"size pool index out of range");
7736 return stat_one_heap(&heaps[heap_idx],
Qnil, hash_or_sym);
7739 return stat_one_heap(&heaps[heap_idx], hash_or_sym,
Qnil);
7742 rb_bug(
"non-hash or symbol given");
7746 rb_bug(
"heap_name must be nil or an Integer");
7758#define RBOOL(v) (v ? Qtrue : Qfalse)
7762rb_gc_impl_config_get(
void *objspace_ptr)
7764#define sym(name) ID2SYM(rb_intern_const(name))
7765 rb_objspace_t *
objspace = objspace_ptr;
7768 rb_hash_aset(hash, sym(
"rgengc_allow_full_mark"), RBOOL(gc_config_full_mark_val));
7776 rb_objspace_t *
objspace = (rb_objspace_t *)data;
7777 if (
rb_sym2id(key) == rb_intern(
"rgengc_allow_full_mark")) {
7779 gc_config_full_mark_set(
RTEST(value));
7785rb_gc_impl_config_set(
void *objspace_ptr,
VALUE hash)
7787 rb_objspace_t *
objspace = objspace_ptr;
7790 rb_raise(rb_eArgError,
"expected keyword arguments");
7797rb_gc_impl_stress_get(
void *objspace_ptr)
7799 rb_objspace_t *
objspace = objspace_ptr;
7800 return ruby_gc_stress_mode;
7804rb_gc_impl_stress_set(
void *objspace_ptr,
VALUE flag)
7806 rb_objspace_t *
objspace = objspace_ptr;
7813get_envparam_size(
const char *name,
size_t *default_value,
size_t lower_bound)
7815 const char *ptr = getenv(name);
7818 if (ptr != NULL && *ptr) {
7821#if SIZEOF_SIZE_T == SIZEOF_LONG_LONG
7822 val = strtoll(ptr, &end, 0);
7824 val = strtol(ptr, &end, 0);
7836 unit = 1024*1024*1024;
7840 while (*end && isspace((
unsigned char)*end)) end++;
7842 if (
RTEST(
ruby_verbose)) fprintf(stderr,
"invalid string for %s: %s\n", name, ptr);
7846 if (val < -(ssize_t)(SIZE_MAX / 2 / unit) || (ssize_t)(SIZE_MAX / 2 / unit) < val) {
7847 if (
RTEST(
ruby_verbose)) fprintf(stderr,
"%s=%s is ignored because it overflows\n", name, ptr);
7852 if (val > 0 && (
size_t)val > lower_bound) {
7854 fprintf(stderr,
"%s=%"PRIdSIZE
" (default value: %"PRIuSIZE
")\n", name, val, *default_value);
7856 *default_value = (size_t)val;
7861 fprintf(stderr,
"%s=%"PRIdSIZE
" (default value: %"PRIuSIZE
") is ignored because it must be greater than %"PRIuSIZE
".\n",
7862 name, val, *default_value, lower_bound);
7871get_envparam_double(
const char *name,
double *default_value,
double lower_bound,
double upper_bound,
int accept_zero)
7873 const char *ptr = getenv(name);
7876 if (ptr != NULL && *ptr) {
7879 if (!*ptr || *end) {
7880 if (
RTEST(
ruby_verbose)) fprintf(stderr,
"invalid string for %s: %s\n", name, ptr);
7884 if (accept_zero && val == 0.0) {
7887 else if (val <= lower_bound) {
7889 fprintf(stderr,
"%s=%f (default value: %f) is ignored because it must be greater than %f.\n",
7890 name, val, *default_value, lower_bound);
7893 else if (upper_bound != 0.0 &&
7894 val > upper_bound) {
7896 fprintf(stderr,
"%s=%f (default value: %f) is ignored because it must be lower than %f.\n",
7897 name, val, *default_value, upper_bound);
7907 if (
RTEST(
ruby_verbose)) fprintf(stderr,
"%s=%f (default value: %f)\n", name, val, *default_value);
7908 *default_value = val;
7953rb_gc_impl_set_params(
void *objspace_ptr)
7955 rb_objspace_t *
objspace = objspace_ptr;
7957 if (get_envparam_size(
"RUBY_GC_HEAP_FREE_SLOTS", &gc_params.heap_free_slots, 0)) {
7961 for (
int i = 0; i < HEAP_COUNT; i++) {
7962 char env_key[
sizeof(
"RUBY_GC_HEAP_" "_INIT_SLOTS") +
DECIMAL_SIZE_OF_BITS(
sizeof(
int) * CHAR_BIT)];
7963 snprintf(env_key,
sizeof(env_key),
"RUBY_GC_HEAP_%d_INIT_SLOTS", i);
7965 get_envparam_size(env_key, &gc_params.heap_init_slots[i], 0);
7968 get_envparam_double(
"RUBY_GC_HEAP_GROWTH_FACTOR", &gc_params.growth_factor, 1.0, 0.0, FALSE);
7969 get_envparam_size (
"RUBY_GC_HEAP_GROWTH_MAX_SLOTS", &gc_params.growth_max_slots, 0);
7970 get_envparam_double(
"RUBY_GC_HEAP_FREE_SLOTS_MIN_RATIO", &gc_params.heap_free_slots_min_ratio,
7972 get_envparam_double(
"RUBY_GC_HEAP_FREE_SLOTS_MAX_RATIO", &gc_params.heap_free_slots_max_ratio,
7973 gc_params.heap_free_slots_min_ratio, 1.0, FALSE);
7974 get_envparam_double(
"RUBY_GC_HEAP_FREE_SLOTS_GOAL_RATIO", &gc_params.heap_free_slots_goal_ratio,
7975 gc_params.heap_free_slots_min_ratio, gc_params.heap_free_slots_max_ratio, TRUE);
7976 get_envparam_double(
"RUBY_GC_HEAP_OLDOBJECT_LIMIT_FACTOR", &gc_params.oldobject_limit_factor, 0.0, 0.0, TRUE);
7977 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);
7979 if (get_envparam_size(
"RUBY_GC_MALLOC_LIMIT", &gc_params.malloc_limit_min, 0)) {
7980 malloc_limit = gc_params.malloc_limit_min;
7982 get_envparam_size (
"RUBY_GC_MALLOC_LIMIT_MAX", &gc_params.malloc_limit_max, 0);
7983 if (!gc_params.malloc_limit_max) {
7984 gc_params.malloc_limit_max = SIZE_MAX;
7986 get_envparam_double(
"RUBY_GC_MALLOC_LIMIT_GROWTH_FACTOR", &gc_params.malloc_limit_growth_factor, 1.0, 0.0, FALSE);
7988#if RGENGC_ESTIMATE_OLDMALLOC
7989 if (get_envparam_size(
"RUBY_GC_OLDMALLOC_LIMIT", &gc_params.oldmalloc_limit_min, 0)) {
7990 objspace->rgengc.oldmalloc_increase_limit = gc_params.oldmalloc_limit_min;
7992 get_envparam_size (
"RUBY_GC_OLDMALLOC_LIMIT_MAX", &gc_params.oldmalloc_limit_max, 0);
7993 get_envparam_double(
"RUBY_GC_OLDMALLOC_LIMIT_GROWTH_FACTOR", &gc_params.oldmalloc_limit_growth_factor, 1.0, 0.0, FALSE);
7998objspace_malloc_size(rb_objspace_t *
objspace,
void *ptr,
size_t hint)
8000#ifdef HAVE_MALLOC_USABLE_SIZE
8002 hint = malloc_usable_size(ptr);
8009 MEMOP_TYPE_MALLOC = 0,
8015atomic_sub_nounderflow(
size_t *var,
size_t sub)
8017 if (sub == 0)
return;
8021 if (val < sub) sub = val;
8026#define gc_stress_full_mark_after_malloc_p() \
8027 (FIXNUM_P(ruby_gc_stress_mode) && (FIX2LONG(ruby_gc_stress_mode) & (1<<gc_stress_full_mark_after_malloc)))
8030objspace_malloc_gc_stress(rb_objspace_t *
objspace)
8033 unsigned int reason = (GPR_FLAG_IMMEDIATE_MARK | GPR_FLAG_IMMEDIATE_SWEEP |
8034 GPR_FLAG_STRESS | GPR_FLAG_MALLOC);
8036 if (gc_stress_full_mark_after_malloc_p()) {
8037 reason |= GPR_FLAG_FULL_MARK;
8039 garbage_collect_with_gvl(
objspace, reason);
8044malloc_increase_commit(rb_objspace_t *
objspace,
size_t new_size,
size_t old_size)
8046 if (new_size > old_size) {
8048#if RGENGC_ESTIMATE_OLDMALLOC
8053 atomic_sub_nounderflow(&malloc_increase, old_size - new_size);
8054#if RGENGC_ESTIMATE_OLDMALLOC
8055 atomic_sub_nounderflow(&
objspace->malloc_counters.oldmalloc_increase, old_size - new_size);
8060#if USE_MALLOC_INCREASE_LOCAL
8062malloc_increase_local_flush(rb_objspace_t *
objspace)
8064 int delta = malloc_increase_local;
8065 if (delta == 0)
return;
8067 malloc_increase_local = 0;
8069 malloc_increase_commit(
objspace, (
size_t)delta, 0);
8072 malloc_increase_commit(
objspace, 0, (
size_t)(-delta));
8077malloc_increase_local_flush(rb_objspace_t *
objspace)
8083objspace_malloc_increase_report(rb_objspace_t *
objspace,
void *mem,
size_t new_size,
size_t old_size,
enum memop_type
type,
bool gc_allowed)
8085 if (0) fprintf(stderr,
"increase - ptr: %p, type: %s, new_size: %"PRIdSIZE
", old_size: %"PRIdSIZE
"\n",
8087 type == MEMOP_TYPE_MALLOC ?
"malloc" :
8088 type == MEMOP_TYPE_FREE ?
"free " :
8089 type == MEMOP_TYPE_REALLOC ?
"realloc":
"error",
8090 new_size, old_size);
8095objspace_malloc_increase_body(rb_objspace_t *
objspace,
void *mem,
size_t new_size,
size_t old_size,
enum memop_type
type,
bool gc_allowed)
8097#if USE_MALLOC_INCREASE_LOCAL
8098 if (new_size < GC_MALLOC_INCREASE_LOCAL_THRESHOLD &&
8099 old_size < GC_MALLOC_INCREASE_LOCAL_THRESHOLD) {
8100 malloc_increase_local += (int)new_size - (
int)old_size;
8102 if (malloc_increase_local >= GC_MALLOC_INCREASE_LOCAL_THRESHOLD ||
8103 malloc_increase_local <= -GC_MALLOC_INCREASE_LOCAL_THRESHOLD) {
8104 malloc_increase_local_flush(
objspace);
8108 malloc_increase_local_flush(
objspace);
8109 malloc_increase_commit(
objspace, new_size, old_size);
8112 malloc_increase_commit(
objspace, new_size, old_size);
8115 if (
type == MEMOP_TYPE_MALLOC && gc_allowed) {
8122 garbage_collect_with_gvl(
objspace, GPR_FLAG_MALLOC);
8126#if MALLOC_ALLOCATED_SIZE
8127 if (new_size >= old_size) {
8131 size_t dec_size = old_size - new_size;
8133#if MALLOC_ALLOCATED_SIZE_CHECK
8134 size_t allocated_size =
objspace->malloc_params.allocated_size;
8135 if (allocated_size < dec_size) {
8136 rb_bug(
"objspace_malloc_increase: underflow malloc_params.allocated_size.");
8139 atomic_sub_nounderflow(&
objspace->malloc_params.allocated_size, dec_size);
8143 case MEMOP_TYPE_MALLOC:
8146 case MEMOP_TYPE_FREE:
8148 size_t allocations =
objspace->malloc_params.allocations;
8149 if (allocations > 0) {
8150 atomic_sub_nounderflow(&
objspace->malloc_params.allocations, 1);
8152#if MALLOC_ALLOCATED_SIZE_CHECK
8154 GC_ASSERT(
objspace->malloc_params.allocations > 0);
8159 case MEMOP_TYPE_REALLOC:
break;
8165#define objspace_malloc_increase(...) \
8166 for (bool malloc_increase_done = objspace_malloc_increase_report(__VA_ARGS__); \
8167 !malloc_increase_done; \
8168 malloc_increase_done = objspace_malloc_increase_body(__VA_ARGS__))
8175objspace_malloc_prepare(rb_objspace_t *
objspace,
size_t size)
8177 if (size == 0) size = 1;
8179#if CALC_EXACT_MALLOC_SIZE
8187malloc_during_gc_p(rb_objspace_t *
objspace)
8197objspace_malloc_fixup(rb_objspace_t *
objspace,
void *mem,
size_t size,
bool gc_allowed)
8199 size = objspace_malloc_size(
objspace, mem, size);
8200 objspace_malloc_increase(
objspace, mem, size, 0, MEMOP_TYPE_MALLOC, gc_allowed) {}
8202#if CALC_EXACT_MALLOC_SIZE
8213#if defined(__GNUC__) && RUBY_DEBUG
8214#define RB_BUG_INSTEAD_OF_RB_MEMERROR 1
8217#ifndef RB_BUG_INSTEAD_OF_RB_MEMERROR
8218# define RB_BUG_INSTEAD_OF_RB_MEMERROR 0
8221#define GC_MEMERROR(...) \
8222 ((RB_BUG_INSTEAD_OF_RB_MEMERROR+0) ? rb_bug("" __VA_ARGS__) : (void)0)
8224#define TRY_WITH_GC(siz, expr) do { \
8225 const gc_profile_record_flag gpr = \
8226 GPR_FLAG_FULL_MARK | \
8227 GPR_FLAG_IMMEDIATE_MARK | \
8228 GPR_FLAG_IMMEDIATE_SWEEP | \
8230 objspace_malloc_gc_stress(objspace); \
8232 if (RB_LIKELY((expr))) { \
8235 else if (gc_allowed && !garbage_collect_with_gvl(objspace, gpr)) { \
8237 GC_MEMERROR("TRY_WITH_GC: could not GC"); \
8239 else if ((expr)) { \
8243 GC_MEMERROR("TRY_WITH_GC: could not allocate:" \
8244 "%"PRIdSIZE" bytes for %s", \
8250check_malloc_not_in_gc(rb_objspace_t *
objspace,
const char *msg)
8252 if (RB_UNLIKELY(malloc_during_gc_p(
objspace))) {
8255 rb_bug(
"Cannot %s during GC", msg);
8260rb_gc_impl_free(
void *objspace_ptr,
void *ptr,
size_t old_size)
8262 rb_objspace_t *
objspace = objspace_ptr;
8271#if CALC_EXACT_MALLOC_SIZE
8274 old_size = info->size;
8276 old_size = objspace_malloc_size(
objspace, ptr, old_size);
8278 objspace_malloc_increase(
objspace, ptr, 0, old_size, MEMOP_TYPE_FREE,
true) {
8281 RB_DEBUG_COUNTER_INC(heap_xfree);
8286rb_gc_impl_malloc(
void *objspace_ptr,
size_t size,
bool gc_allowed)
8288 rb_objspace_t *
objspace = objspace_ptr;
8289 check_malloc_not_in_gc(
objspace,
"malloc");
8293 size = objspace_malloc_prepare(
objspace, size);
8294 TRY_WITH_GC(size, mem = malloc(size));
8295 RB_DEBUG_COUNTER_INC(heap_xmalloc);
8296 if (!mem)
return mem;
8297 return objspace_malloc_fixup(
objspace, mem, size, gc_allowed);
8301rb_gc_impl_calloc(
void *objspace_ptr,
size_t size,
bool gc_allowed)
8303 rb_objspace_t *
objspace = objspace_ptr;
8305 if (RB_UNLIKELY(malloc_during_gc_p(
objspace))) {
8306 rb_warn(
"calloc during GC detected, this could cause crashes if it triggers another GC");
8307#if RGENGC_CHECK_MODE || RUBY_DEBUG
8308 rb_bug(
"Cannot calloc during GC");
8314 size = objspace_malloc_prepare(
objspace, size);
8315 TRY_WITH_GC(size, mem = calloc1(size));
8316 if (!mem)
return mem;
8317 return objspace_malloc_fixup(
objspace, mem, size, gc_allowed);
8321rb_gc_impl_realloc(
void *objspace_ptr,
void *ptr,
size_t new_size,
size_t old_size,
bool gc_allowed)
8323 rb_objspace_t *
objspace = objspace_ptr;
8325 check_malloc_not_in_gc(
objspace,
"realloc");
8329 if (!ptr)
return rb_gc_impl_malloc(
objspace, new_size, gc_allowed);
8336 if (new_size == 0) {
8337 if ((mem = rb_gc_impl_malloc(
objspace, 0, gc_allowed)) != NULL) {
8360 rb_gc_impl_free(
objspace, ptr, old_size);
8374#if CALC_EXACT_MALLOC_SIZE
8379 old_size = info->size;
8383 old_size = objspace_malloc_size(
objspace, ptr, old_size);
8385 if (!mem)
return mem;
8386 new_size = objspace_malloc_size(
objspace, mem, new_size);
8388#if CALC_EXACT_MALLOC_SIZE
8391 info->size = new_size;
8396 objspace_malloc_increase(
objspace, mem, new_size, old_size, MEMOP_TYPE_REALLOC, gc_allowed);
8398 RB_DEBUG_COUNTER_INC(heap_xrealloc);
8403rb_gc_impl_adjust_memory_usage(
void *objspace_ptr, ssize_t diff)
8405 rb_objspace_t *
objspace = objspace_ptr;
8408 objspace_malloc_increase(
objspace, 0, diff, 0, MEMOP_TYPE_REALLOC,
true);
8410 else if (diff < 0) {
8411 objspace_malloc_increase(
objspace, 0, 0, -diff, MEMOP_TYPE_REALLOC,
true);
8420#define GC_PROFILE_RECORD_DEFAULT_SIZE 100
8423current_process_time(
struct timespec *ts)
8425#if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_PROCESS_CPUTIME_ID)
8427 static int try_clock_gettime = 1;
8428 if (try_clock_gettime && clock_gettime(CLOCK_PROCESS_CPUTIME_ID, ts) == 0) {
8432 try_clock_gettime = 0;
8439 struct rusage usage;
8441 if (getrusage(RUSAGE_SELF, &usage) == 0) {
8442 time = usage.ru_utime;
8443 ts->tv_sec = time.tv_sec;
8444 ts->tv_nsec = (int32_t)time.tv_usec * 1000;
8452 FILETIME creation_time, exit_time, kernel_time, user_time;
8455 if (GetProcessTimes(GetCurrentProcess(),
8456 &creation_time, &exit_time, &kernel_time, &user_time) != 0) {
8457 memcpy(&ui, &user_time,
sizeof(FILETIME));
8458#define PER100NSEC (uint64_t)(1000 * 1000 * 10)
8459 ts->tv_nsec = (long)(ui.QuadPart % PER100NSEC);
8460 ts->tv_sec = (time_t)(ui.QuadPart / PER100NSEC);
8473 if (current_process_time(&ts)) {
8474 return ts.tv_sec + ts.tv_nsec * 1e-9;
8483gc_prof_setup_new_record(rb_objspace_t *
objspace,
unsigned int reason)
8486 size_t index =
objspace->profile.next_index;
8493 objspace->profile.size = GC_PROFILE_RECORD_DEFAULT_SIZE;
8496 if (index >=
objspace->profile.size) {
8504 rb_bug(
"gc_profile malloc or realloc miss");
8510 record->flags = reason | (ruby_gc_stressful ? GPR_FLAG_STRESS : 0);
8511#if MALLOC_ALLOCATED_SIZE
8512 record->allocated_size = malloc_allocated_size;
8514#if GC_PROFILE_MORE_DETAIL && GC_PROFILE_DETAIL_MEMORY
8517 struct rusage usage;
8518 if (getrusage(RUSAGE_SELF, &usage) == 0) {
8519 record->maxrss = usage.ru_maxrss;
8520 record->minflt = usage.ru_minflt;
8521 record->majflt = usage.ru_majflt;
8530gc_prof_timer_start(rb_objspace_t *
objspace)
8534#if GC_PROFILE_MORE_DETAIL
8535 record->prepare_time =
objspace->profile.prepare_time;
8537 record->gc_time = 0;
8538 record->gc_invoke_time = getrusage_time();
8543elapsed_time_from(
double time)
8545 double now = getrusage_time();
8555gc_prof_timer_stop(rb_objspace_t *
objspace)
8559 record->gc_time = elapsed_time_from(record->gc_invoke_time);
8560 record->gc_invoke_time -=
objspace->profile.invoke_time;
8564#ifdef BUILDING_MODULAR_GC
8565# define RUBY_DTRACE_GC_HOOK(name)
8567# define RUBY_DTRACE_GC_HOOK(name) \
8568 do {if (RUBY_DTRACE_GC_##name##_ENABLED()) RUBY_DTRACE_GC_##name();} while (0)
8572gc_prof_mark_timer_start(rb_objspace_t *
objspace)
8574 RUBY_DTRACE_GC_HOOK(MARK_BEGIN);
8575#if GC_PROFILE_MORE_DETAIL
8577 gc_prof_record(
objspace)->gc_mark_time = getrusage_time();
8583gc_prof_mark_timer_stop(rb_objspace_t *
objspace)
8585 RUBY_DTRACE_GC_HOOK(MARK_END);
8586#if GC_PROFILE_MORE_DETAIL
8589 record->gc_mark_time = elapsed_time_from(record->gc_mark_time);
8595gc_prof_sweep_timer_start(rb_objspace_t *
objspace)
8597 RUBY_DTRACE_GC_HOOK(SWEEP_BEGIN);
8601 if (record->gc_time > 0 || GC_PROFILE_MORE_DETAIL) {
8602 objspace->profile.gc_sweep_start_time = getrusage_time();
8608gc_prof_sweep_timer_stop(rb_objspace_t *
objspace)
8610 RUBY_DTRACE_GC_HOOK(SWEEP_END);
8616 if (record->gc_time > 0) {
8617 sweep_time = elapsed_time_from(
objspace->profile.gc_sweep_start_time);
8619 record->gc_time += sweep_time;
8621 else if (GC_PROFILE_MORE_DETAIL) {
8622 sweep_time = elapsed_time_from(
objspace->profile.gc_sweep_start_time);
8625#if GC_PROFILE_MORE_DETAIL
8626 record->gc_sweep_time += sweep_time;
8627 if (heap_pages_deferred_final) record->flags |= GPR_FLAG_HAVE_FINALIZE;
8629 if (heap_pages_deferred_final)
objspace->profile.latest_gc_info |= GPR_FLAG_HAVE_FINALIZE;
8634gc_prof_set_malloc_info(rb_objspace_t *
objspace)
8636#if GC_PROFILE_MORE_DETAIL
8639 record->allocate_increase = malloc_increase;
8640 record->allocate_limit = malloc_limit;
8646gc_prof_set_heap_info(rb_objspace_t *
objspace)
8650 size_t live =
objspace->profile.total_allocated_objects_at_gc_start - total_freed_objects(
objspace);
8651 size_t total =
objspace->profile.heap_used_at_gc_start * HEAP_PAGE_OBJ_LIMIT;
8653#if GC_PROFILE_MORE_DETAIL
8654 record->heap_use_pages =
objspace->profile.heap_used_at_gc_start;
8655 record->heap_live_objects = live;
8656 record->heap_free_objects = total - live;
8659 record->heap_total_objects = total;
8660 record->heap_use_size = live * BASE_SLOT_SIZE;
8661 record->heap_total_size = total * BASE_SLOT_SIZE;
8676 rb_objspace_t *
objspace = rb_gc_get_objspace();
8677 void *p =
objspace->profile.records;
8681 objspace->profile.current_record = 0;
8737gc_profile_record_get(
VALUE _)
8742 rb_objspace_t *
objspace = rb_gc_get_objspace();
8748 for (i =0; i <
objspace->profile.next_index; i++) {
8753 rb_hash_aset(prof,
ID2SYM(rb_intern(
"GC_TIME")),
DBL2NUM(record->gc_time));
8754 rb_hash_aset(prof,
ID2SYM(rb_intern(
"GC_INVOKE_TIME")),
DBL2NUM(record->gc_invoke_time));
8755 rb_hash_aset(prof,
ID2SYM(rb_intern(
"HEAP_USE_SIZE")),
SIZET2NUM(record->heap_use_size));
8756 rb_hash_aset(prof,
ID2SYM(rb_intern(
"HEAP_TOTAL_SIZE")),
SIZET2NUM(record->heap_total_size));
8757 rb_hash_aset(prof,
ID2SYM(rb_intern(
"HEAP_TOTAL_OBJECTS")),
SIZET2NUM(record->heap_total_objects));
8758 rb_hash_aset(prof,
ID2SYM(rb_intern(
"MOVED_OBJECTS")),
SIZET2NUM(record->moved_objects));
8759 rb_hash_aset(prof,
ID2SYM(rb_intern(
"GC_IS_MARKED")),
Qtrue);
8760#if GC_PROFILE_MORE_DETAIL
8761 rb_hash_aset(prof,
ID2SYM(rb_intern(
"GC_MARK_TIME")),
DBL2NUM(record->gc_mark_time));
8762 rb_hash_aset(prof,
ID2SYM(rb_intern(
"GC_SWEEP_TIME")),
DBL2NUM(record->gc_sweep_time));
8763 rb_hash_aset(prof,
ID2SYM(rb_intern(
"ALLOCATE_INCREASE")),
SIZET2NUM(record->allocate_increase));
8764 rb_hash_aset(prof,
ID2SYM(rb_intern(
"ALLOCATE_LIMIT")),
SIZET2NUM(record->allocate_limit));
8765 rb_hash_aset(prof,
ID2SYM(rb_intern(
"HEAP_USE_PAGES")),
SIZET2NUM(record->heap_use_pages));
8766 rb_hash_aset(prof,
ID2SYM(rb_intern(
"HEAP_LIVE_OBJECTS")),
SIZET2NUM(record->heap_live_objects));
8767 rb_hash_aset(prof,
ID2SYM(rb_intern(
"HEAP_FREE_OBJECTS")),
SIZET2NUM(record->heap_free_objects));
8769 rb_hash_aset(prof,
ID2SYM(rb_intern(
"REMOVING_OBJECTS")),
SIZET2NUM(record->removing_objects));
8770 rb_hash_aset(prof,
ID2SYM(rb_intern(
"EMPTY_OBJECTS")),
SIZET2NUM(record->empty_objects));
8772 rb_hash_aset(prof,
ID2SYM(rb_intern(
"HAVE_FINALIZE")), (record->flags & GPR_FLAG_HAVE_FINALIZE) ?
Qtrue :
Qfalse);
8775#if RGENGC_PROFILE > 0
8776 rb_hash_aset(prof,
ID2SYM(rb_intern(
"OLD_OBJECTS")),
SIZET2NUM(record->old_objects));
8777 rb_hash_aset(prof,
ID2SYM(rb_intern(
"REMEMBERED_NORMAL_OBJECTS")),
SIZET2NUM(record->remembered_normal_objects));
8778 rb_hash_aset(prof,
ID2SYM(rb_intern(
"REMEMBERED_SHADY_OBJECTS")),
SIZET2NUM(record->remembered_shady_objects));
8786#if GC_PROFILE_MORE_DETAIL
8787#define MAJOR_REASON_MAX 0x10
8790gc_profile_dump_major_reason(
unsigned int flags,
char *buff)
8792 unsigned int reason = flags & GPR_FLAG_MAJOR_MASK;
8795 if (reason == GPR_FLAG_NONE) {
8801 if (reason & GPR_FLAG_MAJOR_BY_##x) { \
8802 buff[i++] = #x[0]; \
8803 if (i >= MAJOR_REASON_MAX) rb_bug("gc_profile_dump_major_reason: overflow"); \
8809#if RGENGC_ESTIMATE_OLDMALLOC
8823 rb_objspace_t *
objspace = rb_gc_get_objspace();
8824 size_t count =
objspace->profile.next_index;
8825#ifdef MAJOR_REASON_MAX
8826 char reason_str[MAJOR_REASON_MAX];
8829 if (
objspace->profile.run && count ) {
8833 append(out, rb_sprintf(
"GC %"PRIuSIZE
" invokes.\n",
objspace->profile.count));
8834 append(out,
rb_str_new_cstr(
"Index Invoke Time(sec) Use Size(byte) Total Size(byte) Total Object GC Time(ms)\n"));
8836 for (i = 0; i < count; i++) {
8837 record = &
objspace->profile.records[i];
8838 append(out, rb_sprintf(
"%5"PRIuSIZE
" %19.3f %20"PRIuSIZE
" %20"PRIuSIZE
" %20"PRIuSIZE
" %30.20f\n",
8839 i+1, record->gc_invoke_time, record->heap_use_size,
8840 record->heap_total_size, record->heap_total_objects, record->gc_time*1000));
8843#if GC_PROFILE_MORE_DETAIL
8844 const char *str =
"\n\n" \
8846 "Prepare Time = Previously GC's rest sweep time\n"
8847 "Index Flags Allocate Inc. Allocate Limit"
8848#if CALC_EXACT_MALLOC_SIZE
8851 " Use Page Mark Time(ms) Sweep Time(ms) Prepare Time(ms) LivingObj FreeObj RemovedObj EmptyObj"
8853 " OldgenObj RemNormObj RemShadObj"
8855#if GC_PROFILE_DETAIL_MEMORY
8856 " MaxRSS(KB) MinorFLT MajorFLT"
8861 for (i = 0; i < count; i++) {
8862 record = &
objspace->profile.records[i];
8863 append(out, rb_sprintf(
"%5"PRIuSIZE
" %4s/%c/%6s%c %13"PRIuSIZE
" %15"PRIuSIZE
8864#
if CALC_EXACT_MALLOC_SIZE
8867 " %9"PRIuSIZE
" %17.12f %17.12f %17.12f %10"PRIuSIZE
" %10"PRIuSIZE
" %10"PRIuSIZE
" %10"PRIuSIZE
8869 "%10"PRIuSIZE
" %10"PRIuSIZE
" %10"PRIuSIZE
8871#
if GC_PROFILE_DETAIL_MEMORY
8877 gc_profile_dump_major_reason(record->flags, reason_str),
8878 (record->flags & GPR_FLAG_HAVE_FINALIZE) ?
'F' :
'.',
8879 (record->flags & GPR_FLAG_NEWOBJ) ?
"NEWOBJ" :
8880 (record->flags & GPR_FLAG_MALLOC) ?
"MALLOC" :
8881 (record->flags & GPR_FLAG_METHOD) ?
"METHOD" :
8882 (record->flags & GPR_FLAG_CAPI) ?
"CAPI__" :
"??????",
8883 (record->flags & GPR_FLAG_STRESS) ?
'!' :
' ',
8884 record->allocate_increase, record->allocate_limit,
8885#
if CALC_EXACT_MALLOC_SIZE
8886 record->allocated_size,
8888 record->heap_use_pages,
8889 record->gc_mark_time*1000,
8890 record->gc_sweep_time*1000,
8891 record->prepare_time*1000,
8893 record->heap_live_objects,
8894 record->heap_free_objects,
8895 record->removing_objects,
8896 record->empty_objects
8899 record->old_objects,
8900 record->remembered_normal_objects,
8901 record->remembered_shady_objects
8903#
if GC_PROFILE_DETAIL_MEMORY
8905 record->maxrss / 1024,
8928gc_profile_result(
VALUE _)
8945gc_profile_report(
int argc,
VALUE *argv,
VALUE self)
8950 gc_profile_dump_on(out, rb_io_write);
8963gc_profile_total_time(
VALUE self)
8966 rb_objspace_t *
objspace = rb_gc_get_objspace();
8970 size_t count =
objspace->profile.next_index;
8972 for (i = 0; i < count; i++) {
8973 time +=
objspace->profile.records[i].gc_time;
8987gc_profile_enable_get(
VALUE self)
8989 rb_objspace_t *
objspace = rb_gc_get_objspace();
9002gc_profile_enable(
VALUE _)
9004 rb_objspace_t *
objspace = rb_gc_get_objspace();
9006 objspace->profile.current_record = 0;
9019gc_profile_disable(
VALUE _)
9021 rb_objspace_t *
objspace = rb_gc_get_objspace();
9024 objspace->profile.current_record = 0;
9029rb_gc_verify_internal_consistency(
void)
9031 gc_verify_internal_consistency(rb_gc_get_objspace());
9045gc_verify_internal_consistency_m(
VALUE dummy)
9047 rb_gc_verify_internal_consistency();
9051#if GC_CAN_COMPILE_COMPACTION
9065 GC_ASSERT(GC_COMPACTION_SUPPORTED);
9067 ruby_enable_autocompact =
RTEST(v);
9069#if RGENGC_CHECK_MODE
9070 ruby_autocompact_compare_func = NULL;
9074 if (
id == rb_intern(
"empty")) {
9075 ruby_autocompact_compare_func = compare_free_slots;
9083# define gc_set_auto_compact rb_f_notimplement
9086#if GC_CAN_COMPILE_COMPACTION
9094gc_get_auto_compact(
VALUE _)
9099# define gc_get_auto_compact rb_f_notimplement
9102#if GC_CAN_COMPILE_COMPACTION
9128gc_compact_stats(
VALUE self)
9130 rb_objspace_t *
objspace = rb_gc_get_objspace();
9137 for (
size_t i = 0; i <
T_MASK; i++) {
9138 if (
objspace->rcompactor.considered_count_table[i]) {
9139 rb_hash_aset(considered, type_sym(i),
SIZET2NUM(
objspace->rcompactor.considered_count_table[i]));
9142 if (
objspace->rcompactor.moved_count_table[i]) {
9143 rb_hash_aset(moved, type_sym(i),
SIZET2NUM(
objspace->rcompactor.moved_count_table[i]));
9146 if (
objspace->rcompactor.moved_up_count_table[i]) {
9147 rb_hash_aset(moved_up, type_sym(i),
SIZET2NUM(
objspace->rcompactor.moved_up_count_table[i]));
9150 if (
objspace->rcompactor.moved_down_count_table[i]) {
9151 rb_hash_aset(moved_down, type_sym(i),
SIZET2NUM(
objspace->rcompactor.moved_down_count_table[i]));
9155 rb_hash_aset(h,
ID2SYM(rb_intern(
"considered")), considered);
9156 rb_hash_aset(h,
ID2SYM(rb_intern(
"moved")), moved);
9157 rb_hash_aset(h,
ID2SYM(rb_intern(
"moved_up")), moved_up);
9158 rb_hash_aset(h,
ID2SYM(rb_intern(
"moved_down")), moved_down);
9163# define gc_compact_stats rb_f_notimplement
9166#if GC_CAN_COMPILE_COMPACTION
9185gc_compact(
VALUE self)
9187 rb_objspace_t *
objspace = rb_gc_get_objspace();
9188 int full_marking_p = gc_config_full_mark_val;
9189 gc_config_full_mark_set(TRUE);
9192 rb_gc_impl_start(rb_gc_get_objspace(),
true,
true,
true,
true);
9193 gc_config_full_mark_set(full_marking_p);
9195 return gc_compact_stats(self);
9198# define gc_compact rb_f_notimplement
9201#if GC_CAN_COMPILE_COMPACTION
9202struct desired_compaction_pages_i_data {
9203 rb_objspace_t *objspace;
9204 size_t required_slots[HEAP_COUNT];
9208desired_compaction_pages_i(
struct heap_page *page,
void *data)
9210 struct desired_compaction_pages_i_data *tdata = data;
9211 rb_objspace_t *
objspace = tdata->objspace;
9213 VALUE vend = vstart + (
VALUE)(page->total_slots * page->heap->slot_size);
9216 for (
VALUE v = vstart; v != vend; v += page->heap->slot_size) {
9217 asan_unpoisoning_object(v) {
9220 rb_heap_t *dest_pool = gc_compact_destination_pool(
objspace, page->heap, v);
9221 size_t dest_pool_idx = dest_pool - heaps;
9222 tdata->required_slots[dest_pool_idx]++;
9246gc_verify_compaction_references(
int argc,
VALUE* argv,
VALUE self)
9248 static ID keywords[3] = {0};
9250 keywords[0] = rb_intern(
"toward");
9251 keywords[1] = rb_intern(
"double_heap");
9252 keywords[2] = rb_intern(
"expand_heap");
9259 int kwarg_count =
rb_get_kwargs(options, keywords, 0, 3, arguments);
9260 bool toward_empty = kwarg_count > 0 &&
SYMBOL_P(arguments[0]) &&
SYM2ID(arguments[0]) == rb_intern(
"empty");
9261 bool expand_heap = (kwarg_count > 1 &&
RTEST(arguments[1])) || (kwarg_count > 2 &&
RTEST(arguments[2]));
9263 rb_objspace_t *
objspace = rb_gc_get_objspace();
9266 rb_gc_impl_start(
objspace,
true,
true,
true,
false);
9268 unsigned int lev = RB_GC_VM_LOCK();
9274 struct desired_compaction_pages_i_data desired_compaction = {
9276 .required_slots = {0},
9279 objspace_each_pages(
objspace, desired_compaction_pages_i, &desired_compaction, TRUE);
9282 size_t max_existing_pages = 0;
9283 for (
int i = 0; i < HEAP_COUNT; i++) {
9284 rb_heap_t *heap = &heaps[i];
9285 max_existing_pages = MAX(max_existing_pages, heap->total_pages);
9289 for (
int i = 0; i < HEAP_COUNT; i++) {
9290 rb_heap_t *heap = &heaps[i];
9292 size_t pages_to_add = 0;
9299 pages_to_add += max_existing_pages - heap->total_pages;
9304 objspace->heap_pages.allocatable_slots = desired_compaction.required_slots[i];
9305 while (
objspace->heap_pages.allocatable_slots > 0) {
9306 heap_page_allocate_and_initialize(
objspace, heap);
9314 for (; pages_to_add > 0; pages_to_add--) {
9315 heap_page_allocate_and_initialize_force(
objspace, heap);
9321 objspace->rcompactor.compare_func = compare_free_slots;
9324 RB_GC_VM_UNLOCK(lev);
9326 rb_gc_impl_start(rb_gc_get_objspace(),
true,
true,
true,
true);
9328 rb_objspace_reachable_objects_from_root(root_obj_check_moved_i,
objspace);
9331 objspace->rcompactor.compare_func = NULL;
9333 return gc_compact_stats(self);
9336# define gc_verify_compaction_references rb_f_notimplement
9340rb_gc_impl_objspace_free(
void *objspace_ptr)
9342 rb_objspace_t *
objspace = objspace_ptr;
9345 rb_bug(
"lazy sweeping underway when freeing object space");
9350 for (
size_t i = 0; i < rb_darray_size(
objspace->heap_pages.sorted); i++) {
9353 rb_darray_free_without_gc(
objspace->heap_pages.sorted);
9354 heap_pages_lomem = 0;
9355 heap_pages_himem = 0;
9357 for (
int i = 0; i < HEAP_COUNT; i++) {
9358 rb_heap_t *heap = &heaps[i];
9359 heap->total_pages = 0;
9360 heap->total_slots = 0;
9363 free_stack_chunks(&
objspace->mark_stack);
9364 mark_stack_free_cache(&
objspace->mark_stack);
9366 rb_darray_free_without_gc(
objspace->weak_references);
9371#if MALLOC_ALLOCATED_SIZE
9382gc_malloc_allocated_size(
VALUE self)
9384 rb_objspace_t *
objspace = (rb_objspace_t *)rb_gc_get_objspace();
9398gc_malloc_allocations(
VALUE self)
9400 rb_objspace_t *
objspace = (rb_objspace_t *)rb_gc_get_objspace();
9406rb_gc_impl_before_fork(
void *objspace_ptr)
9408 rb_objspace_t *
objspace = objspace_ptr;
9410 objspace->fork_vm_lock_lev = RB_GC_VM_LOCK();
9415rb_gc_impl_after_fork(
void *objspace_ptr, rb_pid_t pid)
9417 rb_objspace_t *
objspace = objspace_ptr;
9419 RB_GC_VM_UNLOCK(
objspace->fork_vm_lock_lev);
9423 rb_gc_ractor_newobj_cache_foreach(gc_ractor_newobj_cache_clear, NULL);
9427VALUE rb_ident_hash_new_with_size(st_index_t size);
9429#if GC_DEBUG_STRESS_TO_CLASS
9438rb_gcdebug_add_stress_to_class(
int argc,
VALUE *argv,
VALUE self)
9440 rb_objspace_t *
objspace = rb_gc_get_objspace();
9442 if (!stress_to_class) {
9443 set_stress_to_class(rb_ident_hash_new_with_size(argc));
9446 for (
int i = 0; i < argc; i++) {
9447 VALUE klass = argv[i];
9448 rb_hash_aset(stress_to_class, klass,
Qtrue);
9463rb_gcdebug_remove_stress_to_class(
int argc,
VALUE *argv,
VALUE self)
9465 rb_objspace_t *
objspace = rb_gc_get_objspace();
9467 if (stress_to_class) {
9468 for (
int i = 0; i < argc; ++i) {
9469 rb_hash_delete(stress_to_class, argv[i]);
9472 if (rb_hash_size(stress_to_class) == 0) {
9473 stress_to_class = 0;
9482rb_gc_impl_objspace_alloc(
void)
9484 rb_objspace_t *
objspace = calloc1(
sizeof(rb_objspace_t));
9490rb_gc_impl_objspace_init(
void *objspace_ptr)
9492 rb_objspace_t *
objspace = objspace_ptr;
9494 gc_config_full_mark_set(TRUE);
9497 malloc_limit = gc_params.malloc_limit_min;
9499 if (
objspace->finalize_deferred_pjob == POSTPONED_JOB_HANDLE_INVALID) {
9500 rb_bug(
"Could not preregister postponed job for GC");
9503 for (
int i = 0; i < HEAP_COUNT; i++) {
9504 rb_heap_t *heap = &heaps[i];
9506 heap->slot_size = (1 << i) * BASE_SLOT_SIZE;
9509 static const bits_t slot_bits_masks[] = {
9511 (bits_t)0x5555555555555555ULL,
9512 (bits_t)0x1111111111111111ULL,
9513 (bits_t)0x0101010101010101ULL,
9514 (bits_t)0x0001000100010001ULL,
9516 GC_ASSERT(HEAP_COUNT ==
sizeof(slot_bits_masks) /
sizeof(slot_bits_masks[0]));
9517 heap->slot_bits_mask = slot_bits_masks[i];
9519 ccan_list_head_init(&heap->pages);
9522 rb_darray_make_without_gc(&
objspace->heap_pages.sorted, 0);
9523 rb_darray_make_without_gc(&
objspace->weak_references, 0);
9530#if defined(INIT_HEAP_PAGE_ALLOC_USE_MMAP)
9532 heap_page_alloc_use_mmap = INIT_HEAP_PAGE_ALLOC_USE_MMAP;
9534#if RGENGC_ESTIMATE_OLDMALLOC
9535 objspace->rgengc.oldmalloc_increase_limit = gc_params.oldmalloc_limit_min;
9538 for (
int i = 0; i < HEAP_COUNT; i++) {
9540 gc_params.heap_init_slots[i] = GC_HEAP_INIT_SLOTS;
9543 init_mark_stack(&
objspace->mark_stack);
9545 objspace->profile.invoke_time = getrusage_time();
9546 finalizer_table = st_init_numtable();
9550rb_gc_impl_init(
void)
9553 rb_hash_aset(gc_constants,
ID2SYM(rb_intern(
"DEBUG")), GC_DEBUG ?
Qtrue :
Qfalse);
9554 rb_hash_aset(gc_constants,
ID2SYM(rb_intern(
"BASE_SLOT_SIZE")),
SIZET2NUM(BASE_SLOT_SIZE - RVALUE_OVERHEAD));
9556 rb_hash_aset(gc_constants,
ID2SYM(rb_intern(
"RVALUE_OVERHEAD")),
SIZET2NUM(RVALUE_OVERHEAD));
9557 rb_hash_aset(gc_constants,
ID2SYM(rb_intern(
"HEAP_PAGE_OBJ_LIMIT")),
SIZET2NUM(HEAP_PAGE_OBJ_LIMIT));
9558 rb_hash_aset(gc_constants,
ID2SYM(rb_intern(
"HEAP_PAGE_BITMAP_SIZE")),
SIZET2NUM(HEAP_PAGE_BITMAP_SIZE));
9559 rb_hash_aset(gc_constants,
ID2SYM(rb_intern(
"HEAP_PAGE_SIZE")),
SIZET2NUM(HEAP_PAGE_SIZE));
9560 rb_hash_aset(gc_constants,
ID2SYM(rb_intern(
"HEAP_COUNT")),
LONG2FIX(HEAP_COUNT));
9561 rb_hash_aset(gc_constants,
ID2SYM(rb_intern(
"RVARGC_MAX_ALLOCATE_SIZE")),
LONG2FIX(heap_slot_size(HEAP_COUNT - 1)));
9562 rb_hash_aset(gc_constants,
ID2SYM(rb_intern(
"RVALUE_OLD_AGE")),
LONG2FIX(RVALUE_OLD_AGE));
9563 if (RB_BUG_INSTEAD_OF_RB_MEMERROR+0) {
9564 rb_hash_aset(gc_constants,
ID2SYM(rb_intern(
"RB_BUG_INSTEAD_OF_RB_MEMERROR")),
Qtrue);
9568 rb_define_const(
rb_mGC,
"INTERNAL_CONSTANTS", gc_constants);
9570 if (GC_COMPACTION_SUPPORTED) {
9585#if GC_DEBUG_STRESS_TO_CLASS
9593#if MALLOC_ALLOCATED_SIZE
9612#define OPT(o) if (o) rb_ary_push(opts, rb_interned_str(#o, sizeof(#o) - 1))
9616 OPT(RGENGC_CHECK_MODE);
9617 OPT(RGENGC_PROFILE);
9618 OPT(RGENGC_ESTIMATE_OLDMALLOC);
9619 OPT(GC_PROFILE_MORE_DETAIL);
9620 OPT(GC_ENABLE_LAZY_SWEEP);
9621 OPT(CALC_EXACT_MALLOC_SIZE);
9622 OPT(MALLOC_ALLOCATED_SIZE);
9623 OPT(MALLOC_ALLOCATED_SIZE_CHECK);
9624 OPT(GC_PROFILE_DETAIL_MEMORY);
9625 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.
static VALUE RB_FL_TEST(VALUE obj, VALUE flags)
Tests if the given flag(s) are set or not.
static void RB_FL_SET_RAW(VALUE obj, VALUE flags)
This is an implementation detail of RB_FL_SET().
static void RB_FL_UNSET_RAW(VALUE obj, VALUE flags)
This is an implementation detail of RB_FL_UNSET().
@ 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_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.
void rb_memerror(void)
Triggers out-of-memory error.
static bool RB_OBJ_PROMOTED_RAW(VALUE obj)
This is the implementation of RB_OBJ_PROMOTED().
size_t rb_gc_count(void)
Identical to rb_gc_stat(), with "count" parameter.
VALUE rb_ary_dup(VALUE ary)
Duplicates an array.
VALUE rb_ary_new(void)
Allocates a new, empty array.
VALUE rb_ary_push(VALUE ary, VALUE elem)
Special case of rb_ary_cat() that it adds only one element.
static int rb_check_arity(int argc, int min, int max)
Ensures that the passed integer is in the passed range.
VALUE rb_hash_new(void)
Creates a new, empty hash object.
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.
int len
Length of the buffer.
int ruby_thread_has_gvl_p(void)
Whether the current thread is holding the GVL.
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.
int st_foreach(st_table *q, int_type *w, st_data_t e)
Iteration over the given table.
void rb_hash_foreach(VALUE q, int_type *w, VALUE e)
Iteration over the given hash.
VALUE rb_ensure(type *q, VALUE w, type *e, VALUE r)
An equivalent of ensure clause.
#define RARRAY_LEN
Just another name of rb_array_len.
static void RARRAY_ASET(VALUE ary, long i, VALUE v)
Assigns an object in an array.
#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.
static bool RB_SPECIAL_CONST_P(VALUE obj)
Checks if the given object is of enum ruby_special_consts.
#define RTEST
This is an old name of RB_TEST.
#define _(args)
This was a transition path from K&R to ANSI.
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.
static enum ruby_value_type RB_BUILTIN_TYPE(VALUE obj)
Queries the type of the object.
static bool RB_TYPE_P(VALUE obj, enum ruby_value_type t)
Queries if the given object is of given type.
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.).