Ruby 4.1.0dev (2026-04-18 revision 3803204fd3a863c4936b3580b28940dd4ce22236)
gc.c (3803204fd3a863c4936b3580b28940dd4ce22236)
1/**********************************************************************
2
3 gc.c -
4
5 $Author$
6 created at: Tue Oct 5 09:44:46 JST 1993
7
8 Copyright (C) 1993-2007 Yukihiro Matsumoto
9 Copyright (C) 2000 Network Applied Communication Laboratory, Inc.
10 Copyright (C) 2000 Information-technology Promotion Agency, Japan
11
12**********************************************************************/
13
14#include "ruby/internal/config.h"
15#ifdef _WIN32
16# include "ruby/ruby.h"
17#endif
18
19#if defined(__wasm__) && !defined(__EMSCRIPTEN__)
20# include "wasm/setjmp.h"
21# include "wasm/machine.h"
22#else
23# include <setjmp.h>
24#endif
25#include <stdarg.h>
26#include <stdio.h>
27
28/* MALLOC_HEADERS_BEGIN */
29#ifndef HAVE_MALLOC_USABLE_SIZE
30# ifdef _WIN32
31# define HAVE_MALLOC_USABLE_SIZE
32# define malloc_usable_size(a) _msize(a)
33# elif defined HAVE_MALLOC_SIZE
34# define HAVE_MALLOC_USABLE_SIZE
35# define malloc_usable_size(a) malloc_size(a)
36# endif
37#endif
38
39#ifdef HAVE_MALLOC_USABLE_SIZE
40# ifdef RUBY_ALTERNATIVE_MALLOC_HEADER
41/* Alternative malloc header is included in ruby/missing.h */
42# elif defined(HAVE_MALLOC_H)
43# include <malloc.h>
44# elif defined(HAVE_MALLOC_NP_H)
45# include <malloc_np.h>
46# elif defined(HAVE_MALLOC_MALLOC_H)
47# include <malloc/malloc.h>
48# endif
49#endif
50
51/* MALLOC_HEADERS_END */
52
53#ifdef HAVE_SYS_TIME_H
54# include <sys/time.h>
55#endif
56
57#ifdef HAVE_SYS_RESOURCE_H
58# include <sys/resource.h>
59#endif
60
61#if defined _WIN32 || defined __CYGWIN__
62# include <windows.h>
63#elif defined(HAVE_POSIX_MEMALIGN)
64#elif defined(HAVE_MEMALIGN)
65# include <malloc.h>
66#endif
67
68#include <sys/types.h>
69
70#ifdef __EMSCRIPTEN__
71#include <emscripten.h>
72#endif
73
74/* For ruby_annotate_mmap */
75#ifdef HAVE_SYS_PRCTL_H
76#include <sys/prctl.h>
77#endif
78
79#undef LIST_HEAD /* ccan/list conflicts with BSD-origin sys/queue.h. */
80
81#include "constant.h"
82#include "darray.h"
83#include "debug_counter.h"
84#include "eval_intern.h"
85#include "gc/gc.h"
86#include "id_table.h"
87#include "internal.h"
88#include "internal/class.h"
89#include "internal/compile.h"
90#include "internal/complex.h"
91#include "internal/concurrent_set.h"
92#include "internal/cont.h"
93#include "internal/error.h"
94#include "internal/eval.h"
95#include "internal/gc.h"
96#include "internal/hash.h"
97#include "internal/imemo.h"
98#include "internal/io.h"
99#include "internal/numeric.h"
100#include "internal/object.h"
101#include "internal/proc.h"
102#include "internal/rational.h"
103#include "internal/sanitizers.h"
104#include "internal/struct.h"
105#include "internal/symbol.h"
106#include "internal/thread.h"
107#include "internal/variable.h"
108#include "internal/warnings.h"
109#include "probes.h"
110#include "regint.h"
111#include "ruby/debug.h"
112#include "ruby/io.h"
113#include "ruby/re.h"
114#include "ruby/st.h"
115#include "ruby/thread.h"
116#include "ruby/util.h"
117#include "ruby/vm.h"
118#include "ruby_assert.h"
119#include "ruby_atomic.h"
120#include "symbol.h"
121#include "variable.h"
122#include "vm_core.h"
123#include "vm_sync.h"
124#include "vm_callinfo.h"
125#include "ractor_core.h"
126#include "yjit.h"
127#include "zjit.h"
128
129#include "builtin.h"
130#include "shape.h"
131
132// TODO: Don't export this function in modular GC, instead MMTk should figure out
133// how to combine GC thread backtrace with mutator thread backtrace.
134void
135rb_gc_print_backtrace(void)
136{
137 rb_print_backtrace(stderr);
138}
139
140unsigned int
141rb_gc_vm_lock(const char *file, int line)
142{
143 unsigned int lev = 0;
144 rb_vm_lock_enter(&lev, file, line);
145 return lev;
146}
147
148void
149rb_gc_vm_unlock(unsigned int lev, const char *file, int line)
150{
151 rb_vm_lock_leave(&lev, file, line);
152}
153
154unsigned int
155rb_gc_cr_lock(const char *file, int line)
156{
157 unsigned int lev;
158 rb_vm_lock_enter_cr(GET_RACTOR(), &lev, file, line);
159 return lev;
160}
161
162void
163rb_gc_cr_unlock(unsigned int lev, const char *file, int line)
164{
165 rb_vm_lock_leave_cr(GET_RACTOR(), &lev, file, line);
166}
167
168unsigned int
169rb_gc_vm_lock_no_barrier(const char *file, int line)
170{
171 unsigned int lev = 0;
172 rb_vm_lock_enter_nb(&lev, file, line);
173 return lev;
174}
175
176void
177rb_gc_vm_unlock_no_barrier(unsigned int lev, const char *file, int line)
178{
179 rb_vm_lock_leave_nb(&lev, file, line);
180}
181
182void
183rb_gc_vm_barrier(void)
184{
185 rb_vm_barrier();
186}
187
188void *
189rb_gc_get_ractor_newobj_cache(void)
190{
191 return GET_RACTOR()->newobj_cache;
192}
193
194#if USE_MODULAR_GC
195void
196rb_gc_initialize_vm_context(struct rb_gc_vm_context *context)
197{
198 rb_native_mutex_initialize(&context->lock);
199 context->ec = GET_EC();
200}
201
202void
203rb_gc_worker_thread_set_vm_context(struct rb_gc_vm_context *context)
204{
205 rb_native_mutex_lock(&context->lock);
206
207 GC_ASSERT(rb_current_execution_context(false) == NULL);
208
209#ifdef RB_THREAD_LOCAL_SPECIFIER
210 rb_current_ec_set(context->ec);
211#else
212 native_tls_set(ruby_current_ec_key, context->ec);
213#endif
214}
215
216void
217rb_gc_worker_thread_unset_vm_context(struct rb_gc_vm_context *context)
218{
219 rb_native_mutex_unlock(&context->lock);
220
221 GC_ASSERT(rb_current_execution_context(true) == context->ec);
222
223#ifdef RB_THREAD_LOCAL_SPECIFIER
224 rb_current_ec_set(NULL);
225#else
226 native_tls_set(ruby_current_ec_key, NULL);
227#endif
228}
229#endif
230
231bool
232rb_gc_event_hook_required_p(rb_event_flag_t event)
233{
234 return ruby_vm_event_flags & event;
235}
236
237void
238rb_gc_event_hook(VALUE obj, rb_event_flag_t event)
239{
240 if (LIKELY(!rb_gc_event_hook_required_p(event))) return;
241
242 rb_execution_context_t *ec = GET_EC();
243 if (!ec->cfp) return;
244
245 EXEC_EVENT_HOOK(ec, event, ec->cfp->self, 0, 0, 0, obj);
246}
247
248void *
249rb_gc_get_objspace(void)
250{
251 return GET_VM()->gc.objspace;
252}
253
254
255void
256rb_gc_ractor_newobj_cache_foreach(void (*func)(void *cache, void *data), void *data)
257{
258 rb_ractor_t *r = NULL;
259 if (RB_LIKELY(ruby_single_main_ractor)) {
260 GC_ASSERT(
261 ccan_list_empty(&GET_VM()->ractor.set) ||
262 (ccan_list_top(&GET_VM()->ractor.set, rb_ractor_t, vmlr_node) == ruby_single_main_ractor &&
263 ccan_list_tail(&GET_VM()->ractor.set, rb_ractor_t, vmlr_node) == ruby_single_main_ractor)
264 );
265
266 func(ruby_single_main_ractor->newobj_cache, data);
267 }
268 else {
269 ccan_list_for_each(&GET_VM()->ractor.set, r, vmlr_node) {
270 func(r->newobj_cache, data);
271 }
272 }
273}
274
275void
276rb_gc_run_obj_finalizer(VALUE objid, long count, VALUE (*callback)(long i, void *data), void *data)
277{
278 volatile struct {
279 VALUE errinfo;
280 VALUE final;
282 VALUE *sp;
283 long finished;
284 } saved;
285
286 rb_execution_context_t * volatile ec = GET_EC();
287#define RESTORE_FINALIZER() (\
288 ec->cfp = saved.cfp, \
289 ec->cfp->sp = saved.sp, \
290 ec->errinfo = saved.errinfo)
291
292 saved.errinfo = ec->errinfo;
293 saved.cfp = ec->cfp;
294 saved.sp = ec->cfp->sp;
295 saved.finished = 0;
296 saved.final = Qundef;
297
298 ASSERT_vm_unlocking();
299 rb_ractor_ignore_belonging(true);
300 EC_PUSH_TAG(ec);
301 enum ruby_tag_type state = EC_EXEC_TAG();
302 if (state != TAG_NONE) {
303 ++saved.finished; /* skip failed finalizer */
304
305 VALUE failed_final = saved.final;
306 saved.final = Qundef;
307 if (!UNDEF_P(failed_final) && !NIL_P(ruby_verbose)) {
308 rb_warn("Exception in finalizer %+"PRIsVALUE, failed_final);
309 rb_ec_error_print(ec, ec->errinfo);
310 }
311 }
312
313 for (long i = saved.finished; RESTORE_FINALIZER(), i < count; saved.finished = ++i) {
314 saved.final = callback(i, data);
315 rb_check_funcall(saved.final, idCall, 1, &objid);
316 }
317 EC_POP_TAG();
318 rb_ractor_ignore_belonging(false);
319#undef RESTORE_FINALIZER
320}
321
322void
323rb_gc_set_pending_interrupt(void)
324{
325 rb_execution_context_t *ec = GET_EC();
326 ec->interrupt_mask |= PENDING_INTERRUPT_MASK;
327}
328
329void
330rb_gc_unset_pending_interrupt(void)
331{
332 rb_execution_context_t *ec = GET_EC();
333 ec->interrupt_mask &= ~PENDING_INTERRUPT_MASK;
334}
335
336bool
337rb_gc_multi_ractor_p(void)
338{
339 return rb_multi_ractor_p();
340}
341
342bool
343rb_gc_shutdown_call_finalizer_p(VALUE obj)
344{
345 switch (BUILTIN_TYPE(obj)) {
346 case T_DATA:
347 if (!ruby_free_at_exit_p() && (!DATA_PTR(obj) || !RDATA(obj)->dfree)) return false;
348 if (rb_obj_is_thread(obj)) return false;
349 if (rb_obj_is_mutex(obj)) return false;
350 if (rb_obj_is_fiber(obj)) return false;
351 if (rb_ractor_p(obj)) return false;
352 if (rb_obj_is_fstring_table(obj)) return false;
353 if (rb_obj_is_symbol_table(obj)) return false;
354
355 return true;
356
357 case T_FILE:
358 return true;
359
360 case T_SYMBOL:
361 return true;
362
363 case T_NONE:
364 return false;
365
366 default:
367 return ruby_free_at_exit_p();
368 }
369}
370
371uint32_t
372rb_gc_get_shape(VALUE obj)
373{
374 return (uint32_t)rb_obj_shape_id(obj);
375}
376
377void
378rb_gc_set_shape(VALUE obj, uint32_t shape_id)
379{
380 RBASIC_SET_SHAPE_ID(obj, (uint32_t)shape_id);
381}
382
383uint32_t
384rb_gc_rebuild_shape(VALUE obj, size_t heap_id)
385{
387
388 return (uint32_t)rb_shape_transition_heap(obj, heap_id);
389}
390
391void rb_vm_update_references(void *ptr);
392
393#define rb_setjmp(env) RUBY_SETJMP(env)
394#define rb_jmp_buf rb_jmpbuf_t
395#undef rb_data_object_wrap
396
397#if !defined(MAP_ANONYMOUS) && defined(MAP_ANON)
398#define MAP_ANONYMOUS MAP_ANON
399#endif
400
401#define unless_objspace(objspace) \
402 void *objspace; \
403 rb_vm_t *unless_objspace_vm = GET_VM(); \
404 if (unless_objspace_vm) objspace = unless_objspace_vm->gc.objspace; \
405 else /* return; or objspace will be warned uninitialized */
406
407#define RMOVED(obj) ((struct RMoved *)(obj))
408
409#define TYPED_UPDATE_IF_MOVED(_objspace, _type, _thing) do { \
410 if (gc_object_moved_p_internal((_objspace), (VALUE)(_thing))) { \
411 *(_type *)&(_thing) = (_type)gc_location_internal(_objspace, (VALUE)_thing); \
412 } \
413} while (0)
414
415#define UPDATE_IF_MOVED(_objspace, _thing) TYPED_UPDATE_IF_MOVED(_objspace, VALUE, _thing)
416
417#if RUBY_MARK_FREE_DEBUG
418int ruby_gc_debug_indent = 0;
419#endif
420
421#ifndef RGENGC_OBJ_INFO
422# define RGENGC_OBJ_INFO RGENGC_CHECK_MODE
423#endif
424
425#ifndef CALC_EXACT_MALLOC_SIZE
426# define CALC_EXACT_MALLOC_SIZE 0
427#endif
428
430
431static size_t malloc_offset = 0;
432#if defined(HAVE_MALLOC_USABLE_SIZE)
433static size_t
434gc_compute_malloc_offset(void)
435{
436 // Different allocators use different metadata storage strategies which result in different
437 // ideal sizes.
438 // For instance malloc(64) will waste 8B with glibc, but waste 0B with jemalloc.
439 // But malloc(56) will waste 0B with glibc, but waste 8B with jemalloc.
440 // So we try allocating 64, 56 and 48 bytes and select the first offset that doesn't
441 // waste memory.
442 // This was tested on Linux with glibc 2.35 and jemalloc 5, and for both it result in
443 // no wasted memory.
444 size_t offset = 0;
445 for (offset = 0; offset <= 16; offset += 8) {
446 size_t allocated = (64 - offset);
447 void *test_ptr = malloc(allocated);
448 size_t wasted = malloc_usable_size(test_ptr) - allocated;
449 free(test_ptr);
450
451 if (wasted == 0) {
452 return offset;
453 }
454 }
455 return 0;
456}
457#else
458static size_t
459gc_compute_malloc_offset(void)
460{
461 // If we don't have malloc_usable_size, we use powers of 2.
462 return 0;
463}
464#endif
465
466size_t
467rb_malloc_grow_capa(size_t current, size_t type_size)
468{
469 size_t current_capacity = current;
470 if (current_capacity < 4) {
471 current_capacity = 4;
472 }
473 current_capacity *= type_size;
474
475 // We double the current capacity.
476 size_t new_capacity = (current_capacity * 2);
477
478 // And round up to the next power of 2 if it's not already one.
479 if (rb_popcount64(new_capacity) != 1) {
480 new_capacity = (size_t)(1 << (64 - nlz_int64(new_capacity)));
481 }
482
483 new_capacity -= malloc_offset;
484 new_capacity /= type_size;
485 if (current > new_capacity) {
486 rb_bug("rb_malloc_grow_capa: current_capacity=%zu, new_capacity=%zu, malloc_offset=%zu", current, new_capacity, malloc_offset);
487 }
488 RUBY_ASSERT(new_capacity > current);
489 return new_capacity;
490}
491
492static inline struct rbimpl_size_overflow_tag
493size_mul_add_overflow(size_t x, size_t y, size_t z) /* x * y + z */
494{
495 struct rbimpl_size_overflow_tag t = rbimpl_size_mul_overflow(x, y);
496 struct rbimpl_size_overflow_tag u = rbimpl_size_add_overflow(t.result, z);
497 return (struct rbimpl_size_overflow_tag) { t.overflowed || u.overflowed, u.result };
498}
499
500static inline struct rbimpl_size_overflow_tag
501size_mul_add_mul_overflow(size_t x, size_t y, size_t z, size_t w) /* x * y + z * w */
502{
503 struct rbimpl_size_overflow_tag t = rbimpl_size_mul_overflow(x, y);
504 struct rbimpl_size_overflow_tag u = rbimpl_size_mul_overflow(z, w);
505 struct rbimpl_size_overflow_tag v = rbimpl_size_add_overflow(t.result, u.result);
506 return (struct rbimpl_size_overflow_tag) { t.overflowed || u.overflowed || v.overflowed, v.result };
507}
508
509PRINTF_ARGS(NORETURN(static void gc_raise(VALUE, const char*, ...)), 2, 3);
510
511static inline size_t
512size_mul_or_raise(size_t x, size_t y, VALUE exc)
513{
514 struct rbimpl_size_overflow_tag t = rbimpl_size_mul_overflow(x, y);
515 if (LIKELY(!t.overflowed)) {
516 return t.result;
517 }
518 else if (rb_during_gc()) {
519 rb_memerror(); /* or...? */
520 }
521 else {
522 gc_raise(
523 exc,
524 "integer overflow: %"PRIuSIZE
525 " * %"PRIuSIZE
526 " > %"PRIuSIZE,
527 x, y, (size_t)SIZE_MAX);
528 }
529}
530
531size_t
532rb_size_mul_or_raise(size_t x, size_t y, VALUE exc)
533{
534 return size_mul_or_raise(x, y, exc);
535}
536
537static inline size_t
538size_mul_add_or_raise(size_t x, size_t y, size_t z, VALUE exc)
539{
540 struct rbimpl_size_overflow_tag t = size_mul_add_overflow(x, y, z);
541 if (LIKELY(!t.overflowed)) {
542 return t.result;
543 }
544 else if (rb_during_gc()) {
545 rb_memerror(); /* or...? */
546 }
547 else {
548 gc_raise(
549 exc,
550 "integer overflow: %"PRIuSIZE
551 " * %"PRIuSIZE
552 " + %"PRIuSIZE
553 " > %"PRIuSIZE,
554 x, y, z, (size_t)SIZE_MAX);
555 }
556}
557
558size_t
559rb_size_mul_add_or_raise(size_t x, size_t y, size_t z, VALUE exc)
560{
561 return size_mul_add_or_raise(x, y, z, exc);
562}
563
564static inline size_t
565size_mul_add_mul_or_raise(size_t x, size_t y, size_t z, size_t w, VALUE exc)
566{
567 struct rbimpl_size_overflow_tag t = size_mul_add_mul_overflow(x, y, z, w);
568 if (LIKELY(!t.overflowed)) {
569 return t.result;
570 }
571 else if (rb_during_gc()) {
572 rb_memerror(); /* or...? */
573 }
574 else {
575 gc_raise(
576 exc,
577 "integer overflow: %"PRIdSIZE
578 " * %"PRIdSIZE
579 " + %"PRIdSIZE
580 " * %"PRIdSIZE
581 " > %"PRIdSIZE,
582 x, y, z, w, (size_t)SIZE_MAX);
583 }
584}
585
586#if defined(HAVE_RB_GC_GUARDED_PTR_VAL) && HAVE_RB_GC_GUARDED_PTR_VAL
587/* trick the compiler into thinking a external signal handler uses this */
588volatile VALUE rb_gc_guarded_val;
589volatile VALUE *
590rb_gc_guarded_ptr_val(volatile VALUE *ptr, VALUE val)
591{
592 rb_gc_guarded_val = val;
593
594 return ptr;
595}
596#endif
597
598static const char *obj_type_name(VALUE obj);
599static st_table *id2ref_tbl;
600#include "gc/default/default.c"
601
602#if USE_MODULAR_GC && !defined(HAVE_DLOPEN)
603# error "Modular GC requires dlopen"
604#elif USE_MODULAR_GC
605#include <dlfcn.h>
606
607typedef struct gc_function_map {
608 // Bootup
609 void *(*objspace_alloc)(void);
610 void (*objspace_init)(void *objspace_ptr);
611 void *(*ractor_cache_alloc)(void *objspace_ptr, void *ractor);
612 void (*set_params)(void *objspace_ptr);
613 void (*init)(void);
614 size_t *(*heap_sizes)(void *objspace_ptr);
615 // Shutdown
616 void (*shutdown_free_objects)(void *objspace_ptr);
617 void (*objspace_free)(void *objspace_ptr);
618 void (*ractor_cache_free)(void *objspace_ptr, void *cache);
619 // GC
620 void (*start)(void *objspace_ptr, bool full_mark, bool immediate_mark, bool immediate_sweep, bool compact);
621 bool (*during_gc_p)(void *objspace_ptr);
622 void (*prepare_heap)(void *objspace_ptr);
623 void (*gc_enable)(void *objspace_ptr);
624 void (*gc_disable)(void *objspace_ptr, bool finish_current_gc);
625 bool (*gc_enabled_p)(void *objspace_ptr);
626 VALUE (*config_get)(void *objpace_ptr);
627 void (*config_set)(void *objspace_ptr, VALUE hash);
628 void (*stress_set)(void *objspace_ptr, VALUE flag);
629 VALUE (*stress_get)(void *objspace_ptr);
630 // Object allocation
631 VALUE (*new_obj)(void *objspace_ptr, void *cache_ptr, VALUE klass, VALUE flags, bool wb_protected, size_t alloc_size);
632 size_t (*obj_slot_size)(VALUE obj);
633 size_t (*heap_id_for_size)(void *objspace_ptr, size_t size);
634 bool (*size_allocatable_p)(size_t size);
635 // Malloc
636 void *(*malloc)(void *objspace_ptr, size_t size, bool gc_allowed);
637 void *(*calloc)(void *objspace_ptr, size_t size, bool gc_allowed);
638 void *(*realloc)(void *objspace_ptr, void *ptr, size_t new_size, size_t old_size, bool gc_allowed);
639 void (*free)(void *objspace_ptr, void *ptr, size_t old_size);
640 void (*adjust_memory_usage)(void *objspace_ptr, ssize_t diff);
641 // Marking
642 void (*mark)(void *objspace_ptr, VALUE obj);
643 void (*mark_and_move)(void *objspace_ptr, VALUE *ptr);
644 void (*mark_and_pin)(void *objspace_ptr, VALUE obj);
645 void (*mark_maybe)(void *objspace_ptr, VALUE obj);
646 // Weak references
647 void (*declare_weak_references)(void *objspace_ptr, VALUE obj);
648 bool (*handle_weak_references_alive_p)(void *objspace_ptr, VALUE obj);
649 // Compaction
650 void (*register_pinning_obj)(void *objspace_ptr, VALUE obj);
651 bool (*object_moved_p)(void *objspace_ptr, VALUE obj);
652 VALUE (*location)(void *objspace_ptr, VALUE value);
653 // Write barriers
654 void (*writebarrier)(void *objspace_ptr, VALUE a, VALUE b);
655 void (*writebarrier_unprotect)(void *objspace_ptr, VALUE obj);
656 void (*writebarrier_remember)(void *objspace_ptr, VALUE obj);
657 // Heap walking
658 void (*each_objects)(void *objspace_ptr, int (*callback)(void *, void *, size_t, void *), void *data);
659 void (*each_object)(void *objspace_ptr, void (*func)(VALUE obj, void *data), void *data);
660 // Finalizers
661 void (*make_zombie)(void *objspace_ptr, VALUE obj, void (*dfree)(void *), void *data);
662 VALUE (*define_finalizer)(void *objspace_ptr, VALUE obj, VALUE block);
663 void (*undefine_finalizer)(void *objspace_ptr, VALUE obj);
664 void (*copy_finalizer)(void *objspace_ptr, VALUE dest, VALUE obj);
665 void (*shutdown_call_finalizer)(void *objspace_ptr);
666 // Forking
667 void (*before_fork)(void *objspace_ptr);
668 void (*after_fork)(void *objspace_ptr, rb_pid_t pid);
669 // Statistics
670 void (*set_measure_total_time)(void *objspace_ptr, VALUE flag);
671 bool (*get_measure_total_time)(void *objspace_ptr);
672 unsigned long long (*get_total_time)(void *objspace_ptr);
673 size_t (*gc_count)(void *objspace_ptr);
674 VALUE (*latest_gc_info)(void *objspace_ptr, VALUE key);
675 VALUE (*stat)(void *objspace_ptr, VALUE hash_or_sym);
676 VALUE (*stat_heap)(void *objspace_ptr, VALUE heap_name, VALUE hash_or_sym);
677 const char *(*active_gc_name)(void);
678 // Miscellaneous
679 struct rb_gc_object_metadata_entry *(*object_metadata)(void *objspace_ptr, VALUE obj);
680 bool (*pointer_to_heap_p)(void *objspace_ptr, const void *ptr);
681 bool (*garbage_object_p)(void *objspace_ptr, VALUE obj);
682 void (*set_event_hook)(void *objspace_ptr, const rb_event_flag_t event);
683 void (*copy_attributes)(void *objspace_ptr, VALUE dest, VALUE obj);
684
685 bool modular_gc_loaded_p;
686} rb_gc_function_map_t;
687
688static rb_gc_function_map_t rb_gc_functions;
689
690# define RUBY_GC_LIBRARY "RUBY_GC_LIBRARY"
691# define MODULAR_GC_DIR STRINGIZE(modular_gc_dir)
692
693static void
694ruby_modular_gc_init(void)
695{
696 // Assert that the directory path ends with a /
697 RUBY_ASSERT_ALWAYS(MODULAR_GC_DIR[sizeof(MODULAR_GC_DIR) - 2] == '/');
698
699 const char *gc_so_file = getenv(RUBY_GC_LIBRARY);
700
701 rb_gc_function_map_t gc_functions = { 0 };
702
703 char *gc_so_path = NULL;
704 void *handle = NULL;
705 if (gc_so_file) {
706 /* Check to make sure that gc_so_file matches /[\w-_]+/ so that it does
707 * not load a shared object outside of the directory. */
708 for (size_t i = 0; i < strlen(gc_so_file); i++) {
709 char c = gc_so_file[i];
710 if (isalnum(c)) continue;
711 switch (c) {
712 case '-':
713 case '_':
714 break;
715 default:
716 fprintf(stderr, "Only alphanumeric, dash, and underscore is allowed in "RUBY_GC_LIBRARY"\n");
717 exit(EXIT_FAILURE);
718 }
719 }
720
721 size_t gc_so_path_size = strlen(MODULAR_GC_DIR "librubygc." DLEXT) + strlen(gc_so_file) + 1;
722#ifdef LOAD_RELATIVE
723 Dl_info dli;
724 size_t prefix_len = 0;
725 if (dladdr((void *)(uintptr_t)ruby_modular_gc_init, &dli)) {
726 const char *base = strrchr(dli.dli_fname, '/');
727 if (base) {
728 size_t tail = 0;
729# define end_with_p(lit) \
730 (prefix_len >= (tail = rb_strlen_lit(lit)) && \
731 memcmp(base - tail, lit, tail) == 0)
732
733 prefix_len = base - dli.dli_fname;
734 if (end_with_p("/bin") || end_with_p("/lib")) {
735 prefix_len -= tail;
736 }
737 prefix_len += MODULAR_GC_DIR[0] != '/';
738 gc_so_path_size += prefix_len;
739 }
740 }
741#endif
742 gc_so_path = alloca(gc_so_path_size);
743 {
744 size_t gc_so_path_idx = 0;
745#define GC_SO_PATH_APPEND(str) do { \
746 gc_so_path_idx += strlcpy(gc_so_path + gc_so_path_idx, str, gc_so_path_size - gc_so_path_idx); \
747} while (0)
748#ifdef LOAD_RELATIVE
749 if (prefix_len > 0) {
750 memcpy(gc_so_path, dli.dli_fname, prefix_len);
751 gc_so_path_idx = prefix_len;
752 }
753#endif
754 GC_SO_PATH_APPEND(MODULAR_GC_DIR "librubygc.");
755 GC_SO_PATH_APPEND(gc_so_file);
756 GC_SO_PATH_APPEND(DLEXT);
757 GC_ASSERT(gc_so_path_idx == gc_so_path_size - 1);
758#undef GC_SO_PATH_APPEND
759 }
760
761 handle = dlopen(gc_so_path, RTLD_LAZY | RTLD_GLOBAL);
762 if (!handle) {
763 fprintf(stderr, "ruby_modular_gc_init: Shared library %s cannot be opened: %s\n", gc_so_path, dlerror());
764 exit(EXIT_FAILURE);
765 }
766
767 gc_functions.modular_gc_loaded_p = true;
768 }
769
770 unsigned int err_count = 0;
771
772# define load_modular_gc_func(name) do { \
773 if (handle) { \
774 const char *func_name = "rb_gc_impl_" #name; \
775 gc_functions.name = dlsym(handle, func_name); \
776 if (!gc_functions.name) { \
777 fprintf(stderr, "ruby_modular_gc_init: %s function not exported by library %s\n", func_name, gc_so_path); \
778 err_count++; \
779 } \
780 } \
781 else { \
782 gc_functions.name = rb_gc_impl_##name; \
783 } \
784} while (0)
785
786 // Bootup
787 load_modular_gc_func(objspace_alloc);
788 load_modular_gc_func(objspace_init);
789 load_modular_gc_func(ractor_cache_alloc);
790 load_modular_gc_func(set_params);
791 load_modular_gc_func(init);
792 load_modular_gc_func(heap_sizes);
793 // Shutdown
794 load_modular_gc_func(shutdown_free_objects);
795 load_modular_gc_func(objspace_free);
796 load_modular_gc_func(ractor_cache_free);
797 // GC
798 load_modular_gc_func(start);
799 load_modular_gc_func(during_gc_p);
800 load_modular_gc_func(prepare_heap);
801 load_modular_gc_func(gc_enable);
802 load_modular_gc_func(gc_disable);
803 load_modular_gc_func(gc_enabled_p);
804 load_modular_gc_func(config_set);
805 load_modular_gc_func(config_get);
806 load_modular_gc_func(stress_set);
807 load_modular_gc_func(stress_get);
808 // Object allocation
809 load_modular_gc_func(new_obj);
810 load_modular_gc_func(obj_slot_size);
811 load_modular_gc_func(heap_id_for_size);
812 load_modular_gc_func(size_allocatable_p);
813 // Malloc
814 load_modular_gc_func(malloc);
815 load_modular_gc_func(calloc);
816 load_modular_gc_func(realloc);
817 load_modular_gc_func(free);
818 load_modular_gc_func(adjust_memory_usage);
819 // Marking
820 load_modular_gc_func(mark);
821 load_modular_gc_func(mark_and_move);
822 load_modular_gc_func(mark_and_pin);
823 load_modular_gc_func(mark_maybe);
824 // Weak references
825 load_modular_gc_func(declare_weak_references);
826 load_modular_gc_func(handle_weak_references_alive_p);
827 // Compaction
828 load_modular_gc_func(register_pinning_obj);
829 load_modular_gc_func(object_moved_p);
830 load_modular_gc_func(location);
831 // Write barriers
832 load_modular_gc_func(writebarrier);
833 load_modular_gc_func(writebarrier_unprotect);
834 load_modular_gc_func(writebarrier_remember);
835 // Heap walking
836 load_modular_gc_func(each_objects);
837 load_modular_gc_func(each_object);
838 // Finalizers
839 load_modular_gc_func(make_zombie);
840 load_modular_gc_func(define_finalizer);
841 load_modular_gc_func(undefine_finalizer);
842 load_modular_gc_func(copy_finalizer);
843 load_modular_gc_func(shutdown_call_finalizer);
844 // Forking
845 load_modular_gc_func(before_fork);
846 load_modular_gc_func(after_fork);
847 // Statistics
848 load_modular_gc_func(set_measure_total_time);
849 load_modular_gc_func(get_measure_total_time);
850 load_modular_gc_func(get_total_time);
851 load_modular_gc_func(gc_count);
852 load_modular_gc_func(latest_gc_info);
853 load_modular_gc_func(stat);
854 load_modular_gc_func(stat_heap);
855 load_modular_gc_func(active_gc_name);
856 // Miscellaneous
857 load_modular_gc_func(object_metadata);
858 load_modular_gc_func(pointer_to_heap_p);
859 load_modular_gc_func(garbage_object_p);
860 load_modular_gc_func(set_event_hook);
861 load_modular_gc_func(copy_attributes);
862
863 if (err_count > 0) {
864 fprintf(stderr, "ruby_modular_gc_init: found %u missing exports in library %s\n", err_count, gc_so_path);
865 exit(EXIT_FAILURE);
866 }
867
868# undef load_modular_gc_func
869
870 rb_gc_functions = gc_functions;
871}
872
873// Bootup
874# define rb_gc_impl_objspace_alloc rb_gc_functions.objspace_alloc
875# define rb_gc_impl_objspace_init rb_gc_functions.objspace_init
876# define rb_gc_impl_ractor_cache_alloc rb_gc_functions.ractor_cache_alloc
877# define rb_gc_impl_set_params rb_gc_functions.set_params
878# define rb_gc_impl_init rb_gc_functions.init
879# define rb_gc_impl_heap_sizes rb_gc_functions.heap_sizes
880// Shutdown
881# define rb_gc_impl_shutdown_free_objects rb_gc_functions.shutdown_free_objects
882# define rb_gc_impl_objspace_free rb_gc_functions.objspace_free
883# define rb_gc_impl_ractor_cache_free rb_gc_functions.ractor_cache_free
884// GC
885# define rb_gc_impl_start rb_gc_functions.start
886# define rb_gc_impl_during_gc_p rb_gc_functions.during_gc_p
887# define rb_gc_impl_prepare_heap rb_gc_functions.prepare_heap
888# define rb_gc_impl_gc_enable rb_gc_functions.gc_enable
889# define rb_gc_impl_gc_disable rb_gc_functions.gc_disable
890# define rb_gc_impl_gc_enabled_p rb_gc_functions.gc_enabled_p
891# define rb_gc_impl_config_get rb_gc_functions.config_get
892# define rb_gc_impl_config_set rb_gc_functions.config_set
893# define rb_gc_impl_stress_set rb_gc_functions.stress_set
894# define rb_gc_impl_stress_get rb_gc_functions.stress_get
895// Object allocation
896# define rb_gc_impl_new_obj rb_gc_functions.new_obj
897# define rb_gc_impl_obj_slot_size rb_gc_functions.obj_slot_size
898# define rb_gc_impl_heap_id_for_size rb_gc_functions.heap_id_for_size
899# define rb_gc_impl_size_allocatable_p rb_gc_functions.size_allocatable_p
900// Malloc
901# define rb_gc_impl_malloc rb_gc_functions.malloc
902# define rb_gc_impl_calloc rb_gc_functions.calloc
903# define rb_gc_impl_realloc rb_gc_functions.realloc
904# define rb_gc_impl_free rb_gc_functions.free
905# define rb_gc_impl_adjust_memory_usage rb_gc_functions.adjust_memory_usage
906// Marking
907# define rb_gc_impl_mark rb_gc_functions.mark
908# define rb_gc_impl_mark_and_move rb_gc_functions.mark_and_move
909# define rb_gc_impl_mark_and_pin rb_gc_functions.mark_and_pin
910# define rb_gc_impl_mark_maybe rb_gc_functions.mark_maybe
911// Weak references
912# define rb_gc_impl_declare_weak_references rb_gc_functions.declare_weak_references
913# define rb_gc_impl_handle_weak_references_alive_p rb_gc_functions.handle_weak_references_alive_p
914// Compaction
915# define rb_gc_impl_register_pinning_obj rb_gc_functions.register_pinning_obj
916# define rb_gc_impl_object_moved_p rb_gc_functions.object_moved_p
917# define rb_gc_impl_location rb_gc_functions.location
918// Write barriers
919# define rb_gc_impl_writebarrier rb_gc_functions.writebarrier
920# define rb_gc_impl_writebarrier_unprotect rb_gc_functions.writebarrier_unprotect
921# define rb_gc_impl_writebarrier_remember rb_gc_functions.writebarrier_remember
922// Heap walking
923# define rb_gc_impl_each_objects rb_gc_functions.each_objects
924# define rb_gc_impl_each_object rb_gc_functions.each_object
925// Finalizers
926# define rb_gc_impl_make_zombie rb_gc_functions.make_zombie
927# define rb_gc_impl_define_finalizer rb_gc_functions.define_finalizer
928# define rb_gc_impl_undefine_finalizer rb_gc_functions.undefine_finalizer
929# define rb_gc_impl_copy_finalizer rb_gc_functions.copy_finalizer
930# define rb_gc_impl_shutdown_call_finalizer rb_gc_functions.shutdown_call_finalizer
931// Forking
932# define rb_gc_impl_before_fork rb_gc_functions.before_fork
933# define rb_gc_impl_after_fork rb_gc_functions.after_fork
934// Statistics
935# define rb_gc_impl_set_measure_total_time rb_gc_functions.set_measure_total_time
936# define rb_gc_impl_get_measure_total_time rb_gc_functions.get_measure_total_time
937# define rb_gc_impl_get_total_time rb_gc_functions.get_total_time
938# define rb_gc_impl_gc_count rb_gc_functions.gc_count
939# define rb_gc_impl_latest_gc_info rb_gc_functions.latest_gc_info
940# define rb_gc_impl_stat rb_gc_functions.stat
941# define rb_gc_impl_stat_heap rb_gc_functions.stat_heap
942# define rb_gc_impl_active_gc_name rb_gc_functions.active_gc_name
943// Miscellaneous
944# define rb_gc_impl_object_metadata rb_gc_functions.object_metadata
945# define rb_gc_impl_pointer_to_heap_p rb_gc_functions.pointer_to_heap_p
946# define rb_gc_impl_garbage_object_p rb_gc_functions.garbage_object_p
947# define rb_gc_impl_set_event_hook rb_gc_functions.set_event_hook
948# define rb_gc_impl_copy_attributes rb_gc_functions.copy_attributes
949#endif
950
951#ifdef RUBY_ASAN_ENABLED
952static void
953asan_death_callback(void)
954{
955 if (GET_VM()) {
956 rb_bug_without_die("ASAN error");
957 }
958}
959#endif
960
961static VALUE initial_stress = Qfalse;
962
963void *
964rb_objspace_alloc(void)
965{
966#if USE_MODULAR_GC
967 ruby_modular_gc_init();
968#endif
969
970 void *objspace = rb_gc_impl_objspace_alloc();
971 ruby_current_vm_ptr->gc.objspace = objspace;
972 rb_gc_impl_objspace_init(objspace);
973 rb_gc_impl_stress_set(objspace, initial_stress);
974
975#ifdef RUBY_ASAN_ENABLED
976 __sanitizer_set_death_callback(asan_death_callback);
977#endif
978
979 return objspace;
980}
981
982void
983rb_objspace_free(void *objspace)
984{
985 rb_gc_impl_objspace_free(objspace);
986}
987
988size_t
989rb_gc_obj_slot_size(VALUE obj)
990{
991 return rb_gc_impl_obj_slot_size(obj);
992}
993
994static inline void
995gc_validate_pc(VALUE obj)
996{
997#if RUBY_DEBUG
998 // IMEMOs and objects without a class (e.g managed id table) are not traceable
999 if (RB_TYPE_P(obj, T_IMEMO) || !CLASS_OF(obj)) return;
1000
1001 rb_execution_context_t *ec = GET_EC();
1002 const rb_control_frame_t *cfp = ec->cfp;
1003 if (cfp && VM_FRAME_RUBYFRAME_P(cfp) && CFP_PC(cfp)) {
1004 const VALUE *iseq_encoded = ISEQ_BODY(CFP_ISEQ(cfp))->iseq_encoded;
1005 const VALUE *iseq_encoded_end = iseq_encoded + ISEQ_BODY(CFP_ISEQ(cfp))->iseq_size;
1006 RUBY_ASSERT(CFP_PC(cfp) >= iseq_encoded, "PC not set when allocating, breaking tracing");
1007 RUBY_ASSERT(CFP_PC(cfp) <= iseq_encoded_end, "PC not set when allocating, breaking tracing");
1008 }
1009#endif
1010}
1011
1012NOINLINE(static void gc_newobj_hook(VALUE obj));
1013static void
1014gc_newobj_hook(VALUE obj)
1015{
1016 int lev = RB_GC_VM_LOCK_NO_BARRIER();
1017 {
1018 size_t slot_size = rb_gc_obj_slot_size(obj);
1019 memset((char *)obj + sizeof(struct RBasic), 0, slot_size - sizeof(struct RBasic));
1020
1021 /* We must disable GC here because the callback could call xmalloc
1022 * which could potentially trigger a GC, and a lot of code is unsafe
1023 * to trigger a GC right after an object has been allocated because
1024 * they perform initialization for the object and assume that the
1025 * GC does not trigger before then. */
1026 bool gc_disabled = RTEST(rb_gc_disable_no_rest());
1027 {
1028 rb_gc_event_hook(obj, RUBY_INTERNAL_EVENT_NEWOBJ);
1029 }
1030 if (!gc_disabled) rb_gc_enable();
1031 }
1032 RB_GC_VM_UNLOCK_NO_BARRIER(lev);
1033}
1034
1035static inline VALUE
1036newobj_of(rb_ractor_t *cr, VALUE klass, VALUE flags, shape_id_t shape_id, bool wb_protected, size_t size)
1037{
1038 VALUE obj = rb_gc_impl_new_obj(rb_gc_get_objspace(), cr->newobj_cache, klass, flags, wb_protected, size);
1039 RBASIC_SET_SHAPE_ID_NO_CHECKS(obj, shape_id);
1040
1041 gc_validate_pc(obj);
1042
1043 if (UNLIKELY(rb_gc_event_hook_required_p(RUBY_INTERNAL_EVENT_NEWOBJ))) {
1044 gc_newobj_hook(obj);
1045 }
1046
1047#if RGENGC_CHECK_MODE
1048# ifndef GC_DEBUG_SLOT_FILL_SPECIAL_VALUE
1049# define GC_DEBUG_SLOT_FILL_SPECIAL_VALUE 255
1050# endif
1051
1052 memset(
1053 (void *)(obj + sizeof(struct RBasic)),
1054 GC_DEBUG_SLOT_FILL_SPECIAL_VALUE,
1055 rb_gc_obj_slot_size(obj) - sizeof(struct RBasic)
1056 );
1057#endif
1058
1059 return obj;
1060}
1061
1062VALUE
1063rb_wb_unprotected_newobj_of(VALUE klass, VALUE flags, shape_id_t shape_id, size_t size)
1064{
1065 GC_ASSERT((flags & FL_WB_PROTECTED) == 0);
1066 return newobj_of(GET_RACTOR(), klass, flags, shape_id, FALSE, size);
1067}
1068
1069VALUE
1070rb_wb_protected_newobj_of(rb_execution_context_t *ec, VALUE klass, VALUE flags, shape_id_t shape_id, size_t size)
1071{
1072 GC_ASSERT((flags & FL_WB_PROTECTED) == 0);
1073 return newobj_of(rb_ec_ractor_ptr(ec), klass, flags, shape_id, TRUE, size);
1074}
1075
1076VALUE
1077rb_class_allocate_instance(VALUE klass)
1078{
1079 uint32_t index_tbl_num_entries = RCLASS_MAX_IV_COUNT(klass);
1080
1081 size_t size = rb_obj_embedded_size(index_tbl_num_entries);
1082 if (!rb_gc_size_allocatable_p(size)) {
1083 size = sizeof(struct RObject);
1084 }
1085
1086 // There might be a NEWOBJ tracepoint callback, and it may set fields.
1087 // So the shape must be passed to `NEWOBJ_OF`.
1089 NEWOBJ_OF_WITH_SHAPE(o, struct RObject, klass, flags, rb_shape_root(rb_gc_heap_id_for_size(size)), size, 0);
1090 VALUE obj = (VALUE)o;
1091
1092#if RUBY_DEBUG
1093 RUBY_ASSERT(!rb_shape_obj_too_complex_p(obj));
1094 VALUE *ptr = ROBJECT_FIELDS(obj);
1095 size_t fields_count = RSHAPE_LEN(RBASIC_SHAPE_ID(obj));
1096 for (size_t i = fields_count; i < ROBJECT_FIELDS_CAPACITY(obj); i++) {
1097 ptr[i] = Qundef;
1098 }
1099 if (rb_obj_class(obj) != rb_class_real(klass)) {
1100 rb_bug("Expected rb_class_allocate_instance to set the class correctly");
1101 }
1102#endif
1103
1104 return obj;
1105}
1106
1107void
1108rb_gc_register_pinning_obj(VALUE obj)
1109{
1110 rb_gc_impl_register_pinning_obj(rb_gc_get_objspace(), obj);
1111}
1112
1113#define UNEXPECTED_NODE(func) \
1114 rb_bug(#func"(): GC does not handle T_NODE 0x%x(%p) 0x%"PRIxVALUE, \
1115 BUILTIN_TYPE(obj), (void*)(obj), RBASIC(obj)->flags)
1116
1117static inline void
1118rb_data_object_check(VALUE klass)
1119{
1120 RUBY_ASSERT(!RCLASS_SINGLETON_P(klass));
1121 if (klass != rb_cObject && (rb_get_alloc_func(klass) == rb_class_allocate_instance)) {
1122 rb_undef_alloc_func(klass);
1123 rb_warn("undefining the allocator of T_DATA class %"PRIsVALUE, klass);
1124 }
1125}
1126
1127VALUE
1128rb_data_object_wrap(VALUE klass, void *datap, RUBY_DATA_FUNC dmark, RUBY_DATA_FUNC dfree)
1129{
1131 if (klass) rb_data_object_check(klass);
1132 VALUE obj = newobj_of(GET_RACTOR(), klass, T_DATA, ROOT_SHAPE_ID, !dmark, sizeof(struct RTypedData));
1133
1134 rb_gc_register_pinning_obj(obj);
1135
1136 struct RData *data = (struct RData *)obj;
1137 data->dmark = dmark;
1138 data->dfree = dfree;
1139 data->data = datap;
1140
1141 return obj;
1142}
1143
1144VALUE
1146{
1147 VALUE obj = rb_data_object_wrap(klass, 0, dmark, dfree);
1148 DATA_PTR(obj) = xcalloc(1, size);
1149 return obj;
1150}
1151
1152#define RTYPEDDATA_EMBEDDED_P rbimpl_typeddata_embedded_p
1153#define RB_DATA_TYPE_EMBEDDABLE_P(type) ((type)->flags & RUBY_TYPED_EMBEDDABLE)
1154#define RTYPEDDATA_EMBEDDABLE_P(obj) RB_DATA_TYPE_EMBEDDABLE_P(RTYPEDDATA_TYPE(obj))
1155
1156static VALUE
1157typed_data_alloc(VALUE klass, VALUE typed_flag, void *datap, const rb_data_type_t *type, size_t size)
1158{
1159 RBIMPL_NONNULL_ARG(type);
1160 if (klass) rb_data_object_check(klass);
1161 bool wb_protected = (type->flags & RUBY_FL_WB_PROTECTED) || !type->function.dmark;
1162 VALUE obj = newobj_of(GET_RACTOR(), klass, T_DATA | RUBY_TYPED_FL_IS_TYPED_DATA, ROOT_SHAPE_ID, wb_protected, size);
1163
1164 rb_gc_register_pinning_obj(obj);
1165
1166 struct RTypedData *data = (struct RTypedData *)obj;
1167 data->fields_obj = 0;
1168 *(VALUE *)&data->type = ((VALUE)type) | typed_flag;
1169 data->data = datap;
1170
1171 return obj;
1172}
1173
1174VALUE
1176{
1177 if (UNLIKELY(RB_DATA_TYPE_EMBEDDABLE_P(type))) {
1178 rb_raise(rb_eTypeError, "Cannot wrap an embeddable TypedData");
1179 }
1180
1181 return typed_data_alloc(klass, 0, datap, type, sizeof(struct RTypedData));
1182}
1183
1184VALUE
1186{
1187 if (RB_DATA_TYPE_EMBEDDABLE_P(type)) {
1188 if (!(type->flags & RUBY_TYPED_FREE_IMMEDIATELY)) {
1189 rb_raise(rb_eTypeError, "Embeddable TypedData must be freed immediately");
1190 }
1191
1192 size_t embed_size = offsetof(struct RTypedData, data) + size;
1193 if (rb_gc_size_allocatable_p(embed_size)) {
1194 VALUE obj = typed_data_alloc(klass, TYPED_DATA_EMBEDDED, 0, type, embed_size);
1195 memset((char *)obj + offsetof(struct RTypedData, data), 0, size);
1196 return obj;
1197 }
1198 }
1199
1200 VALUE obj = typed_data_alloc(klass, 0, NULL, type, sizeof(struct RTypedData));
1201 DATA_PTR(obj) = xcalloc(1, size);
1202 return obj;
1203}
1204
1205static size_t
1206rb_objspace_data_type_memsize(VALUE obj)
1207{
1208 size_t size = 0;
1209 if (RTYPEDDATA_P(obj)) {
1210 const void *ptr = RTYPEDDATA_GET_DATA(obj);
1211
1212 if (ptr) {
1213 const rb_data_type_t *type = RTYPEDDATA_TYPE(obj);
1214 if (RTYPEDDATA_EMBEDDABLE_P(obj) && !RTYPEDDATA_EMBEDDED_P(obj)) {
1215#ifdef HAVE_MALLOC_USABLE_SIZE
1216 size += malloc_usable_size((void *)ptr);
1217#endif
1218 }
1219
1220 if (type->function.dsize) {
1221 size += type->function.dsize(ptr);
1222 }
1223 }
1224 }
1225
1226 return size;
1227}
1228
1229const char *
1230rb_objspace_data_type_name(VALUE obj)
1231{
1232 if (RTYPEDDATA_P(obj)) {
1233 return RTYPEDDATA_TYPE(obj)->wrap_struct_name;
1234 }
1235 else {
1236 return 0;
1237 }
1238}
1239
1240void
1241rb_gc_declare_weak_references(VALUE obj)
1242{
1243 rb_gc_impl_declare_weak_references(rb_gc_get_objspace(), obj);
1244}
1245
1246bool
1247rb_gc_handle_weak_references_alive_p(VALUE obj)
1248{
1249 if (SPECIAL_CONST_P(obj)) return true;
1250
1251 return rb_gc_impl_handle_weak_references_alive_p(rb_gc_get_objspace(), obj);
1252}
1253
1254void
1255rb_gc_handle_weak_references(VALUE obj)
1256{
1257 switch (BUILTIN_TYPE(obj)) {
1258 case T_DATA:
1259 if (RTYPEDDATA_P(obj)) {
1260 const rb_data_type_t *type = RTYPEDDATA_TYPE(obj);
1261
1262 if (type->function.handle_weak_references) {
1263 (type->function.handle_weak_references)(RTYPEDDATA_GET_DATA(obj));
1264 }
1265 else {
1266 rb_bug(
1267 "rb_gc_handle_weak_references: TypedData %s does not implement handle_weak_references",
1268 RTYPEDDATA_TYPE(obj)->wrap_struct_name
1269 );
1270 }
1271 }
1272 else {
1273 rb_bug("rb_gc_handle_weak_references: unknown T_DATA");
1274 }
1275 break;
1276
1277 case T_IMEMO: {
1278 GC_ASSERT(imemo_type(obj) == imemo_callcache);
1279
1280 struct rb_callcache *cc = (struct rb_callcache *)obj;
1281 if (cc->klass != Qundef &&
1282 (!rb_gc_handle_weak_references_alive_p(cc->klass) ||
1283 !rb_gc_handle_weak_references_alive_p((VALUE)cc->cme_))) {
1284 vm_cc_invalidate(cc);
1285 }
1286
1287 break;
1288 }
1289 default:
1290 rb_bug("rb_gc_handle_weak_references: type not supported\n");
1291 }
1292}
1293
1294static inline bool
1295rb_gc_imemo_needs_cleanup_p(VALUE obj)
1296{
1297 switch (imemo_type(obj)) {
1298 case imemo_constcache:
1299 case imemo_cref:
1300 case imemo_ifunc:
1301 case imemo_memo:
1302 case imemo_svar:
1303 case imemo_callcache:
1304 case imemo_throw_data:
1305 return false;
1306
1307 case imemo_env:
1308 case imemo_ment:
1309 case imemo_iseq:
1310 case imemo_callinfo:
1311 return true;
1312
1313 case imemo_tmpbuf:
1314 return ((rb_imemo_tmpbuf_t *)obj)->ptr != NULL;
1315
1316 case imemo_fields:
1317 return FL_TEST_RAW(obj, OBJ_FIELD_HEAP) || (id2ref_tbl && rb_shape_obj_has_id(obj));
1318 }
1319 UNREACHABLE_RETURN(true);
1320}
1321
1322/*
1323 * Returns true if the object requires a full rb_gc_obj_free() call during sweep,
1324 * false if it can be freed quickly without calling destructors or cleanup.
1325 *
1326 * Objects that return false are:
1327 * - Simple embedded objects without external allocations
1328 * - Objects without finalizers
1329 * - Objects without object IDs registered in id2ref
1330 * - Objects without generic instance variables
1331 *
1332 * This is used by the GC sweep fast path to avoid function call overhead
1333 * for the majority of simple objects.
1334 */
1335bool
1336rb_gc_obj_needs_cleanup_p(VALUE obj)
1337{
1338 VALUE flags = RBASIC(obj)->flags;
1339
1340 if (flags & FL_FINALIZE) return true;
1341
1342 switch (flags & RUBY_T_MASK) {
1343 case T_IMEMO:
1344 return rb_gc_imemo_needs_cleanup_p(obj);
1345
1346 case T_DATA:
1347 case T_OBJECT:
1348 case T_STRING:
1349 case T_ARRAY:
1350 case T_HASH:
1351 case T_BIGNUM:
1352 case T_STRUCT:
1353 case T_FLOAT:
1354 case T_RATIONAL:
1355 case T_COMPLEX:
1356 break;
1357
1358 case T_FILE:
1359 case T_SYMBOL:
1360 case T_CLASS:
1361 case T_ICLASS:
1362 case T_MODULE:
1363 case T_REGEXP:
1364 case T_MATCH:
1365 return true;
1366 }
1367
1368 shape_id_t shape_id = RBASIC_SHAPE_ID(obj);
1369 if (id2ref_tbl && rb_shape_has_object_id(shape_id)) return true;
1370
1371 switch (flags & RUBY_T_MASK) {
1372 case T_OBJECT:
1373 if (flags & ROBJECT_HEAP) return true;
1374 return false;
1375
1376 case T_DATA:
1377 if (flags & RUBY_TYPED_FL_IS_TYPED_DATA) {
1378 uintptr_t type = (uintptr_t)RTYPEDDATA(obj)->type;
1379 if (type & TYPED_DATA_EMBEDDED) {
1380 RUBY_DATA_FUNC dfree = ((const rb_data_type_t *)(type & TYPED_DATA_PTR_MASK))->function.dfree;
1381 if (dfree == RUBY_NEVER_FREE || dfree == RUBY_TYPED_DEFAULT_FREE) {
1382 return false;
1383 }
1384 }
1385 }
1386 return true;
1387
1388 case T_STRING:
1389 if (flags & (RSTRING_NOEMBED | RSTRING_FSTR)) return true;
1390 return rb_shape_has_fields(shape_id);
1391
1392 case T_ARRAY:
1393 if (!(flags & RARRAY_EMBED_FLAG)) return true;
1394 return rb_shape_has_fields(shape_id);
1395
1396 case T_HASH:
1397 if (flags & RHASH_ST_TABLE_FLAG) return true;
1398 return rb_shape_has_fields(shape_id);
1399
1400 case T_BIGNUM:
1401 if (!(flags & BIGNUM_EMBED_FLAG)) return true;
1402 return rb_shape_has_fields(shape_id);
1403
1404 case T_STRUCT:
1405 if (!(flags & RSTRUCT_EMBED_LEN_MASK)) return true;
1406 if (flags & RSTRUCT_GEN_FIELDS) return rb_shape_has_fields(shape_id);
1407 return false;
1408
1409 case T_FLOAT:
1410 case T_RATIONAL:
1411 case T_COMPLEX:
1412 return rb_shape_has_fields(shape_id);
1413
1414 default:
1415 UNREACHABLE_RETURN(true);
1416 }
1417}
1418
1419static void
1420io_fptr_finalize(void *fptr)
1421{
1422 rb_io_fptr_finalize((struct rb_io *)fptr);
1423}
1424
1425static inline void
1426make_io_zombie(void *objspace, VALUE obj)
1427{
1428 rb_io_t *fptr = RFILE(obj)->fptr;
1429 rb_gc_impl_make_zombie(objspace, obj, io_fptr_finalize, fptr);
1430}
1431
1432static bool
1433rb_data_free(void *objspace, VALUE obj)
1434{
1435 void *data = RTYPEDDATA_P(obj) ? RTYPEDDATA_GET_DATA(obj) : DATA_PTR(obj);
1436 if (data) {
1437 int free_immediately = false;
1438 void (*dfree)(void *);
1439
1440 if (RTYPEDDATA_P(obj)) {
1441 free_immediately = (RTYPEDDATA_TYPE(obj)->flags & RUBY_TYPED_FREE_IMMEDIATELY) != 0;
1442 dfree = RTYPEDDATA_TYPE(obj)->function.dfree;
1443 }
1444 else {
1445 dfree = RDATA(obj)->dfree;
1446 }
1447
1448 if (dfree) {
1449 if (dfree == RUBY_DEFAULT_FREE) {
1450 if (!RTYPEDDATA_P(obj) || !RTYPEDDATA_EMBEDDED_P(obj)) {
1451 xfree(data);
1452 RB_DEBUG_COUNTER_INC(obj_data_xfree);
1453 }
1454 }
1455 else if (free_immediately) {
1456 (*dfree)(data);
1457 if (RTYPEDDATA_EMBEDDABLE_P(obj) && !RTYPEDDATA_EMBEDDED_P(obj)) {
1458 xfree(data);
1459 }
1460
1461 RB_DEBUG_COUNTER_INC(obj_data_imm_free);
1462 }
1463 else {
1464 rb_gc_impl_make_zombie(objspace, obj, dfree, data);
1465 RB_DEBUG_COUNTER_INC(obj_data_zombie);
1466 return FALSE;
1467 }
1468 }
1469 else {
1470 RB_DEBUG_COUNTER_INC(obj_data_empty);
1471 }
1472 }
1473
1474 return true;
1475}
1476
1478 VALUE klass;
1479 rb_objspace_t *objspace; // used for update_*
1480};
1481
1482static void
1483classext_free(rb_classext_t *ext, bool is_prime, VALUE box_value, void *arg)
1484{
1485 struct classext_foreach_args *args = (struct classext_foreach_args *)arg;
1486
1487 rb_class_classext_free(args->klass, ext, is_prime);
1488}
1489
1490static void
1491classext_iclass_free(rb_classext_t *ext, bool is_prime, VALUE box_value, void *arg)
1492{
1493 struct classext_foreach_args *args = (struct classext_foreach_args *)arg;
1494
1495 rb_iclass_classext_free(args->klass, ext, is_prime);
1496}
1497
1498bool
1499rb_gc_obj_free(void *objspace, VALUE obj)
1500{
1501 struct classext_foreach_args args;
1502
1503 RB_DEBUG_COUNTER_INC(obj_free);
1504
1505 switch (BUILTIN_TYPE(obj)) {
1506 case T_NIL:
1507 case T_FIXNUM:
1508 case T_TRUE:
1509 case T_FALSE:
1510 rb_bug("obj_free() called for broken object");
1511 break;
1512 default:
1513 break;
1514 }
1515
1516 switch (BUILTIN_TYPE(obj)) {
1517 case T_OBJECT:
1518 if (FL_TEST_RAW(obj, ROBJECT_HEAP)) {
1519 if (rb_shape_obj_too_complex_p(obj)) {
1520 RB_DEBUG_COUNTER_INC(obj_obj_too_complex);
1521 st_free_table(ROBJECT_FIELDS_HASH(obj));
1522 }
1523 else {
1524 SIZED_FREE_N(ROBJECT(obj)->as.heap.fields, ROBJECT_FIELDS_CAPACITY(obj));
1525 RB_DEBUG_COUNTER_INC(obj_obj_ptr);
1526 }
1527 }
1528 else {
1529 RB_DEBUG_COUNTER_INC(obj_obj_embed);
1530 }
1531 break;
1532 case T_MODULE:
1533 case T_CLASS:
1534#if USE_ZJIT
1535 rb_zjit_klass_free(obj);
1536#endif
1537 args.klass = obj;
1538 rb_class_classext_foreach(obj, classext_free, (void *)&args);
1539 if (RCLASS_CLASSEXT_TBL(obj)) {
1540 st_free_table(RCLASS_CLASSEXT_TBL(obj));
1541 }
1542 (void)RB_DEBUG_COUNTER_INC_IF(obj_module_ptr, BUILTIN_TYPE(obj) == T_MODULE);
1543 (void)RB_DEBUG_COUNTER_INC_IF(obj_class_ptr, BUILTIN_TYPE(obj) == T_CLASS);
1544 break;
1545 case T_STRING:
1546 rb_str_free(obj);
1547 break;
1548 case T_ARRAY:
1549 rb_ary_free(obj);
1550 break;
1551 case T_HASH:
1552#if USE_DEBUG_COUNTER
1553 switch (RHASH_SIZE(obj)) {
1554 case 0:
1555 RB_DEBUG_COUNTER_INC(obj_hash_empty);
1556 break;
1557 case 1:
1558 RB_DEBUG_COUNTER_INC(obj_hash_1);
1559 break;
1560 case 2:
1561 RB_DEBUG_COUNTER_INC(obj_hash_2);
1562 break;
1563 case 3:
1564 RB_DEBUG_COUNTER_INC(obj_hash_3);
1565 break;
1566 case 4:
1567 RB_DEBUG_COUNTER_INC(obj_hash_4);
1568 break;
1569 case 5:
1570 case 6:
1571 case 7:
1572 case 8:
1573 RB_DEBUG_COUNTER_INC(obj_hash_5_8);
1574 break;
1575 default:
1576 GC_ASSERT(RHASH_SIZE(obj) > 8);
1577 RB_DEBUG_COUNTER_INC(obj_hash_g8);
1578 }
1579
1580 if (RHASH_AR_TABLE_P(obj)) {
1581 if (RHASH_AR_TABLE(obj) == NULL) {
1582 RB_DEBUG_COUNTER_INC(obj_hash_null);
1583 }
1584 else {
1585 RB_DEBUG_COUNTER_INC(obj_hash_ar);
1586 }
1587 }
1588 else {
1589 RB_DEBUG_COUNTER_INC(obj_hash_st);
1590 }
1591#endif
1592
1593 rb_hash_free(obj);
1594 break;
1595 case T_REGEXP:
1596 if (RREGEXP(obj)->ptr) {
1597 onig_free(RREGEXP(obj)->ptr);
1598 RB_DEBUG_COUNTER_INC(obj_regexp_ptr);
1599 }
1600 break;
1601 case T_DATA:
1602 if (!rb_data_free(objspace, obj)) return false;
1603 break;
1604 case T_MATCH:
1605 {
1606 rb_matchext_t *rm = RMATCH_EXT(obj);
1607#if USE_DEBUG_COUNTER
1608 if (rm->regs.num_regs >= 8) {
1609 RB_DEBUG_COUNTER_INC(obj_match_ge8);
1610 }
1611 else if (rm->regs.num_regs >= 4) {
1612 RB_DEBUG_COUNTER_INC(obj_match_ge4);
1613 }
1614 else if (rm->regs.num_regs >= 1) {
1615 RB_DEBUG_COUNTER_INC(obj_match_under4);
1616 }
1617#endif
1618 onig_region_free(&rm->regs, 0);
1619 SIZED_FREE_N(rm->char_offset, rm->char_offset_num_allocated);
1620
1621 RB_DEBUG_COUNTER_INC(obj_match_ptr);
1622 }
1623 break;
1624 case T_FILE:
1625 if (RFILE(obj)->fptr) {
1626 make_io_zombie(objspace, obj);
1627 RB_DEBUG_COUNTER_INC(obj_file_ptr);
1628 return FALSE;
1629 }
1630 break;
1631 case T_RATIONAL:
1632 RB_DEBUG_COUNTER_INC(obj_rational);
1633 break;
1634 case T_COMPLEX:
1635 RB_DEBUG_COUNTER_INC(obj_complex);
1636 break;
1637 case T_MOVED:
1638 break;
1639 case T_ICLASS:
1640 args.klass = obj;
1641
1642 rb_class_classext_foreach(obj, classext_iclass_free, (void *)&args);
1643 if (RCLASS_CLASSEXT_TBL(obj)) {
1644 st_free_table(RCLASS_CLASSEXT_TBL(obj));
1645 }
1646
1647 RB_DEBUG_COUNTER_INC(obj_iclass_ptr);
1648 break;
1649
1650 case T_FLOAT:
1651 RB_DEBUG_COUNTER_INC(obj_float);
1652 break;
1653
1654 case T_BIGNUM:
1655 if (!BIGNUM_EMBED_P(obj) && BIGNUM_DIGITS(obj)) {
1656 SIZED_FREE_N(BIGNUM_DIGITS(obj), BIGNUM_LEN(obj));
1657 RB_DEBUG_COUNTER_INC(obj_bignum_ptr);
1658 }
1659 else {
1660 RB_DEBUG_COUNTER_INC(obj_bignum_embed);
1661 }
1662 break;
1663
1664 case T_NODE:
1665 UNEXPECTED_NODE(obj_free);
1666 break;
1667
1668 case T_STRUCT:
1669 if ((RBASIC(obj)->flags & RSTRUCT_EMBED_LEN_MASK) ||
1670 RSTRUCT(obj)->as.heap.ptr == NULL) {
1671 RB_DEBUG_COUNTER_INC(obj_struct_embed);
1672 }
1673 else {
1674 SIZED_FREE_N(RSTRUCT(obj)->as.heap.ptr, RSTRUCT(obj)->as.heap.len);
1675 RB_DEBUG_COUNTER_INC(obj_struct_ptr);
1676 }
1677 break;
1678
1679 case T_SYMBOL:
1680 RB_DEBUG_COUNTER_INC(obj_symbol);
1681 break;
1682
1683 case T_IMEMO:
1684 rb_imemo_free((VALUE)obj);
1685 break;
1686
1687 default:
1688 rb_bug("gc_sweep(): unknown data type 0x%x(%p) 0x%"PRIxVALUE,
1689 BUILTIN_TYPE(obj), (void*)obj, RBASIC(obj)->flags);
1690 }
1691
1692 if (FL_TEST_RAW(obj, FL_FINALIZE)) {
1693 rb_gc_impl_make_zombie(objspace, obj, 0, 0);
1694 return FALSE;
1695 }
1696 else {
1697 return TRUE;
1698 }
1699}
1700
1701void
1702rb_objspace_set_event_hook(const rb_event_flag_t event)
1703{
1704 rb_gc_impl_set_event_hook(rb_gc_get_objspace(), event);
1705}
1706
1707static int
1708internal_object_p(VALUE obj)
1709{
1710 void *ptr = asan_unpoison_object_temporary(obj);
1711
1712 if (RBASIC(obj)->flags) {
1713 switch (BUILTIN_TYPE(obj)) {
1714 case T_NODE:
1715 UNEXPECTED_NODE(internal_object_p);
1716 break;
1717 case T_NONE:
1718 case T_MOVED:
1719 case T_IMEMO:
1720 case T_ICLASS:
1721 case T_ZOMBIE:
1722 break;
1723 case T_CLASS:
1724 if (obj == rb_mRubyVMFrozenCore)
1725 return 1;
1726
1727 if (!RBASIC_CLASS(obj)) break;
1728 if (RCLASS_SINGLETON_P(obj)) {
1729 return rb_singleton_class_internal_p(obj);
1730 }
1731 return 0;
1732 default:
1733 if (!RBASIC(obj)->klass) break;
1734 return 0;
1735 }
1736 }
1737 if (ptr || !RBASIC(obj)->flags) {
1738 rb_asan_poison_object(obj);
1739 }
1740 return 1;
1741}
1742
1743int
1744rb_objspace_internal_object_p(VALUE obj)
1745{
1746 return internal_object_p(obj);
1747}
1748
1750 size_t num;
1751 VALUE of;
1752};
1753
1754static int
1755os_obj_of_i(void *vstart, void *vend, size_t stride, void *data)
1756{
1757 struct os_each_struct *oes = (struct os_each_struct *)data;
1758
1759 VALUE v = (VALUE)vstart;
1760 for (; v != (VALUE)vend; v += stride) {
1761 if (!internal_object_p(v)) {
1762 if (!oes->of || rb_obj_is_kind_of(v, oes->of)) {
1763 if (!rb_multi_ractor_p() || rb_ractor_shareable_p(v)) {
1764 rb_yield(v);
1765 oes->num++;
1766 }
1767 }
1768 }
1769 }
1770
1771 return 0;
1772}
1773
1774static VALUE
1775os_obj_of(VALUE of)
1776{
1777 struct os_each_struct oes;
1778
1779 oes.num = 0;
1780 oes.of = of;
1781 rb_objspace_each_objects(os_obj_of_i, &oes);
1782 return SIZET2NUM(oes.num);
1783}
1784
1785/*
1786 * call-seq:
1787 * ObjectSpace.each_object([module]) {|obj| ... } -> integer
1788 * ObjectSpace.each_object([module]) -> an_enumerator
1789 *
1790 * Calls the block once for each living, nonimmediate object in this
1791 * Ruby process. If <i>module</i> is specified, calls the block
1792 * for only those classes or modules that match (or are a subclass of)
1793 * <i>module</i>. Returns the number of objects found. Immediate
1794 * objects (such as <code>Fixnum</code>s, static <code>Symbol</code>s
1795 * <code>true</code>, <code>false</code> and <code>nil</code>) are
1796 * never returned.
1797 *
1798 * If no block is given, an enumerator is returned instead.
1799 *
1800 * Job = Class.new
1801 * jobs = [Job.new, Job.new]
1802 * count = ObjectSpace.each_object(Job) {|x| p x }
1803 * puts "Total count: #{count}"
1804 *
1805 * <em>produces:</em>
1806 *
1807 * #<Job:0x000000011d6cbbf0>
1808 * #<Job:0x000000011d6cbc68>
1809 * Total count: 2
1810 *
1811 * Due to a current Ractor implementation issue, this method does not yield
1812 * Ractor-unshareable objects when the process is in multi-Ractor mode. Multi-ractor
1813 * mode is enabled when <code>Ractor.new</code> has been called for the first time.
1814 * See https://bugs.ruby-lang.org/issues/19387 for more information.
1815 *
1816 * a = 12345678987654321 # shareable
1817 * b = [].freeze # shareable
1818 * c = {} # not shareable
1819 * ObjectSpace.each_object {|x| x } # yields a, b, and c
1820 * Ractor.new {} # enter multi-Ractor mode
1821 * ObjectSpace.each_object {|x| x } # does not yield c
1822 *
1823 */
1824
1825static VALUE
1826os_each_obj(int argc, VALUE *argv, VALUE os)
1827{
1828 VALUE of;
1829
1830 of = (!rb_check_arity(argc, 0, 1) ? 0 : argv[0]);
1831 RETURN_ENUMERATOR(os, 1, &of);
1832 return os_obj_of(of);
1833}
1834
1835/*
1836 * call-seq:
1837 * ObjectSpace.undefine_finalizer(obj)
1838 *
1839 * Removes all finalizers for <i>obj</i>.
1840 *
1841 */
1842
1843static VALUE
1844undefine_final(VALUE os, VALUE obj)
1845{
1846 return rb_undefine_finalizer(obj);
1847}
1848
1849VALUE
1850rb_undefine_finalizer(VALUE obj)
1851{
1852 rb_check_frozen(obj);
1853
1854 rb_gc_impl_undefine_finalizer(rb_gc_get_objspace(), obj);
1855
1856 return obj;
1857}
1858
1859static void
1860should_be_callable(VALUE block)
1861{
1862 if (!rb_obj_respond_to(block, idCall, TRUE)) {
1863 rb_raise(rb_eArgError, "wrong type argument %"PRIsVALUE" (should be callable)",
1864 rb_obj_class(block));
1865 }
1866}
1867
1868static void
1869should_be_finalizable(VALUE obj)
1870{
1871 if (!FL_ABLE(obj)) {
1872 rb_raise(rb_eArgError, "cannot define finalizer for %s",
1873 rb_obj_classname(obj));
1874 }
1875 rb_check_frozen(obj);
1876}
1877
1878void
1879rb_gc_copy_finalizer(VALUE dest, VALUE obj)
1880{
1881 rb_gc_impl_copy_finalizer(rb_gc_get_objspace(), dest, obj);
1882}
1883
1884/*
1885 * call-seq:
1886 * ObjectSpace.define_finalizer(obj) {|id| ... } -> array
1887 * ObjectSpace.define_finalizer(obj, finalizer) -> array
1888 *
1889 * Adds a new finalizer for +obj+ that is called when +obj+ is destroyed
1890 * by the garbage collector or when Ruby shuts down (which ever comes first).
1891 *
1892 * With a block given, uses the block as the callback. Without a block given,
1893 * uses a callable object +finalizer+ as the callback. The callback is called
1894 * when +obj+ is destroyed with a single argument +id+ which is the object
1895 * ID of +obj+ (see Object#object_id).
1896 *
1897 * The return value is an array <code>[0, callback]</code>, where +callback+
1898 * is a Proc created from the block if one was given or +finalizer+ otherwise.
1899 *
1900 * Note that defining a finalizer in an instance method of the object may prevent
1901 * the object from being garbage collected since if the block or +finalizer+ refers
1902 * to +obj+ then +obj+ will never be reclaimed by the garbage collector. For example,
1903 * the following script demonstrates the issue:
1904 *
1905 * class Foo
1906 * def define_final
1907 * ObjectSpace.define_finalizer(self) do |id|
1908 * puts "Running finalizer for #{id}!"
1909 * end
1910 * end
1911 * end
1912 *
1913 * obj = Foo.new
1914 * obj.define_final
1915 *
1916 * There are two patterns to solve this issue:
1917 *
1918 * - Create the finalizer in a non-instance method so it can safely capture
1919 * the needed state:
1920 *
1921 * class Foo
1922 * def define_final
1923 * ObjectSpace.define_finalizer(self, self.class.create_finalizer)
1924 * end
1925 *
1926 * def self.create_finalizer
1927 * proc do |id|
1928 * puts "Running finalizer for #{id}!"
1929 * end
1930 * end
1931 * end
1932 *
1933 * - Use a callable object:
1934 *
1935 * class Foo
1936 * class Finalizer
1937 * def call(id)
1938 * puts "Running finalizer for #{id}!"
1939 * end
1940 * end
1941 *
1942 * def define_final
1943 * ObjectSpace.define_finalizer(self, Finalizer.new)
1944 * end
1945 * end
1946 *
1947 * Note that finalization can be unpredictable and is never guaranteed
1948 * to be run except on exit.
1949 */
1950
1951static VALUE
1952define_final(int argc, VALUE *argv, VALUE os)
1953{
1954 VALUE obj, block;
1955
1956 rb_scan_args(argc, argv, "11", &obj, &block);
1957 if (argc == 1) {
1958 block = rb_block_proc();
1959 }
1960
1961 if (rb_callable_receiver(block) == obj) {
1962 rb_warn("finalizer references object to be finalized");
1963 }
1964
1965 return rb_define_finalizer(obj, block);
1966}
1967
1968VALUE
1969rb_define_finalizer(VALUE obj, VALUE block)
1970{
1971 should_be_finalizable(obj);
1972 should_be_callable(block);
1973
1974 block = rb_gc_impl_define_finalizer(rb_gc_get_objspace(), obj, block);
1975
1976 block = rb_ary_new3(2, INT2FIX(0), block);
1977 OBJ_FREEZE(block);
1978 return block;
1979}
1980
1981void
1982rb_objspace_call_finalizer(void)
1983{
1984 rb_gc_impl_shutdown_call_finalizer(rb_gc_get_objspace());
1985}
1986
1987void
1988rb_objspace_free_objects(void *objspace)
1989{
1990 rb_gc_impl_shutdown_free_objects(objspace);
1991}
1992
1993int
1994rb_objspace_garbage_object_p(VALUE obj)
1995{
1996 return !SPECIAL_CONST_P(obj) && rb_gc_impl_garbage_object_p(rb_gc_get_objspace(), obj);
1997}
1998
1999bool
2000rb_gc_pointer_to_heap_p(VALUE obj)
2001{
2002 return rb_gc_impl_pointer_to_heap_p(rb_gc_get_objspace(), (void *)obj);
2003}
2004
2005#define OBJ_ID_INCREMENT (RUBY_IMMEDIATE_MASK + 1)
2006#define LAST_OBJECT_ID() (object_id_counter * OBJ_ID_INCREMENT)
2007static VALUE id2ref_value = 0;
2008
2009#if SIZEOF_SIZE_T == SIZEOF_LONG_LONG
2010static size_t object_id_counter = 1;
2011#else
2012static unsigned long long object_id_counter = 1;
2013#endif
2014
2015static inline VALUE
2016generate_next_object_id(void)
2017{
2018#if SIZEOF_SIZE_T == SIZEOF_LONG_LONG
2019 // 64bit atomics are available
2020 return SIZET2NUM(RUBY_ATOMIC_SIZE_FETCH_ADD(object_id_counter, 1) * OBJ_ID_INCREMENT);
2021#else
2022 unsigned int lock_lev = RB_GC_VM_LOCK();
2023 VALUE id = ULL2NUM(++object_id_counter * OBJ_ID_INCREMENT);
2024 RB_GC_VM_UNLOCK(lock_lev);
2025 return id;
2026#endif
2027}
2028
2029void
2030rb_gc_obj_id_moved(VALUE obj)
2031{
2032 if (UNLIKELY(id2ref_tbl)) {
2033 st_insert(id2ref_tbl, (st_data_t)rb_obj_id(obj), (st_data_t)obj);
2034 }
2035}
2036
2037static int
2038object_id_cmp(st_data_t x, st_data_t y)
2039{
2040 if (RB_TYPE_P(x, T_BIGNUM)) {
2041 return !rb_big_eql(x, y);
2042 }
2043 else {
2044 return x != y;
2045 }
2046}
2047
2048static st_index_t
2049object_id_hash(st_data_t n)
2050{
2051 return FIX2LONG(rb_hash((VALUE)n));
2052}
2053
2054static const struct st_hash_type object_id_hash_type = {
2055 object_id_cmp,
2056 object_id_hash,
2057};
2058
2059static void gc_mark_tbl_no_pin(st_table *table);
2060
2061static void
2062id2ref_tbl_mark(void *data)
2063{
2064 st_table *table = (st_table *)data;
2065 if (UNLIKELY(!RB_POSFIXABLE(LAST_OBJECT_ID()))) {
2066 // It's very unlikely, but if enough object ids were generated, keys may be T_BIGNUM
2067 rb_mark_set(table);
2068 }
2069 // We purposely don't mark values, as they are weak references.
2070 // rb_gc_obj_free_vm_weak_references takes care of cleaning them up.
2071}
2072
2073static size_t
2074id2ref_tbl_memsize(const void *data)
2075{
2076 return rb_st_memsize(data);
2077}
2078
2079static void
2080id2ref_tbl_free(void *data)
2081{
2082 id2ref_tbl = NULL; // clear global ref
2083 st_table *table = (st_table *)data;
2084 st_free_table(table);
2085}
2086
2087static const rb_data_type_t id2ref_tbl_type = {
2088 .wrap_struct_name = "VM/_id2ref_table",
2089 .function = {
2090 .dmark = id2ref_tbl_mark,
2091 .dfree = id2ref_tbl_free,
2092 .dsize = id2ref_tbl_memsize,
2093 // dcompact function not required because the table is reference updated
2094 // in rb_gc_vm_weak_table_foreach
2095 },
2096 .flags = RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_FREE_IMMEDIATELY
2097};
2098
2099static VALUE
2100class_object_id(VALUE klass)
2101{
2102 VALUE id = RUBY_ATOMIC_VALUE_LOAD(RCLASS(klass)->object_id);
2103 if (!id) {
2104 unsigned int lock_lev = RB_GC_VM_LOCK();
2105 id = generate_next_object_id();
2106 VALUE existing_id = RUBY_ATOMIC_VALUE_CAS(RCLASS(klass)->object_id, 0, id);
2107 if (existing_id) {
2108 id = existing_id;
2109 }
2110 else if (RB_UNLIKELY(id2ref_tbl)) {
2111 st_insert(id2ref_tbl, id, klass);
2112 }
2113 RB_GC_VM_UNLOCK(lock_lev);
2114 }
2115 return id;
2116}
2117
2118static inline VALUE
2119object_id_get(VALUE obj, shape_id_t shape_id)
2120{
2121 VALUE id;
2122 if (rb_shape_too_complex_p(shape_id)) {
2123 id = rb_obj_field_get(obj, ROOT_TOO_COMPLEX_WITH_OBJ_ID);
2124 }
2125 else {
2126 id = rb_obj_field_get(obj, rb_shape_object_id(shape_id));
2127 }
2128
2129#if RUBY_DEBUG
2130 if (!(FIXNUM_P(id) || RB_TYPE_P(id, T_BIGNUM))) {
2131 rb_p(obj);
2132 rb_bug("Object's shape includes object_id, but it's missing %s", rb_obj_info(obj));
2133 }
2134#endif
2135
2136 return id;
2137}
2138
2139static VALUE
2140object_id0(VALUE obj)
2141{
2142 VALUE id = Qfalse;
2143 shape_id_t shape_id = RBASIC_SHAPE_ID(obj);
2144
2145 if (rb_shape_has_object_id(shape_id)) {
2146 return object_id_get(obj, shape_id);
2147 }
2148
2149 shape_id_t object_id_shape_id = rb_shape_transition_object_id(obj);
2150
2151 id = generate_next_object_id();
2152 rb_obj_field_set(obj, object_id_shape_id, 0, id);
2153
2154 RUBY_ASSERT(RBASIC_SHAPE_ID(obj) == object_id_shape_id);
2155 RUBY_ASSERT(rb_shape_obj_has_id(obj));
2156
2157 if (RB_UNLIKELY(id2ref_tbl)) {
2158 RB_VM_LOCKING() {
2159 st_insert(id2ref_tbl, (st_data_t)id, (st_data_t)obj);
2160 }
2161 }
2162 return id;
2163}
2164
2165static VALUE
2166object_id(VALUE obj)
2167{
2168 switch (BUILTIN_TYPE(obj)) {
2169 case T_CLASS:
2170 case T_MODULE:
2171 // With Ruby Box, classes and modules have different fields
2172 // in different boxes, so we cannot store the object id
2173 // in fields.
2174 return class_object_id(obj);
2175 case T_IMEMO:
2176 RUBY_ASSERT(IMEMO_TYPE_P(obj, imemo_fields));
2177 break;
2178 default:
2179 break;
2180 }
2181
2182 if (UNLIKELY(rb_gc_multi_ractor_p() && rb_ractor_shareable_p(obj))) {
2183 unsigned int lock_lev = RB_GC_VM_LOCK();
2184 VALUE id = object_id0(obj);
2185 RB_GC_VM_UNLOCK(lock_lev);
2186 return id;
2187 }
2188
2189 return object_id0(obj);
2190}
2191
2192static void
2193build_id2ref_i(VALUE obj, void *data)
2194{
2195 st_table *id2ref_tbl = (st_table *)data;
2196
2197 switch (BUILTIN_TYPE(obj)) {
2198 case T_CLASS:
2199 case T_MODULE:
2200 RUBY_ASSERT(!rb_objspace_garbage_object_p(obj));
2201 if (RCLASS(obj)->object_id) {
2202 st_insert(id2ref_tbl, RCLASS(obj)->object_id, obj);
2203 }
2204 break;
2205 case T_IMEMO:
2206 RUBY_ASSERT(!rb_objspace_garbage_object_p(obj));
2207 if (IMEMO_TYPE_P(obj, imemo_fields) && rb_shape_obj_has_id(obj)) {
2208 st_insert(id2ref_tbl, rb_obj_id(obj), rb_imemo_fields_owner(obj));
2209 }
2210 break;
2211 case T_OBJECT:
2212 RUBY_ASSERT(!rb_objspace_garbage_object_p(obj));
2213 if (rb_shape_obj_has_id(obj)) {
2214 st_insert(id2ref_tbl, rb_obj_id(obj), obj);
2215 }
2216 break;
2217 default:
2218 // For generic_fields, the T_IMEMO/fields is responsible for populating the entry.
2219 break;
2220 }
2221}
2222
2223static VALUE
2224object_id_to_ref(void *objspace_ptr, VALUE object_id)
2225{
2226 rb_objspace_t *objspace = objspace_ptr;
2227
2228 unsigned int lev = RB_GC_VM_LOCK();
2229
2230 if (!id2ref_tbl) {
2231 rb_gc_vm_barrier(); // stop other ractors
2232
2233 // GC Must not trigger while we build the table, otherwise if we end
2234 // up freeing an object that had an ID, we might try to delete it from
2235 // the table even though it wasn't inserted yet.
2236 st_table *tmp_id2ref_tbl = st_init_table(&object_id_hash_type);
2237 VALUE tmp_id2ref_value = TypedData_Wrap_Struct(0, &id2ref_tbl_type, tmp_id2ref_tbl);
2238
2239 // build_id2ref_i will most certainly malloc, which could trigger GC and sweep
2240 // objects we just added to the table.
2241 // By calling rb_gc_disable() we also save having to handle potentially garbage objects.
2242 bool gc_disabled = RTEST(rb_gc_disable());
2243 {
2244 id2ref_tbl = tmp_id2ref_tbl;
2245 id2ref_value = tmp_id2ref_value;
2246
2247 rb_gc_impl_each_object(objspace, build_id2ref_i, (void *)id2ref_tbl);
2248 }
2249 if (!gc_disabled) rb_gc_enable();
2250 }
2251
2252 VALUE obj;
2253 bool found = st_lookup(id2ref_tbl, object_id, &obj) && !rb_gc_impl_garbage_object_p(objspace, obj);
2254
2255 RB_GC_VM_UNLOCK(lev);
2256
2257 if (found) {
2258 return obj;
2259 }
2260
2261 if (rb_funcall(object_id, rb_intern(">="), 1, ULL2NUM(LAST_OBJECT_ID()))) {
2262 rb_raise(rb_eRangeError, "%+"PRIsVALUE" is not an id value", rb_funcall(object_id, rb_intern("to_s"), 1, INT2FIX(10)));
2263 }
2264 else {
2265 rb_raise(rb_eRangeError, "%+"PRIsVALUE" is a recycled object", rb_funcall(object_id, rb_intern("to_s"), 1, INT2FIX(10)));
2266 }
2267}
2268
2269static inline void
2270obj_free_object_id(VALUE obj)
2271{
2272 VALUE obj_id = 0;
2273 if (RB_UNLIKELY(id2ref_tbl)) {
2274 switch (BUILTIN_TYPE(obj)) {
2275 case T_CLASS:
2276 case T_MODULE:
2277 obj_id = RCLASS(obj)->object_id;
2278 break;
2279 case T_IMEMO:
2280 if (!IMEMO_TYPE_P(obj, imemo_fields)) {
2281 return;
2282 }
2283 // fallthrough
2284 case T_OBJECT:
2285 {
2286 shape_id_t shape_id = RBASIC_SHAPE_ID(obj);
2287 if (rb_shape_has_object_id(shape_id)) {
2288 obj_id = object_id_get(obj, shape_id);
2289 }
2290 break;
2291 }
2292 default:
2293 // For generic_fields, the T_IMEMO/fields is responsible for freeing the id.
2294 return;
2295 }
2296
2297 if (RB_UNLIKELY(obj_id)) {
2298 RUBY_ASSERT(FIXNUM_P(obj_id) || RB_TYPE_P(obj_id, T_BIGNUM));
2299
2300 if (!st_delete(id2ref_tbl, (st_data_t *)&obj_id, NULL)) {
2301 // The the object is a T_IMEMO/fields, then it's possible the actual object
2302 // has been garbage collected already.
2303 if (!RB_TYPE_P(obj, T_IMEMO)) {
2304 rb_bug("Object ID seen, but not in _id2ref table: object_id=%llu object=%s", NUM2ULL(obj_id), rb_obj_info(obj));
2305 }
2306 }
2307 }
2308 }
2309}
2310
2311void
2312rb_gc_obj_free_vm_weak_references(VALUE obj)
2313{
2315 obj_free_object_id(obj);
2316
2317 if (rb_obj_gen_fields_p(obj)) {
2319 }
2320
2321 switch (BUILTIN_TYPE(obj)) {
2322 case T_STRING:
2323 if (FL_TEST_RAW(obj, RSTRING_FSTR)) {
2324 rb_gc_free_fstring(obj);
2325 }
2326 break;
2327 case T_SYMBOL:
2328 rb_gc_free_dsymbol(obj);
2329 break;
2330 case T_IMEMO:
2331 switch (imemo_type(obj)) {
2332 case imemo_callinfo:
2333 rb_vm_ci_free((const struct rb_callinfo *)obj);
2334 break;
2335 case imemo_ment:
2336 rb_free_method_entry_vm_weak_references((const rb_method_entry_t *)obj);
2337 break;
2338 default:
2339 break;
2340 }
2341 break;
2342 default:
2343 break;
2344 }
2345}
2346
2347/*
2348 * call-seq:
2349 * ObjectSpace._id2ref(object_id) -> an_object
2350 *
2351 * Converts an object id to a reference to the object. May not be
2352 * called on an object id passed as a parameter to a finalizer.
2353 *
2354 * s = "I am a string" #=> "I am a string"
2355 * r = ObjectSpace._id2ref(s.object_id) #=> "I am a string"
2356 * r == s #=> true
2357 *
2358 * On multi-ractor mode, if the object is not shareable, it raises
2359 * RangeError.
2360 *
2361 * This method is deprecated and should no longer be used.
2362 */
2363
2364static VALUE
2365id2ref(VALUE objid)
2366{
2367 objid = rb_to_int(objid);
2368 if (FIXNUM_P(objid) || rb_big_size(objid) <= SIZEOF_VOIDP) {
2369 VALUE ptr = (VALUE)NUM2PTR(objid);
2370 if (SPECIAL_CONST_P(ptr)) {
2371 if (ptr == Qtrue) return Qtrue;
2372 if (ptr == Qfalse) return Qfalse;
2373 if (NIL_P(ptr)) return Qnil;
2374 if (FIXNUM_P(ptr)) return ptr;
2375 if (FLONUM_P(ptr)) return ptr;
2376
2377 if (SYMBOL_P(ptr)) {
2378 // Check that the symbol is valid
2379 if (rb_static_id_valid_p(SYM2ID(ptr))) {
2380 return ptr;
2381 }
2382 else {
2383 rb_raise(rb_eRangeError, "%p is not a symbol id value", (void *)ptr);
2384 }
2385 }
2386
2387 rb_raise(rb_eRangeError, "%+"PRIsVALUE" is not an id value", rb_int2str(objid, 10));
2388 }
2389 }
2390
2391 VALUE obj = object_id_to_ref(rb_gc_get_objspace(), objid);
2392 if (!rb_multi_ractor_p() || rb_ractor_shareable_p(obj)) {
2393 return obj;
2394 }
2395 else {
2396 rb_raise(rb_eRangeError, "%+"PRIsVALUE" is the id of an unshareable object on multi-ractor", rb_int2str(objid, 10));
2397 }
2398}
2399
2400/* :nodoc: */
2401static VALUE
2402os_id2ref(VALUE os, VALUE objid)
2403{
2404 rb_category_warn(RB_WARN_CATEGORY_DEPRECATED, "ObjectSpace._id2ref is deprecated");
2405 return id2ref(objid);
2406}
2407
2408static VALUE
2409rb_find_object_id(void *objspace, VALUE obj, VALUE (*get_heap_object_id)(VALUE))
2410{
2411 if (SPECIAL_CONST_P(obj)) {
2412#if SIZEOF_LONG == SIZEOF_VOIDP
2413 return LONG2NUM((SIGNED_VALUE)obj);
2414#else
2415 return LL2NUM((SIGNED_VALUE)obj);
2416#endif
2417 }
2418
2419 return get_heap_object_id(obj);
2420}
2421
2422static VALUE
2423nonspecial_obj_id(VALUE obj)
2424{
2425#if SIZEOF_LONG == SIZEOF_VOIDP
2426 return (VALUE)((SIGNED_VALUE)(obj)|FIXNUM_FLAG);
2427#elif SIZEOF_LONG_LONG == SIZEOF_VOIDP
2428 return LL2NUM((SIGNED_VALUE)(obj) / 2);
2429#else
2430# error not supported
2431#endif
2432}
2433
2434VALUE
2435rb_memory_id(VALUE obj)
2436{
2437 return rb_find_object_id(NULL, obj, nonspecial_obj_id);
2438}
2439
2440/*
2441 * Document-method: __id__
2442 * Document-method: object_id
2443 *
2444 * call-seq:
2445 * obj.__id__ -> integer
2446 * obj.object_id -> integer
2447 *
2448 * Returns an integer identifier for +obj+.
2449 *
2450 * The same number will be returned on all calls to +object_id+ for a given
2451 * object, and no two active objects will share an id.
2452 *
2453 * Note: that some objects of builtin classes are reused for optimization.
2454 * This is the case for immediate values and frozen string literals.
2455 *
2456 * BasicObject implements +__id__+, Kernel implements +object_id+.
2457 *
2458 * Immediate values are not passed by reference but are passed by value:
2459 * +nil+, +true+, +false+, Fixnums, Symbols, and some Floats.
2460 *
2461 * Object.new.object_id == Object.new.object_id # => false
2462 * (21 * 2).object_id == (21 * 2).object_id # => true
2463 * "hello".object_id == "hello".object_id # => false
2464 * "hi".freeze.object_id == "hi".freeze.object_id # => true
2465 */
2466
2467VALUE
2468rb_obj_id(VALUE obj)
2469{
2470 /* If obj is an immediate, the object ID is obj directly converted to a Numeric.
2471 * Otherwise, the object ID is a Numeric that is a non-zero multiple of
2472 * (RUBY_IMMEDIATE_MASK + 1) which guarantees that it does not collide with
2473 * any immediates. */
2474 return rb_find_object_id(rb_gc_get_objspace(), obj, object_id);
2475}
2476
2477bool
2478rb_obj_id_p(VALUE obj)
2479{
2480 return !RB_TYPE_P(obj, T_IMEMO) && rb_shape_obj_has_id(obj);
2481}
2482
2483/*
2484 * GC implementations should call this function before the GC phase that updates references
2485 * embedded in the machine code generated by JIT compilers. JIT compilers usually enforce the
2486 * "W^X" policy and protect the code memory from being modified during execution. This function
2487 * makes the code memory writeable.
2488 */
2489void
2490rb_gc_before_updating_jit_code(void)
2491{
2492#if USE_YJIT
2493 rb_yjit_mark_all_writeable();
2494#endif
2495#if USE_ZJIT
2496 rb_zjit_mark_all_writable();
2497#endif
2498}
2499
2500/*
2501 * GC implementations should call this function before the GC phase that updates references
2502 * embedded in the machine code generated by JIT compilers. This function makes the code memory
2503 * executable again.
2504 */
2505void
2506rb_gc_after_updating_jit_code(void)
2507{
2508#if USE_YJIT
2509 rb_yjit_mark_all_executable();
2510#endif
2511#if USE_ZJIT
2512 rb_zjit_mark_all_executable();
2513#endif
2514}
2515
2516static void
2517classext_memsize(rb_classext_t *ext, bool prime, VALUE box_value, void *arg)
2518{
2519 size_t *size = (size_t *)arg;
2520 size_t s = 0;
2521
2522 if (RCLASSEXT_M_TBL(ext)) {
2523 s += rb_id_table_memsize(RCLASSEXT_M_TBL(ext));
2524 }
2525 if (RCLASSEXT_CVC_TBL(ext)) {
2526 s += rb_id_table_memsize(RCLASSEXT_CVC_TBL(ext));
2527 }
2528 if (RCLASSEXT_CONST_TBL(ext)) {
2529 s += rb_id_table_memsize(RCLASSEXT_CONST_TBL(ext));
2530 }
2531 if (RCLASSEXT_SUPERCLASSES_WITH_SELF(ext)) {
2532 s += (RCLASSEXT_SUPERCLASS_DEPTH(ext) + 1) * sizeof(VALUE);
2533 }
2534 if (!prime) {
2535 s += sizeof(rb_classext_t);
2536 }
2537 *size += s;
2538}
2539
2540static void
2541classext_superclasses_memsize(rb_classext_t *ext, bool prime, VALUE box_value, void *arg)
2542{
2543 size_t *size = (size_t *)arg;
2544 size_t array_size;
2545 if (RCLASSEXT_SUPERCLASSES_WITH_SELF(ext)) {
2546 RUBY_ASSERT(prime);
2547 array_size = RCLASSEXT_SUPERCLASS_DEPTH(ext) + 1;
2548 *size += array_size * sizeof(VALUE);
2549 }
2550}
2551
2552size_t
2553rb_obj_memsize_of(VALUE obj)
2554{
2555 size_t size = 0;
2556
2557 if (SPECIAL_CONST_P(obj)) {
2558 return 0;
2559 }
2560
2561 switch (BUILTIN_TYPE(obj)) {
2562 case T_OBJECT:
2563 if (FL_TEST_RAW(obj, ROBJECT_HEAP)) {
2564 if (rb_shape_obj_too_complex_p(obj)) {
2565 size += rb_st_memsize(ROBJECT_FIELDS_HASH(obj));
2566 }
2567 else {
2568 size += ROBJECT_FIELDS_CAPACITY(obj) * sizeof(VALUE);
2569 }
2570 }
2571 break;
2572 case T_MODULE:
2573 case T_CLASS:
2574 rb_class_classext_foreach(obj, classext_memsize, (void *)&size);
2575 rb_class_classext_foreach(obj, classext_superclasses_memsize, (void *)&size);
2576 break;
2577 case T_ICLASS:
2578 if (RICLASS_OWNS_M_TBL_P(obj)) {
2579 if (RCLASS_M_TBL(obj)) {
2580 size += rb_id_table_memsize(RCLASS_M_TBL(obj));
2581 }
2582 }
2583 break;
2584 case T_STRING:
2585 size += rb_str_memsize(obj);
2586 break;
2587 case T_ARRAY:
2588 size += rb_ary_memsize(obj);
2589 break;
2590 case T_HASH:
2591 if (RHASH_ST_TABLE_P(obj)) {
2592 VM_ASSERT(RHASH_ST_TABLE(obj) != NULL);
2593 /* st_table is in the slot */
2594 size += st_memsize(RHASH_ST_TABLE(obj)) - sizeof(st_table);
2595 }
2596 break;
2597 case T_REGEXP:
2598 if (RREGEXP_PTR(obj)) {
2599 size += onig_memsize(RREGEXP_PTR(obj));
2600 }
2601 break;
2602 case T_DATA:
2603 size += rb_objspace_data_type_memsize(obj);
2604 break;
2605 case T_MATCH:
2606 {
2607 rb_matchext_t *rm = RMATCH_EXT(obj);
2608 size += onig_region_memsize(&rm->regs);
2609 size += sizeof(struct rmatch_offset) * rm->char_offset_num_allocated;
2610 }
2611 break;
2612 case T_FILE:
2613 if (RFILE(obj)->fptr) {
2614 size += rb_io_memsize(RFILE(obj)->fptr);
2615 }
2616 break;
2617 case T_RATIONAL:
2618 case T_COMPLEX:
2619 break;
2620 case T_IMEMO:
2621 size += rb_imemo_memsize(obj);
2622 break;
2623
2624 case T_FLOAT:
2625 case T_SYMBOL:
2626 break;
2627
2628 case T_BIGNUM:
2629 if (!(RBASIC(obj)->flags & BIGNUM_EMBED_FLAG) && BIGNUM_DIGITS(obj)) {
2630 size += BIGNUM_LEN(obj) * sizeof(BDIGIT);
2631 }
2632 break;
2633
2634 case T_NODE:
2635 UNEXPECTED_NODE(obj_memsize_of);
2636 break;
2637
2638 case T_STRUCT:
2639 if (RSTRUCT_EMBED_LEN(obj) == 0) {
2640 size += sizeof(VALUE) * RSTRUCT_LEN_RAW(obj);
2641 }
2642 break;
2643
2644 case T_ZOMBIE:
2645 case T_MOVED:
2646 break;
2647
2648 default:
2649 rb_bug("objspace/memsize_of(): unknown data type 0x%x(%p)",
2650 BUILTIN_TYPE(obj), (void*)obj);
2651 }
2652
2653 return size + rb_gc_obj_slot_size(obj);
2654}
2655
2656static int
2657set_zero(st_data_t key, st_data_t val, st_data_t arg)
2658{
2659 VALUE k = (VALUE)key;
2660 VALUE hash = (VALUE)arg;
2661 rb_hash_aset(hash, k, INT2FIX(0));
2662 return ST_CONTINUE;
2663}
2664
2666 size_t counts[T_MASK+1];
2667 size_t freed;
2668 size_t total;
2669};
2670
2671static void
2672count_objects_i(VALUE obj, void *d)
2673{
2674 struct count_objects_data *data = (struct count_objects_data *)d;
2675
2676 if (RBASIC(obj)->flags) {
2677 data->counts[BUILTIN_TYPE(obj)]++;
2678 }
2679 else {
2680 data->freed++;
2681 }
2682
2683 data->total++;
2684}
2685
2686/*
2687 * call-seq:
2688 * ObjectSpace.count_objects([result_hash]) -> hash
2689 *
2690 * Counts all objects grouped by type.
2691 *
2692 * It returns a hash, such as:
2693 * {
2694 * :TOTAL=>10000,
2695 * :FREE=>3011,
2696 * :T_OBJECT=>6,
2697 * :T_CLASS=>404,
2698 * # ...
2699 * }
2700 *
2701 * The contents of the returned hash are implementation specific.
2702 * It may be changed in future.
2703 *
2704 * The keys starting with +:T_+ means live objects.
2705 * For example, +:T_ARRAY+ is the number of arrays.
2706 * +:FREE+ means object slots which is not used now.
2707 * +:TOTAL+ means sum of above.
2708 *
2709 * If the optional argument +result_hash+ is given,
2710 * it is overwritten and returned. This is intended to avoid probe effect.
2711 *
2712 * h = {}
2713 * ObjectSpace.count_objects(h)
2714 * puts h
2715 * # => { :TOTAL=>10000, :T_CLASS=>158280, :T_MODULE=>20672, :T_STRING=>527249 }
2716 *
2717 * This method is only expected to work on C Ruby.
2718 *
2719 */
2720
2721static VALUE
2722count_objects(int argc, VALUE *argv, VALUE os)
2723{
2724 struct count_objects_data data = { 0 };
2725 VALUE hash = Qnil;
2726 VALUE types[T_MASK + 1];
2727
2728 if (rb_check_arity(argc, 0, 1) == 1) {
2729 hash = argv[0];
2730 if (!RB_TYPE_P(hash, T_HASH))
2731 rb_raise(rb_eTypeError, "non-hash given");
2732 }
2733
2734 for (size_t i = 0; i <= T_MASK; i++) {
2735 // type_sym can allocate an object,
2736 // so we need to create all key symbols in advance
2737 // not to disturb the result
2738 types[i] = type_sym(i);
2739 }
2740
2741 // Same as type_sym, we need to create all key symbols in advance
2742 VALUE total = ID2SYM(rb_intern("TOTAL"));
2743 VALUE free = ID2SYM(rb_intern("FREE"));
2744
2745 rb_gc_impl_each_object(rb_gc_get_objspace(), count_objects_i, &data);
2746
2747 if (NIL_P(hash)) {
2748 hash = rb_hash_new();
2749 }
2750 else if (!RHASH_EMPTY_P(hash)) {
2751 rb_hash_stlike_foreach(hash, set_zero, hash);
2752 }
2753 rb_hash_aset(hash, total, SIZET2NUM(data.total));
2754 rb_hash_aset(hash, free, SIZET2NUM(data.freed));
2755
2756 for (size_t i = 0; i <= T_MASK; i++) {
2757 if (data.counts[i]) {
2758 rb_hash_aset(hash, types[i], SIZET2NUM(data.counts[i]));
2759 }
2760 }
2761
2762 return hash;
2763}
2764
2765#define SET_STACK_END SET_MACHINE_STACK_END(&ec->machine.stack_end)
2766
2767#define STACK_START (ec->machine.stack_start)
2768#define STACK_END (ec->machine.stack_end)
2769#define STACK_LEVEL_MAX (ec->machine.stack_maxsize/sizeof(VALUE))
2770
2771#if STACK_GROW_DIRECTION < 0
2772# define STACK_LENGTH (size_t)(STACK_START - STACK_END)
2773#elif STACK_GROW_DIRECTION > 0
2774# define STACK_LENGTH (size_t)(STACK_END - STACK_START + 1)
2775#else
2776# define STACK_LENGTH ((STACK_END < STACK_START) ? (size_t)(STACK_START - STACK_END) \
2777 : (size_t)(STACK_END - STACK_START + 1))
2778#endif
2779#if !STACK_GROW_DIRECTION
2780int ruby_stack_grow_direction;
2781int
2782ruby_get_stack_grow_direction(volatile VALUE *addr)
2783{
2784 VALUE *end;
2785 SET_MACHINE_STACK_END(&end);
2786
2787 if (end > addr) return ruby_stack_grow_direction = 1;
2788 return ruby_stack_grow_direction = -1;
2789}
2790#endif
2791
2792size_t
2794{
2795 rb_execution_context_t *ec = GET_EC();
2796 SET_STACK_END;
2797 if (p) *p = STACK_UPPER(STACK_END, STACK_START, STACK_END);
2798 return STACK_LENGTH;
2799}
2800
2801#define PREVENT_STACK_OVERFLOW 1
2802#ifndef PREVENT_STACK_OVERFLOW
2803#if !(defined(POSIX_SIGNAL) && defined(SIGSEGV) && defined(HAVE_SIGALTSTACK))
2804# define PREVENT_STACK_OVERFLOW 1
2805#else
2806# define PREVENT_STACK_OVERFLOW 0
2807#endif
2808#endif
2809#if PREVENT_STACK_OVERFLOW && !defined(__EMSCRIPTEN__)
2810static int
2811stack_check(rb_execution_context_t *ec, int water_mark)
2812{
2813 SET_STACK_END;
2814
2815 size_t length = STACK_LENGTH;
2816 size_t maximum_length = STACK_LEVEL_MAX - water_mark;
2817
2818 return length > maximum_length;
2819}
2820#else
2821#define stack_check(ec, water_mark) FALSE
2822#endif
2823
2824#define STACKFRAME_FOR_CALL_CFUNC 2048
2825
2826int
2827rb_ec_stack_check(rb_execution_context_t *ec)
2828{
2829 return stack_check(ec, STACKFRAME_FOR_CALL_CFUNC);
2830}
2831
2832int
2834{
2835 return stack_check(GET_EC(), STACKFRAME_FOR_CALL_CFUNC);
2836}
2837
2838/* ==================== Marking ==================== */
2839
2840#define RB_GC_MARK_OR_TRAVERSE(func, obj_or_ptr, obj, check_obj) do { \
2841 if (!RB_SPECIAL_CONST_P(obj)) { \
2842 rb_vm_t *vm = GET_VM(); \
2843 void *objspace = vm->gc.objspace; \
2844 if (LIKELY(vm->gc.mark_func_data == NULL)) { \
2845 GC_ASSERT(rb_gc_impl_during_gc_p(objspace)); \
2846 (func)(objspace, (obj_or_ptr)); \
2847 } \
2848 else if (check_obj ? \
2849 rb_gc_impl_pointer_to_heap_p(objspace, (const void *)obj) && \
2850 !rb_gc_impl_garbage_object_p(objspace, obj) : \
2851 true) { \
2852 GC_ASSERT(!rb_gc_impl_during_gc_p(objspace)); \
2853 struct gc_mark_func_data_struct *mark_func_data = vm->gc.mark_func_data; \
2854 vm->gc.mark_func_data = NULL; \
2855 mark_func_data->mark_func((obj), mark_func_data->data); \
2856 vm->gc.mark_func_data = mark_func_data; \
2857 } \
2858 } \
2859} while (0)
2860
2861static inline void
2862gc_mark_internal(VALUE obj)
2863{
2864 RB_GC_MARK_OR_TRAVERSE(rb_gc_impl_mark, obj, obj, false);
2865}
2866
2867void
2868rb_gc_mark_movable(VALUE obj)
2869{
2870 gc_mark_internal(obj);
2871}
2872
2873void
2874rb_gc_mark_and_move(VALUE *ptr)
2875{
2876 RB_GC_MARK_OR_TRAVERSE(rb_gc_impl_mark_and_move, ptr, *ptr, false);
2877}
2878
2879static inline void
2880gc_mark_and_pin_internal(VALUE obj)
2881{
2882 RB_GC_MARK_OR_TRAVERSE(rb_gc_impl_mark_and_pin, obj, obj, false);
2883}
2884
2885void
2886rb_gc_mark(VALUE obj)
2887{
2888 gc_mark_and_pin_internal(obj);
2889}
2890
2891static inline void
2892gc_mark_maybe_internal(VALUE obj)
2893{
2894 RB_GC_MARK_OR_TRAVERSE(rb_gc_impl_mark_maybe, obj, obj, true);
2895}
2896
2897void
2898rb_gc_mark_maybe(VALUE obj)
2899{
2900 gc_mark_maybe_internal(obj);
2901}
2902
2903ATTRIBUTE_NO_ADDRESS_SAFETY_ANALYSIS(static void each_location(register const VALUE *x, register long n, void (*cb)(VALUE, void *), void *data));
2904static void
2905each_location(register const VALUE *x, register long n, void (*cb)(VALUE, void *), void *data)
2906{
2907 VALUE v;
2908 while (n--) {
2909 v = *x;
2910 cb(v, data);
2911 x++;
2912 }
2913}
2914
2915static void
2916each_location_ptr(const VALUE *start, const VALUE *end, void (*cb)(VALUE, void *), void *data)
2917{
2918 if (end <= start) return;
2919 each_location(start, end - start, cb, data);
2920}
2921
2922static void
2923gc_mark_maybe_each_location(VALUE obj, void *data)
2924{
2925 gc_mark_maybe_internal(obj);
2926}
2927
2928void
2929rb_gc_mark_locations(const VALUE *start, const VALUE *end)
2930{
2931 each_location_ptr(start, end, gc_mark_maybe_each_location, NULL);
2932}
2933
2934void
2935rb_gc_mark_values(long n, const VALUE *values)
2936{
2937 for (long i = 0; i < n; i++) {
2938 gc_mark_internal(values[i]);
2939 }
2940}
2941
2942void
2943rb_gc_mark_vm_stack_values(long n, const VALUE *values)
2944{
2945 for (long i = 0; i < n; i++) {
2946 gc_mark_and_pin_internal(values[i]);
2947 }
2948}
2949
2950static int
2951mark_key(st_data_t key, st_data_t value, st_data_t data)
2952{
2953 gc_mark_and_pin_internal((VALUE)key);
2954
2955 return ST_CONTINUE;
2956}
2957
2958void
2959rb_mark_set(st_table *tbl)
2960{
2961 if (!tbl) return;
2962
2963 st_foreach(tbl, mark_key, (st_data_t)rb_gc_get_objspace());
2964}
2965
2966static int
2967mark_keyvalue(st_data_t key, st_data_t value, st_data_t data)
2968{
2969 gc_mark_internal((VALUE)key);
2970 gc_mark_internal((VALUE)value);
2971
2972 return ST_CONTINUE;
2973}
2974
2975static int
2976pin_key_pin_value(st_data_t key, st_data_t value, st_data_t data)
2977{
2978 gc_mark_and_pin_internal((VALUE)key);
2979 gc_mark_and_pin_internal((VALUE)value);
2980
2981 return ST_CONTINUE;
2982}
2983
2984static int
2985pin_key_mark_value(st_data_t key, st_data_t value, st_data_t data)
2986{
2987 gc_mark_and_pin_internal((VALUE)key);
2988 gc_mark_internal((VALUE)value);
2989
2990 return ST_CONTINUE;
2991}
2992
2993static void
2994mark_hash(VALUE hash)
2995{
2996 if (rb_hash_compare_by_id_p(hash)) {
2997 rb_hash_stlike_foreach(hash, pin_key_mark_value, 0);
2998 }
2999 else {
3000 rb_hash_stlike_foreach(hash, mark_keyvalue, 0);
3001 }
3002
3003 gc_mark_internal(RHASH(hash)->ifnone);
3004}
3005
3006void
3007rb_mark_hash(st_table *tbl)
3008{
3009 if (!tbl) return;
3010
3011 st_foreach(tbl, pin_key_pin_value, 0);
3012}
3013
3014static enum rb_id_table_iterator_result
3015mark_method_entry_i(VALUE me, void *objspace)
3016{
3017 gc_mark_internal(me);
3018
3019 return ID_TABLE_CONTINUE;
3020}
3021
3022static void
3023mark_m_tbl(void *objspace, struct rb_id_table *tbl)
3024{
3025 if (tbl) {
3026 rb_id_table_foreach_values(tbl, mark_method_entry_i, objspace);
3027 }
3028}
3029
3030static enum rb_id_table_iterator_result
3031mark_const_entry_i(VALUE value, void *objspace)
3032{
3033 const rb_const_entry_t *ce = (const rb_const_entry_t *)value;
3034
3035 if (!rb_gc_checking_shareable()) {
3036 gc_mark_internal(ce->value);
3037 gc_mark_internal(ce->file); // TODO: ce->file should be shareable?
3038 }
3039 return ID_TABLE_CONTINUE;
3040}
3041
3042static void
3043mark_const_tbl(rb_objspace_t *objspace, struct rb_id_table *tbl)
3044{
3045 if (!tbl) return;
3046 rb_id_table_foreach_values(tbl, mark_const_entry_i, objspace);
3047}
3048
3049static enum rb_id_table_iterator_result
3050mark_cvc_tbl_i(VALUE cvc_entry, void *objspace)
3051{
3052 struct rb_cvar_class_tbl_entry *entry;
3053
3054 entry = (struct rb_cvar_class_tbl_entry *)cvc_entry;
3055
3056 RUBY_ASSERT(entry->cref == 0 || (BUILTIN_TYPE((VALUE)entry->cref) == T_IMEMO && IMEMO_TYPE_P(entry->cref, imemo_cref)));
3057 gc_mark_internal((VALUE)entry->cref);
3058
3059 return ID_TABLE_CONTINUE;
3060}
3061
3062static void
3063mark_cvc_tbl(rb_objspace_t *objspace, struct rb_id_table *tbl)
3064{
3065 if (!tbl) return;
3066 rb_id_table_foreach_values(tbl, mark_cvc_tbl_i, objspace);
3067}
3068
3069#if STACK_GROW_DIRECTION < 0
3070#define GET_STACK_BOUNDS(start, end, appendix) ((start) = STACK_END, (end) = STACK_START)
3071#elif STACK_GROW_DIRECTION > 0
3072#define GET_STACK_BOUNDS(start, end, appendix) ((start) = STACK_START, (end) = STACK_END+(appendix))
3073#else
3074#define GET_STACK_BOUNDS(start, end, appendix) \
3075 ((STACK_END < STACK_START) ? \
3076 ((start) = STACK_END, (end) = STACK_START) : ((start) = STACK_START, (end) = STACK_END+(appendix)))
3077#endif
3078
3079static void
3080gc_mark_machine_stack_location_maybe(VALUE obj, void *data)
3081{
3082 gc_mark_maybe_internal(obj);
3083
3084#ifdef RUBY_ASAN_ENABLED
3085 const rb_execution_context_t *ec = (const rb_execution_context_t *)data;
3086 void *fake_frame_start;
3087 void *fake_frame_end;
3088 bool is_fake_frame = asan_get_fake_stack_extents(
3089 ec->machine.asan_fake_stack_handle, obj,
3090 ec->machine.stack_start, ec->machine.stack_end,
3091 &fake_frame_start, &fake_frame_end
3092 );
3093 if (is_fake_frame) {
3094 each_location_ptr(fake_frame_start, fake_frame_end, gc_mark_maybe_each_location, NULL);
3095 }
3096#endif
3097}
3098
3099static bool
3100gc_object_moved_p_internal(void *objspace, VALUE obj)
3101{
3102 if (SPECIAL_CONST_P(obj)) {
3103 return false;
3104 }
3105
3106 return rb_gc_impl_object_moved_p(objspace, obj);
3107}
3108
3109static VALUE
3110gc_location_internal(void *objspace, VALUE value)
3111{
3112 if (SPECIAL_CONST_P(value)) {
3113 return value;
3114 }
3115
3116 GC_ASSERT(rb_gc_impl_pointer_to_heap_p(objspace, (void *)value));
3117
3118 return rb_gc_impl_location(objspace, value);
3119}
3120
3121VALUE
3122rb_gc_location(VALUE value)
3123{
3124 return gc_location_internal(rb_gc_get_objspace(), value);
3125}
3126
3127#if defined(__wasm__)
3128
3129
3130static VALUE *rb_stack_range_tmp[2];
3131
3132static void
3133rb_mark_locations(void *begin, void *end)
3134{
3135 rb_stack_range_tmp[0] = begin;
3136 rb_stack_range_tmp[1] = end;
3137}
3138
3139void
3140rb_gc_save_machine_context(void)
3141{
3142 // no-op
3143}
3144
3145# if defined(__EMSCRIPTEN__)
3146
3147static void
3148mark_current_machine_context(const rb_execution_context_t *ec)
3149{
3150 emscripten_scan_stack(rb_mark_locations);
3151 each_location_ptr(rb_stack_range_tmp[0], rb_stack_range_tmp[1], gc_mark_maybe_each_location, NULL);
3152
3153 emscripten_scan_registers(rb_mark_locations);
3154 each_location_ptr(rb_stack_range_tmp[0], rb_stack_range_tmp[1], gc_mark_maybe_each_location, NULL);
3155}
3156# else // use Asyncify version
3157
3158static void
3159mark_current_machine_context(rb_execution_context_t *ec)
3160{
3161 VALUE *stack_start, *stack_end;
3162 SET_STACK_END;
3163 GET_STACK_BOUNDS(stack_start, stack_end, 1);
3164 each_location_ptr(stack_start, stack_end, gc_mark_maybe_each_location, NULL);
3165
3166 rb_wasm_scan_locals(rb_mark_locations);
3167 each_location_ptr(rb_stack_range_tmp[0], rb_stack_range_tmp[1], gc_mark_maybe_each_location, NULL);
3168}
3169
3170# endif
3171
3172#else // !defined(__wasm__)
3173
3174void
3175rb_gc_save_machine_context(void)
3176{
3177 rb_thread_t *thread = GET_THREAD();
3178
3179 RB_VM_SAVE_MACHINE_CONTEXT(thread);
3180}
3181
3182
3183static void
3184mark_current_machine_context(const rb_execution_context_t *ec)
3185{
3186 rb_gc_mark_machine_context(ec);
3187}
3188#endif
3189
3190void
3191rb_gc_mark_machine_context(const rb_execution_context_t *ec)
3192{
3193 VALUE *stack_start, *stack_end;
3194
3195 GET_STACK_BOUNDS(stack_start, stack_end, 0);
3196 RUBY_DEBUG_LOG("ec->th:%u stack_start:%p stack_end:%p", rb_ec_thread_ptr(ec)->serial, stack_start, stack_end);
3197
3198 void *data =
3199#ifdef RUBY_ASAN_ENABLED
3200 /* gc_mark_machine_stack_location_maybe() uses data as const */
3202#else
3203 NULL;
3204#endif
3205
3206 each_location_ptr(stack_start, stack_end, gc_mark_machine_stack_location_maybe, data);
3207 int num_regs = sizeof(ec->machine.regs)/(sizeof(VALUE));
3208 each_location((VALUE*)&ec->machine.regs, num_regs, gc_mark_machine_stack_location_maybe, data);
3209}
3210
3211static int
3212rb_mark_tbl_i(st_data_t key, st_data_t value, st_data_t data)
3213{
3214 gc_mark_and_pin_internal((VALUE)value);
3215
3216 return ST_CONTINUE;
3217}
3218
3219void
3220rb_mark_tbl(st_table *tbl)
3221{
3222 if (!tbl || tbl->num_entries == 0) return;
3223
3224 st_foreach(tbl, rb_mark_tbl_i, 0);
3225}
3226
3227static void
3228gc_mark_tbl_no_pin(st_table *tbl)
3229{
3230 if (!tbl || tbl->num_entries == 0) return;
3231
3232 st_foreach(tbl, gc_mark_tbl_no_pin_i, 0);
3233}
3234
3235void
3236rb_mark_tbl_no_pin(st_table *tbl)
3237{
3238 gc_mark_tbl_no_pin(tbl);
3239}
3240
3241static bool
3242gc_declarative_marking_p(const rb_data_type_t *type)
3243{
3244 return (type->flags & RUBY_TYPED_DECL_MARKING) != 0;
3245}
3246
3247void
3248rb_gc_mark_roots(void *objspace, const char **categoryp)
3249{
3250 rb_execution_context_t *ec = GET_EC();
3251 rb_vm_t *vm = rb_ec_vm_ptr(ec);
3252
3253#define MARK_CHECKPOINT(category) do { \
3254 if (categoryp) *categoryp = category; \
3255} while (0)
3256
3257 MARK_CHECKPOINT("vm");
3258 rb_vm_mark(vm);
3259
3260 MARK_CHECKPOINT("end_proc");
3261 rb_mark_end_proc();
3262
3263 MARK_CHECKPOINT("global_tbl");
3264 rb_gc_mark_global_tbl();
3265
3266#if USE_YJIT
3267 void rb_yjit_root_mark(void); // in Rust
3268
3269 if (rb_yjit_enabled_p) {
3270 MARK_CHECKPOINT("YJIT");
3271 rb_yjit_root_mark();
3272 }
3273#endif
3274
3275#if USE_ZJIT
3276 void rb_zjit_root_mark(void);
3277 if (rb_zjit_enabled_p) {
3278 MARK_CHECKPOINT("ZJIT");
3279 rb_zjit_root_mark();
3280 }
3281#endif
3282
3283 MARK_CHECKPOINT("machine_context");
3284 mark_current_machine_context(ec);
3285
3286 MARK_CHECKPOINT("global_symbols");
3287 rb_sym_global_symbols_mark_and_move();
3288
3289 MARK_CHECKPOINT("finish");
3290
3291#undef MARK_CHECKPOINT
3292}
3293
3298
3299static void
3300gc_mark_classext_module(rb_classext_t *ext, bool prime, VALUE box_value, void *arg)
3301{
3303 rb_objspace_t *objspace = foreach_arg->objspace;
3304
3305 if (RCLASSEXT_SUPER(ext)) {
3306 gc_mark_internal(RCLASSEXT_SUPER(ext));
3307 }
3308 mark_m_tbl(objspace, RCLASSEXT_M_TBL(ext));
3309
3310 if (!rb_gc_checking_shareable()) {
3311 // unshareable
3312 gc_mark_internal(RCLASSEXT_FIELDS_OBJ(ext));
3313 }
3314
3315 if (!RCLASSEXT_SHARED_CONST_TBL(ext) && RCLASSEXT_CONST_TBL(ext)) {
3316 mark_const_tbl(objspace, RCLASSEXT_CONST_TBL(ext));
3317 }
3318 mark_m_tbl(objspace, RCLASSEXT_CALLABLE_M_TBL(ext));
3319 gc_mark_internal(RCLASSEXT_CC_TBL(ext));
3320 mark_cvc_tbl(objspace, RCLASSEXT_CVC_TBL(ext));
3321 gc_mark_internal(RCLASSEXT_CLASSPATH(ext));
3322}
3323
3324static void
3325gc_mark_classext_iclass(rb_classext_t *ext, bool prime, VALUE box_value, void *arg)
3326{
3328 rb_objspace_t *objspace = foreach_arg->objspace;
3329
3330 if (RCLASSEXT_SUPER(ext)) {
3331 gc_mark_internal(RCLASSEXT_SUPER(ext));
3332 }
3333 if (RCLASSEXT_ICLASS_IS_ORIGIN(ext) && !RCLASSEXT_ICLASS_ORIGIN_SHARED_MTBL(ext)) {
3334 mark_m_tbl(objspace, RCLASSEXT_M_TBL(ext));
3335 }
3336 if (RCLASSEXT_INCLUDER(ext)) {
3337 gc_mark_internal(RCLASSEXT_INCLUDER(ext));
3338 }
3339 mark_m_tbl(objspace, RCLASSEXT_CALLABLE_M_TBL(ext));
3340 gc_mark_internal(RCLASSEXT_CC_TBL(ext));
3341}
3342
3343#define TYPED_DATA_REFS_OFFSET_LIST(d) (size_t *)(uintptr_t)RTYPEDDATA_TYPE(d)->function.dmark
3344
3345void
3346rb_gc_move_obj_during_marking(VALUE from, VALUE to)
3347{
3348 if (rb_obj_using_gen_fields_table_p(to)) {
3349 rb_mark_generic_ivar(from);
3350 }
3351}
3352
3353void
3354rb_gc_mark_children(void *objspace, VALUE obj)
3355{
3356 struct gc_mark_classext_foreach_arg foreach_args;
3357
3358 if (rb_obj_using_gen_fields_table_p(obj)) {
3359 rb_mark_generic_ivar(obj);
3360 }
3361
3362 switch (BUILTIN_TYPE(obj)) {
3363 case T_FLOAT:
3364 case T_BIGNUM:
3365 return;
3366
3367 case T_NIL:
3368 case T_FIXNUM:
3369 rb_bug("rb_gc_mark() called for broken object");
3370 break;
3371
3372 case T_NODE:
3373 UNEXPECTED_NODE(rb_gc_mark);
3374 break;
3375
3376 case T_IMEMO:
3377 rb_imemo_mark_and_move(obj, false);
3378 return;
3379
3380 default:
3381 break;
3382 }
3383
3384 gc_mark_internal(RBASIC(obj)->klass);
3385
3386 switch (BUILTIN_TYPE(obj)) {
3387 case T_CLASS:
3388 if (FL_TEST_RAW(obj, FL_SINGLETON) &&
3389 !rb_gc_checking_shareable()) {
3390 gc_mark_internal(RCLASS_ATTACHED_OBJECT(obj));
3391 }
3392 // Continue to the shared T_CLASS/T_MODULE
3393 case T_MODULE:
3394 foreach_args.objspace = objspace;
3395 foreach_args.obj = obj;
3396 rb_class_classext_foreach(obj, gc_mark_classext_module, (void *)&foreach_args);
3397 if (BOX_USER_P(RCLASS_PRIME_BOX(obj))) {
3398 gc_mark_internal(RCLASS_PRIME_BOX(obj)->box_object);
3399 }
3400 break;
3401
3402 case T_ICLASS:
3403 foreach_args.objspace = objspace;
3404 foreach_args.obj = obj;
3405 rb_class_classext_foreach(obj, gc_mark_classext_iclass, (void *)&foreach_args);
3406 if (BOX_USER_P(RCLASS_PRIME_BOX(obj))) {
3407 gc_mark_internal(RCLASS_PRIME_BOX(obj)->box_object);
3408 }
3409 break;
3410
3411 case T_ARRAY:
3412 if (ARY_SHARED_P(obj)) {
3413 VALUE root = ARY_SHARED_ROOT(obj);
3414 gc_mark_internal(root);
3415 }
3416 else {
3417 long len = RARRAY_LEN(obj);
3418 const VALUE *ptr = RARRAY_CONST_PTR(obj);
3419 for (long i = 0; i < len; i++) {
3420 gc_mark_internal(ptr[i]);
3421 }
3422 }
3423 break;
3424
3425 case T_HASH:
3426 mark_hash(obj);
3427 break;
3428
3429 case T_SYMBOL:
3430 gc_mark_internal(RSYMBOL(obj)->fstr);
3431 break;
3432
3433 case T_STRING:
3434 if (STR_SHARED_P(obj)) {
3435 if (STR_EMBED_P(RSTRING(obj)->as.heap.aux.shared)) {
3436 /* Embedded shared strings cannot be moved because this string
3437 * points into the slot of the shared string. There may be code
3438 * using the RSTRING_PTR on the stack, which would pin this
3439 * string but not pin the shared string, causing it to move. */
3440 gc_mark_and_pin_internal(RSTRING(obj)->as.heap.aux.shared);
3441 }
3442 else {
3443 gc_mark_internal(RSTRING(obj)->as.heap.aux.shared);
3444 }
3445 }
3446 break;
3447
3448 case T_DATA: {
3449 bool typed_data = RTYPEDDATA_P(obj);
3450 void *const ptr = typed_data ? RTYPEDDATA_GET_DATA(obj) : DATA_PTR(obj);
3451
3452 if (typed_data) {
3453 gc_mark_internal(RTYPEDDATA(obj)->fields_obj);
3454 }
3455
3456 if (ptr) {
3457 if (typed_data && gc_declarative_marking_p(RTYPEDDATA_TYPE(obj))) {
3458 size_t *offset_list = TYPED_DATA_REFS_OFFSET_LIST(obj);
3459
3460 for (size_t offset = *offset_list; offset != RUBY_REF_END; offset = *offset_list++) {
3461 gc_mark_internal(*(VALUE *)((char *)ptr + offset));
3462 }
3463 }
3464 else {
3465 RUBY_DATA_FUNC mark_func = typed_data ?
3467 RDATA(obj)->dmark;
3468 if (mark_func) (*mark_func)(ptr);
3469 }
3470 }
3471
3472 break;
3473 }
3474
3475 case T_OBJECT: {
3476 uint32_t len;
3477 if (rb_shape_obj_too_complex_p(obj)) {
3478 gc_mark_tbl_no_pin(ROBJECT_FIELDS_HASH(obj));
3479 len = ROBJECT_FIELDS_COUNT_COMPLEX(obj);
3480 }
3481 else {
3482 const VALUE * const ptr = ROBJECT_FIELDS(obj);
3483
3484 len = ROBJECT_FIELDS_COUNT_NOT_COMPLEX(obj);
3485 for (uint32_t i = 0; i < len; i++) {
3486 gc_mark_internal(ptr[i]);
3487 }
3488 }
3489
3490 attr_index_t fields_count = (attr_index_t)len;
3491 if (fields_count) {
3492 VALUE klass = RBASIC_CLASS(obj);
3493
3494 // Increment max_iv_count if applicable, used to determine size pool allocation
3495 if (RCLASS_MAX_IV_COUNT(klass) < fields_count) {
3496 RCLASS_SET_MAX_IV_COUNT(klass, fields_count);
3497 }
3498 }
3499
3500 break;
3501 }
3502
3503 case T_FILE:
3504 if (RFILE(obj)->fptr) {
3505 gc_mark_internal(RFILE(obj)->fptr->self);
3506 gc_mark_internal(RFILE(obj)->fptr->pathv);
3507 gc_mark_internal(RFILE(obj)->fptr->tied_io_for_writing);
3508 gc_mark_internal(RFILE(obj)->fptr->writeconv_asciicompat);
3509 gc_mark_internal(RFILE(obj)->fptr->writeconv_pre_ecopts);
3510 gc_mark_internal(RFILE(obj)->fptr->encs.ecopts);
3511 gc_mark_internal(RFILE(obj)->fptr->write_lock);
3512 gc_mark_internal(RFILE(obj)->fptr->timeout);
3513 gc_mark_internal(RFILE(obj)->fptr->wakeup_mutex);
3514 }
3515 break;
3516
3517 case T_REGEXP:
3518 gc_mark_internal(RREGEXP(obj)->src);
3519 break;
3520
3521 case T_MATCH:
3522 gc_mark_internal(RMATCH(obj)->regexp);
3523 if (RMATCH(obj)->str) {
3524 gc_mark_internal(RMATCH(obj)->str);
3525 }
3526 break;
3527
3528 case T_RATIONAL:
3529 gc_mark_internal(RRATIONAL(obj)->num);
3530 gc_mark_internal(RRATIONAL(obj)->den);
3531 break;
3532
3533 case T_COMPLEX:
3534 gc_mark_internal(RCOMPLEX(obj)->real);
3535 gc_mark_internal(RCOMPLEX(obj)->imag);
3536 break;
3537
3538 case T_STRUCT: {
3539 const long len = RSTRUCT_LEN(obj);
3540 const VALUE * const ptr = RSTRUCT_CONST_PTR(obj);
3541
3542 for (long i = 0; i < len; i++) {
3543 gc_mark_internal(ptr[i]);
3544 }
3545
3546 if (rb_shape_obj_has_fields(obj) && !FL_TEST_RAW(obj, RSTRUCT_GEN_FIELDS)) {
3547 gc_mark_internal(RSTRUCT_FIELDS_OBJ(obj));
3548 }
3549
3550 break;
3551 }
3552
3553 default:
3554 if (BUILTIN_TYPE(obj) == T_MOVED) rb_bug("rb_gc_mark(): %p is T_MOVED", (void *)obj);
3555 if (BUILTIN_TYPE(obj) == T_NONE) rb_bug("rb_gc_mark(): %p is T_NONE", (void *)obj);
3556 if (BUILTIN_TYPE(obj) == T_ZOMBIE) rb_bug("rb_gc_mark(): %p is T_ZOMBIE", (void *)obj);
3557 rb_bug("rb_gc_mark(): unknown data type 0x%x(%p) %s",
3558 BUILTIN_TYPE(obj), (void *)obj,
3559 rb_gc_impl_pointer_to_heap_p(objspace, (void *)obj) ? "corrupted object" : "non object");
3560 }
3561}
3562
3563size_t
3564rb_gc_obj_optimal_size(VALUE obj)
3565{
3566 switch (BUILTIN_TYPE(obj)) {
3567 case T_ARRAY:
3568 {
3569 size_t size = rb_ary_size_as_embedded(obj);
3570 if (rb_gc_size_allocatable_p(size)) {
3571 return size;
3572 }
3573 else {
3574 return sizeof(struct RArray);
3575 }
3576 }
3577
3578 case T_OBJECT:
3579 if (rb_shape_obj_too_complex_p(obj)) {
3580 return sizeof(struct RObject);
3581 }
3582 else {
3583 size_t size = rb_obj_embedded_size(ROBJECT_FIELDS_CAPACITY(obj));
3584 if (rb_gc_size_allocatable_p(size)) {
3585 return size;
3586 }
3587 else {
3588 return sizeof(struct RObject);
3589 }
3590 }
3591
3592 case T_STRING:
3593 {
3594 size_t size = rb_str_size_as_embedded(obj);
3595 if (rb_gc_size_allocatable_p(size)) {
3596 return size;
3597 }
3598 else {
3599 return sizeof(struct RString);
3600 }
3601 }
3602
3603 case T_HASH:
3604 {
3605 if (RB_OBJ_FROZEN(obj) && RHASH_AR_TABLE_P(obj)) {
3606 return sizeof(struct RHash) + offsetof(ar_table, pairs) + RHASH_AR_TABLE_BOUND(obj) * sizeof(ar_table_pair);
3607 }
3608 return sizeof(struct RHash) + (RHASH_ST_TABLE_P(obj) ? sizeof(st_table) : sizeof(ar_table));
3609 }
3610
3611 default:
3612 return 0;
3613 }
3614}
3615
3616void
3617rb_gc_writebarrier(VALUE a, VALUE b)
3618{
3619 rb_gc_impl_writebarrier(rb_gc_get_objspace(), a, b);
3620}
3621
3622void
3623rb_gc_writebarrier_unprotect(VALUE obj)
3624{
3625 rb_gc_impl_writebarrier_unprotect(rb_gc_get_objspace(), obj);
3626}
3627
3628/*
3629 * remember `obj' if needed.
3630 */
3631void
3632rb_gc_writebarrier_remember(VALUE obj)
3633{
3634 rb_gc_impl_writebarrier_remember(rb_gc_get_objspace(), obj);
3635}
3636
3637void
3638rb_gc_copy_attributes(VALUE dest, VALUE obj)
3639{
3640 rb_gc_impl_copy_attributes(rb_gc_get_objspace(), dest, obj);
3641}
3642
3643int
3644rb_gc_modular_gc_loaded_p(void)
3645{
3646#if USE_MODULAR_GC
3647 return rb_gc_functions.modular_gc_loaded_p;
3648#else
3649 return false;
3650#endif
3651}
3652
3653const char *
3654rb_gc_active_gc_name(void)
3655{
3656 const char *gc_name = rb_gc_impl_active_gc_name();
3657
3658 const size_t len = strlen(gc_name);
3659 if (len > RB_GC_MAX_NAME_LEN) {
3660 rb_bug("GC should have a name no more than %d chars long. Currently: %zu (%s)",
3661 RB_GC_MAX_NAME_LEN, len, gc_name);
3662 }
3663
3664 return gc_name;
3665}
3666
3668rb_gc_object_metadata(VALUE obj)
3669{
3670 return rb_gc_impl_object_metadata(rb_gc_get_objspace(), obj);
3671}
3672
3673/* GC */
3674
3675void *
3676rb_gc_ractor_cache_alloc(rb_ractor_t *ractor)
3677{
3678 return rb_gc_impl_ractor_cache_alloc(rb_gc_get_objspace(), ractor);
3679}
3680
3681void
3682rb_gc_ractor_cache_free(void *cache)
3683{
3684 rb_gc_impl_ractor_cache_free(rb_gc_get_objspace(), cache);
3685}
3686
3687void
3688rb_gc_register_mark_object(VALUE obj)
3689{
3690 if (!rb_gc_impl_pointer_to_heap_p(rb_gc_get_objspace(), (void *)obj))
3691 return;
3692
3693 rb_vm_register_global_object(obj);
3694}
3695
3696void
3697rb_gc_register_address(VALUE *addr)
3698{
3699 rb_vm_t *vm = GET_VM();
3700
3701 VALUE obj = *addr;
3702
3703 struct global_object_list *tmp = ALLOC(struct global_object_list);
3704 RB_VM_LOCKING() {
3705 tmp->next = vm->global_object_list;
3706 tmp->varptr = addr;
3707 vm->global_object_list = tmp;
3708 }
3709
3710 /*
3711 * Because some C extensions have assignment-then-register bugs,
3712 * we guard `obj` here so that it would not get swept defensively.
3713 */
3714 RB_GC_GUARD(obj);
3715 if (0 && !SPECIAL_CONST_P(obj)) {
3716 rb_warn("Object is assigned to registering address already: %"PRIsVALUE,
3717 rb_obj_class(obj));
3718 rb_print_backtrace(stderr);
3719 }
3720}
3721
3722void
3723rb_gc_unregister_address(VALUE *addr)
3724{
3725 rb_vm_t *vm = GET_VM();
3726 struct global_object_list *tmp;
3727 RB_VM_LOCKING() {
3728 tmp = vm->global_object_list;
3729 if (tmp->varptr == addr) {
3730 vm->global_object_list = tmp->next;
3731 SIZED_FREE(tmp);
3732 }
3733 else {
3734 while (tmp->next) {
3735 if (tmp->next->varptr == addr) {
3736 struct global_object_list *t = tmp->next;
3737
3738 tmp->next = tmp->next->next;
3739 SIZED_FREE(t);
3740 break;
3741 }
3742 tmp = tmp->next;
3743 }
3744 }
3745 }
3746}
3747
3748void
3750{
3751 rb_gc_register_address(var);
3752}
3753
3754static VALUE
3755gc_start_internal(rb_execution_context_t *ec, VALUE self, VALUE full_mark, VALUE immediate_mark, VALUE immediate_sweep, VALUE compact)
3756{
3757 rb_gc_impl_start(rb_gc_get_objspace(), RTEST(full_mark), RTEST(immediate_mark), RTEST(immediate_sweep), RTEST(compact));
3758
3759 return Qnil;
3760}
3761
3762/*
3763 * rb_objspace_each_objects() is special C API to walk through
3764 * Ruby object space. This C API is too difficult to use it.
3765 * To be frank, you should not use it. Or you need to read the
3766 * source code of this function and understand what this function does.
3767 *
3768 * 'callback' will be called several times (the number of heap page,
3769 * at current implementation) with:
3770 * vstart: a pointer to the first living object of the heap_page.
3771 * vend: a pointer to next to the valid heap_page area.
3772 * stride: a distance to next VALUE.
3773 *
3774 * If callback() returns non-zero, the iteration will be stopped.
3775 *
3776 * This is a sample callback code to iterate liveness objects:
3777 *
3778 * static int
3779 * sample_callback(void *vstart, void *vend, int stride, void *data)
3780 * {
3781 * VALUE v = (VALUE)vstart;
3782 * for (; v != (VALUE)vend; v += stride) {
3783 * if (!rb_objspace_internal_object_p(v)) { // liveness check
3784 * // do something with live object 'v'
3785 * }
3786 * }
3787 * return 0; // continue to iteration
3788 * }
3789 *
3790 * Note: 'vstart' is not a top of heap_page. This point the first
3791 * living object to grasp at least one object to avoid GC issue.
3792 * This means that you can not walk through all Ruby object page
3793 * including freed object page.
3794 *
3795 * Note: On this implementation, 'stride' is the same as sizeof(RVALUE).
3796 * However, there are possibilities to pass variable values with
3797 * 'stride' with some reasons. You must use stride instead of
3798 * use some constant value in the iteration.
3799 */
3800void
3801rb_objspace_each_objects(int (*callback)(void *, void *, size_t, void *), void *data)
3802{
3803 rb_gc_impl_each_objects(rb_gc_get_objspace(), callback, data);
3804}
3805
3806static void
3807gc_ref_update_array(void *objspace, VALUE v)
3808{
3809 if (ARY_SHARED_P(v)) {
3810 VALUE old_root = RARRAY(v)->as.heap.aux.shared_root;
3811
3812 UPDATE_IF_MOVED(objspace, RARRAY(v)->as.heap.aux.shared_root);
3813
3814 VALUE new_root = RARRAY(v)->as.heap.aux.shared_root;
3815 // If the root is embedded and its location has changed
3816 if (ARY_EMBED_P(new_root) && new_root != old_root) {
3817 size_t offset = (size_t)(RARRAY(v)->as.heap.ptr - RARRAY(old_root)->as.ary);
3818 GC_ASSERT(RARRAY(v)->as.heap.ptr >= RARRAY(old_root)->as.ary);
3819 RARRAY(v)->as.heap.ptr = RARRAY(new_root)->as.ary + offset;
3820 }
3821 }
3822 else {
3823 long len = RARRAY_LEN(v);
3824
3825 if (len > 0) {
3826 VALUE *ptr = (VALUE *)RARRAY_CONST_PTR(v);
3827 for (long i = 0; i < len; i++) {
3828 UPDATE_IF_MOVED(objspace, ptr[i]);
3829 }
3830 }
3831
3832 if (rb_gc_obj_slot_size(v) >= rb_ary_size_as_embedded(v)) {
3833 if (rb_ary_embeddable_p(v)) {
3834 rb_ary_make_embedded(v);
3835 }
3836 }
3837 }
3838}
3839
3840static void
3841gc_ref_update_object(void *objspace, VALUE v)
3842{
3843 VALUE *ptr = ROBJECT_FIELDS(v);
3844
3845 if (FL_TEST_RAW(v, ROBJECT_HEAP)) {
3846 if (rb_shape_obj_too_complex_p(v)) {
3847 gc_ref_update_table_values_only(ROBJECT_FIELDS_HASH(v));
3848 return;
3849 }
3850
3851 size_t slot_size = rb_gc_obj_slot_size(v);
3852 size_t embed_size = rb_obj_embedded_size(ROBJECT_FIELDS_CAPACITY(v));
3853 if (slot_size >= embed_size) {
3854 // Object can be re-embedded
3855 memcpy(ROBJECT(v)->as.ary, ptr, sizeof(VALUE) * ROBJECT_FIELDS_COUNT(v));
3856 SIZED_FREE_N(ptr, ROBJECT_FIELDS_CAPACITY(v));
3857 FL_UNSET_RAW(v, ROBJECT_HEAP);
3858 ptr = ROBJECT(v)->as.ary;
3859 }
3860 }
3861
3862 for (uint32_t i = 0; i < ROBJECT_FIELDS_COUNT(v); i++) {
3863 UPDATE_IF_MOVED(objspace, ptr[i]);
3864 }
3865}
3866
3867void
3868rb_gc_ref_update_table_values_only(st_table *tbl)
3869{
3870 gc_ref_update_table_values_only(tbl);
3871}
3872
3873/* Update MOVED references in a VALUE=>VALUE st_table */
3874void
3875rb_gc_update_tbl_refs(st_table *ptr)
3876{
3877 gc_update_table_refs(ptr);
3878}
3879
3880static void
3881gc_ref_update_hash(void *objspace, VALUE v)
3882{
3883 rb_hash_stlike_foreach_with_replace(v, hash_foreach_replace, hash_replace_ref, (st_data_t)objspace);
3884}
3885
3886static void
3887gc_update_values(void *objspace, long n, VALUE *values)
3888{
3889 for (long i = 0; i < n; i++) {
3890 UPDATE_IF_MOVED(objspace, values[i]);
3891 }
3892}
3893
3894void
3895rb_gc_update_values(long n, VALUE *values)
3896{
3897 gc_update_values(rb_gc_get_objspace(), n, values);
3898}
3899
3900static enum rb_id_table_iterator_result
3901check_id_table_move(VALUE value, void *data)
3902{
3903 void *objspace = (void *)data;
3904
3905 if (gc_object_moved_p_internal(objspace, (VALUE)value)) {
3906 return ID_TABLE_REPLACE;
3907 }
3908
3909 return ID_TABLE_CONTINUE;
3910}
3911
3912void
3913rb_gc_prepare_heap_process_object(VALUE obj)
3914{
3915 switch (BUILTIN_TYPE(obj)) {
3916 case T_STRING:
3917 // Precompute the string coderange. This both save time for when it will be
3918 // eventually needed, and avoid mutating heap pages after a potential fork.
3920 break;
3921 default:
3922 break;
3923 }
3924}
3925
3926void
3927rb_gc_prepare_heap(void)
3928{
3929 rb_gc_impl_prepare_heap(rb_gc_get_objspace());
3930}
3931
3932size_t
3933rb_gc_heap_id_for_size(size_t size)
3934{
3935 return rb_gc_impl_heap_id_for_size(rb_gc_get_objspace(), size);
3936}
3937
3938bool
3939rb_gc_size_allocatable_p(size_t size)
3940{
3941 return rb_gc_impl_size_allocatable_p(size);
3942}
3943
3944static enum rb_id_table_iterator_result
3945update_id_table(VALUE *value, void *data, int existing)
3946{
3947 void *objspace = (void *)data;
3948
3949 if (gc_object_moved_p_internal(objspace, (VALUE)*value)) {
3950 *value = gc_location_internal(objspace, (VALUE)*value);
3951 }
3952
3953 return ID_TABLE_CONTINUE;
3954}
3955
3956static void
3957update_m_tbl(void *objspace, struct rb_id_table *tbl)
3958{
3959 if (tbl) {
3960 rb_id_table_foreach_values_with_replace(tbl, check_id_table_move, update_id_table, objspace);
3961 }
3962}
3963
3964static enum rb_id_table_iterator_result
3965update_cvc_tbl_i(VALUE cvc_entry, void *objspace)
3966{
3967 struct rb_cvar_class_tbl_entry *entry;
3968
3969 entry = (struct rb_cvar_class_tbl_entry *)cvc_entry;
3970
3971 if (entry->cref) {
3972 TYPED_UPDATE_IF_MOVED(objspace, rb_cref_t *, entry->cref);
3973 }
3974
3975 entry->class_value = gc_location_internal(objspace, entry->class_value);
3976
3977 return ID_TABLE_CONTINUE;
3978}
3979
3980static void
3981update_cvc_tbl(void *objspace, struct rb_id_table *tbl)
3982{
3983 if (!tbl) return;
3984 rb_id_table_foreach_values(tbl, update_cvc_tbl_i, objspace);
3985}
3986
3987static enum rb_id_table_iterator_result
3988update_const_tbl_i(VALUE value, void *objspace)
3989{
3990 rb_const_entry_t *ce = (rb_const_entry_t *)value;
3991
3992 if (gc_object_moved_p_internal(objspace, ce->value)) {
3993 ce->value = gc_location_internal(objspace, ce->value);
3994 }
3995
3996 if (gc_object_moved_p_internal(objspace, ce->file)) {
3997 ce->file = gc_location_internal(objspace, ce->file);
3998 }
3999
4000 return ID_TABLE_CONTINUE;
4001}
4002
4003static void
4004update_const_tbl(void *objspace, struct rb_id_table *tbl)
4005{
4006 if (!tbl) return;
4007 rb_id_table_foreach_values(tbl, update_const_tbl_i, objspace);
4008}
4009
4010static void
4011update_subclasses(void *objspace, rb_classext_t *ext)
4012{
4013 rb_subclass_entry_t *entry = RCLASSEXT_SUBCLASSES(ext);
4014 if (!entry) return;
4015 while (entry) {
4016 if (entry->klass)
4017 UPDATE_IF_MOVED(objspace, entry->klass);
4018 entry = entry->next;
4019 }
4020}
4021
4022static void
4023update_superclasses(rb_objspace_t *objspace, rb_classext_t *ext)
4024{
4025 if (RCLASSEXT_SUPERCLASSES_WITH_SELF(ext)) {
4026 size_t array_size = RCLASSEXT_SUPERCLASS_DEPTH(ext) + 1;
4027 for (size_t i = 0; i < array_size; i++) {
4028 UPDATE_IF_MOVED(objspace, RCLASSEXT_SUPERCLASSES(ext)[i]);
4029 }
4030 }
4031}
4032
4033static void
4034update_classext_values(rb_objspace_t *objspace, rb_classext_t *ext, bool is_iclass)
4035{
4036 UPDATE_IF_MOVED(objspace, RCLASSEXT_ORIGIN(ext));
4037 UPDATE_IF_MOVED(objspace, RCLASSEXT_REFINED_CLASS(ext));
4038 UPDATE_IF_MOVED(objspace, RCLASSEXT_CLASSPATH(ext));
4039 if (is_iclass) {
4040 UPDATE_IF_MOVED(objspace, RCLASSEXT_INCLUDER(ext));
4041 }
4042}
4043
4044static void
4045update_classext(rb_classext_t *ext, bool is_prime, VALUE box_value, void *arg)
4046{
4047 struct classext_foreach_args *args = (struct classext_foreach_args *)arg;
4048 rb_objspace_t *objspace = args->objspace;
4049
4050 if (RCLASSEXT_SUPER(ext)) {
4051 UPDATE_IF_MOVED(objspace, RCLASSEXT_SUPER(ext));
4052 }
4053
4054 update_m_tbl(objspace, RCLASSEXT_M_TBL(ext));
4055
4056 UPDATE_IF_MOVED(objspace, ext->fields_obj);
4057 if (!RCLASSEXT_SHARED_CONST_TBL(ext)) {
4058 update_const_tbl(objspace, RCLASSEXT_CONST_TBL(ext));
4059 }
4060 UPDATE_IF_MOVED(objspace, RCLASSEXT_CC_TBL(ext));
4061 update_cvc_tbl(objspace, RCLASSEXT_CVC_TBL(ext));
4062 update_superclasses(objspace, ext);
4063 update_subclasses(objspace, ext);
4064
4065 update_classext_values(objspace, ext, false);
4066}
4067
4068static void
4069update_iclass_classext(rb_classext_t *ext, bool is_prime, VALUE box_value, void *arg)
4070{
4071 struct classext_foreach_args *args = (struct classext_foreach_args *)arg;
4072 rb_objspace_t *objspace = args->objspace;
4073
4074 if (RCLASSEXT_SUPER(ext)) {
4075 UPDATE_IF_MOVED(objspace, RCLASSEXT_SUPER(ext));
4076 }
4077 update_m_tbl(objspace, RCLASSEXT_M_TBL(ext));
4078 update_m_tbl(objspace, RCLASSEXT_CALLABLE_M_TBL(ext));
4079 UPDATE_IF_MOVED(objspace, RCLASSEXT_CC_TBL(ext));
4080 update_subclasses(objspace, ext);
4081
4082 update_classext_values(objspace, ext, true);
4083}
4084
4086 vm_table_foreach_callback_func callback;
4087 vm_table_update_callback_func update_callback;
4088 void *data;
4089 bool weak_only;
4090};
4091
4092static int
4093vm_weak_table_foreach_weak_key(st_data_t key, st_data_t value, st_data_t data, int error)
4094{
4095 struct global_vm_table_foreach_data *iter_data = (struct global_vm_table_foreach_data *)data;
4096
4097 int ret = iter_data->callback((VALUE)key, iter_data->data);
4098
4099 if (!iter_data->weak_only) {
4100 if (ret != ST_CONTINUE) return ret;
4101
4102 ret = iter_data->callback((VALUE)value, iter_data->data);
4103 }
4104
4105 return ret;
4106}
4107
4108static int
4109vm_weak_table_foreach_update_weak_key(st_data_t *key, st_data_t *value, st_data_t data, int existing)
4110{
4111 struct global_vm_table_foreach_data *iter_data = (struct global_vm_table_foreach_data *)data;
4112
4113 int ret = iter_data->update_callback((VALUE *)key, iter_data->data);
4114
4115 if (!iter_data->weak_only) {
4116 if (ret != ST_CONTINUE) return ret;
4117
4118 ret = iter_data->update_callback((VALUE *)value, iter_data->data);
4119 }
4120
4121 return ret;
4122}
4123
4124static int
4125vm_weak_table_sym_set_foreach(VALUE *sym_ptr, void *data)
4126{
4127 VALUE sym = *sym_ptr;
4128 struct global_vm_table_foreach_data *iter_data = (struct global_vm_table_foreach_data *)data;
4129
4130 if (RB_SPECIAL_CONST_P(sym)) return ST_CONTINUE;
4131
4132 int ret = iter_data->callback(sym, iter_data->data);
4133
4134 if (ret == ST_REPLACE) {
4135 ret = iter_data->update_callback(sym_ptr, iter_data->data);
4136 }
4137
4138 return ret;
4139}
4140
4141struct st_table *rb_generic_fields_tbl_get(void);
4142
4143static int
4144vm_weak_table_id2ref_foreach(st_data_t key, st_data_t value, st_data_t data, int error)
4145{
4146 struct global_vm_table_foreach_data *iter_data = (struct global_vm_table_foreach_data *)data;
4147
4148 if (!iter_data->weak_only && !FIXNUM_P((VALUE)key)) {
4149 int ret = iter_data->callback((VALUE)key, iter_data->data);
4150 if (ret != ST_CONTINUE) return ret;
4151 }
4152
4153 return iter_data->callback((VALUE)value, iter_data->data);
4154}
4155
4156static int
4157vm_weak_table_id2ref_foreach_update(st_data_t *key, st_data_t *value, st_data_t data, int existing)
4158{
4159 struct global_vm_table_foreach_data *iter_data = (struct global_vm_table_foreach_data *)data;
4160
4161 iter_data->update_callback((VALUE *)value, iter_data->data);
4162
4163 if (!iter_data->weak_only && !FIXNUM_P((VALUE)*key)) {
4164 iter_data->update_callback((VALUE *)key, iter_data->data);
4165 }
4166
4167 return ST_CONTINUE;
4168}
4169
4170static int
4171vm_weak_table_gen_fields_foreach(st_data_t key, st_data_t value, st_data_t data)
4172{
4173 struct global_vm_table_foreach_data *iter_data = (struct global_vm_table_foreach_data *)data;
4174
4175 int ret = iter_data->callback((VALUE)key, iter_data->data);
4176
4177 VALUE new_value = (VALUE)value;
4178 VALUE new_key = (VALUE)key;
4179
4180 switch (ret) {
4181 case ST_CONTINUE:
4182 break;
4183
4184 case ST_DELETE:
4185 RBASIC_SET_SHAPE_ID((VALUE)key, ROOT_SHAPE_ID);
4186 return ST_DELETE;
4187
4188 case ST_REPLACE: {
4189 ret = iter_data->update_callback(&new_key, iter_data->data);
4190 if (key != new_key) {
4191 ret = ST_DELETE;
4192 }
4193 break;
4194 }
4195
4196 default:
4197 rb_bug("vm_weak_table_gen_fields_foreach: return value %d not supported", ret);
4198 }
4199
4200 if (!iter_data->weak_only) {
4201 int ivar_ret = iter_data->callback(new_value, iter_data->data);
4202 switch (ivar_ret) {
4203 case ST_CONTINUE:
4204 break;
4205
4206 case ST_REPLACE:
4207 iter_data->update_callback(&new_value, iter_data->data);
4208 break;
4209
4210 default:
4211 rb_bug("vm_weak_table_gen_fields_foreach: return value %d not supported", ivar_ret);
4212 }
4213 }
4214
4215 if (key != new_key || value != new_value) {
4216 DURING_GC_COULD_MALLOC_REGION_START();
4217 {
4218 st_insert(rb_generic_fields_tbl_get(), (st_data_t)new_key, new_value);
4219 }
4220 DURING_GC_COULD_MALLOC_REGION_END();
4221 }
4222
4223 return ret;
4224}
4225
4226static int
4227vm_weak_table_frozen_strings_foreach(VALUE *str, void *data)
4228{
4229 // int retval = vm_weak_table_foreach_weak_key(key, value, data, error);
4230 struct global_vm_table_foreach_data *iter_data = (struct global_vm_table_foreach_data *)data;
4231 int retval = iter_data->callback(*str, iter_data->data);
4232
4233 if (retval == ST_REPLACE) {
4234 retval = iter_data->update_callback(str, iter_data->data);
4235 }
4236
4237 if (retval == ST_DELETE) {
4238 FL_UNSET(*str, RSTRING_FSTR);
4239 }
4240
4241 return retval;
4242}
4243
4244void rb_fstring_foreach_with_replace(int (*callback)(VALUE *str, void *data), void *data);
4245void
4246rb_gc_vm_weak_table_foreach(vm_table_foreach_callback_func callback,
4247 vm_table_update_callback_func update_callback,
4248 void *data,
4249 bool weak_only,
4250 enum rb_gc_vm_weak_tables table)
4251{
4252 rb_vm_t *vm = GET_VM();
4253
4254 struct global_vm_table_foreach_data foreach_data = {
4255 .callback = callback,
4256 .update_callback = update_callback,
4257 .data = data,
4258 .weak_only = weak_only,
4259 };
4260
4261 switch (table) {
4262 case RB_GC_VM_CI_TABLE: {
4263 st_foreach_with_replace(
4264 &vm->ci_table,
4265 vm_weak_table_foreach_weak_key,
4266 vm_weak_table_foreach_update_weak_key,
4267 (st_data_t)&foreach_data
4268 );
4269 break;
4270 }
4271 case RB_GC_VM_OVERLOADED_CME_TABLE: {
4272 st_foreach_with_replace(
4273 &vm->overloaded_cme_table,
4274 vm_weak_table_foreach_weak_key,
4275 vm_weak_table_foreach_update_weak_key,
4276 (st_data_t)&foreach_data
4277 );
4278 break;
4279 }
4280 case RB_GC_VM_GLOBAL_SYMBOLS_TABLE: {
4281 rb_sym_global_symbol_table_foreach_weak_reference(
4282 vm_weak_table_sym_set_foreach,
4283 &foreach_data
4284 );
4285 break;
4286 }
4287 case RB_GC_VM_ID2REF_TABLE: {
4288 if (id2ref_tbl) {
4289 st_foreach_with_replace(
4290 id2ref_tbl,
4291 vm_weak_table_id2ref_foreach,
4292 vm_weak_table_id2ref_foreach_update,
4293 (st_data_t)&foreach_data
4294 );
4295 }
4296 break;
4297 }
4298 case RB_GC_VM_GENERIC_FIELDS_TABLE: {
4299 st_table *generic_fields_tbl = rb_generic_fields_tbl_get();
4300 if (generic_fields_tbl) {
4301 st_foreach(
4302 generic_fields_tbl,
4303 vm_weak_table_gen_fields_foreach,
4304 (st_data_t)&foreach_data
4305 );
4306 }
4307 break;
4308 }
4309 case RB_GC_VM_FROZEN_STRINGS_TABLE: {
4310 rb_fstring_foreach_with_replace(
4311 vm_weak_table_frozen_strings_foreach,
4312 &foreach_data
4313 );
4314 break;
4315 }
4316 case RB_GC_VM_WEAK_TABLE_COUNT:
4317 rb_bug("Unreachable");
4318 default:
4319 rb_bug("rb_gc_vm_weak_table_foreach: unknown table %d", table);
4320 }
4321}
4322
4323void
4324rb_gc_update_vm_references(void *objspace)
4325{
4326 rb_execution_context_t *ec = GET_EC();
4327 rb_vm_t *vm = rb_ec_vm_ptr(ec);
4328
4329 rb_vm_update_references(vm);
4330 rb_gc_update_global_tbl();
4331 rb_sym_global_symbols_mark_and_move();
4332
4333#if USE_YJIT
4334 void rb_yjit_root_update_references(void); // in Rust
4335
4336 if (rb_yjit_enabled_p) {
4337 rb_yjit_root_update_references();
4338 }
4339#endif
4340
4341#if USE_ZJIT
4342 void rb_zjit_root_update_references(void); // in Rust
4343
4344 if (rb_zjit_enabled_p) {
4345 rb_zjit_root_update_references();
4346 }
4347#endif
4348}
4349
4350void
4351rb_gc_update_object_references(void *objspace, VALUE obj)
4352{
4353 struct classext_foreach_args args;
4354
4355 switch (BUILTIN_TYPE(obj)) {
4356 case T_CLASS:
4357 if (FL_TEST_RAW(obj, FL_SINGLETON)) {
4358 UPDATE_IF_MOVED(objspace, RCLASS_ATTACHED_OBJECT(obj));
4359 }
4360 // Continue to the shared T_CLASS/T_MODULE
4361 case T_MODULE:
4362 args.klass = obj;
4363 args.objspace = objspace;
4364 rb_class_classext_foreach(obj, update_classext, (void *)&args);
4365 break;
4366
4367 case T_ICLASS:
4368 args.objspace = objspace;
4369 rb_class_classext_foreach(obj, update_iclass_classext, (void *)&args);
4370 break;
4371
4372 case T_IMEMO:
4373 rb_imemo_mark_and_move(obj, true);
4374 return;
4375
4376 case T_NIL:
4377 case T_FIXNUM:
4378 case T_NODE:
4379 case T_MOVED:
4380 case T_NONE:
4381 /* These can't move */
4382 return;
4383
4384 case T_ARRAY:
4385 gc_ref_update_array(objspace, obj);
4386 break;
4387
4388 case T_HASH:
4389 gc_ref_update_hash(objspace, obj);
4390 UPDATE_IF_MOVED(objspace, RHASH(obj)->ifnone);
4391 break;
4392
4393 case T_STRING:
4394 {
4395 if (STR_SHARED_P(obj)) {
4396 UPDATE_IF_MOVED(objspace, RSTRING(obj)->as.heap.aux.shared);
4397 }
4398
4399 /* If, after move the string is not embedded, and can fit in the
4400 * slot it's been placed in, then re-embed it. */
4401 if (rb_gc_obj_slot_size(obj) >= rb_str_size_as_embedded(obj)) {
4402 if (!STR_EMBED_P(obj) && rb_str_reembeddable_p(obj)) {
4403 rb_str_make_embedded(obj);
4404 }
4405 }
4406
4407 break;
4408 }
4409 case T_DATA:
4410 /* Call the compaction callback, if it exists */
4411 {
4412 bool typed_data = RTYPEDDATA_P(obj);
4413 void *const ptr = typed_data ? RTYPEDDATA_GET_DATA(obj) : DATA_PTR(obj);
4414
4415 if (typed_data) {
4416 UPDATE_IF_MOVED(objspace, RTYPEDDATA(obj)->fields_obj);
4417 }
4418
4419 if (ptr) {
4420 if (typed_data && gc_declarative_marking_p(RTYPEDDATA_TYPE(obj))) {
4421 size_t *offset_list = TYPED_DATA_REFS_OFFSET_LIST(obj);
4422
4423 for (size_t offset = *offset_list; offset != RUBY_REF_END; offset = *offset_list++) {
4424 VALUE *ref = (VALUE *)((char *)ptr + offset);
4425 *ref = gc_location_internal(objspace, *ref);
4426 }
4427 }
4428 else if (typed_data) {
4429 RUBY_DATA_FUNC compact_func = RTYPEDDATA_TYPE(obj)->function.dcompact;
4430 if (compact_func) (*compact_func)(ptr);
4431 }
4432 }
4433 }
4434 break;
4435
4436 case T_OBJECT:
4437 gc_ref_update_object(objspace, obj);
4438 break;
4439
4440 case T_FILE:
4441 if (RFILE(obj)->fptr) {
4442 UPDATE_IF_MOVED(objspace, RFILE(obj)->fptr->self);
4443 UPDATE_IF_MOVED(objspace, RFILE(obj)->fptr->pathv);
4444 UPDATE_IF_MOVED(objspace, RFILE(obj)->fptr->tied_io_for_writing);
4445 UPDATE_IF_MOVED(objspace, RFILE(obj)->fptr->writeconv_asciicompat);
4446 UPDATE_IF_MOVED(objspace, RFILE(obj)->fptr->writeconv_pre_ecopts);
4447 UPDATE_IF_MOVED(objspace, RFILE(obj)->fptr->encs.ecopts);
4448 UPDATE_IF_MOVED(objspace, RFILE(obj)->fptr->write_lock);
4449 UPDATE_IF_MOVED(objspace, RFILE(obj)->fptr->timeout);
4450 UPDATE_IF_MOVED(objspace, RFILE(obj)->fptr->wakeup_mutex);
4451 }
4452 break;
4453 case T_REGEXP:
4454 UPDATE_IF_MOVED(objspace, RREGEXP(obj)->src);
4455 break;
4456
4457 case T_SYMBOL:
4458 UPDATE_IF_MOVED(objspace, RSYMBOL(obj)->fstr);
4459 break;
4460
4461 case T_FLOAT:
4462 case T_BIGNUM:
4463 break;
4464
4465 case T_MATCH:
4466 UPDATE_IF_MOVED(objspace, RMATCH(obj)->regexp);
4467
4468 if (RMATCH(obj)->str) {
4469 UPDATE_IF_MOVED(objspace, RMATCH(obj)->str);
4470 }
4471 break;
4472
4473 case T_RATIONAL:
4474 UPDATE_IF_MOVED(objspace, RRATIONAL(obj)->num);
4475 UPDATE_IF_MOVED(objspace, RRATIONAL(obj)->den);
4476 break;
4477
4478 case T_COMPLEX:
4479 UPDATE_IF_MOVED(objspace, RCOMPLEX(obj)->real);
4480 UPDATE_IF_MOVED(objspace, RCOMPLEX(obj)->imag);
4481
4482 break;
4483
4484 case T_STRUCT:
4485 {
4486 long i, len = RSTRUCT_LEN(obj);
4487 VALUE *ptr = (VALUE *)RSTRUCT_CONST_PTR(obj);
4488
4489 for (i = 0; i < len; i++) {
4490 UPDATE_IF_MOVED(objspace, ptr[i]);
4491 }
4492
4493 if (RSTRUCT_EMBED_LEN(obj)) {
4494 if (!FL_TEST_RAW(obj, RSTRUCT_GEN_FIELDS)) {
4495 UPDATE_IF_MOVED(objspace, ptr[len]);
4496 }
4497 }
4498 else {
4499 UPDATE_IF_MOVED(objspace, RSTRUCT(obj)->as.heap.fields_obj);
4500 }
4501 }
4502 break;
4503 default:
4504 rb_bug("unreachable");
4505 break;
4506 }
4507
4508 UPDATE_IF_MOVED(objspace, RBASIC(obj)->klass);
4509}
4510
4511VALUE
4512rb_gc_start(void)
4513{
4514 rb_gc();
4515 return Qnil;
4516}
4517
4518void
4519rb_gc(void)
4520{
4521 unless_objspace(objspace) { return; }
4522
4523 rb_gc_impl_start(objspace, true, true, true, false);
4524}
4525
4526int
4527rb_during_gc(void)
4528{
4529 unless_objspace(objspace) { return FALSE; }
4530
4531 return rb_gc_impl_during_gc_p(objspace);
4532}
4533
4534size_t
4535rb_gc_count(void)
4536{
4537 return rb_gc_impl_gc_count(rb_gc_get_objspace());
4538}
4539
4540static VALUE
4541gc_count(rb_execution_context_t *ec, VALUE self)
4542{
4543 return SIZET2NUM(rb_gc_count());
4544}
4545
4546VALUE
4547rb_gc_latest_gc_info(VALUE key)
4548{
4549 if (!SYMBOL_P(key) && !RB_TYPE_P(key, T_HASH)) {
4550 rb_raise(rb_eTypeError, "non-hash or symbol given");
4551 }
4552
4553 VALUE val = rb_gc_impl_latest_gc_info(rb_gc_get_objspace(), key);
4554
4555 if (val == Qundef) {
4556 rb_raise(rb_eArgError, "unknown key: %"PRIsVALUE, rb_sym2str(key));
4557 }
4558
4559 return val;
4560}
4561
4562static VALUE
4563gc_stat(rb_execution_context_t *ec, VALUE self, VALUE arg) // arg is (nil || hash || symbol)
4564{
4565 if (NIL_P(arg)) {
4566 arg = rb_hash_new();
4567 }
4568 else if (!RB_TYPE_P(arg, T_HASH) && !SYMBOL_P(arg)) {
4569 rb_raise(rb_eTypeError, "non-hash or symbol given");
4570 }
4571
4572 VALUE ret = rb_gc_impl_stat(rb_gc_get_objspace(), arg);
4573
4574 if (ret == Qundef) {
4575 GC_ASSERT(SYMBOL_P(arg));
4576
4577 rb_raise(rb_eArgError, "unknown key: %"PRIsVALUE, rb_sym2str(arg));
4578 }
4579
4580 return ret;
4581}
4582
4583size_t
4584rb_gc_stat(VALUE arg)
4585{
4586 if (!RB_TYPE_P(arg, T_HASH) && !SYMBOL_P(arg)) {
4587 rb_raise(rb_eTypeError, "non-hash or symbol given");
4588 }
4589
4590 VALUE ret = rb_gc_impl_stat(rb_gc_get_objspace(), arg);
4591
4592 if (ret == Qundef) {
4593 GC_ASSERT(SYMBOL_P(arg));
4594
4595 rb_raise(rb_eArgError, "unknown key: %"PRIsVALUE, rb_sym2str(arg));
4596 }
4597
4598 if (SYMBOL_P(arg)) {
4599 return NUM2SIZET(ret);
4600 }
4601 else {
4602 return 0;
4603 }
4604}
4605
4606static VALUE
4607gc_stat_heap(rb_execution_context_t *ec, VALUE self, VALUE heap_name, VALUE arg)
4608{
4609 if (NIL_P(arg)) {
4610 arg = rb_hash_new();
4611 }
4612
4613 if (NIL_P(heap_name)) {
4614 if (!RB_TYPE_P(arg, T_HASH)) {
4615 rb_raise(rb_eTypeError, "non-hash given");
4616 }
4617 }
4618 else if (FIXNUM_P(heap_name)) {
4619 if (!SYMBOL_P(arg) && !RB_TYPE_P(arg, T_HASH)) {
4620 rb_raise(rb_eTypeError, "non-hash or symbol given");
4621 }
4622 }
4623 else {
4624 rb_raise(rb_eTypeError, "heap_name must be nil or an Integer");
4625 }
4626
4627 VALUE ret = rb_gc_impl_stat_heap(rb_gc_get_objspace(), heap_name, arg);
4628
4629 if (ret == Qundef) {
4630 GC_ASSERT(SYMBOL_P(arg));
4631
4632 rb_raise(rb_eArgError, "unknown key: %"PRIsVALUE, rb_sym2str(arg));
4633 }
4634
4635 return ret;
4636}
4637
4638static VALUE
4639gc_config_get(rb_execution_context_t *ec, VALUE self)
4640{
4641 VALUE cfg_hash = rb_gc_impl_config_get(rb_gc_get_objspace());
4642 rb_hash_aset(cfg_hash, sym("implementation"), rb_fstring_cstr(rb_gc_impl_active_gc_name()));
4643
4644 return cfg_hash;
4645}
4646
4647static VALUE
4648gc_config_set(rb_execution_context_t *ec, VALUE self, VALUE hash)
4649{
4650 void *objspace = rb_gc_get_objspace();
4651
4652 rb_gc_impl_config_set(objspace, hash);
4653
4654 return Qnil;
4655}
4656
4657static VALUE
4658gc_stress_get(rb_execution_context_t *ec, VALUE self)
4659{
4660 return rb_gc_impl_stress_get(rb_gc_get_objspace());
4661}
4662
4663static VALUE
4664gc_stress_set_m(rb_execution_context_t *ec, VALUE self, VALUE flag)
4665{
4666 rb_gc_impl_stress_set(rb_gc_get_objspace(), flag);
4667
4668 return flag;
4669}
4670
4671void
4672rb_gc_initial_stress_set(VALUE flag)
4673{
4674 initial_stress = flag;
4675}
4676
4677size_t *
4678rb_gc_heap_sizes(void)
4679{
4680 return rb_gc_impl_heap_sizes(rb_gc_get_objspace());
4681}
4682
4683VALUE
4684rb_gc_enable(void)
4685{
4686 return rb_objspace_gc_enable(rb_gc_get_objspace());
4687}
4688
4689VALUE
4690rb_objspace_gc_enable(void *objspace)
4691{
4692 bool disabled = !rb_gc_impl_gc_enabled_p(objspace);
4693 rb_gc_impl_gc_enable(objspace);
4694 return RBOOL(disabled);
4695}
4696
4697static VALUE
4698gc_enable(rb_execution_context_t *ec, VALUE _)
4699{
4700 return rb_gc_enable();
4701}
4702
4703static VALUE
4704gc_disable_no_rest(void *objspace)
4705{
4706 bool disabled = !rb_gc_impl_gc_enabled_p(objspace);
4707 rb_gc_impl_gc_disable(objspace, false);
4708 return RBOOL(disabled);
4709}
4710
4711VALUE
4712rb_gc_disable_no_rest(void)
4713{
4714 return gc_disable_no_rest(rb_gc_get_objspace());
4715}
4716
4717VALUE
4718rb_gc_disable(void)
4719{
4720 return rb_objspace_gc_disable(rb_gc_get_objspace());
4721}
4722
4723VALUE
4724rb_objspace_gc_disable(void *objspace)
4725{
4726 bool disabled = !rb_gc_impl_gc_enabled_p(objspace);
4727 rb_gc_impl_gc_disable(objspace, true);
4728 return RBOOL(disabled);
4729}
4730
4731static VALUE
4732gc_disable(rb_execution_context_t *ec, VALUE _)
4733{
4734 return rb_gc_disable();
4735}
4736
4737// TODO: think about moving ruby_gc_set_params into Init_heap or Init_gc
4738void
4739ruby_gc_set_params(void)
4740{
4741 rb_gc_impl_set_params(rb_gc_get_objspace());
4742}
4743
4744void
4745rb_objspace_reachable_objects_from(VALUE obj, void (func)(VALUE, void *), void *data)
4746{
4747 RB_VM_LOCKING() {
4748 if (rb_gc_impl_during_gc_p(rb_gc_get_objspace())) rb_bug("rb_objspace_reachable_objects_from() is not supported while during GC");
4749
4750 if (!RB_SPECIAL_CONST_P(obj)) {
4751 rb_vm_t *vm = GET_VM();
4752 struct gc_mark_func_data_struct *prev_mfd = vm->gc.mark_func_data;
4753 struct gc_mark_func_data_struct mfd = {
4754 .mark_func = func,
4755 .data = data,
4756 };
4757
4758 vm->gc.mark_func_data = &mfd;
4759 rb_gc_mark_children(rb_gc_get_objspace(), obj);
4760 vm->gc.mark_func_data = prev_mfd;
4761 }
4762 }
4763}
4764
4766 const char *category;
4767 void (*func)(const char *category, VALUE, void *);
4768 void *data;
4769};
4770
4771static void
4772root_objects_from(VALUE obj, void *ptr)
4773{
4774 const struct root_objects_data *data = (struct root_objects_data *)ptr;
4775 (*data->func)(data->category, obj, data->data);
4776}
4777
4778void
4779rb_objspace_reachable_objects_from_root(void (func)(const char *category, VALUE, void *), void *passing_data)
4780{
4781 if (rb_gc_impl_during_gc_p(rb_gc_get_objspace())) rb_bug("rb_gc_impl_objspace_reachable_objects_from_root() is not supported while during GC");
4782
4783 rb_vm_t *vm = GET_VM();
4784
4785 struct root_objects_data data = {
4786 .func = func,
4787 .data = passing_data,
4788 };
4789
4790 struct gc_mark_func_data_struct *prev_mfd = vm->gc.mark_func_data;
4791 struct gc_mark_func_data_struct mfd = {
4792 .mark_func = root_objects_from,
4793 .data = &data,
4794 };
4795
4796 vm->gc.mark_func_data = &mfd;
4797 rb_gc_save_machine_context();
4798 rb_gc_mark_roots(vm->gc.objspace, &data.category);
4799 vm->gc.mark_func_data = prev_mfd;
4800}
4801
4802/*
4803 ------------------------------ DEBUG ------------------------------
4804*/
4805
4806static const char *
4807type_name(int type, VALUE obj)
4808{
4809 switch (type) {
4810#define TYPE_NAME(t) case (t): return #t;
4811 TYPE_NAME(T_NONE);
4812 TYPE_NAME(T_OBJECT);
4813 TYPE_NAME(T_CLASS);
4814 TYPE_NAME(T_MODULE);
4815 TYPE_NAME(T_FLOAT);
4816 TYPE_NAME(T_STRING);
4817 TYPE_NAME(T_REGEXP);
4818 TYPE_NAME(T_ARRAY);
4819 TYPE_NAME(T_HASH);
4820 TYPE_NAME(T_STRUCT);
4821 TYPE_NAME(T_BIGNUM);
4822 TYPE_NAME(T_FILE);
4823 TYPE_NAME(T_MATCH);
4824 TYPE_NAME(T_COMPLEX);
4825 TYPE_NAME(T_RATIONAL);
4826 TYPE_NAME(T_NIL);
4827 TYPE_NAME(T_TRUE);
4828 TYPE_NAME(T_FALSE);
4829 TYPE_NAME(T_SYMBOL);
4830 TYPE_NAME(T_FIXNUM);
4831 TYPE_NAME(T_UNDEF);
4832 TYPE_NAME(T_IMEMO);
4833 TYPE_NAME(T_ICLASS);
4834 TYPE_NAME(T_MOVED);
4835 TYPE_NAME(T_ZOMBIE);
4836 case T_DATA:
4837 if (obj && rb_objspace_data_type_name(obj)) {
4838 return rb_objspace_data_type_name(obj);
4839 }
4840 return "T_DATA";
4841#undef TYPE_NAME
4842 }
4843 return "unknown";
4844}
4845
4846static const char *
4847obj_type_name(VALUE obj)
4848{
4849 return type_name(TYPE(obj), obj);
4850}
4851
4852const char *
4853rb_method_type_name(rb_method_type_t type)
4854{
4855 switch (type) {
4856 case VM_METHOD_TYPE_ISEQ: return "iseq";
4857 case VM_METHOD_TYPE_ATTRSET: return "attrset";
4858 case VM_METHOD_TYPE_IVAR: return "ivar";
4859 case VM_METHOD_TYPE_BMETHOD: return "bmethod";
4860 case VM_METHOD_TYPE_ALIAS: return "alias";
4861 case VM_METHOD_TYPE_REFINED: return "refined";
4862 case VM_METHOD_TYPE_CFUNC: return "cfunc";
4863 case VM_METHOD_TYPE_ZSUPER: return "zsuper";
4864 case VM_METHOD_TYPE_MISSING: return "missing";
4865 case VM_METHOD_TYPE_OPTIMIZED: return "optimized";
4866 case VM_METHOD_TYPE_UNDEF: return "undef";
4867 case VM_METHOD_TYPE_NOTIMPLEMENTED: return "notimplemented";
4868 }
4869 rb_bug("rb_method_type_name: unreachable (type: %d)", type);
4870}
4871
4872static void
4873rb_raw_iseq_info(char *const buff, const size_t buff_size, const rb_iseq_t *iseq)
4874{
4875 if (buff_size > 0 && ISEQ_BODY(iseq) && ISEQ_BODY(iseq)->location.label && !RB_TYPE_P(ISEQ_BODY(iseq)->location.pathobj, T_MOVED)) {
4876 VALUE path = rb_iseq_path(iseq);
4877 int n = ISEQ_BODY(iseq)->location.first_lineno;
4878 snprintf(buff, buff_size, " %s@%s:%d",
4879 RSTRING_PTR(ISEQ_BODY(iseq)->location.label),
4880 RSTRING_PTR(path), n);
4881 }
4882}
4883
4884static int
4885str_len_no_raise(VALUE str)
4886{
4887 long len = RSTRING_LEN(str);
4888 if (len < 0) return 0;
4889 if (len > INT_MAX) return INT_MAX;
4890 return (int)len;
4891}
4892
4893#define BUFF_ARGS buff + pos, buff_size - pos
4894#define APPEND_F(...) if ((pos += snprintf(BUFF_ARGS, "" __VA_ARGS__)) >= buff_size) goto end
4895#define APPEND_S(s) do { \
4896 if ((pos + (int)rb_strlen_lit(s)) >= buff_size) { \
4897 goto end; \
4898 } \
4899 else { \
4900 memcpy(buff + pos, (s), rb_strlen_lit(s) + 1); \
4901 } \
4902 } while (0)
4903#define C(c, s) ((c) != 0 ? (s) : " ")
4904
4905static size_t
4906rb_raw_obj_info_common(char *const buff, const size_t buff_size, const VALUE obj)
4907{
4908 size_t pos = 0;
4909
4910 if (SPECIAL_CONST_P(obj)) {
4911 APPEND_F("%s", obj_type_name(obj));
4912
4913 if (FIXNUM_P(obj)) {
4914 APPEND_F(" %ld", FIX2LONG(obj));
4915 }
4916 else if (SYMBOL_P(obj)) {
4917 APPEND_F(" %s", rb_id2name(SYM2ID(obj)));
4918 }
4919 }
4920 else {
4921 // const int age = RVALUE_AGE_GET(obj);
4922
4923 if (rb_gc_impl_pointer_to_heap_p(rb_gc_get_objspace(), (void *)obj)) {
4924 APPEND_F("%p %s/", (void *)obj, obj_type_name(obj));
4925 // TODO: fixme
4926 // APPEND_F("%p [%d%s%s%s%s%s%s] %s ",
4927 // (void *)obj, age,
4928 // C(RVALUE_UNCOLLECTIBLE_BITMAP(obj), "L"),
4929 // C(RVALUE_MARK_BITMAP(obj), "M"),
4930 // C(RVALUE_PIN_BITMAP(obj), "P"),
4931 // C(RVALUE_MARKING_BITMAP(obj), "R"),
4932 // C(RVALUE_WB_UNPROTECTED_BITMAP(obj), "U"),
4933 // C(rb_objspace_garbage_object_p(obj), "G"),
4934 // obj_type_name(obj));
4935 }
4936 else {
4937 /* fake */
4938 // APPEND_F("%p [%dXXXX] %s",
4939 // (void *)obj, age,
4940 // obj_type_name(obj));
4941 }
4942
4943 if (internal_object_p(obj)) {
4944 /* ignore */
4945 }
4946 else if (RBASIC(obj)->klass == 0) {
4947 APPEND_S("(temporary internal)");
4948 }
4949 else if (RTEST(RBASIC(obj)->klass)) {
4950 VALUE class_path = rb_class_path_cached(RBASIC(obj)->klass);
4951 if (!NIL_P(class_path)) {
4952 APPEND_F("%s ", RSTRING_PTR(class_path));
4953 }
4954 }
4955 }
4956 end:
4957
4958 return pos;
4959}
4960
4961const char *rb_raw_obj_info(char *const buff, const size_t buff_size, VALUE obj);
4962
4963static size_t
4964rb_raw_obj_info_buitin_type(char *const buff, const size_t buff_size, const VALUE obj, size_t pos)
4965{
4966 if (LIKELY(pos < buff_size) && !SPECIAL_CONST_P(obj)) {
4967 const enum ruby_value_type type = BUILTIN_TYPE(obj);
4968
4969 switch (type) {
4970 case T_NODE:
4971 UNEXPECTED_NODE(rb_raw_obj_info);
4972 break;
4973 case T_ARRAY:
4974 if (ARY_SHARED_P(obj)) {
4975 APPEND_S("shared -> ");
4976 rb_raw_obj_info(BUFF_ARGS, ARY_SHARED_ROOT(obj));
4977 }
4978 else {
4979 APPEND_F("[%s%s%s] ",
4980 C(ARY_EMBED_P(obj), "E"),
4981 C(ARY_SHARED_P(obj), "S"),
4982 C(ARY_SHARED_ROOT_P(obj), "R"));
4983
4984 if (ARY_EMBED_P(obj)) {
4985 APPEND_F("len: %ld (embed)",
4986 RARRAY_LEN(obj));
4987 }
4988 else {
4989 APPEND_F("len: %ld, capa:%ld ptr:%p",
4990 RARRAY_LEN(obj),
4991 RARRAY(obj)->as.heap.aux.capa,
4992 (void *)RARRAY_CONST_PTR(obj));
4993 }
4994 }
4995 break;
4996 case T_STRING: {
4997 APPEND_F("[%s%s] ",
4998 C(FL_TEST(obj, RSTRING_FSTR), "F"),
4999 C(RB_OBJ_FROZEN(obj), "R"));
5000
5001 if (STR_SHARED_P(obj)) {
5002 APPEND_F(" [shared] len: %ld", RSTRING_LEN(obj));
5003 }
5004 else {
5005 if (STR_EMBED_P(obj)) APPEND_S(" [embed]");
5006
5007 APPEND_F(" len: %ld, capa: %" PRIdSIZE, RSTRING_LEN(obj), rb_str_capacity(obj));
5008 }
5009 APPEND_F(" \"%.*s\"", str_len_no_raise(obj), RSTRING_PTR(obj));
5010 break;
5011 }
5012 case T_SYMBOL: {
5013 VALUE fstr = RSYMBOL(obj)->fstr;
5014 ID id = RSYMBOL(obj)->id;
5015 if (RB_TYPE_P(fstr, T_STRING)) {
5016 APPEND_F(":%s id:%d", RSTRING_PTR(fstr), (unsigned int)id);
5017 }
5018 else {
5019 APPEND_F("(%p) id:%d", (void *)fstr, (unsigned int)id);
5020 }
5021 break;
5022 }
5023 case T_MOVED: {
5024 APPEND_F("-> %p", (void*)gc_location_internal(rb_gc_get_objspace(), obj));
5025 break;
5026 }
5027 case T_HASH: {
5028 APPEND_F("[%c] %"PRIdSIZE,
5029 RHASH_AR_TABLE_P(obj) ? 'A' : 'S',
5030 RHASH_SIZE(obj));
5031 break;
5032 }
5033 case T_CLASS:
5034 case T_MODULE:
5035 {
5036 VALUE class_path = rb_class_path_cached(obj);
5037 if (!NIL_P(class_path)) {
5038 APPEND_F("%s", RSTRING_PTR(class_path));
5039 }
5040 else {
5041 APPEND_S("(anon)");
5042 }
5043 break;
5044 }
5045 case T_ICLASS:
5046 {
5047 VALUE class_path = rb_class_path_cached(RBASIC_CLASS(obj));
5048 if (!NIL_P(class_path)) {
5049 APPEND_F("src:%s", RSTRING_PTR(class_path));
5050 }
5051 break;
5052 }
5053 case T_OBJECT:
5054 {
5055 if (FL_TEST_RAW(obj, ROBJECT_HEAP)) {
5056 if (rb_shape_obj_too_complex_p(obj)) {
5057 size_t hash_len = rb_st_table_size(ROBJECT_FIELDS_HASH(obj));
5058 APPEND_F("(too_complex) len:%zu", hash_len);
5059 }
5060 else {
5061 APPEND_F("(embed) len:%d capa:%d", RSHAPE_LEN(RBASIC_SHAPE_ID(obj)), ROBJECT_FIELDS_CAPACITY(obj));
5062 }
5063 }
5064 else {
5065 APPEND_F("len:%d capa:%d ptr:%p", RSHAPE_LEN(RBASIC_SHAPE_ID(obj)), ROBJECT_FIELDS_CAPACITY(obj), (void *)ROBJECT_FIELDS(obj));
5066 }
5067 }
5068 break;
5069 case T_DATA: {
5070 const struct rb_block *block;
5071 const rb_iseq_t *iseq;
5072 if (rb_obj_is_proc(obj) &&
5073 (block = vm_proc_block(obj)) != NULL &&
5074 (vm_block_type(block) == block_type_iseq) &&
5075 (iseq = vm_block_iseq(block)) != NULL) {
5076 rb_raw_iseq_info(BUFF_ARGS, iseq);
5077 }
5078 else if (rb_ractor_p(obj)) {
5079 rb_ractor_t *r = (void *)DATA_PTR(obj);
5080 if (r) {
5081 APPEND_F("r:%d", r->pub.id);
5082 }
5083 }
5084 break;
5085 }
5086 case T_IMEMO: {
5087 APPEND_F("<%s> ", rb_imemo_name(imemo_type(obj)));
5088
5089 switch (imemo_type(obj)) {
5090 case imemo_ment:
5091 {
5092 const rb_method_entry_t *me = (const rb_method_entry_t *)obj;
5093
5094 APPEND_F(":%s (%s%s%s%s) type:%s aliased:%d owner:%p defined_class:%p",
5095 rb_id2name(me->called_id),
5096 METHOD_ENTRY_VISI(me) == METHOD_VISI_PUBLIC ? "pub" :
5097 METHOD_ENTRY_VISI(me) == METHOD_VISI_PRIVATE ? "pri" : "pro",
5098 METHOD_ENTRY_COMPLEMENTED(me) ? ",cmp" : "",
5099 METHOD_ENTRY_CACHED(me) ? ",cc" : "",
5100 METHOD_ENTRY_INVALIDATED(me) ? ",inv" : "",
5101 me->def ? rb_method_type_name(me->def->type) : "NULL",
5102 me->def ? me->def->aliased : -1,
5103 (void *)me->owner, // obj_info(me->owner),
5104 (void *)me->defined_class); //obj_info(me->defined_class)));
5105
5106 if (me->def) {
5107 switch (me->def->type) {
5108 case VM_METHOD_TYPE_ISEQ:
5109 APPEND_S(" (iseq:");
5110 rb_raw_obj_info(BUFF_ARGS, (VALUE)me->def->body.iseq.iseqptr);
5111 APPEND_S(")");
5112 break;
5113 default:
5114 break;
5115 }
5116 }
5117
5118 break;
5119 }
5120 case imemo_iseq: {
5121 const rb_iseq_t *iseq = (const rb_iseq_t *)obj;
5122 rb_raw_iseq_info(BUFF_ARGS, iseq);
5123 break;
5124 }
5125 case imemo_callinfo:
5126 {
5127 const struct rb_callinfo *ci = (const struct rb_callinfo *)obj;
5128 APPEND_F("(mid:%s, flag:%x argc:%d, kwarg:%s)",
5129 rb_id2name(vm_ci_mid(ci)),
5130 vm_ci_flag(ci),
5131 vm_ci_argc(ci),
5132 vm_ci_kwarg(ci) ? "available" : "NULL");
5133 break;
5134 }
5135 case imemo_callcache:
5136 {
5137 const struct rb_callcache *cc = (const struct rb_callcache *)obj;
5138 VALUE class_path = vm_cc_valid(cc) ? rb_class_path_cached(cc->klass) : Qnil;
5139 const rb_callable_method_entry_t *cme = vm_cc_cme(cc);
5140
5141 APPEND_F("(klass:%s cme:%s%s (%p) call:%p",
5142 NIL_P(class_path) ? (vm_cc_valid(cc) ? "??" : "<NULL>") : RSTRING_PTR(class_path),
5143 cme ? rb_id2name(cme->called_id) : "<NULL>",
5144 cme ? (METHOD_ENTRY_INVALIDATED(cme) ? " [inv]" : "") : "",
5145 (void *)cme,
5146 (void *)(uintptr_t)vm_cc_call(cc));
5147 break;
5148 }
5149 default:
5150 break;
5151 }
5152 }
5153 default:
5154 break;
5155 }
5156 }
5157 end:
5158
5159 return pos;
5160}
5161
5162#undef C
5163
5164#ifdef RUBY_ASAN_ENABLED
5165void
5166rb_asan_poison_object(VALUE obj)
5167{
5168 MAYBE_UNUSED(struct RVALUE *) ptr = (void *)obj;
5169 asan_poison_memory_region(ptr, rb_gc_obj_slot_size(obj));
5170}
5171
5172void
5173rb_asan_unpoison_object(VALUE obj, bool newobj_p)
5174{
5175 MAYBE_UNUSED(struct RVALUE *) ptr = (void *)obj;
5176 asan_unpoison_memory_region(ptr, rb_gc_obj_slot_size(obj), newobj_p);
5177}
5178
5179void *
5180rb_asan_poisoned_object_p(VALUE obj)
5181{
5182 MAYBE_UNUSED(struct RVALUE *) ptr = (void *)obj;
5183 return __asan_region_is_poisoned(ptr, rb_gc_obj_slot_size(obj));
5184}
5185#endif
5186
5187static void
5188raw_obj_info(char *const buff, const size_t buff_size, VALUE obj)
5189{
5190 size_t pos = rb_raw_obj_info_common(buff, buff_size, obj);
5191 pos = rb_raw_obj_info_buitin_type(buff, buff_size, obj, pos);
5192 if (pos >= buff_size) {} // truncated
5193}
5194
5195const char *
5196rb_raw_obj_info(char *const buff, const size_t buff_size, VALUE obj)
5197{
5198 void *objspace = rb_gc_get_objspace();
5199
5200 if (SPECIAL_CONST_P(obj)) {
5201 raw_obj_info(buff, buff_size, obj);
5202 }
5203 else if (!rb_gc_impl_pointer_to_heap_p(objspace, (const void *)obj)) {
5204 snprintf(buff, buff_size, "out-of-heap:%p", (void *)obj);
5205 }
5206#if 0 // maybe no need to check it?
5207 else if (0 && rb_gc_impl_garbage_object_p(objspace, obj)) {
5208 snprintf(buff, buff_size, "garbage:%p", (void *)obj);
5209 }
5210#endif
5211 else {
5212 asan_unpoisoning_object(obj) {
5213 raw_obj_info(buff, buff_size, obj);
5214 }
5215 }
5216 return buff;
5217}
5218
5219#undef APPEND_S
5220#undef APPEND_F
5221#undef BUFF_ARGS
5222
5223/* Increments *var atomically and resets *var to 0 when maxval is
5224 * reached. Returns the wraparound old *var value (0...maxval). */
5225static rb_atomic_t
5226atomic_inc_wraparound(rb_atomic_t *var, const rb_atomic_t maxval)
5227{
5228 rb_atomic_t oldval = RUBY_ATOMIC_FETCH_ADD(*var, 1);
5229 if (RB_UNLIKELY(oldval >= maxval - 1)) { // wraparound *var
5230 const rb_atomic_t newval = oldval + 1;
5231 RUBY_ATOMIC_CAS(*var, newval, newval % maxval);
5232 oldval %= maxval;
5233 }
5234 return oldval;
5235}
5236
5237static const char *
5238obj_info(VALUE obj)
5239{
5240 if (RGENGC_OBJ_INFO) {
5241 static struct {
5242 rb_atomic_t index;
5243 char buffers[10][0x100];
5244 } info = {0};
5245
5246 rb_atomic_t index = atomic_inc_wraparound(&info.index, numberof(info.buffers));
5247 char *const buff = info.buffers[index];
5248 return rb_raw_obj_info(buff, sizeof(info.buffers[0]), obj);
5249 }
5250 return obj_type_name(obj);
5251}
5252
5253/*
5254 ------------------------ Extended allocator ------------------------
5255*/
5256
5258 VALUE exc;
5259 const char *fmt;
5260 va_list *ap;
5261};
5262
5263static void *
5264gc_vraise(void *ptr)
5265{
5266 struct gc_raise_tag *argv = ptr;
5267 rb_vraise(argv->exc, argv->fmt, *argv->ap);
5268 UNREACHABLE_RETURN(NULL);
5269}
5270
5271static void
5272gc_raise(VALUE exc, const char *fmt, ...)
5273{
5274 va_list ap;
5275 va_start(ap, fmt);
5276 struct gc_raise_tag argv = {
5277 exc, fmt, &ap,
5278 };
5279
5280 if (ruby_native_thread_p()) {
5281 rb_thread_call_with_gvl(gc_vraise, &argv);
5283 }
5284 else {
5285 /* Not in a ruby thread */
5286 fprintf(stderr, "%s", "[FATAL] ");
5287 vfprintf(stderr, fmt, ap);
5288 }
5289
5290 va_end(ap);
5291 abort();
5292}
5293
5294NORETURN(static void negative_size_allocation_error(const char *));
5295static void
5296negative_size_allocation_error(const char *msg)
5297{
5298 gc_raise(rb_eNoMemError, "%s", msg);
5299}
5300
5301static void *
5302ruby_memerror_body(void *dummy)
5303{
5304 rb_memerror();
5305 return 0;
5306}
5307
5308NORETURN(static void ruby_memerror(void));
5310static void
5311ruby_memerror(void)
5312{
5313 if (ruby_thread_has_gvl_p()) {
5314 rb_memerror();
5315 }
5316 else {
5317 if (ruby_native_thread_p()) {
5318 rb_thread_call_with_gvl(ruby_memerror_body, 0);
5319 }
5320 else {
5321 /* no ruby thread */
5322 fprintf(stderr, "[FATAL] failed to allocate memory\n");
5323 }
5324 }
5325
5326 /* We have discussions whether we should die here; */
5327 /* We might rethink about it later. */
5328 exit(EXIT_FAILURE);
5329}
5330
5331void
5332rb_memerror(void)
5333{
5334 /* the `GET_VM()->special_exceptions` below assumes that
5335 * the VM is reachable from the current thread. We should
5336 * definitely make sure of that. */
5337 RUBY_ASSERT_ALWAYS(ruby_thread_has_gvl_p());
5338
5339 rb_execution_context_t *ec = GET_EC();
5340 VALUE exc = GET_VM()->special_exceptions[ruby_error_nomemory];
5341
5342 if (!exc ||
5343 rb_ec_raised_p(ec, RAISED_NOMEMORY) ||
5344 rb_ec_vm_lock_rec(ec) != ec->tag->lock_rec) {
5345 fprintf(stderr, "[FATAL] failed to allocate memory\n");
5346 exit(EXIT_FAILURE);
5347 }
5348 if (rb_ec_raised_p(ec, RAISED_NOMEMORY)) {
5349 rb_ec_raised_clear(ec);
5350 }
5351 else {
5352 rb_ec_raised_set(ec, RAISED_NOMEMORY);
5353 exc = ruby_vm_special_exception_copy(exc);
5354 }
5355 ec->errinfo = exc;
5356 EC_JUMP_TAG(ec, TAG_RAISE);
5357}
5358
5359bool
5360rb_memerror_reentered(void)
5361{
5362 rb_execution_context_t *ec = GET_EC();
5363 return (ec && rb_ec_raised_p(ec, RAISED_NOMEMORY));
5364}
5365
5366static void *
5367handle_malloc_failure(void *ptr)
5368{
5369 if (LIKELY(ptr)) {
5370 return ptr;
5371 }
5372 else {
5373 ruby_memerror();
5374 UNREACHABLE_RETURN(ptr);
5375 }
5376}
5377
5378static void *ruby_xmalloc_body(size_t size);
5379
5380void *
5381ruby_xmalloc(size_t size)
5382{
5383 return handle_malloc_failure(ruby_xmalloc_body(size));
5384}
5385
5386static bool
5387malloc_gc_allowed(void)
5388{
5389 rb_ractor_t *r = rb_current_ractor_raw(false);
5390
5391 return r == NULL || !r->malloc_gc_disabled;
5392}
5393
5394static void *
5395ruby_xmalloc_body(size_t size)
5396{
5397 if ((ssize_t)size < 0) {
5398 negative_size_allocation_error("too large allocation size");
5399 }
5400
5401 return rb_gc_impl_malloc(rb_gc_get_objspace(), size, malloc_gc_allowed());
5402}
5403
5404void
5405ruby_malloc_size_overflow(size_t count, size_t elsize)
5406{
5407 rb_raise(rb_eArgError,
5408 "malloc: possible integer overflow (%"PRIuSIZE"*%"PRIuSIZE")",
5409 count, elsize);
5410}
5411
5412void
5413ruby_malloc_add_size_overflow(size_t x, size_t y)
5414{
5415 rb_raise(rb_eArgError,
5416 "malloc: possible integer overflow (%"PRIuSIZE"+%"PRIuSIZE")",
5417 x, y);
5418}
5419
5420static void *ruby_xmalloc2_body(size_t n, size_t size);
5421
5422void *
5423ruby_xmalloc2(size_t n, size_t size)
5424{
5425 return handle_malloc_failure(ruby_xmalloc2_body(n, size));
5426}
5427
5428static void *
5429ruby_xmalloc2_body(size_t n, size_t size)
5430{
5431 return rb_gc_impl_malloc(rb_gc_get_objspace(), xmalloc2_size(n, size), malloc_gc_allowed());
5432}
5433
5434static void *ruby_xcalloc_body(size_t n, size_t size);
5435
5436void *
5437ruby_xcalloc(size_t n, size_t size)
5438{
5439 return handle_malloc_failure(ruby_xcalloc_body(n, size));
5440}
5441
5442static void *
5443ruby_xcalloc_body(size_t n, size_t size)
5444{
5445 return rb_gc_impl_calloc(rb_gc_get_objspace(), xmalloc2_size(n, size), malloc_gc_allowed());
5446}
5447
5448static void *ruby_xrealloc_sized_body(void *ptr, size_t new_size, size_t old_size);
5449
5450#ifdef ruby_xrealloc_sized
5451#undef ruby_xrealloc_sized
5452#endif
5453void *
5454ruby_xrealloc_sized(void *ptr, size_t new_size, size_t old_size)
5455{
5456 return handle_malloc_failure(ruby_xrealloc_sized_body(ptr, new_size, old_size));
5457}
5458
5459static void *
5460ruby_xrealloc_sized_body(void *ptr, size_t new_size, size_t old_size)
5461{
5462 if ((ssize_t)new_size < 0) {
5463 negative_size_allocation_error("too large allocation size");
5464 }
5465
5466 return rb_gc_impl_realloc(rb_gc_get_objspace(), ptr, new_size, old_size, malloc_gc_allowed());
5467}
5468
5469void *
5470ruby_xrealloc(void *ptr, size_t new_size)
5471{
5472 return ruby_xrealloc_sized(ptr, new_size, 0);
5473}
5474
5475static void *ruby_xrealloc2_sized_body(void *ptr, size_t n, size_t size, size_t old_n);
5476
5477#ifdef ruby_xrealloc2_sized
5478#undef ruby_xrealloc2_sized
5479#endif
5480void *
5481ruby_xrealloc2_sized(void *ptr, size_t n, size_t size, size_t old_n)
5482{
5483 return handle_malloc_failure(ruby_xrealloc2_sized_body(ptr, n, size, old_n));
5484}
5485
5486static void *
5487ruby_xrealloc2_sized_body(void *ptr, size_t n, size_t size, size_t old_n)
5488{
5489 size_t len = xmalloc2_size(n, size);
5490 return rb_gc_impl_realloc(rb_gc_get_objspace(), ptr, len, old_n * size, malloc_gc_allowed());
5491}
5492
5493void *
5494ruby_xrealloc2(void *ptr, size_t n, size_t size)
5495{
5496 return ruby_xrealloc2_sized(ptr, n, size, 0);
5497}
5498
5499#ifdef ruby_xfree_sized
5500#undef ruby_xfree_sized
5501#endif
5502void
5503ruby_xfree_sized(void *x, size_t size)
5504{
5505 if (LIKELY(x)) {
5506 /* It's possible for a C extension's pthread destructor function set by pthread_key_create
5507 * to be called after ruby_vm_destruct and attempt to free memory. Fall back to mimfree in
5508 * that case. */
5509 if (LIKELY(GET_VM())) {
5510 rb_gc_impl_free(rb_gc_get_objspace(), x, size);
5511 }
5512 else {
5513 ruby_mimfree(x);
5514 }
5515 }
5516}
5517
5518void
5519ruby_xfree(void *x)
5520{
5521 ruby_xfree_sized(x, 0);
5522}
5523
5524void *
5525rb_xmalloc_mul_add(size_t x, size_t y, size_t z) /* x * y + z */
5526{
5527 size_t w = size_mul_add_or_raise(x, y, z, rb_eArgError);
5528 return ruby_xmalloc(w);
5529}
5530
5531void *
5532rb_xcalloc_mul_add(size_t x, size_t y, size_t z) /* x * y + z */
5533{
5534 size_t w = size_mul_add_or_raise(x, y, z, rb_eArgError);
5535 return ruby_xcalloc(w, 1);
5536}
5537
5538void *
5539rb_xrealloc_mul_add(const void *p, size_t x, size_t y, size_t z) /* x * y + z */
5540{
5541 size_t w = size_mul_add_or_raise(x, y, z, rb_eArgError);
5542 return ruby_xrealloc((void *)p, w);
5543}
5544
5545void *
5546rb_xmalloc_mul_add_mul(size_t x, size_t y, size_t z, size_t w) /* x * y + z * w */
5547{
5548 size_t u = size_mul_add_mul_or_raise(x, y, z, w, rb_eArgError);
5549 return ruby_xmalloc(u);
5550}
5551
5552void *
5553rb_xcalloc_mul_add_mul(size_t x, size_t y, size_t z, size_t w) /* x * y + z * w */
5554{
5555 size_t u = size_mul_add_mul_or_raise(x, y, z, w, rb_eArgError);
5556 return ruby_xcalloc(u, 1);
5557}
5558
5559/* Mimic ruby_xmalloc, but need not rb_objspace.
5560 * should return pointer suitable for ruby_xfree
5561 */
5562void *
5563ruby_mimmalloc(size_t size)
5564{
5565 void *mem;
5566#if CALC_EXACT_MALLOC_SIZE
5567 size += sizeof(struct malloc_obj_info);
5568#endif
5569 mem = malloc(size);
5570#if CALC_EXACT_MALLOC_SIZE
5571 if (!mem) {
5572 return NULL;
5573 }
5574 else
5575 /* set 0 for consistency of allocated_size/allocations */
5576 {
5577 struct malloc_obj_info *info = mem;
5578 info->size = 0;
5579 mem = info + 1;
5580 }
5581#endif
5582 return mem;
5583}
5584
5585void *
5586ruby_mimcalloc(size_t num, size_t size)
5587{
5588 void *mem;
5589#if CALC_EXACT_MALLOC_SIZE
5590 struct rbimpl_size_overflow_tag t = rbimpl_size_mul_overflow(num, size);
5591 if (UNLIKELY(t.overflowed)) {
5592 return NULL;
5593 }
5594 size = t.result + sizeof(struct malloc_obj_info);
5595 mem = calloc1(size);
5596 if (!mem) {
5597 return NULL;
5598 }
5599 else
5600 /* set 0 for consistency of allocated_size/allocations */
5601 {
5602 struct malloc_obj_info *info = mem;
5603 info->size = 0;
5604 mem = info + 1;
5605 }
5606#else
5607 mem = calloc(num, size);
5608#endif
5609 return mem;
5610}
5611
5612void
5613ruby_mimfree(void *ptr)
5614{
5615#if CALC_EXACT_MALLOC_SIZE
5616 struct malloc_obj_info *info = (struct malloc_obj_info *)ptr - 1;
5617 ptr = info;
5618#endif
5619 free(ptr);
5620}
5621
5622void
5623rb_gc_adjust_memory_usage(ssize_t diff)
5624{
5625 unless_objspace(objspace) { return; }
5626
5627 rb_gc_impl_adjust_memory_usage(objspace, diff);
5628}
5629
5630const char *
5631rb_obj_info(VALUE obj)
5632{
5633 return obj_info(obj);
5634}
5635
5636void
5637rb_obj_info_dump(VALUE obj)
5638{
5639 char buff[0x100];
5640 fprintf(stderr, "rb_obj_info_dump: %s\n", rb_raw_obj_info(buff, 0x100, obj));
5641}
5642
5643void
5644rb_obj_info_dump_loc(VALUE obj, const char *file, int line, const char *func)
5645{
5646 char buff[0x100];
5647 fprintf(stderr, "<OBJ_INFO:%s@%s:%d> %s\n", func, file, line, rb_raw_obj_info(buff, 0x100, obj));
5648}
5649
5650void
5651rb_gc_before_fork(void)
5652{
5653 rb_gc_impl_before_fork(rb_gc_get_objspace());
5654}
5655
5656void
5657rb_gc_after_fork(rb_pid_t pid)
5658{
5659 rb_gc_impl_after_fork(rb_gc_get_objspace(), pid);
5660}
5661
5662bool
5663rb_gc_obj_shareable_p(VALUE obj)
5664{
5665 return RB_OBJ_SHAREABLE_P(obj);
5666}
5667
5668void
5669rb_gc_rp(VALUE obj)
5670{
5671 rp(obj);
5672}
5673
5675 VALUE parent;
5676 long err_count;
5677};
5678
5679static void
5680check_shareable_i(const VALUE child, void *ptr)
5681{
5682 struct check_shareable_data *data = (struct check_shareable_data *)ptr;
5683
5684 if (!rb_gc_obj_shareable_p(child)) {
5685 fprintf(stderr, "(a) ");
5686 rb_gc_rp(data->parent);
5687 fprintf(stderr, "(b) ");
5688 rb_gc_rp(child);
5689 fprintf(stderr, "check_shareable_i: shareable (a) -> unshareable (b)\n");
5690
5691 data->err_count++;
5692 rb_bug("!! violate shareable constraint !!");
5693 }
5694}
5695
5696static bool gc_checking_shareable = false;
5697
5698static void
5699gc_verify_shareable(void *objspace, VALUE obj, void *data)
5700{
5701 // while gc_checking_shareable is true,
5702 // other Ractors should not run the GC, until the flag is not local.
5703 // TODO: remove VM locking if the flag is Ractor local
5704
5705 unsigned int lev = RB_GC_VM_LOCK();
5706 {
5707 gc_checking_shareable = true;
5708 rb_objspace_reachable_objects_from(obj, check_shareable_i, (void *)data);
5709 gc_checking_shareable = false;
5710 }
5711 RB_GC_VM_UNLOCK(lev);
5712}
5713
5714// TODO: only one level (non-recursive)
5715void
5716rb_gc_verify_shareable(VALUE obj)
5717{
5718 rb_objspace_t *objspace = rb_gc_get_objspace();
5719 struct check_shareable_data data = {
5720 .parent = obj,
5721 .err_count = 0,
5722 };
5723 gc_verify_shareable(objspace, obj, &data);
5724
5725 if (data.err_count > 0) {
5726 rb_bug("rb_gc_verify_shareable");
5727 }
5728}
5729
5730bool
5731rb_gc_checking_shareable(void)
5732{
5733 return gc_checking_shareable;
5734}
5735
5736/*
5737 * Document-module: ObjectSpace
5738 *
5739 * The ObjectSpace module contains a number of routines
5740 * that interact with the garbage collection facility and allow you to
5741 * traverse all living objects with an iterator.
5742 *
5743 * ObjectSpace also provides support for object finalizers, procs that will be
5744 * called after a specific object was destroyed by garbage collection. See
5745 * the documentation for +ObjectSpace.define_finalizer+ for important
5746 * information on how to use this method correctly.
5747 *
5748 * a = "A"
5749 * b = "B"
5750 *
5751 * ObjectSpace.define_finalizer(a, proc {|id| puts "Finalizer one on #{id}" })
5752 * ObjectSpace.define_finalizer(b, proc {|id| puts "Finalizer two on #{id}" })
5753 *
5754 * a = nil
5755 * b = nil
5756 *
5757 * _produces:_
5758 *
5759 * Finalizer two on 537763470
5760 * Finalizer one on 537763480
5761 */
5762
5763/* Document-class: GC::Profiler
5764 *
5765 * The GC profiler provides access to information on GC runs including time,
5766 * length and object space size.
5767 *
5768 * Example:
5769 *
5770 * GC::Profiler.enable
5771 *
5772 * require 'rdoc/rdoc'
5773 *
5774 * GC::Profiler.report
5775 *
5776 * GC::Profiler.disable
5777 *
5778 * See also GC.count, GC.malloc_allocated_size and GC.malloc_allocations
5779 */
5780
5781#include "gc.rbinc"
5782
5783void
5784Init_GC(void)
5785{
5786#undef rb_intern
5787 rb_gc_register_address(&id2ref_value);
5788
5789 malloc_offset = gc_compute_malloc_offset();
5790
5791 rb_mGC = rb_define_module("GC");
5792
5793 VALUE rb_mObjSpace = rb_define_module("ObjectSpace");
5794
5795 rb_define_module_function(rb_mObjSpace, "each_object", os_each_obj, -1);
5796
5797 rb_define_module_function(rb_mObjSpace, "define_finalizer", define_final, -1);
5798 rb_define_module_function(rb_mObjSpace, "undefine_finalizer", undefine_final, 1);
5799
5800 rb_define_module_function(rb_mObjSpace, "_id2ref", os_id2ref, 1);
5801
5802 rb_vm_register_special_exception(ruby_error_nomemory, rb_eNoMemError, "failed to allocate memory");
5803
5804 rb_define_method(rb_cBasicObject, "__id__", rb_obj_id, 0);
5805 rb_define_method(rb_mKernel, "object_id", rb_obj_id, 0);
5806
5807 rb_define_module_function(rb_mObjSpace, "count_objects", count_objects, -1);
5808
5809 rb_gc_impl_init();
5810}
5811
5812// Set a name for the anonymous virtual memory area. `addr` is the starting
5813// address of the area and `size` is its length in bytes. `name` is a
5814// NUL-terminated human-readable string.
5815//
5816// This function is usually called after calling `mmap()`. The human-readable
5817// annotation helps developers identify the call site of `mmap()` that created
5818// the memory mapping.
5819//
5820// This function currently only works on Linux 5.17 or higher. After calling
5821// this function, we can see annotations in the form of "[anon:...]" in
5822// `/proc/self/maps`, where `...` is the content of `name`. This function has
5823// no effect when called on other platforms.
5824void
5825ruby_annotate_mmap(const void *addr, unsigned long size, const char *name)
5826{
5827#if defined(HAVE_SYS_PRCTL_H) && defined(PR_SET_VMA) && defined(PR_SET_VMA_ANON_NAME)
5828 // The name length cannot exceed 80 (including the '\0').
5829 RUBY_ASSERT(strlen(name) < 80);
5830 prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME, (unsigned long)addr, size, name);
5831 // We ignore errors in prctl. prctl may set errno to EINVAL for several
5832 // reasons.
5833 // 1. The attr (PR_SET_VMA_ANON_NAME) is not a valid attribute.
5834 // 2. addr is an invalid address.
5835 // 3. The string pointed by name is too long.
5836 // The first error indicates PR_SET_VMA_ANON_NAME is not available, and may
5837 // happen if we run the compiled binary on an old kernel. In theory, all
5838 // other errors should result in a failure. But since EINVAL cannot tell
5839 // the first error from others, and this function is mainly used for
5840 // debugging, we silently ignore the error.
5841 errno = 0;
5842#endif
5843}
#define RUBY_ASSERT_ALWAYS(expr,...)
A variant of RUBY_ASSERT that does not interface with RUBY_DEBUG.
Definition assert.h:199
#define RUBY_ASSERT(...)
Asserts that the given expression is truthy if and only if RUBY_DEBUG is truthy.
Definition assert.h:219
#define RUBY_ATOMIC_VALUE_CAS(var, oldval, newval)
Identical to RUBY_ATOMIC_CAS, except it expects its arguments are VALUE.
Definition atomic.h:406
#define RUBY_ATOMIC_SIZE_FETCH_ADD(var, val)
Identical to RUBY_ATOMIC_FETCH_ADD, except it expects its arguments to be size_t.
Definition atomic.h:235
#define RUBY_ATOMIC_CAS(var, oldval, newval)
Atomic compare-and-swap.
Definition atomic.h:165
std::atomic< unsigned > rb_atomic_t
Type that is eligible for atomic operations.
Definition atomic.h:69
#define RUBY_ATOMIC_FETCH_ADD(var, val)
Atomically replaces the value pointed by var with the result of addition of val to the old value of v...
Definition atomic.h:118
#define rb_define_method(klass, mid, func, arity)
Defines klass#mid.
#define rb_define_module_function(klass, mid, func, arity)
Defines klass#mid and makes it a module function.
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 bool RB_OBJ_FROZEN(VALUE obj)
Checks if an object is frozen.
Definition fl_type.h:711
@ RUBY_FL_WB_PROTECTED
Definition fl_type.h:186
VALUE rb_define_module(const char *name)
Defines a top-level module.
Definition class.c:1639
int rb_scan_args(int argc, const VALUE *argv, const char *fmt,...)
Retrieves argument from argc and argv to given VALUE references according to the format string.
Definition class.c:3183
#define T_COMPLEX
Old name of RUBY_T_COMPLEX.
Definition value_type.h:59
#define TYPE(_)
Old name of rb_type.
Definition value_type.h:108
#define FL_SINGLETON
Old name of RUBY_FL_SINGLETON.
Definition fl_type.h:58
#define T_FILE
Old name of RUBY_T_FILE.
Definition value_type.h:62
#define FL_UNSET_RAW
Old name of RB_FL_UNSET_RAW.
Definition fl_type.h:130
#define ALLOC
Old name of RB_ALLOC.
Definition memory.h:400
#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 T_NIL
Old name of RUBY_T_NIL.
Definition value_type.h:72
#define UNREACHABLE
Old name of RBIMPL_UNREACHABLE.
Definition assume.h:28
#define T_FLOAT
Old name of RUBY_T_FLOAT.
Definition value_type.h:64
#define T_IMEMO
Old name of RUBY_T_IMEMO.
Definition value_type.h:67
#define ID2SYM
Old name of RB_ID2SYM.
Definition symbol.h:44
#define T_BIGNUM
Old name of RUBY_T_BIGNUM.
Definition value_type.h:57
#define SPECIAL_CONST_P
Old name of RB_SPECIAL_CONST_P.
#define T_STRUCT
Old name of RUBY_T_STRUCT.
Definition value_type.h:79
#define OBJ_FREEZE
Old name of RB_OBJ_FREEZE.
Definition fl_type.h:131
#define T_FIXNUM
Old name of RUBY_T_FIXNUM.
Definition value_type.h:63
#define UNREACHABLE_RETURN
Old name of RBIMPL_UNREACHABLE_RETURN.
Definition assume.h:29
#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 FIXNUM_FLAG
Old name of RUBY_FIXNUM_FLAG.
#define LL2NUM
Old name of RB_LL2NUM.
Definition long_long.h:30
#define CLASS_OF
Old name of rb_class_of.
Definition globals.h:205
#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 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 ASSUME
Old name of RBIMPL_ASSUME.
Definition assume.h:27
#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 FL_ABLE
Old name of RB_FL_ABLE.
Definition fl_type.h:118
#define FL_TEST_RAW
Old name of RB_FL_TEST_RAW.
Definition fl_type.h:128
#define rb_ary_new3
Old name of rb_ary_new_from_args.
Definition array.h:658
#define LONG2NUM
Old name of RB_LONG2NUM.
Definition long.h:50
#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 FLONUM_P
Old name of RB_FLONUM_P.
#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 NUM2ULL
Old name of RB_NUM2ULL.
Definition long_long.h:35
#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 T_MATCH
Old name of RUBY_T_MATCH.
Definition value_type.h:69
#define T_CLASS
Old name of RUBY_T_CLASS.
Definition value_type.h:58
#define BUILTIN_TYPE
Old name of RB_BUILTIN_TYPE.
Definition value_type.h:85
#define T_MOVED
Old name of RUBY_T_MOVED.
Definition value_type.h:71
#define FL_TEST
Old name of RB_FL_TEST.
Definition fl_type.h:127
#define xcalloc
Old name of ruby_xcalloc.
Definition xmalloc.h:55
#define FL_UNSET
Old name of RB_FL_UNSET.
Definition fl_type.h:129
#define FIXNUM_P
Old name of RB_FIXNUM_P.
#define NUM2SIZET
Old name of RB_NUM2SIZE.
Definition size_t.h:61
#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
size_t ruby_stack_length(VALUE **p)
Queries what Ruby thinks is the machine stack.
Definition gc.c:2793
int ruby_stack_check(void)
Checks for stack overflow.
Definition gc.c:2833
void rb_category_warn(rb_warning_category_t category, const char *fmt,...)
Identical to rb_category_warning(), except it reports unless $VERBOSE is nil.
Definition error.c:477
VALUE rb_eNoMemError
NoMemoryError exception.
Definition error.c:1438
VALUE rb_eRangeError
RangeError exception.
Definition error.c:1431
#define ruby_verbose
This variable controls whether the interpreter is in debug mode.
Definition error.h:476
VALUE rb_eTypeError
TypeError exception.
Definition error.c:1427
void rb_warn(const char *fmt,...)
Identical to rb_warning(), except it reports unless $VERBOSE is nil.
Definition error.c:467
@ RB_WARN_CATEGORY_DEPRECATED
Warning is for deprecated features.
Definition error.h:48
VALUE rb_mKernel
Kernel module.
Definition object.c:60
VALUE rb_cObject
Object class.
Definition object.c:61
VALUE rb_mGC
GC module.
Definition gc.c:429
VALUE rb_obj_class(VALUE obj)
Queries the class of an object.
Definition object.c:235
VALUE rb_cBasicObject
BasicObject class.
Definition object.c:59
VALUE rb_class_real(VALUE klass)
Finds a "real" class.
Definition object.c:226
VALUE rb_obj_is_kind_of(VALUE obj, VALUE klass)
Queries if the given object is an instance (of possibly descendants) of the given class.
Definition object.c:894
VALUE rb_to_int(VALUE val)
Identical to rb_check_to_int(), except it raises in case of conversion mismatch.
Definition object.c:3334
#define RB_POSFIXABLE(_)
Checks if the passed value is in range of fixnum, assuming it is a positive number.
Definition fixnum.h:43
int rb_enc_str_coderange(VALUE str)
Scans the passed string to collect its code range.
Definition string.c:945
VALUE rb_funcall(VALUE recv, ID mid, int n,...)
Calls a method.
Definition vm_eval.c:1120
#define RGENGC_WB_PROTECTED_OBJECT
This is a compile-time flag to enable/disable write barrier for struct RObject.
Definition gc.h:490
Defines RBIMPL_HAS_BUILTIN.
void rb_ary_free(VALUE ary)
Destroys the given array for no reason.
#define RETURN_ENUMERATOR(obj, argc, argv)
Identical to RETURN_SIZED_ENUMERATOR(), except its size is unknown.
Definition enumerator.h:242
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_block_proc(void)
Constructs a Proc object from implicitly passed components.
Definition proc.c:988
VALUE rb_obj_is_proc(VALUE recv)
Queries if the given object is a proc.
Definition proc.c:122
void rb_str_free(VALUE str)
Destroys the given string for no reason.
Definition string.c:1750
size_t rb_str_capacity(VALUE str)
Queries the capacity of the given string.
Definition string.c:999
VALUE rb_class_path_cached(VALUE mod)
Just another name of rb_mod_name.
Definition variable.c:389
void rb_free_generic_ivar(VALUE obj)
Frees the list of instance variables.
Definition variable.c:1318
void rb_undef_alloc_func(VALUE klass)
Deletes the allocator function of a class.
Definition vm_method.c:1731
VALUE rb_check_funcall(VALUE recv, ID mid, int argc, const VALUE *argv)
Identical to rb_funcallv(), except it returns RUBY_Qundef instead of raising rb_eNoMethodError.
Definition vm_eval.c:689
rb_alloc_func_t rb_get_alloc_func(VALUE klass)
Queries the allocator function of a class.
Definition vm_method.c:1740
int rb_obj_respond_to(VALUE obj, ID mid, int private_p)
Identical to rb_respond_to(), except it additionally takes the visibility parameter.
Definition vm_method.c:3458
VALUE rb_sym2str(VALUE symbol)
Obtain a frozen string representation of a symbol (not including the leading colon).
Definition symbol.c:1024
int rb_io_fptr_finalize(rb_io_t *fptr)
Destroys the given IO.
Definition io.c:5700
int len
Length of the buffer.
Definition io.h:8
static bool rb_ractor_shareable_p(VALUE obj)
Queries if multiple Ractors can share the passed object or not.
Definition ractor.h:249
#define RB_OBJ_SHAREABLE_P(obj)
Queries if the passed object has previously classified as shareable or not.
Definition ractor.h:235
void * rb_thread_call_with_gvl(void *(*func)(void *), void *data1)
(Re-)acquires the GVL.
Definition thread.c:2063
VALUE rb_yield(VALUE val)
Yields the block.
Definition vm_eval.c:1375
#define RBIMPL_ATTR_MAYBE_UNUSED()
Wraps (or simulates) [[maybe_unused]]
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
Definition memory.h:167
VALUE type(ANYARGS)
ANYARGS-ed function type.
#define RARRAY_LEN
Just another name of rb_array_len.
Definition rarray.h:51
#define RARRAY(obj)
Convenient casting macro.
Definition rarray.h:44
#define RARRAY_CONST_PTR
Just another name of rb_array_const_ptr.
Definition rarray.h:52
static VALUE RBASIC_CLASS(VALUE obj)
Queries the class of an object.
Definition rbasic.h:166
#define RBASIC(obj)
Convenient casting macro.
Definition rbasic.h:40
#define RCLASS(obj)
Convenient casting macro.
Definition rclass.h:38
VALUE rb_data_object_wrap(VALUE klass, void *datap, RUBY_DATA_FUNC dmark, RUBY_DATA_FUNC dfree)
This is the primitive way to wrap an existing C struct into RData.
Definition gc.c:1128
#define DATA_PTR(obj)
Convenient getter macro.
Definition rdata.h:67
VALUE rb_data_object_zalloc(VALUE klass, size_t size, RUBY_DATA_FUNC dmark, RUBY_DATA_FUNC dfree)
Identical to rb_data_object_wrap(), except it allocates a new data region internally instead of takin...
Definition gc.c:1145
#define RDATA(obj)
Convenient casting macro.
Definition rdata.h:59
#define RUBY_DEFAULT_FREE
This is a value you can set to RData::dfree.
Definition rdata.h:78
void(* RUBY_DATA_FUNC)(void *)
This is the type of callbacks registered to RData.
Definition rdata.h:104
#define RUBY_NEVER_FREE
This is a value you can set to RData::dfree.
Definition rdata.h:85
#define RFILE(obj)
Convenient casting macro.
Definition rfile.h:50
#define RHASH_SIZE(h)
Queries the size of the hash.
Definition rhash.h:69
#define RHASH_EMPTY_P(h)
Checks if the hash is empty.
Definition rhash.h:79
#define RMATCH(obj)
Convenient casting macro.
Definition rmatch.h:37
#define ROBJECT(obj)
Convenient casting macro.
Definition robject.h:43
static VALUE * ROBJECT_FIELDS(VALUE obj)
Queries the instance variables.
Definition robject.h:128
#define RREGEXP(obj)
Convenient casting macro.
Definition rregexp.h:37
#define RREGEXP_PTR(obj)
Convenient accessor macro.
Definition rregexp.h:45
#define RSTRING(obj)
Convenient casting macro.
Definition rstring.h:41
static long RSTRUCT_LEN(VALUE st)
Returns the number of struct members.
Definition rstruct.h:82
static bool RTYPEDDATA_P(VALUE obj)
Checks whether the passed object is RTypedData or RData.
Definition rtypeddata.h:669
#define RUBY_TYPED_DEFAULT_FREE
This is a value you can set to rb_data_type_struct::dfree.
Definition rtypeddata.h:81
VALUE rb_data_typed_object_wrap(VALUE klass, void *datap, const rb_data_type_t *type)
This is the primitive way to wrap an existing C struct into RTypedData.
Definition gc.c:1175
VALUE rb_data_typed_object_zalloc(VALUE klass, size_t size, const rb_data_type_t *type)
Identical to rb_data_typed_object_wrap(), except it allocates a new data region internally instead of...
Definition gc.c:1185
#define RUBY_TYPED_FREE_IMMEDIATELY
Macros to see if each corresponding flag is defined.
Definition rtypeddata.h:122
static const rb_data_type_t * RTYPEDDATA_TYPE(VALUE obj)
Queries for the type of given object.
Definition rtypeddata.h:687
#define TypedData_Wrap_Struct(klass, data_type, sval)
Converts sval, a pointer to your struct, into a Ruby object.
Definition rtypeddata.h:531
#define RTYPEDDATA(obj)
Convenient casting macro.
Definition rtypeddata.h:96
const char * rb_obj_classname(VALUE obj)
Queries the name of the class of the passed object.
Definition variable.c:515
void rb_p(VALUE obj)
Inspects an object.
Definition io.c:9063
#define errno
Ractor-aware version of errno.
Definition ruby.h:388
int ruby_native_thread_p(void)
Queries if the thread which calls this function is a ruby's thread.
Definition thread.c:5815
static bool RB_SPECIAL_CONST_P(VALUE obj)
Checks if the given object is of enum ruby_special_consts.
#define RTEST
This is an old name of RB_TEST.
Defines old _.
#define _(args)
This was a transition path from K&R to ANSI.
Definition stdarg.h:35
Ruby's array.
Definition rarray.h:128
Ruby object's base components.
Definition rbasic.h:69
Definition rdata.h:120
RUBY_DATA_FUNC dfree
This function is called when the object is no longer used.
Definition rdata.h:143
RUBY_DATA_FUNC dmark
This function is called when the object is experiencing GC marks.
Definition rdata.h:134
void * data
Pointer to the actual C level struct that you want to wrap.
Definition rdata.h:149
Definition hash.h:53
Ruby's ordinal objects.
Definition robject.h:85
Ruby's String.
Definition rstring.h:196
"Typed" user data.
Definition rtypeddata.h:384
void * data
Pointer to the actual C level struct that you want to wrap.
Definition rtypeddata.h:404
VALUE fields_obj
Direct reference to the slots that holds instance variables, if any.
Definition rtypeddata.h:390
Definition method.h:63
Definition constant.h:33
CREF (Class REFerence)
Definition method.h:45
Definition class.h:37
This is the struct that holds necessary info for a struct.
Definition rtypeddata.h:229
RUBY_DATA_FUNC dfree
This function is called when the object is no longer used.
Definition rtypeddata.h:259
RUBY_DATA_FUNC dcompact
This function is called when the object is relocated.
Definition rtypeddata.h:280
struct rb_data_type_struct::@57 function
Function pointers.
const char * wrap_struct_name
Name of structs of this kind.
Definition rtypeddata.h:236
RUBY_DATA_FUNC dmark
This function is called when the object is experiencing GC marks.
Definition rtypeddata.h:250
VALUE flags
Type-specific behavioural characteristics.
Definition rtypeddata.h:343
Definition gc_impl.h:15
Ruby's IO, metadata and buffers.
Definition io.h:295
Represents a match.
Definition rmatch.h:71
struct rmatch_offset * char_offset
Capture group offsets, in C array.
Definition rmatch.h:79
int char_offset_num_allocated
Number of rmatch_offset that ::rmatch::char_offset holds.
Definition rmatch.h:82
struct re_registers regs
"Registers" of a match.
Definition rmatch.h:76
Definition method.h:55
const rb_iseq_t * iseqptr
iseq pointer, should be separated from iseqval
Definition method.h:143
Internal header for Class.
Definition class.h:30
Represents the region of a capture group.
Definition rmatch.h:65
Definition st.h:79
void rb_native_mutex_lock(rb_nativethread_lock_t *lock)
Just another name of rb_nativethread_lock_lock.
void rb_native_mutex_initialize(rb_nativethread_lock_t *lock)
Just another name of rb_nativethread_lock_initialize.
void rb_native_mutex_unlock(rb_nativethread_lock_t *lock)
Just another name of rb_nativethread_lock_unlock.
intptr_t SIGNED_VALUE
A signed integer type that has the same width with VALUE.
Definition value.h:63
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 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_MASK
Bitmask of ruby_value_type.
Definition value_type.h:145