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