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