Ruby: gc.c Source File

Ruby 3.4.8p72 (2025-12-17 revision 995b59f66677d44767ce9faac6957e5543617ff9)

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