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