Ruby 4.1.0dev (2026-10-06 revision 28da13e768d5a463bec19a874d54d351f41f306f)
gc.c (28da13e768d5a463bec19a874d54d351f41f306f)
1/**********************************************************************
2
3 gc.c -
4
5 $Author$
6 created at: Tue Oct 5 09:44:46 JST 1993
7
8 Copyright (C) 1993-2007 Yukihiro Matsumoto
9 Copyright (C) 2000 Network Applied Communication Laboratory, Inc.
10 Copyright (C) 2000 Information-technology Promotion Agency, Japan
11
12**********************************************************************/
13
14#include "ruby/internal/config.h"
15#ifdef _WIN32
16# include "ruby/ruby.h"
17#endif
18
19#if defined(__wasm__) && !defined(__EMSCRIPTEN__)
20# include "wasm/setjmp.h"
21# include "wasm/machine.h"
22#else
23# include <setjmp.h>
24#endif
25#include <stdarg.h>
26#include <stdio.h>
27
28/* MALLOC_HEADERS_BEGIN */
29#ifndef HAVE_MALLOC_USABLE_SIZE
30# ifdef _WIN32
31# define HAVE_MALLOC_USABLE_SIZE
32# define malloc_usable_size(a) _msize(a)
33# elif defined HAVE_MALLOC_SIZE
34# define HAVE_MALLOC_USABLE_SIZE
35# define malloc_usable_size(a) malloc_size(a)
36# endif
37#endif
38
39#ifdef HAVE_MALLOC_USABLE_SIZE
40# ifdef RUBY_ALTERNATIVE_MALLOC_HEADER
41/* Alternative malloc header is included in ruby/missing.h */
42# elif defined(HAVE_MALLOC_H)
43# include <malloc.h>
44# elif defined(HAVE_MALLOC_NP_H)
45# include <malloc_np.h>
46# elif defined(HAVE_MALLOC_MALLOC_H)
47# include <malloc/malloc.h>
48# endif
49#endif
50
51/* MALLOC_HEADERS_END */
52
53#ifdef HAVE_SYS_TIME_H
54# include <sys/time.h>
55#endif
56
57#ifdef HAVE_SYS_RESOURCE_H
58# include <sys/resource.h>
59#endif
60
61#if defined _WIN32 || defined __CYGWIN__
62# include <windows.h>
63#elif defined(HAVE_POSIX_MEMALIGN)
64#elif defined(HAVE_MEMALIGN)
65# include <malloc.h>
66#endif
67
68#include <sys/types.h>
69
70#ifdef __EMSCRIPTEN__
71#include <emscripten.h>
72#endif
73
74/* For ruby_annotate_mmap */
75#ifdef HAVE_SYS_PRCTL_H
76#include <sys/prctl.h>
77#endif
78
79#undef LIST_HEAD /* ccan/list conflicts with BSD-origin sys/queue.h. */
80
81#include "constant.h"
82#include "debug_counter.h"
83#include "eval_intern.h"
84#include "gc/gc.h"
85#include "id_table.h"
86#include "internal.h"
87#include "internal/class.h"
88#include "internal/compile.h"
89#include "internal/complex.h"
90#include "internal/concurrent_set.h"
91#include "internal/cont.h"
92#include "internal/error.h"
93#include "internal/eval.h"
94#include "internal/gc.h"
95#include "internal/hash.h"
96#include "internal/imemo.h"
97#include "internal/io.h"
98#include "internal/numeric.h"
99#include "internal/object.h"
100#include "internal/proc.h"
101#include "internal/rational.h"
102#include "internal/re.h"
103#include "internal/sanitizers.h"
104#include "internal/struct.h"
105#include "internal/symbol.h"
106#include "internal/thread.h"
107#include "internal/variable.h"
108#include "internal/warnings.h"
109#include "probes.h"
110#include "regint.h"
111#include "ruby/debug.h"
112#include "ruby/io.h"
113#include "ruby/re.h"
114#include "ruby/st.h"
115#include "ruby/thread.h"
116#include "ruby/util.h"
117#include "ruby/vm.h"
118#include "ruby_assert.h"
119#include "ruby_atomic.h"
120#include "symbol.h"
121#include "variable.h"
122#include "vm_core.h"
123#include "vm_sync.h"
124#include "vm_callinfo.h"
125#include "ractor_core.h"
126#include "internal/ractor.h"
127#include "yjit.h"
128#include "zjit.h"
129
130#include "builtin.h"
131#include "shape.h"
132
133// TODO: Don't export this function in modular GC, instead MMTk should figure out
134// how to combine GC thread backtrace with mutator thread backtrace.
135void
136rb_gc_print_backtrace(void)
137{
138 rb_print_backtrace(stderr);
139}
140
141unsigned int
142rb_gc_vm_lock(const char *file, int line)
143{
144 unsigned int lev = 0;
145 rb_vm_lock_enter(&lev, file, line);
146 return lev;
147}
148
149void
150rb_gc_vm_unlock(unsigned int lev, const char *file, int line)
151{
152 rb_vm_lock_leave(&lev, file, line);
153}
154
155unsigned int
156rb_gc_vm_lock_no_barrier(const char *file, int line)
157{
158 unsigned int lev = 0;
159 rb_vm_lock_enter_nb(&lev, file, line);
160 return lev;
161}
162
163void
164rb_gc_vm_unlock_no_barrier(unsigned int lev, const char *file, int line)
165{
166 rb_vm_lock_leave_nb(&lev, file, line);
167}
168
169void
170rb_gc_vm_barrier(void)
171{
172 rb_vm_barrier();
173}
174
175void *
176rb_gc_get_ractor_newobj_cache(void)
177{
178 return GET_RACTOR()->newobj_cache;
179}
180
181void
182rb_gc_initialize_vm_context(struct rb_gc_vm_context *context)
183{
184 context->ec = GET_EC();
185}
186
187bool
188rb_gc_event_hook_required_p(rb_event_flag_t event)
189{
190 return ruby_vm_event_flags & event;
191}
192
193void
194rb_gc_event_hook(VALUE obj, rb_event_flag_t event)
195{
196 if (LIKELY(!rb_gc_event_hook_required_p(event))) return;
197
198 /* Event hooks run user code in the context of the currently running
199 * thread, so they must use the current EC. rb_gc_get_ec() may instead
200 * return the GC's snapshot (vm_context.ec, taken at marking), which can
201 * belong to a different thread once lazy sweep is continued from another
202 * thread's allocation; running the hook on it would set trace_arg on the
203 * wrong EC and break get_trace_arg() (GET_EC()->trace_arg would be NULL). */
204 rb_execution_context_t *ec = GET_EC();
205
206#if USE_MODULAR_GC
207 bool gc_thread_p = false;
208 if (!ec) {
209 /* A dedicated GC thread has no mutator EC: borrow the GC's snapshot and
210 * install it as the current EC so GET_EC() stays consistent inside the
211 * hook (e.g. for get_trace_arg()). */
212 ec = rb_gc_get_ec();
213 gc_thread_p = true;
214
215# ifdef RB_THREAD_LOCAL_SPECIFIER
216 rb_current_ec_set(ec);
217# else
218 native_tls_set(ruby_current_ec_key, ec);
219# endif
220 }
221#endif
222
223 if (RB_LIKELY(ec->cfp != NULL)) {
224 EXEC_EVENT_HOOK(ec, event, ec->cfp->self, 0, 0, 0, obj);
225 }
226
227#if USE_MODULAR_GC
228 if (gc_thread_p) {
229# ifdef RB_THREAD_LOCAL_SPECIFIER
230 rb_current_ec_set(NULL);
231# else
232 native_tls_set(ruby_current_ec_key, NULL);
233# endif
234 }
235#endif
236}
237
238/* Nonzero once the cleanup walk has stashed an objspace, which is the only case where a
239 * thread needs one other than its own Ractor's. One unsynchronised load gates it,
240 * keeping the per-reference marking path and the malloc paths clear of the lookups
241 * below. It is never unwound, so a stale zero only costs a resolution that predates the
242 * stash. */
243static rb_atomic_t gc_objspace_override_count;
244
245/* VM destruct's free-at-exit walk can free the thread and Ractor structs first, so
246 * resolving through the current Ractor would use freed memory; return the objspace
247 * stashed before the walk started. */
248
249void
250rb_gc_stash_cleanup_objspace(void)
251{
252 GET_VM()->gc.cleanup_objspace = rb_gc_get_objspace();
253 /* Never unwound, as the VM is going away: from here every resolution takes the slow
254 * path, which is where the stashed objspace is returned from. */
255 RUBY_ATOMIC_INC(gc_objspace_override_count);
256}
257
258/* Out of line to keep the rare arms out of RB_GC_MARK_OR_TRAVERSE's inline expansions. */
259NOINLINE(static void *gc_current_objspace_slow(rb_ractor_t *const cr));
260
261static void *
262gc_current_objspace_slow(rb_ractor_t *const cr)
263{
264 /* Checked before anything reads cr or the EC: the cleanup walk is the case where
265 * both may already be freed (see rb_gc_stash_cleanup_objspace). */
266 if (RB_UNLIKELY(ruby_vm_during_cleanup) && GET_VM()->gc.cleanup_objspace) {
267 return GET_VM()->gc.cleanup_objspace;
268 }
269 if (cr == NULL) {
270 /* A thread with no current Ractor (a GVL-less native thread freeing in
271 * thread_sched_reclaim, say) uses the main Ractor's objspace. */
272 return GET_VM()->ractor.main_ractor->objspace;
273 }
274 /* A live current Ractor always has an objspace. */
275 RUBY_ASSERT(cr->objspace != NULL);
276 return cr->objspace;
277}
278
279static inline void *
280gc_current_objspace_of(rb_ractor_t *const cr)
281{
282 if (RB_LIKELY(cr != NULL && gc_objspace_override_count == 0)) {
283 RUBY_ASSERT(cr->objspace != NULL);
284 return cr->objspace;
285 }
286 return gc_current_objspace_slow(cr);
287}
288
289void *
290rb_gc_get_objspace(void)
291{
292 return gc_current_objspace_of(rb_current_ractor_raw(false));
293}
294
295void
296rb_gc_run_obj_finalizer(VALUE objid, long count, VALUE (*callback)(long i, void *data), void *data)
297{
298 volatile struct {
299 VALUE errinfo;
300 VALUE final;
302 VALUE *sp;
303 long finished;
304 } saved;
305
306 rb_execution_context_t * volatile ec = GET_EC();
307#define RESTORE_FINALIZER() (\
308 ec->cfp = saved.cfp, \
309 ec->cfp->sp = saved.sp, \
310 ec->errinfo = saved.errinfo)
311
312 saved.errinfo = ec->errinfo;
313 saved.cfp = ec->cfp;
314 saved.sp = ec->cfp->sp;
315 saved.finished = 0;
316 saved.final = Qundef;
317
318 ASSERT_vm_unlocking();
319 rb_ractor_ignore_belonging(true);
320 EC_PUSH_TAG(ec);
321 enum ruby_tag_type state = EC_EXEC_TAG();
322 if (state != TAG_NONE) {
323 ++saved.finished; /* skip failed finalizer */
324
325 VALUE failed_final = saved.final;
326 saved.final = Qundef;
327 if (!UNDEF_P(failed_final) && !NIL_P(ruby_verbose)) {
328 rb_warn("Exception in finalizer %+"PRIsVALUE, failed_final);
329 rb_ec_error_print(ec, ec->errinfo);
330 }
331 }
332
333 for (long i = saved.finished; RESTORE_FINALIZER(), i < count; saved.finished = ++i) {
334 saved.final = callback(i, data);
335 rb_check_funcall(saved.final, idCall, 1, &objid);
336 }
337 EC_POP_TAG();
338 rb_ractor_ignore_belonging(false);
339#undef RESTORE_FINALIZER
340}
341
342void
343rb_gc_set_pending_interrupt(void)
344{
345 rb_execution_context_t *ec = GET_EC();
346 ec->interrupt_mask |= PENDING_INTERRUPT_MASK;
347}
348
349/* Schedule an objspace's deferred finalizers. A global GC sweeps other Ractors'
350 * objspaces too, so target the owning Ractor rather than the sweeping driver. For an
351 * objspace with no live owner the untargeted fallback is only a wake-up: a zombie's
352 * entries move to the inheriting objspace in the absorb, which re-triggers there. */
353void
354rb_gc_trigger_finalize_deferred(void *objspace, rb_postponed_job_handle_t pjob)
355{
356 rb_ractor_t *const cr = rb_current_ractor_raw(false);
357 if (cr == NULL || cr->objspace != objspace) {
358 /* Only a global GC (stop-the-world) or an absorb settle (under the VM lock)
359 * defers another objspace's finalizers, so ractor.set is stable here. */
360 ASSERT_vm_locking();
361 rb_vm_t *vm = GET_VM();
362 rb_ractor_t *r;
363 ccan_list_for_each(&vm->ractor.set, r, vmlr_node) {
364 if (r->objspace == objspace) {
365 rb_postponed_job_trigger_for_ractor(pjob, r->pub.self);
366 return;
367 }
368 }
369 }
371}
372
373void
374rb_gc_trigger_postponed_job_on_main(rb_postponed_job_handle_t pjob)
375{
376 rb_postponed_job_trigger_for_ractor(pjob, GET_VM()->ractor.main_ractor->pub.self);
377}
378
379void
380rb_gc_unset_pending_interrupt(void)
381{
382 rb_execution_context_t *ec = GET_EC();
383 ec->interrupt_mask &= ~PENDING_INTERRUPT_MASK;
384}
385
386bool
387rb_gc_multi_ractor_p(void)
388{
389 return rb_multi_ractor_p();
390}
391
392bool
393rb_gc_shutdown_call_finalizer_p(VALUE obj)
394{
395 switch (BUILTIN_TYPE(obj)) {
396 case T_DATA:
397 if (!ruby_free_at_exit_p()) {
398 if (!RDATA(obj)->type) return false;
399 if (!rbimpl_typeddata_embedded_p(obj) && !RTYPEDDATA(obj)->data) return false;
400 }
401 if (rb_obj_is_thread(obj)) return false;
402 if (rb_obj_is_mutex(obj)) return false;
403 if (rb_obj_is_fiber(obj)) return false;
404 if (rb_ractor_p(obj)) return false;
405 if (rb_obj_is_fstring_table(obj)) return false;
406 if (rb_obj_is_symbol_table(obj)) return false;
407
408 return true;
409
410 case T_FILE:
411 return true;
412
413 case T_SYMBOL:
414 return true;
415
416 case T_NONE:
417 return false;
418
419 default:
420 return ruby_free_at_exit_p();
421 }
422}
423
424void
425rb_gc_obj_changed_slot_size(VALUE obj, size_t slot_size)
426{
427 shape_id_t shape_id = rb_obj_shape_transition_capacity(obj, rb_shape_capacity_for_slot_size(slot_size));
428 RBASIC_SET_FULL_SHAPE_ID(obj, shape_id);
429}
430
431void rb_vm_update_references(void *ptr);
432
433#define rb_setjmp(env) RUBY_SETJMP(env)
434#define rb_jmp_buf rb_jmpbuf_t
435
436#if !defined(MAP_ANONYMOUS) && defined(MAP_ANON)
437#define MAP_ANONYMOUS MAP_ANON
438#endif
439
440#define unless_objspace(objspace) \
441 void *objspace; \
442 rb_vm_t *unless_objspace_vm = GET_VM(); \
443 if (unless_objspace_vm) objspace = rb_gc_get_objspace(); \
444 else /* return; or objspace will be warned uninitialized */
445
446#define RMOVED(obj) ((struct RMoved *)(obj))
447
448#define TYPED_UPDATE_IF_MOVED(_objspace, _type, _thing) do { \
449 if (gc_object_moved_p_internal((_objspace), (VALUE)(_thing))) { \
450 *(_type *)&(_thing) = (_type)gc_location_internal(_objspace, (VALUE)_thing); \
451 } \
452} while (0)
453
454#define UPDATE_IF_MOVED(_objspace, _thing) TYPED_UPDATE_IF_MOVED(_objspace, VALUE, _thing)
455
456#if RUBY_MARK_FREE_DEBUG
457int ruby_gc_debug_indent = 0;
458#endif
459
460#ifndef RGENGC_OBJ_INFO
461# define RGENGC_OBJ_INFO RGENGC_CHECK_MODE
462#endif
463
464#ifndef CALC_EXACT_MALLOC_SIZE
465# define CALC_EXACT_MALLOC_SIZE 0
466#endif
467
469
470static size_t malloc_offset = 0;
471#if defined(HAVE_MALLOC_USABLE_SIZE)
472static size_t
473gc_compute_malloc_offset(void)
474{
475 // Different allocators use different metadata storage strategies which result in different
476 // ideal sizes.
477 // For instance malloc(64) will waste 8B with glibc, but waste 0B with jemalloc.
478 // But malloc(56) will waste 0B with glibc, but waste 8B with jemalloc.
479 // So we try allocating 64, 56 and 48 bytes and select the first offset that doesn't
480 // waste memory.
481 // This was tested on Linux with glibc 2.35 and jemalloc 5, and for both it result in
482 // no wasted memory.
483 size_t offset = 0;
484 for (offset = 0; offset <= 16; offset += 8) {
485 size_t allocated = (64 - offset);
486 void *test_ptr = malloc(allocated);
487 size_t wasted = malloc_usable_size(test_ptr) - allocated;
488 free(test_ptr);
489
490 if (wasted == 0) {
491 return offset;
492 }
493 }
494 return 0;
495}
496#else
497static size_t
498gc_compute_malloc_offset(void)
499{
500 // If we don't have malloc_usable_size, we use powers of 2.
501 return 0;
502}
503#endif
504
505size_t
506rb_malloc_grow_capa(size_t current, size_t type_size)
507{
508 size_t current_capacity = current;
509 if (current_capacity < 4) {
510 current_capacity = 4;
511 }
512 current_capacity *= type_size;
513
514 // We double the current capacity.
515 size_t new_capacity = (current_capacity * 2);
516
517 // And round up to the next power of 2 if it's not already one.
518 if (rb_popcount64(new_capacity) != 1) {
519 new_capacity = (size_t)(1 << (64 - nlz_int64(new_capacity)));
520 }
521
522 new_capacity -= malloc_offset;
523 new_capacity /= type_size;
524 if (current > new_capacity) {
525 rb_bug("rb_malloc_grow_capa: current_capacity=%zu, new_capacity=%zu, malloc_offset=%zu", current, new_capacity, malloc_offset);
526 }
527 RUBY_ASSERT(new_capacity > current);
528 return new_capacity;
529}
530
531static inline struct rbimpl_size_overflow_tag
532size_mul_add_overflow(size_t x, size_t y, size_t z) /* x * y + z */
533{
534 struct rbimpl_size_overflow_tag t = rbimpl_size_mul_overflow(x, y);
535 struct rbimpl_size_overflow_tag u = rbimpl_size_add_overflow(t.result, z);
536 return (struct rbimpl_size_overflow_tag) { t.overflowed || u.overflowed, u.result };
537}
538
539static inline struct rbimpl_size_overflow_tag
540size_mul_add_mul_overflow(size_t x, size_t y, size_t z, size_t w) /* x * y + z * w */
541{
542 struct rbimpl_size_overflow_tag t = rbimpl_size_mul_overflow(x, y);
543 struct rbimpl_size_overflow_tag u = rbimpl_size_mul_overflow(z, w);
544 struct rbimpl_size_overflow_tag v = rbimpl_size_add_overflow(t.result, u.result);
545 return (struct rbimpl_size_overflow_tag) { t.overflowed || u.overflowed || v.overflowed, v.result };
546}
547
548PRINTF_ARGS(NORETURN(static void gc_raise(VALUE, const char*, ...)), 2, 3);
549
550static inline size_t
551size_mul_or_raise(size_t x, size_t y, VALUE exc)
552{
553 struct rbimpl_size_overflow_tag t = rbimpl_size_mul_overflow(x, y);
554 if (LIKELY(!t.overflowed)) {
555 return t.result;
556 }
557 else if (rb_during_gc()) {
558 rb_memerror(); /* or...? */
559 }
560 else {
561 gc_raise(
562 exc,
563 "integer overflow: %"PRIuSIZE
564 " * %"PRIuSIZE
565 " > %"PRIuSIZE,
566 x, y, (size_t)SIZE_MAX);
567 }
568}
569
570size_t
571rb_size_mul_or_raise(size_t x, size_t y, VALUE exc)
572{
573 return size_mul_or_raise(x, y, exc);
574}
575
576static inline size_t
577size_mul_add_or_raise(size_t x, size_t y, size_t z, VALUE exc)
578{
579 struct rbimpl_size_overflow_tag t = size_mul_add_overflow(x, y, z);
580 if (LIKELY(!t.overflowed)) {
581 return t.result;
582 }
583 else if (rb_during_gc()) {
584 rb_memerror(); /* or...? */
585 }
586 else {
587 gc_raise(
588 exc,
589 "integer overflow: %"PRIuSIZE
590 " * %"PRIuSIZE
591 " + %"PRIuSIZE
592 " > %"PRIuSIZE,
593 x, y, z, (size_t)SIZE_MAX);
594 }
595}
596
597size_t
598rb_size_mul_add_or_raise(size_t x, size_t y, size_t z, VALUE exc)
599{
600 return size_mul_add_or_raise(x, y, z, exc);
601}
602
603static inline size_t
604size_mul_add_mul_or_raise(size_t x, size_t y, size_t z, size_t w, VALUE exc)
605{
606 struct rbimpl_size_overflow_tag t = size_mul_add_mul_overflow(x, y, z, w);
607 if (LIKELY(!t.overflowed)) {
608 return t.result;
609 }
610 else if (rb_during_gc()) {
611 rb_memerror(); /* or...? */
612 }
613 else {
614 gc_raise(
615 exc,
616 "integer overflow: %"PRIdSIZE
617 " * %"PRIdSIZE
618 " + %"PRIdSIZE
619 " * %"PRIdSIZE
620 " > %"PRIdSIZE,
621 x, y, z, w, (size_t)SIZE_MAX);
622 }
623}
624
625#if defined(HAVE_RB_GC_GUARDED_PTR_VAL) && HAVE_RB_GC_GUARDED_PTR_VAL
626/* trick the compiler into thinking a external signal handler uses this */
627volatile VALUE rb_gc_guarded_val;
628volatile VALUE *
629rb_gc_guarded_ptr_val(volatile VALUE *ptr, VALUE val)
630{
631 rb_gc_guarded_val = val;
632
633 return ptr;
634}
635#endif
636
637static const char *obj_type_name(VALUE obj);
638
639/* A forking parent can hold registered_addrs.lock; inheriting it locked would make
640 * the child's first register wait forever, so rebuild it, like the generic_fields
641 * lock. */
642void
643rb_gc_atfork_global_locks(void)
644{
645 rb_vm_t *vm = GET_VM();
646 rb_native_mutex_initialize(&vm->gc.registered_addrs.lock);
647}
648
649#include "gc/default/default.c"
650
651#if USE_MODULAR_GC && !defined(HAVE_DLOPEN)
652# error "Modular GC requires dlopen"
653#elif USE_MODULAR_GC
654#include <dlfcn.h>
655
656typedef struct gc_function_map {
657 // Bootup
658 void *(*objspace_alloc)(void);
659 void (*objspace_init)(void *objspace_ptr);
660 void *(*ractor_cache_alloc)(void *objspace_ptr, void *ractor);
661 void (*objspace_retire_gc)(void *objspace_ptr);
662 void (*set_params)(void *objspace_ptr);
663 void (*init)(void);
664 // Shutdown
665 void (*shutdown_free_objects)(void *objspace_ptr);
666 void (*objspace_free)(void *objspace_ptr);
667 void (*ractor_cache_free)(void *objspace_ptr, void *cache);
668 // GC
669 void (*start)(void *objspace_ptr, bool full_mark, bool immediate_mark, bool immediate_sweep, bool compact, bool global);
670 bool (*during_gc_p)(void *objspace_ptr);
671 void (*prepare_heap)(void *objspace_ptr);
672 void (*gc_enable)(void *objspace_ptr);
673 void (*gc_disable)(void *objspace_ptr, bool finish_current_gc);
674 bool (*gc_enabled_p)(void *objspace_ptr);
675 bool (*user_gc_disabled_set)(void *objspace_ptr, bool disable);
676 bool (*user_gc_disabled_p)(void *objspace_ptr);
677 bool (*multi_objspace_p)(void);
678 bool (*during_global_gc_p)(void *objspace_ptr);
679 bool (*during_postmortem_p)(void *objspace_ptr);
680 bool (*obj_foreign_p)(void *objspace_ptr, VALUE obj);
681 bool (*shref_marked_p)(void *objspace_ptr, VALUE obj);
682 size_t (*heap_page_count)(void *objspace_ptr);
683 void (*objspace_absorb)(void *dst_ptr, void *src_ptr);
684 void (*gc_rest)(void *objspace_ptr);
685 VALUE (*config_get)(void *objpace_ptr);
686 void (*config_set)(void *objspace_ptr, VALUE hash);
687 void (*stress_set)(void *objspace_ptr, VALUE flag);
688 VALUE (*stress_get)(void *objspace_ptr);
689 struct rb_gc_vm_context *(*get_vm_context)(void *objspace_ptr);
690 // Object allocation
691 VALUE (*new_obj)(void *objspace_ptr, void *cache_ptr, VALUE klass, VALUE flags, bool wb_protected, size_t alloc_size, size_t *actual_alloc_size);
692 bool (*zjit_new_obj_fastpath)(void *objspace_ptr, size_t alloc_size, VALUE flags, VALUE klass, struct rb_gc_zjit_fastpath *fastpath);
693 size_t (*obj_slot_size)(VALUE obj);
694 size_t (*size_slot_size)(void *objspace_ptr, size_t size);
695 bool (*size_allocatable_p)(size_t size);
696 size_t (*max_allocation_size)(void);
697 // Malloc
698 void *(*malloc)(void *objspace_ptr, size_t size, bool gc_allowed);
699 void *(*calloc)(void *objspace_ptr, size_t size, bool gc_allowed);
700 void *(*realloc)(void *objspace_ptr, void *ptr, size_t new_size, size_t old_size, bool gc_allowed);
701 void (*free)(void *objspace_ptr, void *ptr, size_t old_size);
702 void (*adjust_memory_usage)(void *objspace_ptr, ssize_t diff);
703 // Marking
704 void (*mark)(void *objspace_ptr, VALUE obj);
705 void (*mark_and_move)(void *objspace_ptr, VALUE *ptr);
706 void (*mark_and_pin)(void *objspace_ptr, VALUE obj);
707 void (*mark_maybe)(void *objspace_ptr, VALUE obj);
708 // Weak references
709 void (*declare_weak_references)(void *objspace_ptr, VALUE obj);
710 bool (*handle_weak_references_alive_p)(void *objspace_ptr, VALUE obj);
711 // Compaction
712 void (*register_pinning_obj)(void *objspace_ptr, VALUE obj);
713 bool (*object_moved_p)(void *objspace_ptr, VALUE obj);
714 bool (*pinned_p)(void *objspace_ptr, VALUE obj);
715 VALUE (*location)(void *objspace_ptr, VALUE value);
716 // Write barriers
717 void (*writebarrier)(void *objspace_ptr, VALUE a, VALUE b);
718 void (*writebarrier_unprotect)(void *objspace_ptr, VALUE obj);
719 void (*writebarrier_remember)(void *objspace_ptr, VALUE obj);
720 void (*obj_became_shareable)(void *objspace_ptr, VALUE obj);
721 // Heap walking
722 void (*each_objects)(void *objspace_ptr, int (*callback)(void *, void *, size_t, void *), void *data);
723 void (*each_objects_shareable)(void *objspace_ptr, int (*callback)(void *, void *, size_t, void *), void *data);
724 void (*each_objects_foreign)(void *objspace_ptr, int (*callback)(void *, void *, size_t, void *), void *data);
725 void (*each_object)(void *objspace_ptr, void (*func)(VALUE obj, void *data), void *data);
726 // Finalizers
727 void (*make_zombie)(void *objspace_ptr, VALUE obj, void (*dfree)(void *), void *data);
728 VALUE (*define_finalizer)(void *objspace_ptr, VALUE obj, VALUE block);
729 void (*undefine_finalizer)(void *objspace_ptr, VALUE obj);
730 void (*copy_finalizer)(void *objspace_ptr, VALUE dest, VALUE obj);
731 void (*shutdown_call_finalizer)(void *objspace_ptr);
732 // Forking
733 void (*before_fork)(void *objspace_ptr);
734 void (*after_fork)(void *objspace_ptr, rb_pid_t pid);
735 // Statistics
736 void (*set_measure_total_time)(void *objspace_ptr, VALUE flag);
737 bool (*get_measure_total_time)(void *objspace_ptr);
738 unsigned long long (*get_total_time)(void *objspace_ptr);
739 size_t (*gc_count)(void *objspace_ptr);
740 VALUE (*latest_gc_info)(void *objspace_ptr, VALUE key);
741 VALUE (*stat)(void *objspace_ptr, VALUE hash_or_sym);
742 VALUE (*stat_heap)(void *objspace_ptr, VALUE heap_name, VALUE hash_or_sym);
743 const char *(*active_gc_name)(void);
744 // Miscellaneous
745 struct rb_gc_object_metadata_entry *(*object_metadata)(void *objspace_ptr, VALUE obj);
746 bool (*live_object_p)(void *objspace_ptr, const void *ptr);
747 bool (*garbage_object_p)(void *objspace_ptr, VALUE obj);
748 void (*set_event_hook)(void *objspace_ptr, const rb_event_flag_t event);
749 void (*copy_attributes)(void *objspace_ptr, VALUE dest, VALUE obj);
750
751 bool modular_gc_loaded_p;
752} rb_gc_function_map_t;
753
754static rb_gc_function_map_t rb_gc_functions;
755
756# define RUBY_GC_LIBRARY "RUBY_GC_LIBRARY"
757# define MODULAR_GC_DIR STRINGIZE(modular_gc_dir)
758
759static void
760ruby_modular_gc_init(void)
761{
762 // Assert that the directory path ends with a /
763 RUBY_ASSERT_ALWAYS(MODULAR_GC_DIR[sizeof(MODULAR_GC_DIR) - 2] == '/');
764
765 const char *gc_so_file = getenv(RUBY_GC_LIBRARY);
766
767 rb_gc_function_map_t gc_functions = { 0 };
768
769 char *gc_so_path = NULL;
770 void *handle = NULL;
771 if (gc_so_file) {
772 /* Check to make sure that gc_so_file matches /[\w-_]+/ so that it does
773 * not load a shared object outside of the directory. */
774 for (size_t i = 0; i < strlen(gc_so_file); i++) {
775 char c = gc_so_file[i];
776 if (isalnum(c)) continue;
777 switch (c) {
778 case '-':
779 case '_':
780 break;
781 default:
782 fprintf(stderr, "Only alphanumeric, dash, and underscore is allowed in "RUBY_GC_LIBRARY"\n");
783 exit(EXIT_FAILURE);
784 }
785 }
786
787 size_t gc_so_path_size = strlen(MODULAR_GC_DIR "librubygc." DLEXT) + strlen(gc_so_file) + 1;
788#ifdef LOAD_RELATIVE
789 Dl_info dli;
790 size_t prefix_len = 0;
791 if (dladdr((void *)(uintptr_t)ruby_modular_gc_init, &dli)) {
792 const char *base = strrchr(dli.dli_fname, '/');
793 if (base) {
794 size_t tail = 0;
795# define end_with_p(lit) \
796 (prefix_len >= (tail = rb_strlen_lit(lit)) && \
797 memcmp(base - tail, lit, tail) == 0)
798
799 prefix_len = base - dli.dli_fname;
800 if (end_with_p("/bin") || end_with_p("/lib")) {
801 prefix_len -= tail;
802 }
803 prefix_len += MODULAR_GC_DIR[0] != '/';
804 gc_so_path_size += prefix_len;
805 }
806 }
807#endif
808 gc_so_path = alloca(gc_so_path_size);
809 {
810 size_t gc_so_path_idx = 0;
811#define GC_SO_PATH_APPEND(str) do { \
812 gc_so_path_idx += strlcpy(gc_so_path + gc_so_path_idx, str, gc_so_path_size - gc_so_path_idx); \
813} while (0)
814#ifdef LOAD_RELATIVE
815 if (prefix_len > 0) {
816 memcpy(gc_so_path, dli.dli_fname, prefix_len);
817 gc_so_path_idx = prefix_len;
818 }
819#endif
820 GC_SO_PATH_APPEND(MODULAR_GC_DIR "librubygc.");
821 GC_SO_PATH_APPEND(gc_so_file);
822 GC_SO_PATH_APPEND(DLEXT);
823 GC_ASSERT(gc_so_path_idx == gc_so_path_size - 1);
824#undef GC_SO_PATH_APPEND
825 }
826
827 handle = dlopen(gc_so_path, RTLD_LAZY | RTLD_GLOBAL);
828 if (!handle) {
829 fprintf(stderr, "ruby_modular_gc_init: Shared library %s cannot be opened: %s\n", gc_so_path, dlerror());
830 exit(EXIT_FAILURE);
831 }
832
833 gc_functions.modular_gc_loaded_p = true;
834 }
835
836 unsigned int err_count = 0;
837
838# define load_modular_gc_func(name) do { \
839 if (handle) { \
840 const char *func_name = "rb_gc_impl_" #name; \
841 gc_functions.name = dlsym(handle, func_name); \
842 if (!gc_functions.name) { \
843 fprintf(stderr, "ruby_modular_gc_init: %s function not exported by library %s\n", func_name, gc_so_path); \
844 err_count++; \
845 } \
846 } \
847 else { \
848 gc_functions.name = rb_gc_impl_##name; \
849 } \
850} while (0)
851
852 // Bootup
853 load_modular_gc_func(objspace_alloc);
854 load_modular_gc_func(objspace_init);
855 load_modular_gc_func(ractor_cache_alloc);
856 load_modular_gc_func(objspace_retire_gc);
857 load_modular_gc_func(set_params);
858 load_modular_gc_func(init);
859 // Shutdown
860 load_modular_gc_func(shutdown_free_objects);
861 load_modular_gc_func(objspace_free);
862 load_modular_gc_func(ractor_cache_free);
863 // GC
864 load_modular_gc_func(start);
865 load_modular_gc_func(during_gc_p);
866 load_modular_gc_func(prepare_heap);
867 load_modular_gc_func(gc_enable);
868 load_modular_gc_func(gc_disable);
869 load_modular_gc_func(gc_enabled_p);
870 load_modular_gc_func(user_gc_disabled_set);
871 load_modular_gc_func(user_gc_disabled_p);
872 load_modular_gc_func(multi_objspace_p);
873 load_modular_gc_func(during_global_gc_p);
874 load_modular_gc_func(during_postmortem_p);
875 load_modular_gc_func(obj_foreign_p);
876 load_modular_gc_func(shref_marked_p);
877 load_modular_gc_func(heap_page_count);
878 load_modular_gc_func(objspace_absorb);
879 load_modular_gc_func(gc_rest);
880 load_modular_gc_func(config_set);
881 load_modular_gc_func(config_get);
882 load_modular_gc_func(stress_set);
883 load_modular_gc_func(stress_get);
884 load_modular_gc_func(get_vm_context);
885 // Object allocation
886 load_modular_gc_func(new_obj);
887 load_modular_gc_func(zjit_new_obj_fastpath);
888 load_modular_gc_func(obj_slot_size);
889 load_modular_gc_func(size_slot_size);
890 load_modular_gc_func(size_allocatable_p);
891 load_modular_gc_func(max_allocation_size);
892 // Malloc
893 load_modular_gc_func(malloc);
894 load_modular_gc_func(calloc);
895 load_modular_gc_func(realloc);
896 load_modular_gc_func(free);
897 load_modular_gc_func(adjust_memory_usage);
898 // Marking
899 load_modular_gc_func(mark);
900 load_modular_gc_func(mark_and_move);
901 load_modular_gc_func(mark_and_pin);
902 load_modular_gc_func(mark_maybe);
903 // Weak references
904 load_modular_gc_func(declare_weak_references);
905 load_modular_gc_func(handle_weak_references_alive_p);
906 // Compaction
907 load_modular_gc_func(register_pinning_obj);
908 load_modular_gc_func(object_moved_p);
909 load_modular_gc_func(pinned_p);
910 load_modular_gc_func(location);
911 // Write barriers
912 load_modular_gc_func(writebarrier);
913 load_modular_gc_func(writebarrier_unprotect);
914 load_modular_gc_func(writebarrier_remember);
915 load_modular_gc_func(obj_became_shareable);
916 // Heap walking
917 load_modular_gc_func(each_objects);
918 load_modular_gc_func(each_objects_shareable);
919 load_modular_gc_func(each_objects_foreign);
920 load_modular_gc_func(each_object);
921 // Finalizers
922 load_modular_gc_func(make_zombie);
923 load_modular_gc_func(define_finalizer);
924 load_modular_gc_func(undefine_finalizer);
925 load_modular_gc_func(copy_finalizer);
926 load_modular_gc_func(shutdown_call_finalizer);
927 // Forking
928 load_modular_gc_func(before_fork);
929 load_modular_gc_func(after_fork);
930 // Statistics
931 load_modular_gc_func(set_measure_total_time);
932 load_modular_gc_func(get_measure_total_time);
933 load_modular_gc_func(get_total_time);
934 load_modular_gc_func(gc_count);
935 load_modular_gc_func(latest_gc_info);
936 load_modular_gc_func(stat);
937 load_modular_gc_func(stat_heap);
938 load_modular_gc_func(active_gc_name);
939 // Miscellaneous
940 load_modular_gc_func(object_metadata);
941 load_modular_gc_func(live_object_p);
942 load_modular_gc_func(garbage_object_p);
943 load_modular_gc_func(set_event_hook);
944 load_modular_gc_func(copy_attributes);
945
946 if (err_count > 0) {
947 fprintf(stderr, "ruby_modular_gc_init: found %u missing exports in library %s\n", err_count, gc_so_path);
948 exit(EXIT_FAILURE);
949 }
950
951# undef load_modular_gc_func
952
953 rb_gc_functions = gc_functions;
954}
955
956// Bootup
957# define rb_gc_impl_objspace_alloc rb_gc_functions.objspace_alloc
958# define rb_gc_impl_objspace_init rb_gc_functions.objspace_init
959# define rb_gc_impl_ractor_cache_alloc rb_gc_functions.ractor_cache_alloc
960# define rb_gc_impl_objspace_retire_gc rb_gc_functions.objspace_retire_gc
961# define rb_gc_impl_set_params rb_gc_functions.set_params
962# define rb_gc_impl_init rb_gc_functions.init
963// Shutdown
964# define rb_gc_impl_shutdown_free_objects rb_gc_functions.shutdown_free_objects
965# define rb_gc_impl_objspace_free rb_gc_functions.objspace_free
966# define rb_gc_impl_ractor_cache_free rb_gc_functions.ractor_cache_free
967// GC
968# define rb_gc_impl_start rb_gc_functions.start
969# define rb_gc_impl_during_gc_p rb_gc_functions.during_gc_p
970# define rb_gc_impl_prepare_heap rb_gc_functions.prepare_heap
971# define rb_gc_impl_gc_enable rb_gc_functions.gc_enable
972# define rb_gc_impl_gc_disable rb_gc_functions.gc_disable
973# define rb_gc_impl_gc_enabled_p rb_gc_functions.gc_enabled_p
974# define rb_gc_impl_user_gc_disabled_set rb_gc_functions.user_gc_disabled_set
975# define rb_gc_impl_user_gc_disabled_p rb_gc_functions.user_gc_disabled_p
976# define rb_gc_impl_multi_objspace_p rb_gc_functions.multi_objspace_p
977# define rb_gc_impl_during_global_gc_p rb_gc_functions.during_global_gc_p
978# define rb_gc_impl_during_postmortem_p rb_gc_functions.during_postmortem_p
979# define rb_gc_impl_obj_foreign_p rb_gc_functions.obj_foreign_p
980# define rb_gc_impl_shref_marked_p rb_gc_functions.shref_marked_p
981# define rb_gc_impl_heap_page_count rb_gc_functions.heap_page_count
982# define rb_gc_impl_objspace_absorb rb_gc_functions.objspace_absorb
983# define rb_gc_impl_gc_rest rb_gc_functions.gc_rest
984# define rb_gc_impl_config_get rb_gc_functions.config_get
985# define rb_gc_impl_config_set rb_gc_functions.config_set
986# define rb_gc_impl_stress_set rb_gc_functions.stress_set
987# define rb_gc_impl_stress_get rb_gc_functions.stress_get
988# define rb_gc_impl_get_vm_context rb_gc_functions.get_vm_context
989// Object allocation
990# define rb_gc_impl_new_obj rb_gc_functions.new_obj
991# define rb_gc_impl_zjit_new_obj_fastpath rb_gc_functions.zjit_new_obj_fastpath
992# define rb_gc_impl_obj_slot_size rb_gc_functions.obj_slot_size
993# define rb_gc_impl_size_slot_size rb_gc_functions.size_slot_size
994# define rb_gc_impl_size_allocatable_p rb_gc_functions.size_allocatable_p
995# define rb_gc_impl_max_allocation_size rb_gc_functions.max_allocation_size
996// Malloc
997# define rb_gc_impl_malloc rb_gc_functions.malloc
998# define rb_gc_impl_calloc rb_gc_functions.calloc
999# define rb_gc_impl_realloc rb_gc_functions.realloc
1000# define rb_gc_impl_free rb_gc_functions.free
1001# define rb_gc_impl_adjust_memory_usage rb_gc_functions.adjust_memory_usage
1002// Marking
1003# define rb_gc_impl_mark rb_gc_functions.mark
1004# define rb_gc_impl_mark_and_move rb_gc_functions.mark_and_move
1005# define rb_gc_impl_mark_and_pin rb_gc_functions.mark_and_pin
1006# define rb_gc_impl_mark_maybe rb_gc_functions.mark_maybe
1007// Weak references
1008# define rb_gc_impl_declare_weak_references rb_gc_functions.declare_weak_references
1009# define rb_gc_impl_handle_weak_references_alive_p rb_gc_functions.handle_weak_references_alive_p
1010// Compaction
1011# define rb_gc_impl_register_pinning_obj rb_gc_functions.register_pinning_obj
1012# define rb_gc_impl_object_moved_p rb_gc_functions.object_moved_p
1013# define rb_gc_impl_pinned_p rb_gc_functions.pinned_p
1014# define rb_gc_impl_location rb_gc_functions.location
1015// Write barriers
1016# define rb_gc_impl_writebarrier rb_gc_functions.writebarrier
1017# define rb_gc_impl_writebarrier_unprotect rb_gc_functions.writebarrier_unprotect
1018# define rb_gc_impl_writebarrier_remember rb_gc_functions.writebarrier_remember
1019# define rb_gc_impl_obj_became_shareable rb_gc_functions.obj_became_shareable
1020// Heap walking
1021# define rb_gc_impl_each_objects rb_gc_functions.each_objects
1022# define rb_gc_impl_each_objects_shareable rb_gc_functions.each_objects_shareable
1023# define rb_gc_impl_each_objects_foreign rb_gc_functions.each_objects_foreign
1024# define rb_gc_impl_each_object rb_gc_functions.each_object
1025// Finalizers
1026# define rb_gc_impl_make_zombie rb_gc_functions.make_zombie
1027# define rb_gc_impl_define_finalizer rb_gc_functions.define_finalizer
1028# define rb_gc_impl_undefine_finalizer rb_gc_functions.undefine_finalizer
1029# define rb_gc_impl_copy_finalizer rb_gc_functions.copy_finalizer
1030# define rb_gc_impl_shutdown_call_finalizer rb_gc_functions.shutdown_call_finalizer
1031// Forking
1032# define rb_gc_impl_before_fork rb_gc_functions.before_fork
1033# define rb_gc_impl_after_fork rb_gc_functions.after_fork
1034// Statistics
1035# define rb_gc_impl_set_measure_total_time rb_gc_functions.set_measure_total_time
1036# define rb_gc_impl_get_measure_total_time rb_gc_functions.get_measure_total_time
1037# define rb_gc_impl_get_total_time rb_gc_functions.get_total_time
1038# define rb_gc_impl_gc_count rb_gc_functions.gc_count
1039# define rb_gc_impl_latest_gc_info rb_gc_functions.latest_gc_info
1040# define rb_gc_impl_stat rb_gc_functions.stat
1041# define rb_gc_impl_stat_heap rb_gc_functions.stat_heap
1042# define rb_gc_impl_active_gc_name rb_gc_functions.active_gc_name
1043// Miscellaneous
1044# define rb_gc_impl_object_metadata rb_gc_functions.object_metadata
1045# define rb_gc_impl_live_object_p rb_gc_functions.live_object_p
1046# define rb_gc_impl_garbage_object_p rb_gc_functions.garbage_object_p
1047# define rb_gc_impl_set_event_hook rb_gc_functions.set_event_hook
1048# define rb_gc_impl_copy_attributes rb_gc_functions.copy_attributes
1049#endif
1050
1051#ifdef RUBY_ASAN_ENABLED
1052static void
1053asan_death_callback(void)
1054{
1055 if (GET_VM()) {
1056 rb_bug_without_die("ASAN error");
1057 }
1058}
1059#endif
1060
1061static VALUE initial_stress = Qfalse;
1062
1063void
1064rb_gc_init_objspaces(void)
1065{
1066#if USE_MODULAR_GC
1067 ruby_modular_gc_init();
1068#endif
1069
1070 rb_vm_t *vm = ruby_current_vm_ptr;
1071
1072 void *objspace = rb_gc_impl_objspace_alloc();
1073 RUBY_ASSERT(vm->ractor.main_ractor != NULL);
1074 vm->ractor.main_ractor->objspace = objspace;
1075 rb_gc_impl_objspace_init(objspace);
1076 rb_gc_impl_stress_set(objspace, initial_stress);
1077
1078#ifdef RUBY_ASAN_ENABLED
1079 __sanitizer_set_death_callback(asan_death_callback);
1080#endif
1081}
1082
1083/* Stays true once the process has gone multi-Ractor (rb_multi_ractor_p goes back to
1084 * false when the other Ractors finish). Used by verification that spans generation
1085 * state built while multiple Ractors ran. */
1086static bool gc_ever_multi_ractor = false;
1087
1088bool
1089rb_gc_ever_multi_ractor_p(void)
1090{
1091 if (!gc_ever_multi_ractor && rb_multi_ractor_p()) gc_ever_multi_ractor = true;
1092 return gc_ever_multi_ractor;
1093}
1094
1095/* Allocate the objspace of a new non-main Ractor. Called on the creating Ractor's
1096 * thread, before the new Ractor starts running. */
1097void *
1098rb_gc_objspace_alloc(void)
1099{
1100 gc_ever_multi_ractor = true;
1101 if (!rb_gc_impl_multi_objspace_p()) {
1102 /* One objspace shared by every Ractor. */
1103 return rb_gc_get_objspace();
1104 }
1105 void *objspace = rb_gc_impl_objspace_alloc();
1106 rb_gc_impl_objspace_init(objspace);
1107
1108 return objspace;
1109}
1110
1111void
1112rb_objspace_free(void *objspace)
1113{
1114 rb_gc_impl_objspace_free(objspace);
1115}
1116
1117size_t
1118rb_gc_obj_slot_size(VALUE obj)
1119{
1120 return rb_gc_impl_obj_slot_size(obj);
1121}
1122
1123static inline void
1124gc_validate_pc(VALUE obj)
1125{
1126#if RUBY_DEBUG
1127 // IMEMOs and objects without a class (e.g managed id table) are not traceable
1128 if (RB_TYPE_P(obj, T_IMEMO) || !CLASS_OF(obj)) return;
1129
1130 rb_execution_context_t *ec = GET_EC();
1131 const rb_control_frame_t *cfp = ec->cfp;
1132 if (cfp && VM_FRAME_RUBYFRAME_P(cfp) && CFP_PC(cfp)) {
1133 const VALUE *iseq_encoded = ISEQ_BODY(CFP_ISEQ(cfp))->iseq_encoded;
1134 const VALUE *iseq_encoded_end = iseq_encoded + ISEQ_BODY(CFP_ISEQ(cfp))->iseq_size;
1135 RUBY_ASSERT(CFP_PC(cfp) >= iseq_encoded, "PC not set when allocating, breaking tracing");
1136 RUBY_ASSERT(CFP_PC(cfp) <= iseq_encoded_end, "PC not set when allocating, breaking tracing");
1137 }
1138#endif
1139}
1140
1141NOINLINE(static void gc_newobj_hook(VALUE obj));
1142static void
1143gc_newobj_hook(VALUE obj)
1144{
1145 int lev = RB_GC_VM_LOCK_NO_BARRIER();
1146 {
1147 size_t slot_size = rb_gc_obj_slot_size(obj);
1148 memset((char *)obj + sizeof(struct RBasic), 0, slot_size - sizeof(struct RBasic));
1149
1150 /* We must disable GC here because the callback could call xmalloc
1151 * which could potentially trigger a GC, and a lot of code is unsafe
1152 * to trigger a GC right after an object has been allocated because
1153 * they perform initialization for the object and assume that the
1154 * GC does not trigger before then. */
1155 bool gc_disabled = RTEST(rb_gc_local_disable_no_rest());
1156 {
1157 rb_gc_event_hook(obj, RUBY_INTERNAL_EVENT_NEWOBJ);
1158 }
1159 if (!gc_disabled) rb_gc_local_enable();
1160 }
1161 RB_GC_VM_UNLOCK_NO_BARRIER(lev);
1162}
1163
1164ALWAYS_INLINE(static VALUE newobj_body(rb_ractor_t *cr, void *objspace, VALUE klass, VALUE flags, shape_id_t shape_id, bool wb_protected, size_t size));
1165
1166/* The allocation body shared by rb_newobj and rb_ec_newobj_of, forced inline into
1167 * both: left to this big translation unit's inline budget, gcc drops it from one
1168 * entry point or the other and that allocation path grows a call. */
1169static VALUE
1170newobj_body(rb_ractor_t *cr, void *objspace, VALUE klass, VALUE flags, shape_id_t shape_id, bool wb_protected, size_t size)
1171{
1172 GC_ASSERT((flags & FL_WB_PROTECTED) == 0);
1173 size_t actual_alloc_size;
1174 VALUE obj = rb_gc_impl_new_obj(objspace, cr->newobj_cache, klass, flags, wb_protected, size, &actual_alloc_size);
1175
1176 GC_ASSERT(actual_alloc_size >= size);
1177 shape_id = rb_shape_transition_slot_size(shape_id, actual_alloc_size);
1178
1179 RBASIC_SET_FULL_SHAPE_ID_NO_CHECKS(obj, shape_id);
1180
1181 gc_validate_pc(obj);
1182
1183 if (UNLIKELY(rb_gc_event_hook_required_p(RUBY_INTERNAL_EVENT_NEWOBJ))) {
1184 gc_newobj_hook(obj);
1185 }
1186
1187 if (RUBY_DTRACE_GC_OBJ_NEW_ENABLED()) {
1188 RUBY_DTRACE_GC_OBJ_NEW((void*)obj, flags);
1189 }
1190
1191#if RGENGC_CHECK_MODE
1192# ifndef GC_DEBUG_SLOT_FILL_SPECIAL_VALUE
1193# define GC_DEBUG_SLOT_FILL_SPECIAL_VALUE 255
1194# endif
1195
1196 memset(
1197 (void *)(obj + sizeof(struct RBasic)),
1198 GC_DEBUG_SLOT_FILL_SPECIAL_VALUE,
1199 rb_gc_obj_slot_size(obj) - sizeof(struct RBasic)
1200 );
1201#endif
1202
1203 return obj;
1204}
1205
1206VALUE
1207rb_newobj(rb_execution_context_t *ec, VALUE klass, VALUE flags, shape_id_t shape_id, bool wb_protected, size_t size)
1208{
1209 /* Read the Ractor's slot directly: rb_gc_get_objspace() would look cr up through
1210 * TLS on every allocation. */
1211 rb_ractor_t *cr = rb_ec_ractor_ptr(ec);
1212 return newobj_body(cr, cr->objspace, klass, flags, shape_id, wb_protected, size);
1213}
1214
1215/* Build the object in a named objspace rather than the current Ractor's. The only
1216 * foreign objspace allowed is the child this Ractor is building
1217 * (create_ractor_alloc_thread), whose wrappers must be objects the child owns.
1218 *
1219 * That target has no thread of its own yet, which is what makes this cheap: nothing
1220 * allocates, sweeps or collects there, so the half-built objects need no root and its
1221 * GC can be suppressed outright. Aiming at a live Ractor's objspace -- to build a
1222 * copy where it will be used, say -- needs three things this does not have: a root the
1223 * target's own GC marks the objects under construction from, a newobj_cache paired
1224 * with that objspace (today the only multi-objspace collector has no per-Ractor cache,
1225 * and the ones that do are single-objspace), and write barriers aimed at the target.
1226 * The assertion stops the shortcut. */
1227static VALUE
1228rb_newobj_in_objspace(rb_execution_context_t *ec, void *objspace, VALUE klass, VALUE flags, shape_id_t shape_id, bool wb_protected, size_t size)
1229{
1230 rb_ractor_t *cr = rb_ec_ractor_ptr(ec);
1231 RUBY_ASSERT(objspace == cr->objspace || objspace == cr->creating_child_objspace);
1232 return newobj_body(cr, objspace, klass, flags, shape_id, wb_protected, size);
1233}
1234
1235VALUE
1236rb_ec_newobj_of(rb_execution_context_t *ec, VALUE klass, VALUE flags, size_t size)
1237{
1238 VALUE type = flags & T_MASK;
1244 (void)type;
1245
1246 rb_ractor_t *cr = rb_ec_ractor_ptr(ec);
1247 return newobj_body(cr, cr->objspace, klass, flags, ROOT_SHAPE_ID | SHAPE_ID_LAYOUT_OTHER, true, size);
1248}
1249
1250static VALUE
1251rb_newobj_of_with_shape(VALUE klass, VALUE flags, shape_id_t shape_id, size_t size)
1252{
1253 return rb_newobj(GET_EC(), klass, flags, shape_id, true, size);
1254}
1255
1256VALUE
1257rb_newobj_of(VALUE klass, VALUE flags, size_t size)
1258{
1259 return rb_newobj(GET_EC(), klass, flags, ROOT_SHAPE_ID | SHAPE_ID_LAYOUT_OTHER, true, size);
1260}
1261
1262static
1263VALUE class_allocate_complex_instance(VALUE klass, uint32_t capacity)
1264{
1265 VALUE obj = rb_newobj_of_with_shape(klass, T_OBJECT, rb_shape_transition_extended(ROOT_COMPLEX_SHAPE_ID), sizeof(struct RObject));
1266 // The shape already says extended, so a GC during the allocation below
1267 // would mark an uninitialized as.extended.
1268 ROBJECT(obj)->as.extended = Qfalse;
1269 VALUE fields_obj = rb_imemo_fields_new_complex(obj, ROOT_COMPLEX_SHAPE_ID, capacity, false);
1270 ROBJECT_SET_EXTENDED(obj, fields_obj);
1271 return obj;
1272}
1273
1274static inline size_t
1275robject_embedded_size(uint32_t fields_count)
1276{
1277 size_t size = rb_obj_embedded_size(fields_count);
1278 if (!rb_gc_size_allocatable_p(size)) {
1279 size = sizeof(struct RObject);
1280 }
1281 return size;
1282}
1283
1284VALUE
1285rb_class_allocate_instance_capa(VALUE klass, attr_index_t max_iv_count)
1286{
1287 VALUE obj;
1288
1289 // Directly start as COMPLEX if we know we're over the limit.
1290 RUBY_ASSERT(rb_shape_max_capacity() > 0);
1291 if (RB_UNLIKELY(max_iv_count > rb_shape_max_capacity())) {
1292 obj = class_allocate_complex_instance(klass, max_iv_count);
1293 }
1294 else {
1295 size_t size = robject_embedded_size(max_iv_count);
1296
1297 // There might be a NEWOBJ tracepoint callback, and it may set fields.
1298 // So the shape must be passed to `NEWOBJ_OF`.
1299 obj = rb_newobj_of_with_shape(klass, T_OBJECT, rb_shape_transition_robject(0), size);
1300
1301 #if RUBY_DEBUG
1302 VALUE *ptr = ROBJECT_FIELDS(obj);
1303 shape_id_t shape_id = RBASIC_SHAPE_ID(obj);
1304 attr_index_t fields_count = RSHAPE_LEN(shape_id);
1305 attr_index_t capacity = RSHAPE_CAPACITY(shape_id);
1306
1307 for (attr_index_t i = fields_count; i < capacity; i++) {
1308 ptr[i] = Qundef;
1309 }
1310 #endif
1311 }
1312
1313#if RUBY_DEBUG
1314 if (rb_obj_class(obj) != rb_class_real(klass)) {
1315 rb_bug("Expected rb_class_allocate_instance to set the class correctly");
1316 }
1317#endif
1318
1319 return obj;
1320}
1321
1322VALUE
1323rb_class_allocate_instance(VALUE klass)
1324{
1325 return rb_class_allocate_instance_capa(klass, RCLASS_MAX_IV_COUNT(klass));
1326}
1327
1328#if USE_ZJIT
1329bool
1330rb_zjit_class_allocate_instance_fastpath(VALUE klass, size_t *size_out, VALUE *flags_out)
1331{
1332 uint32_t index_tbl_num_entries = RCLASS_MAX_IV_COUNT(klass);
1333
1334 RUBY_ASSERT(rb_shape_max_capacity() > 0);
1335 if (RB_UNLIKELY(index_tbl_num_entries > rb_shape_max_capacity())) {
1336 return false;
1337 }
1338
1339 *size_out = robject_embedded_size(index_tbl_num_entries);
1340 *flags_out = T_OBJECT | rb_shape_transition_robject(0);
1341
1342 return true;
1343}
1344
1345bool
1346rb_zjit_newobj_hook_enabled_p(void)
1347{
1348 return rb_gc_event_hook_required_p(RUBY_INTERNAL_EVENT_NEWOBJ);
1349}
1350#endif
1351
1352void
1353rb_gc_register_pinning_obj(VALUE obj)
1354{
1355 rb_gc_impl_register_pinning_obj(rb_gc_get_objspace(), obj);
1356}
1357
1358#define UNEXPECTED_NODE(func) \
1359 rb_bug(#func"(): GC does not handle T_NODE 0x%x(%p) 0x%"PRIxVALUE, \
1360 BUILTIN_TYPE(obj), (void*)(obj), RBASIC(obj)->flags)
1361
1362static inline void
1363rb_data_object_check(VALUE klass)
1364{
1365 RUBY_ASSERT(!RCLASS_SINGLETON_P(klass));
1366 if (klass != rb_cObject && (rb_get_alloc_func(klass) == rb_class_allocate_instance)) {
1367 rb_undef_alloc_func(klass);
1368 rb_warn("undefining the allocator of T_DATA class %"PRIsVALUE, klass);
1369 }
1370}
1371
1372#define RTYPEDDATA_EMBEDDED_P rbimpl_typeddata_embedded_p
1373#define RB_DATA_TYPE_EMBEDDABLE_P(type) ((type)->flags & RUBY_TYPED_EMBEDDABLE)
1374#define RTYPEDDATA_EMBEDDABLE_P(obj) RB_DATA_TYPE_EMBEDDABLE_P(RTYPEDDATA_TYPE(obj))
1375
1376static VALUE
1377typed_data_alloc_in(void *objspace, VALUE klass, VALUE typed_flag, void *datap, const rb_data_type_t *type, size_t size)
1378{
1379 RBIMPL_NONNULL_ARG(type);
1380 if (klass) rb_data_object_check(klass);
1381 bool wb_protected = (type->flags & RUBY_FL_WB_PROTECTED) || !type->function.dmark;
1382 VALUE obj = rb_newobj_in_objspace(GET_EC(), objspace, klass, T_DATA, ROOT_SHAPE_ID | SHAPE_ID_LAYOUT_RDATA, wb_protected, size);
1383
1384 rb_gc_register_pinning_obj(obj);
1385
1386 struct RTypedData *data = (struct RTypedData *)obj;
1387 data->fields_obj = 0;
1388 *(VALUE *)&data->type = ((VALUE)type) | typed_flag;
1389 data->data = datap;
1390
1391 return obj;
1392}
1393
1394static VALUE
1395typed_data_wrap_in(void *objspace, VALUE klass, void *datap, const rb_data_type_t *type)
1396{
1397 if (UNLIKELY(RB_DATA_TYPE_EMBEDDABLE_P(type))) {
1398 rb_raise(rb_eTypeError, "Cannot wrap an embeddable TypedData");
1399 }
1400
1401 return typed_data_alloc_in(objspace, klass, 0, datap, type, sizeof(struct RTypedData));
1402}
1403
1404VALUE
1406{
1407 return typed_data_wrap_in(rb_ec_ractor_ptr(GET_EC())->objspace, klass, datap, type);
1408}
1409
1410VALUE
1411rb_data_typed_object_wrap_in_objspace(void *objspace, VALUE klass, void *datap, const rb_data_type_t *type)
1412{
1413 return typed_data_wrap_in(objspace, klass, datap, type);
1414}
1415
1416static VALUE
1417typed_data_zalloc_in(void *objspace, VALUE klass, size_t size, const rb_data_type_t *type)
1418{
1419 if (RB_DATA_TYPE_EMBEDDABLE_P(type)) {
1420 if (!(type->flags & (RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_THREAD_SAFE_FREE))) {
1421 rb_raise(rb_eTypeError, "Embeddable TypedData must be freed immediately");
1422 }
1423
1424 /* A deferred free outlives the slot: the sweep copies the type and data pointer
1425 * out and hands the slot straight back, which it can only do when the payload is
1426 * not in the slot. Force such a type onto the heap -- an embeddable type already
1427 * has to cope with that, since a payload too large for a slot lands there too. */
1428 size_t embed_size = offsetof(struct RTypedData, data) + size;
1429 if (rb_gc_size_allocatable_p(embed_size) && !rb_gc_data_type_deferred_free_p(type)) {
1430 VALUE obj = typed_data_alloc_in(objspace, klass, TYPED_DATA_EMBEDDED, 0, type, embed_size);
1431 memset((char *)obj + offsetof(struct RTypedData, data), 0, size);
1432 return obj;
1433 }
1434 }
1435
1436 VALUE obj = typed_data_alloc_in(objspace, klass, 0, NULL, type, sizeof(struct RTypedData));
1437 DATA_PTR(obj) = xcalloc(1, size);
1438 return obj;
1439}
1440
1441VALUE
1443{
1444 return typed_data_zalloc_in(rb_ec_ractor_ptr(GET_EC())->objspace, klass, size, type);
1445}
1446
1447VALUE
1448rb_data_typed_object_zalloc_in_objspace(void *objspace, VALUE klass, size_t size, const rb_data_type_t *type)
1449{
1450 return typed_data_zalloc_in(objspace, klass, size, type);
1451}
1452
1453static size_t
1454ruby_xmalloc_usable_size(void *ptr)
1455{
1456#ifdef HAVE_MALLOC_USABLE_SIZE
1457#if CALC_EXACT_MALLOC_SIZE
1458 struct malloc_obj_info *info = (struct malloc_obj_info *)ptr - 1;
1459 return malloc_usable_size(info) - sizeof(struct malloc_obj_info);
1460#else
1461 return malloc_usable_size(ptr);
1462#endif
1463#else
1464 return 0;
1465#endif
1466}
1467
1468static size_t
1469rb_objspace_data_type_memsize(VALUE obj)
1470{
1471 size_t size = 0;
1472 const void *ptr = RTYPEDDATA_GET_DATA(obj);
1473
1474 if (ptr) {
1475 if (RTYPEDDATA_EMBEDDABLE_P(obj) && !RTYPEDDATA_EMBEDDED_P(obj)) {
1476 size += ruby_xmalloc_usable_size((void *)ptr);
1477 }
1478
1479 const rb_data_type_t *type = RTYPEDDATA_TYPE(obj);
1480 if (type->function.dsize) {
1481 size += type->function.dsize(ptr);
1482 }
1483 }
1484
1485 return size;
1486}
1487
1488const char *
1489rb_objspace_data_type_name(VALUE obj)
1490{
1491 return RTYPEDDATA_TYPE(obj)->wrap_struct_name;
1492}
1493
1494void
1495rb_gc_declare_weak_references(VALUE obj)
1496{
1497 rb_gc_impl_declare_weak_references(rb_gc_get_objspace(), obj);
1498}
1499
1500bool
1501rb_gc_handle_weak_references_alive_p(VALUE obj)
1502{
1503 if (SPECIAL_CONST_P(obj)) return true;
1504
1505 return rb_gc_impl_handle_weak_references_alive_p(rb_gc_get_objspace(), obj);
1506}
1507
1508void
1509rb_gc_handle_weak_references(VALUE obj)
1510{
1511 switch (BUILTIN_TYPE(obj)) {
1512 case T_DATA:
1513 {
1514 const rb_data_type_t *type = RTYPEDDATA_TYPE(obj);
1515
1516 if (type->function.handle_weak_references) {
1517 (type->function.handle_weak_references)(RTYPEDDATA_GET_DATA(obj));
1518 }
1519 else {
1520 rb_bug(
1521 "rb_gc_handle_weak_references: TypedData %s does not implement handle_weak_references",
1522 RTYPEDDATA_TYPE(obj)->wrap_struct_name
1523 );
1524 }
1525 }
1526 break;
1527
1528 case T_IMEMO: {
1529 switch (imemo_type(obj)) {
1530 case imemo_callcache: {
1531 struct rb_callcache *cc = (struct rb_callcache *)obj;
1532 if (cc->klass != Qundef &&
1533 (!rb_gc_handle_weak_references_alive_p(cc->klass) ||
1534 !rb_gc_handle_weak_references_alive_p((VALUE)cc->cme_))) {
1535 vm_cc_invalidate(cc);
1536 }
1537 break;
1538 }
1539 case imemo_subclasses: {
1540 struct rb_subclasses *subs = (struct rb_subclasses *)obj;
1541 VALUE *entries = rb_imemo_subclasses_entries(obj);
1542 for (uint32_t i = 0; i < subs->count; i++) {
1543 if (entries[i] && !rb_gc_handle_weak_references_alive_p(entries[i])) {
1544 entries[i] = 0;
1545 }
1546 }
1547 break;
1548 }
1549 default:
1550 rb_bug("rb_gc_handle_weak_references: unexpected imemo type");
1551 }
1552
1553 break;
1554 }
1555 default:
1556 rb_bug("rb_gc_handle_weak_references: type not supported\n");
1557 }
1558}
1559
1560static inline bool
1561rb_gc_imemo_needs_cleanup_p(VALUE obj)
1562{
1563 switch (imemo_type(obj)) {
1564 case imemo_constcache:
1565 case imemo_cref:
1566 case imemo_ifunc:
1567 case imemo_memo:
1568 case imemo_svar:
1569 case imemo_callcache:
1570 case imemo_throw_data:
1571 case imemo_cvar_entry:
1572 return false;
1573
1574 case imemo_env:
1575 case imemo_ment:
1576 case imemo_iseq:
1577 case imemo_callinfo:
1578 case imemo_cdhash:
1579 return true;
1580
1581 case imemo_subclasses:
1582 return FL_TEST_RAW(obj, IMEMO_SUBCLASSES_HEAP);
1583
1584 case imemo_tmpbuf:
1585 return ((rb_imemo_tmpbuf_t *)obj)->ptr != NULL;
1586
1587 case imemo_fields:
1588 return rb_obj_shape_complex_p(obj);
1589 }
1590 UNREACHABLE_RETURN(true);
1591}
1592
1593/*
1594 * Returns true if the object requires a full rb_gc_obj_free() call during sweep,
1595 * false if it can be freed quickly without calling destructors or cleanup.
1596 *
1597 * Objects that return false are:
1598 * - Simple embedded objects without external allocations
1599 * - Objects without finalizers
1600 * - Objects without generic instance variables
1601 *
1602 * This is used by the GC sweep fast path to avoid function call overhead
1603 * for the majority of simple objects.
1604 */
1605bool
1606rb_gc_obj_needs_cleanup_p(VALUE obj)
1607{
1608 VALUE flags = RBASIC(obj)->flags;
1609
1610 if (flags & FL_FINALIZE) return true;
1611
1612 if ((flags & RUBY_T_MASK) == T_IMEMO) {
1613 return rb_gc_imemo_needs_cleanup_p(obj);
1614 }
1615
1616 /* A host with generic fields must drop its table entry when it is freed. The
1617 * process-wide table holds every Ractor's entries, so a sweep cannot bulk-wipe it;
1618 * this per-object cleanup carries the correctness. */
1619 shape_id_t shape_id = RBASIC_SHAPE_ID(obj);
1620 if (rb_shape_has_fields(shape_id) && rb_shape_layout(shape_id) == SHAPE_ID_LAYOUT_OTHER) {
1621 return true;
1622 }
1623
1624 switch (flags & RUBY_T_MASK) {
1625 case T_FLOAT:
1626 case T_RATIONAL:
1627 case T_COMPLEX:
1628 case T_OBJECT:
1629 return false;
1630
1631 case T_FILE:
1632 case T_SYMBOL:
1633 case T_CLASS:
1634 case T_ICLASS:
1635 case T_MODULE:
1636 case T_REGEXP:
1637 return true;
1638
1639 case T_IMEMO:
1640 UNREACHABLE_RETURN(true);
1641
1642 case T_DATA:
1643 {
1644 uintptr_t type = (uintptr_t)RTYPEDDATA(obj)->type;
1645 if (type & TYPED_DATA_EMBEDDED) {
1646 RUBY_DATA_FUNC dfree = ((const rb_data_type_t *)(type & TYPED_DATA_PTR_MASK))->function.dfree;
1647 if (dfree == RUBY_NEVER_FREE || dfree == RUBY_TYPED_DEFAULT_FREE) {
1648 return false;
1649 }
1650 }
1651 }
1652 return true;
1653
1654 case T_STRING:
1655 return (flags & (RSTRING_NOEMBED | RSTRING_FSTR));
1656
1657 case T_ARRAY:
1658 return !(flags & RARRAY_EMBED_FLAG);
1659
1660 case T_HASH:
1661 return (flags & RHASH_ST_TABLE_FLAG);
1662
1663 case T_MATCH:
1664 return (flags & (RMATCH_ONIG | RMATCH_OFFSETS_EXTERNAL)) || USE_DEBUG_COUNTER;
1665
1666 case T_BIGNUM:
1667 return !(flags & BIGNUM_EMBED_FLAG);
1668
1669 case T_STRUCT:
1670 return !(flags & RSTRUCT_EMBED_LEN_MASK);
1671 }
1672
1673 UNREACHABLE_RETURN(true);
1674}
1675
1676static void
1677io_fptr_finalize(void *fptr)
1678{
1679 rb_io_fptr_finalize((struct rb_io *)fptr);
1680}
1681
1682static inline void
1683make_io_zombie(void *objspace, VALUE obj)
1684{
1685 rb_io_t *fptr = RFILE(obj)->fptr;
1686 rb_gc_impl_make_zombie(objspace, obj, io_fptr_finalize, fptr);
1687}
1688
1689static bool
1690rb_data_free(void *objspace, VALUE obj)
1691{
1692 void *data = RTYPEDDATA_GET_DATA(obj);
1693 if (data) {
1694 const rb_data_type_t *type = RTYPEDDATA_TYPE(obj);
1695 void (*dfree)(void *) = type->function.dfree;
1696
1697 if (dfree) {
1698 bool embedded = RTYPEDDATA_EMBEDDED_P(obj);
1699 int free_immediately = (type->flags & (RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_THREAD_SAFE_FREE)) != 0;
1700 bool free_embeddable_data = RB_DATA_TYPE_EMBEDDABLE_P(type) && !embedded;
1701
1702 if (dfree == RUBY_DEFAULT_FREE) {
1703 if (!embedded) {
1704 xfree(data);
1705 RB_DEBUG_COUNTER_INC(obj_data_xfree);
1706 }
1707 }
1708 else if (free_immediately) {
1709 (*dfree)(data);
1710 if (free_embeddable_data) {
1711 xfree(data);
1712 }
1713
1714 RB_DEBUG_COUNTER_INC(obj_data_imm_free);
1715 }
1716 else {
1717 rb_gc_impl_make_zombie(objspace, obj, dfree, data);
1718 RB_DEBUG_COUNTER_INC(obj_data_zombie);
1719 return FALSE;
1720 }
1721 }
1722 else {
1723 RB_DEBUG_COUNTER_INC(obj_data_empty);
1724 }
1725 }
1726
1727 return true;
1728}
1729
1731 VALUE klass;
1732 rb_objspace_t *objspace; // used for update_*
1733};
1734
1735static void
1736classext_free(rb_classext_t *ext, bool is_prime, VALUE box_value, void *arg)
1737{
1738 struct classext_foreach_args *args = (struct classext_foreach_args *)arg;
1739
1740 rb_class_classext_free(args->klass, ext, is_prime);
1741}
1742
1743static void
1744classext_iclass_free(rb_classext_t *ext, bool is_prime, VALUE box_value, void *arg)
1745{
1746 struct classext_foreach_args *args = (struct classext_foreach_args *)arg;
1747
1748 rb_iclass_classext_free(args->klass, ext, is_prime);
1749}
1750
1751bool
1752rb_gc_obj_free(void *objspace, VALUE obj)
1753{
1754 struct classext_foreach_args args;
1755
1756 RB_DEBUG_COUNTER_INC(obj_free);
1757
1758 enum ruby_value_type builtin_type = BUILTIN_TYPE(obj);
1759
1760 if (RUBY_DTRACE_GC_OBJ_FREE_ENABLED()) {
1761 RUBY_DTRACE_GC_OBJ_FREE((void*)obj, RBASIC(obj)->flags);
1762 }
1763
1764 switch (builtin_type) {
1765 case T_NIL:
1766 case T_FIXNUM:
1767 case T_TRUE:
1768 case T_FALSE:
1769 rb_bug("obj_free() called for broken object");
1770 break;
1771 default:
1772 break;
1773 }
1774
1775 switch (builtin_type) {
1776 case T_OBJECT:
1777 break;
1778 case T_MODULE:
1779 case T_CLASS:
1780#if USE_ZJIT
1781 rb_zjit_klass_free(obj);
1782#endif
1783 args.klass = obj;
1784 rb_class_classext_foreach(obj, classext_free, (void *)&args);
1785 if (RCLASS_CLASSEXT_TBL(obj)) {
1786 st_free_table(RCLASS_CLASSEXT_TBL(obj));
1787 }
1788 (void)RB_DEBUG_COUNTER_INC_IF(obj_module_ptr, BUILTIN_TYPE(obj) == T_MODULE);
1789 (void)RB_DEBUG_COUNTER_INC_IF(obj_class_ptr, BUILTIN_TYPE(obj) == T_CLASS);
1790 break;
1791 case T_STRING:
1792 rb_str_free(obj);
1793 break;
1794 case T_ARRAY:
1795 rb_ary_free(obj);
1796 break;
1797 case T_HASH:
1798#if USE_DEBUG_COUNTER
1799 switch (RHASH_SIZE(obj)) {
1800 case 0:
1801 RB_DEBUG_COUNTER_INC(obj_hash_empty);
1802 break;
1803 case 1:
1804 RB_DEBUG_COUNTER_INC(obj_hash_1);
1805 break;
1806 case 2:
1807 RB_DEBUG_COUNTER_INC(obj_hash_2);
1808 break;
1809 case 3:
1810 RB_DEBUG_COUNTER_INC(obj_hash_3);
1811 break;
1812 case 4:
1813 RB_DEBUG_COUNTER_INC(obj_hash_4);
1814 break;
1815 case 5:
1816 case 6:
1817 case 7:
1818 case 8:
1819 RB_DEBUG_COUNTER_INC(obj_hash_5_8);
1820 break;
1821 default:
1822 GC_ASSERT(RHASH_SIZE(obj) > 8);
1823 RB_DEBUG_COUNTER_INC(obj_hash_g8);
1824 }
1825
1826 if (RHASH_AR_TABLE_P(obj)) {
1827 if (RHASH_AR_TABLE(obj) == NULL) {
1828 RB_DEBUG_COUNTER_INC(obj_hash_null);
1829 }
1830 else {
1831 RB_DEBUG_COUNTER_INC(obj_hash_ar);
1832 }
1833 }
1834 else {
1835 RB_DEBUG_COUNTER_INC(obj_hash_st);
1836 }
1837#endif
1838
1839 rb_hash_free(obj);
1840 break;
1841 case T_REGEXP:
1842 if (FL_TEST_RAW(obj, RREGEXP_INITIALIZED)) {
1843 onig_free_body(RREGEXP_PTR(obj));
1844 RB_DEBUG_COUNTER_INC(obj_regexp_ptr);
1845 }
1846 break;
1847 case T_DATA:
1848 if (!rb_data_free(objspace, obj)) return false;
1849 break;
1850 case T_MATCH:
1851 {
1852 struct RMatch *rm = RMATCH(obj);
1853#if USE_DEBUG_COUNTER
1854 if (rm->num_regs >= 8) {
1855 RB_DEBUG_COUNTER_INC(obj_match_ge8);
1856 }
1857 else if (rm->num_regs >= 4) {
1858 RB_DEBUG_COUNTER_INC(obj_match_ge4);
1859 }
1860 else if (rm->num_regs >= 1) {
1861 RB_DEBUG_COUNTER_INC(obj_match_under4);
1862 }
1863#endif
1864 if (FL_TEST_RAW(obj, RMATCH_ONIG)) {
1865 onig_region_free(&rm->as.onig, 0);
1866 }
1867 SIZED_FREE_N(rm->char_offset, rm->char_offset_num_allocated);
1868
1869 RB_DEBUG_COUNTER_INC(obj_match_ptr);
1870 }
1871 break;
1872 case T_FILE:
1873 if (RFILE(obj)->fptr) {
1874 bool closed = rb_io_fptr_finalize_closed(RFILE(obj)->fptr);
1875 if (!closed) make_io_zombie(objspace, obj);
1876 RB_DEBUG_COUNTER_INC(obj_file_ptr);
1877 return closed;
1878 }
1879 break;
1880 case T_RATIONAL:
1881 RB_DEBUG_COUNTER_INC(obj_rational);
1882 break;
1883 case T_COMPLEX:
1884 RB_DEBUG_COUNTER_INC(obj_complex);
1885 break;
1886 case T_MOVED:
1887 break;
1888 case T_ICLASS:
1889 args.klass = obj;
1890
1891 rb_class_classext_foreach(obj, classext_iclass_free, (void *)&args);
1892 if (RCLASS_CLASSEXT_TBL(obj)) {
1893 st_free_table(RCLASS_CLASSEXT_TBL(obj));
1894 }
1895
1896 RB_DEBUG_COUNTER_INC(obj_iclass_ptr);
1897 break;
1898
1899 case T_FLOAT:
1900 RB_DEBUG_COUNTER_INC(obj_float);
1901 break;
1902
1903 case T_BIGNUM:
1904 if (!BIGNUM_EMBED_P(obj) && BIGNUM_DIGITS(obj)) {
1905 SIZED_FREE_N(BIGNUM_DIGITS(obj), BIGNUM_LEN(obj));
1906 RB_DEBUG_COUNTER_INC(obj_bignum_ptr);
1907 }
1908 else {
1909 RB_DEBUG_COUNTER_INC(obj_bignum_embed);
1910 }
1911 break;
1912
1913 case T_NODE:
1914 UNEXPECTED_NODE(obj_free);
1915 break;
1916
1917 case T_STRUCT:
1918 if ((RBASIC(obj)->flags & RSTRUCT_EMBED_LEN_MASK) ||
1919 RSTRUCT(obj)->as.heap.ptr == NULL) {
1920 RB_DEBUG_COUNTER_INC(obj_struct_embed);
1921 }
1922 else {
1923 SIZED_FREE_N(RSTRUCT(obj)->as.heap.ptr, RSTRUCT(obj)->as.heap.len);
1924 RB_DEBUG_COUNTER_INC(obj_struct_ptr);
1925 }
1926 break;
1927
1928 case T_SYMBOL:
1929 RB_DEBUG_COUNTER_INC(obj_symbol);
1930 break;
1931
1932 case T_IMEMO:
1933 rb_imemo_free((VALUE)obj);
1934 break;
1935
1936 default:
1937 rb_bug("gc_sweep(): unknown data type 0x%x(%p) 0x%"PRIxVALUE,
1938 BUILTIN_TYPE(obj), (void*)obj, RBASIC(obj)->flags);
1939 }
1940
1941 if (FL_TEST_RAW(obj, FL_FINALIZE)) {
1942 rb_gc_impl_make_zombie(objspace, obj, 0, 0);
1943 return FALSE;
1944 }
1945 else {
1946 return TRUE;
1947 }
1948}
1949
1950void
1951rb_objspace_set_event_hook(const rb_event_flag_t event)
1952{
1953 /* Only the main objspace may enable the FREEOBJ hook: it runs user callbacks from
1954 * inside the sweep, which is unsafe in a non-main Ractor's lock-free local GC.
1955 * Extending it VM-wide is future work. */
1956 rb_event_flag_t e = event;
1957 const rb_ractor_t *const cr = rb_current_ractor_raw(false);
1958 if (cr != NULL && cr != GET_VM()->ractor.main_ractor) {
1959 e &= ~RUBY_INTERNAL_EVENT_FREEOBJ;
1960 }
1961 rb_gc_impl_set_event_hook(rb_gc_get_objspace(), e);
1962}
1963
1964static int
1965internal_object_p(VALUE obj)
1966{
1967 void *ptr = asan_unpoison_object_temporary(obj);
1968
1969 if (RBASIC(obj)->flags) {
1970 switch (BUILTIN_TYPE(obj)) {
1971 case T_NODE:
1972 UNEXPECTED_NODE(internal_object_p);
1973 break;
1974 case T_NONE:
1975 case T_MOVED:
1976 case T_IMEMO:
1977 case T_ICLASS:
1978 case T_ZOMBIE:
1979 break;
1980 case T_CLASS:
1981 if (obj == rb_mRubyVMFrozenCore)
1982 return 1;
1983
1984 if (!RBASIC_CLASS(obj)) break;
1985 if (RCLASS_SINGLETON_P(obj)) {
1986 return rb_singleton_class_internal_p(obj);
1987 }
1988 return 0;
1989 default:
1990 if (!RBASIC(obj)->klass) break;
1991 return 0;
1992 }
1993 }
1994 if (ptr || !RBASIC(obj)->flags) {
1995 rb_asan_poison_object(obj);
1996 }
1997 return 1;
1998}
1999
2000int
2001rb_objspace_internal_object_p(VALUE obj)
2002{
2003 return internal_object_p(obj);
2004}
2005
2007 size_t num;
2008 VALUE of;
2009};
2010
2011static int
2012os_obj_of_i(void *vstart, void *vend, size_t stride, void *data)
2013{
2014 struct os_each_struct *oes = (struct os_each_struct *)data;
2015
2016 VALUE v = (VALUE)vstart;
2017 for (; v != (VALUE)vend; v += stride) {
2018 if (!internal_object_p(v)) {
2019 if (!oes->of || rb_obj_is_kind_of(v, oes->of)) {
2020 rb_yield(v);
2021 oes->num++;
2022 }
2023 }
2024 }
2025
2026 return 0;
2027}
2028
2029/* Like os_obj_of_i but collects into an array: foreign shareable objects are walked
2030 * under the barrier, where yielding is unsafe (see os_obj_of). Pure C, allocates no
2031 * object (rb_ary_push only grows the buffer), so it reaches no safepoint. */
2033 VALUE of;
2034 VALUE buffer;
2035};
2036
2037static int
2038os_shareable_collect_i(void *vstart, void *vend, size_t stride, void *data)
2039{
2040 struct os_shareable_collect_struct *ocs = (struct os_shareable_collect_struct *)data;
2041
2042 VALUE v = (VALUE)vstart;
2043 for (; v != (VALUE)vend; v += stride) {
2044 /* We walk a foreign Ractor's objspace, so collect only shareable objects. The
2045 * walk already filters on shareable_bits; check again so an unshareable object
2046 * can never be exposed. */
2047 if (rb_ractor_shareable_p(v) && !internal_object_p(v)) {
2048 if (!ocs->of || rb_obj_is_kind_of(v, ocs->of)) {
2049 rb_ary_push(ocs->buffer, v);
2050 }
2051 }
2052 }
2053
2054 return 0;
2055}
2056
2057static void rb_gc_critical_disable(void);
2058static void rb_gc_critical_enable(void);
2059
2060static VALUE
2061os_obj_of(VALUE of)
2062{
2063 struct os_each_struct oes;
2064
2065 oes.num = 0;
2066 oes.of = of;
2067
2068 /* Phase 1: our own Ractor's objspace, yielding every object directly with no
2069 * barrier. The walk snapshots the page list and tolerates pages being freed
2070 * concurrently, so no VM lock is needed and the block may allocate, GC or block. */
2071 rb_gc_impl_each_objects(rb_gc_get_objspace(), os_obj_of_i, &oes);
2072
2073 /* Phase 2 (multi-Ractor): other live Ractors' shareable objects, readable only
2074 * under the barrier (where a user block must not run), so collect them in pure C
2075 * with GC disabled and yield after the barrier is released. */
2076 if (rb_multi_ractor_p()) {
2077 struct os_shareable_collect_struct ocs;
2078 ocs.of = of;
2079 ocs.buffer = rb_ary_new();
2080
2081 rb_gc_critical_disable();
2082 RB_VM_LOCKING() {
2083 rb_vm_barrier();
2084
2085 void *self = rb_gc_get_objspace();
2086 rb_vm_t *vm = GET_VM();
2087 rb_ractor_t *r;
2088 ccan_list_for_each(&vm->ractor.set, r, vmlr_node) {
2089 if (r->objspace && r->objspace != self) {
2090 rb_gc_impl_each_objects_shareable(r->objspace, os_shareable_collect_i, &ocs);
2091 }
2092 }
2093 }
2094 rb_gc_critical_enable();
2095
2096 long len = RARRAY_LEN(ocs.buffer);
2097 for (long i = 0; i < len; i++) {
2098 rb_yield(RARRAY_AREF(ocs.buffer, i));
2099 oes.num++;
2100 }
2101 RB_GC_GUARD(ocs.buffer);
2102 }
2103
2104 return SIZET2NUM(oes.num);
2105}
2106
2107/*
2108 * call-seq:
2109 * ObjectSpace.each_object {|obj| ... } -> integer
2110 * ObjectSpace.each_object(module) {|obj| ... } -> integer
2111 * ObjectSpace.each_object -> enumerator
2112 * ObjectSpace.each_object(module) -> enumerator
2113 *
2114 * Calls the block once for each living, non-immediate object in this Ruby
2115 * process, and returns the number of objects found.
2116 *
2117 * If +module+ is given, calls the block only for objects that are an instance
2118 * of +module+ or one of its subclasses.
2119 *
2120 * Immediate objects (such as small integers, static symbols, +true+, +false+,
2121 * and +nil+) are never yielded.
2122 *
2123 * With no block given, returns a new Enumerator.
2124 *
2125 * Job = Class.new
2126 * jobs = [Job.new, Job.new]
2127 * count = ObjectSpace.each_object(Job) {|x| p x }
2128 * puts "Total count: #{count}"
2129 *
2130 * <em>produces:</em>
2131 *
2132 * #<Job:0x000000011d6cbbf0>
2133 * #<Job:0x000000011d6cbc68>
2134 * Total count: 2
2135 *
2136 * Because every live object is visited, this method is mainly useful for
2137 * debugging, profiling, and introspecting a running process.
2138 *
2139 * In multi-Ractor mode this method yields every object of the current Ractor, plus
2140 * the objects of the other Ractors that have been made Ractor-shareable. Another
2141 * Ractor's unshareable objects are never yielded: they belong to that Ractor and the
2142 * current one must not touch them.
2143 *
2144 * c = {} # not shareable, belongs to the main Ractor
2145 * r = Ractor.new { d = {}; receive } # d belongs to r
2146 * ObjectSpace.each_object {|x| x } # yields c, but not d
2147 *
2148 */
2149
2150static VALUE
2151os_each_obj(int argc, VALUE *argv, VALUE os)
2152{
2153 VALUE of;
2154
2155 of = (!rb_check_arity(argc, 0, 1) ? 0 : argv[0]);
2156 RETURN_ENUMERATOR(os, 1, &of);
2157 return os_obj_of(of);
2158}
2159
2160/*
2161 * call-seq:
2162 * ObjectSpace.undefine_finalizer(obj) -> obj
2163 *
2164 * Removes all finalizers registered for +obj+ with
2165 * ObjectSpace.define_finalizer, and returns +obj+.
2166 *
2167 * Does nothing if +obj+ has no finalizers.
2168 */
2169
2170static VALUE
2171undefine_final(VALUE os, VALUE obj)
2172{
2173 return rb_undefine_finalizer(obj);
2174}
2175
2176VALUE
2177rb_undefine_finalizer(VALUE obj)
2178{
2179 rb_check_frozen(obj);
2180
2181 rb_gc_impl_undefine_finalizer(rb_gc_get_objspace(), obj);
2182
2183 return obj;
2184}
2185
2186static void
2187should_be_callable(VALUE block)
2188{
2189 if (!rb_obj_respond_to(block, idCall, TRUE)) {
2190 rb_raise(rb_eArgError, "wrong type argument %"PRIsVALUE" (should be callable)",
2191 rb_obj_class(block));
2192 }
2193}
2194
2195static void
2196should_be_finalizable(VALUE obj)
2197{
2198 if (!FL_ABLE(obj)) {
2199 rb_raise(rb_eArgError, "cannot define finalizer for %s",
2200 rb_obj_classname(obj));
2201 }
2202 rb_check_frozen(obj);
2203}
2204
2205void
2206rb_gc_copy_finalizer(VALUE dest, VALUE obj)
2207{
2208 rb_gc_impl_copy_finalizer(rb_gc_get_objspace(), dest, obj);
2209}
2210
2211/*
2212 * call-seq:
2213 * ObjectSpace.define_finalizer(obj) {|id| ... } -> array
2214 * ObjectSpace.define_finalizer(obj, finalizer) -> array
2215 *
2216 * Adds a new finalizer for +obj+ that is called when +obj+ is destroyed
2217 * by the garbage collector or when Ruby shuts down (which ever comes first).
2218 *
2219 * With a block given, uses the block as the callback. Without a block given,
2220 * uses a callable object +finalizer+ as the callback. The callback is called
2221 * when +obj+ is destroyed with a single argument +id+ which is the object
2222 * ID of +obj+ (see Object#object_id).
2223 *
2224 * The return value is an array <code>[0, callback]</code>, where +callback+
2225 * is a Proc created from the block if one was given or +finalizer+ otherwise.
2226 *
2227 * Note that defining a finalizer in an instance method of the object may prevent
2228 * the object from being garbage collected since if the block or +finalizer+ refers
2229 * to +obj+ then +obj+ will never be reclaimed by the garbage collector. For example,
2230 * the following script demonstrates the issue:
2231 *
2232 * class Foo
2233 * def define_final
2234 * ObjectSpace.define_finalizer(self) do |id|
2235 * puts "Running finalizer for #{id}!"
2236 * end
2237 * end
2238 * end
2239 *
2240 * obj = Foo.new
2241 * obj.define_final
2242 *
2243 * There are two patterns to solve this issue:
2244 *
2245 * - Create the finalizer in a non-instance method so it can safely capture
2246 * the needed state:
2247 *
2248 * class Foo
2249 * def define_final
2250 * ObjectSpace.define_finalizer(self, self.class.create_finalizer)
2251 * end
2252 *
2253 * def self.create_finalizer
2254 * proc do |id|
2255 * puts "Running finalizer for #{id}!"
2256 * end
2257 * end
2258 * end
2259 *
2260 * - Use a callable object:
2261 *
2262 * class Foo
2263 * class Finalizer
2264 * def call(id)
2265 * puts "Running finalizer for #{id}!"
2266 * end
2267 * end
2268 *
2269 * def define_final
2270 * ObjectSpace.define_finalizer(self, Finalizer.new)
2271 * end
2272 * end
2273 *
2274 * Note that finalization can be unpredictable and is never guaranteed
2275 * to be run except on exit.
2276 */
2277
2278static VALUE
2279define_final(int argc, VALUE *argv, VALUE os)
2280{
2281 VALUE obj, block;
2282
2283 rb_scan_args(argc, argv, "11", &obj, &block);
2284 if (argc == 1) {
2285 block = rb_block_proc();
2286 }
2287
2288 if (rb_callable_receiver(block) == obj) {
2289 rb_warn("finalizer references object to be finalized");
2290 }
2291
2292 return rb_define_finalizer(obj, block);
2293}
2294
2295VALUE
2296rb_define_finalizer(VALUE obj, VALUE block)
2297{
2298 should_be_finalizable(obj);
2299 should_be_callable(block);
2300
2301 block = rb_gc_impl_define_finalizer(rb_gc_get_objspace(), obj, block);
2302
2303 block = rb_ary_new3(2, INT2FIX(0), block);
2304 OBJ_FREEZE(block);
2305 return block;
2306}
2307
2308void
2309rb_objspace_call_finalizer(void)
2310{
2311 rb_gc_impl_shutdown_call_finalizer(rb_gc_get_objspace());
2312}
2313
2314void
2315rb_objspace_free_objects(void *objspace)
2316{
2317 rb_gc_impl_shutdown_free_objects(objspace);
2318}
2319
2320int
2321rb_objspace_garbage_object_p(VALUE obj)
2322{
2323 return !SPECIAL_CONST_P(obj) && rb_gc_impl_garbage_object_p(rb_gc_get_objspace(), obj);
2324}
2325
2326int
2327rb_objspace_foreign_object_p(VALUE obj)
2328{
2329 return !SPECIAL_CONST_P(obj) && rb_gc_obj_foreign_p(obj);
2330}
2331
2332#define OBJ_ID_INCREMENT (RUBY_IMMEDIATE_MASK + 1)
2333#define LAST_OBJECT_ID() (object_id_counter * OBJ_ID_INCREMENT)
2334
2335#if SIZEOF_SIZE_T == SIZEOF_LONG_LONG
2336static size_t object_id_counter = 1;
2337#else
2338static unsigned long long object_id_counter = 1;
2339#endif
2340
2341static inline VALUE
2342generate_next_object_id(void)
2343{
2344#if SIZEOF_SIZE_T == SIZEOF_LONG_LONG
2345 // 64bit atomics are available
2346 return SIZET2NUM(RUBY_ATOMIC_SIZE_FETCH_ADD(object_id_counter, 1) * OBJ_ID_INCREMENT);
2347#else
2348 unsigned int lock_lev = RB_GC_VM_LOCK();
2349 VALUE id = ULL2NUM(++object_id_counter * OBJ_ID_INCREMENT);
2350 RB_GC_VM_UNLOCK(lock_lev);
2351 return id;
2352#endif
2353}
2354
2355static VALUE
2356class_object_id(VALUE klass)
2357{
2358 VALUE id = RUBY_ATOMIC_VALUE_LOAD(RCLASS(klass)->object_id);
2359 if (!id) {
2360 unsigned int lock_lev = RB_GC_VM_LOCK();
2361 id = generate_next_object_id();
2362 VALUE existing_id = RUBY_ATOMIC_VALUE_CAS(RCLASS(klass)->object_id, 0, id);
2363 if (existing_id) {
2364 id = existing_id;
2365 }
2366 RB_GC_VM_UNLOCK(lock_lev);
2367 }
2368 return id;
2369}
2370
2371static inline VALUE
2372object_id_get(VALUE obj, shape_id_t shape_id)
2373{
2374 VALUE id;
2375 if (rb_shape_complex_p(shape_id)) {
2376 id = rb_obj_field_get(obj, ROOT_COMPLEX_WITH_OBJ_ID);
2377 }
2378 else {
2379 id = rb_obj_field_get(obj, rb_shape_object_id(shape_id));
2380 }
2381
2382#if RUBY_DEBUG
2383 if (!(FIXNUM_P(id) || RB_TYPE_P(id, T_BIGNUM))) {
2384 rb_p(obj);
2385 rb_bug("Object's shape includes object_id, but it's missing %s", rb_obj_info(obj));
2386 }
2387#endif
2388
2389 return id;
2390}
2391
2392static VALUE
2393object_id0(VALUE obj)
2394{
2395 VALUE id = Qfalse;
2396 shape_id_t shape_id = RBASIC_SHAPE_ID(obj);
2397
2398 if (rb_shape_has_object_id(shape_id)) {
2399 return object_id_get(obj, shape_id);
2400 }
2401
2402 shape_id_t object_id_shape_id = rb_obj_shape_transition_object_id(obj);
2403
2404 id = generate_next_object_id();
2405 rb_obj_field_set(obj, object_id_shape_id, 0, id);
2406
2407 RUBY_ASSERT(rb_obj_shape_has_id(obj));
2408
2409 return id;
2410}
2411
2412static VALUE
2413object_id(VALUE obj)
2414{
2415 switch (BUILTIN_TYPE(obj)) {
2416 case T_CLASS:
2417 case T_MODULE:
2418 // With Ruby Box, classes and modules have different fields
2419 // in different boxes, so we cannot store the object id
2420 // in fields.
2421 return class_object_id(obj);
2422 case T_IMEMO:
2423 RUBY_ASSERT(IMEMO_TYPE_P(obj, imemo_fields));
2424 break;
2425 default:
2426 break;
2427 }
2428
2429 if (UNLIKELY(rb_gc_multi_ractor_p() && rb_ractor_shareable_p(obj))) {
2430 unsigned int lock_lev = RB_GC_VM_LOCK();
2431 VALUE id = object_id0(obj);
2432 RB_GC_VM_UNLOCK(lock_lev);
2433 return id;
2434 }
2435
2436 return object_id0(obj);
2437}
2438
2439void
2440rb_gc_obj_free_vm_weak_references(VALUE obj)
2441{
2443
2444 /* Drop a generic-fields entry when its host's slot is freed. The table is
2445 * process-wide, so no sweep bulk-wipes it; a stale entry would let the global GC's
2446 * weak pass (or a reader after the slot is reused) walk a freed page. */
2447 if (rb_obj_gen_fields_p(obj)) {
2449 }
2450
2451 switch (BUILTIN_TYPE(obj)) {
2452 case T_STRING:
2453 if (FL_TEST_RAW(obj, RSTRING_FSTR)) {
2454 rb_gc_free_fstring(obj);
2455 }
2456 break;
2457 case T_SYMBOL:
2458 rb_gc_free_dsymbol(obj);
2459 break;
2460 case T_IMEMO:
2461 switch (imemo_type(obj)) {
2462 case imemo_callinfo:
2463 rb_vm_ci_free((const struct rb_callinfo *)obj);
2464 break;
2465 case imemo_ment:
2466 rb_free_method_entry_vm_weak_references((const rb_method_entry_t *)obj);
2467 break;
2468 default:
2469 break;
2470 }
2471 break;
2472 default:
2473 break;
2474 }
2475}
2476
2477static VALUE
2478rb_find_object_id(void *objspace, VALUE obj, VALUE (*get_heap_object_id)(VALUE))
2479{
2480 if (SPECIAL_CONST_P(obj)) {
2481#if SIZEOF_LONG == SIZEOF_VOIDP
2482 return LONG2NUM((SIGNED_VALUE)obj);
2483#else
2484 return LL2NUM((SIGNED_VALUE)obj);
2485#endif
2486 }
2487
2488 return get_heap_object_id(obj);
2489}
2490
2491static VALUE
2492nonspecial_obj_id(VALUE obj)
2493{
2494#if SIZEOF_LONG == SIZEOF_VOIDP
2495 return (VALUE)((SIGNED_VALUE)(obj)|FIXNUM_FLAG);
2496#elif SIZEOF_LONG_LONG == SIZEOF_VOIDP
2497 return LL2NUM((SIGNED_VALUE)(obj) / 2);
2498#else
2499# error not supported
2500#endif
2501}
2502
2503VALUE
2504rb_memory_id(VALUE obj)
2505{
2506 return rb_find_object_id(NULL, obj, nonspecial_obj_id);
2507}
2508
2509/*
2510 * Document-method: __id__
2511 * Document-method: object_id
2512 *
2513 * call-seq:
2514 * obj.__id__ -> integer
2515 * obj.object_id -> integer
2516 *
2517 * Returns an integer identifier for +obj+.
2518 *
2519 * The same number will be returned on all calls to +object_id+ for a given
2520 * object, and no two active objects will share an id.
2521 *
2522 * Note: that some objects of builtin classes are reused for optimization.
2523 * This is the case for immediate values and frozen string literals.
2524 *
2525 * BasicObject implements +__id__+, Kernel implements +object_id+.
2526 *
2527 * Immediate values are not passed by reference but are passed by value:
2528 * +nil+, +true+, +false+, Fixnums, Symbols, and some Floats.
2529 *
2530 * Object.new.object_id == Object.new.object_id # => false
2531 * (21 * 2).object_id == (21 * 2).object_id # => true
2532 * "hello".object_id == "hello".object_id # => false
2533 * "hi".freeze.object_id == "hi".freeze.object_id # => true
2534 */
2535
2536VALUE
2537rb_obj_id(VALUE obj)
2538{
2539 /* If obj is an immediate, the object ID is obj directly converted to a Numeric.
2540 * Otherwise, the object ID is a Numeric that is a non-zero multiple of
2541 * (RUBY_IMMEDIATE_MASK + 1) which guarantees that it does not collide with
2542 * any immediates. */
2543 return rb_find_object_id(rb_gc_get_objspace(), obj, object_id);
2544}
2545
2546bool
2547rb_obj_id_p(VALUE obj)
2548{
2549 return !RB_TYPE_P(obj, T_IMEMO) && rb_obj_shape_has_id(obj);
2550}
2551
2552/*
2553 * GC implementations should call this function before the GC phase that updates references
2554 * embedded in the machine code generated by JIT compilers. JIT compilers usually enforce the
2555 * "W^X" policy and protect the code memory from being modified during execution. This function
2556 * makes the code memory writeable.
2557 */
2558void
2559rb_gc_before_updating_jit_code(void)
2560{
2561#if USE_YJIT
2562 rb_yjit_mark_all_writeable();
2563#endif
2564#if USE_ZJIT
2565 rb_zjit_mark_all_writable();
2566#endif
2567}
2568
2569/*
2570 * GC implementations should call this function before the GC phase that updates references
2571 * embedded in the machine code generated by JIT compilers. This function makes the code memory
2572 * executable again.
2573 */
2574void
2575rb_gc_after_updating_jit_code(void)
2576{
2577#if USE_YJIT
2578 rb_yjit_mark_all_executable();
2579#endif
2580#if USE_ZJIT
2581 rb_zjit_mark_all_executable();
2582#endif
2583}
2584
2585static void
2586classext_memsize(rb_classext_t *ext, bool prime, VALUE box_value, void *arg)
2587{
2588 size_t *size = (size_t *)arg;
2589 size_t s = 0;
2590
2591 if (RCLASSEXT_M_TBL(ext)) {
2592 s += rb_id_table_memsize(RCLASSEXT_M_TBL(ext));
2593 }
2594 if (RCLASSEXT_CONST_TBL(ext)) {
2595 s += rb_id_table_memsize(RCLASSEXT_CONST_TBL(ext));
2596 }
2597 if (RCLASSEXT_SUPERCLASSES_WITH_SELF(ext)) {
2598 s += (RCLASSEXT_SUPERCLASS_DEPTH(ext) + 1) * sizeof(VALUE);
2599 }
2600 if (!prime) {
2601 s += sizeof(rb_classext_t);
2602 }
2603 *size += s;
2604}
2605
2606static void
2607classext_superclasses_memsize(rb_classext_t *ext, bool prime, VALUE box_value, void *arg)
2608{
2609 size_t *size = (size_t *)arg;
2610 size_t array_size;
2611 if (RCLASSEXT_SUPERCLASSES_WITH_SELF(ext)) {
2612 RUBY_ASSERT(prime);
2613 array_size = RCLASSEXT_SUPERCLASS_DEPTH(ext) + 1;
2614 *size += array_size * sizeof(VALUE);
2615 }
2616}
2617
2618size_t
2619rb_obj_memsize_of(VALUE obj)
2620{
2621 size_t size = 0;
2622
2623 if (SPECIAL_CONST_P(obj)) {
2624 return 0;
2625 }
2626
2627 switch (BUILTIN_TYPE(obj)) {
2628 case T_OBJECT:
2629 break;
2630 case T_MODULE:
2631 case T_CLASS:
2632 rb_class_classext_foreach(obj, classext_memsize, (void *)&size);
2633 rb_class_classext_foreach(obj, classext_superclasses_memsize, (void *)&size);
2634 break;
2635 case T_ICLASS:
2636 if (RICLASS_OWNS_M_TBL_P(obj)) {
2637 if (RCLASS_M_TBL(obj)) {
2638 size += rb_id_table_memsize(RCLASS_M_TBL(obj));
2639 }
2640 }
2641 break;
2642 case T_STRING:
2643 size += rb_str_memsize(obj);
2644 break;
2645 case T_ARRAY:
2646 size += rb_ary_memsize(obj);
2647 break;
2648 case T_HASH:
2649 if (RHASH_ST_TABLE_P(obj)) {
2650 VM_ASSERT(RHASH_ST_TABLE(obj) != NULL);
2651 /* st_table is in the slot */
2652 size += st_memsize(RHASH_ST_TABLE(obj)) - sizeof(st_table);
2653 }
2654 break;
2655 case T_REGEXP:
2656 if (RREGEXP_PTR(obj)) {
2657 size += onig_memsize(RREGEXP_PTR(obj));
2658 }
2659 break;
2660 case T_DATA:
2661 size += rb_objspace_data_type_memsize(obj);
2662 break;
2663 case T_MATCH:
2664 {
2665 struct RMatch *rm = RMATCH(obj);
2666 if (FL_TEST_RAW(obj, RMATCH_ONIG)) {
2667 size += onig_region_memsize(&rm->as.onig);
2668 }
2669 size += sizeof(struct rmatch_offset) * rm->char_offset_num_allocated;
2670 }
2671 break;
2672 case T_FILE:
2673 if (RFILE(obj)->fptr) {
2674 size += rb_io_memsize(RFILE(obj)->fptr);
2675 }
2676 break;
2677 case T_RATIONAL:
2678 case T_COMPLEX:
2679 break;
2680 case T_IMEMO:
2681 size += rb_imemo_memsize(obj);
2682 break;
2683
2684 case T_FLOAT:
2685 case T_SYMBOL:
2686 break;
2687
2688 case T_BIGNUM:
2689 if (!(RBASIC(obj)->flags & BIGNUM_EMBED_FLAG) && BIGNUM_DIGITS(obj)) {
2690 size += BIGNUM_LEN(obj) * sizeof(BDIGIT);
2691 }
2692 break;
2693
2694 case T_NODE:
2695 UNEXPECTED_NODE(obj_memsize_of);
2696 break;
2697
2698 case T_STRUCT:
2699 if (RSTRUCT_EMBED_LEN(obj) == 0) {
2700 size += sizeof(VALUE) * RSTRUCT_LEN_RAW(obj);
2701 }
2702 break;
2703
2704 case T_ZOMBIE:
2705 case T_MOVED:
2706 break;
2707
2708 default:
2709 rb_bug("objspace/memsize_of(): unknown data type 0x%x(%p)",
2710 BUILTIN_TYPE(obj), (void*)obj);
2711 }
2712
2713 return size + rb_gc_obj_slot_size(obj);
2714}
2715
2716static int
2717set_zero(st_data_t key, st_data_t val, st_data_t arg)
2718{
2719 VALUE k = (VALUE)key;
2720 VALUE hash = (VALUE)arg;
2721 rb_hash_aset(hash, k, INT2FIX(0));
2722 return ST_CONTINUE;
2723}
2724
2726 size_t counts[T_MASK+1];
2727 size_t freed;
2728 size_t total;
2729};
2730
2731static void
2732count_objects_i(VALUE obj, void *d)
2733{
2734 struct count_objects_data *data = (struct count_objects_data *)d;
2735
2736 if (RBASIC(obj)->flags) {
2737 data->counts[BUILTIN_TYPE(obj)]++;
2738 }
2739 else {
2740 data->freed++;
2741 }
2742
2743 data->total++;
2744}
2745
2746/*
2747 * call-seq:
2748 * ObjectSpace.count_objects(result_hash = {}) -> hash
2749 *
2750 * Counts the number of objects, grouped by type.
2751 *
2752 * It returns a hash that looks like:
2753 *
2754 * {
2755 * TOTAL: 10000,
2756 * FREE: 3011,
2757 * T_OBJECT: 6,
2758 * T_CLASS: 404,
2759 * # ...
2760 * }
2761 *
2762 * The contents of the returned hash are implementation specific and
2763 * may be changed in future versions without notice.
2764 *
2765 * The keys starting with +:T_+ are live objects of a particular type.
2766 * For example, +:T_ARRAY+ is the number of arrays.
2767 *
2768 * The key +:FREE+ is the number of object slots which are empty.
2769 *
2770 * The key +:TOTAL+ is the total number of slots (which is the sum of
2771 * all of the other values).
2772 *
2773 * If the optional argument +result_hash+ is given,
2774 * it is overwritten and returned.
2775 * This is intended to avoid the probe effect.
2776 *
2777 * h = {}
2778 * ObjectSpace.count_objects(h)
2779 * puts h
2780 * # => { TOTAL: 10000, T_CLASS: 158280, T_MODULE: 20672, T_STRING: 527249 }
2781 *
2782 * This method is only expected to work on C Ruby.
2783 *
2784 */
2785
2786static VALUE
2787count_objects(int argc, VALUE *argv, VALUE os)
2788{
2789 struct count_objects_data data = { 0 };
2790 VALUE hash = Qnil;
2791 VALUE types[T_MASK + 1];
2792
2793 if (rb_check_arity(argc, 0, 1) == 1) {
2794 hash = argv[0];
2795 if (!RB_TYPE_P(hash, T_HASH))
2796 rb_raise(rb_eTypeError, "non-hash given");
2797 }
2798
2799 for (size_t i = 0; i <= T_MASK; i++) {
2800 // type_sym can allocate an object,
2801 // so we need to create all key symbols in advance
2802 // not to disturb the result
2803 types[i] = type_sym(i);
2804 }
2805
2806 // Same as type_sym, we need to create all key symbols in advance
2807 VALUE total = ID2SYM(rb_intern("TOTAL"));
2808 VALUE free = ID2SYM(rb_intern("FREE"));
2809
2810 rb_gc_impl_each_object(rb_gc_get_objspace(), count_objects_i, &data);
2811
2812 if (NIL_P(hash)) {
2813 hash = rb_hash_new_capa(2 + T_MASK);
2814 }
2815 else if (!RHASH_EMPTY_P(hash)) {
2816 rb_hash_stlike_foreach(hash, set_zero, hash);
2817 }
2818 rb_hash_aset(hash, total, SIZET2NUM(data.total));
2819 rb_hash_aset(hash, free, SIZET2NUM(data.freed));
2820
2821 for (size_t i = 0; i <= T_MASK; i++) {
2822 if (data.counts[i]) {
2823 rb_hash_aset(hash, types[i], SIZET2NUM(data.counts[i]));
2824 }
2825 }
2826
2827 return hash;
2828}
2829
2830#define SET_STACK_END SET_MACHINE_STACK_END(&ec->machine.stack_end)
2831
2832#define STACK_START (ec->machine.stack_start)
2833#define STACK_END (ec->machine.stack_end)
2834#define STACK_LEVEL_MAX (ec->machine.stack_maxsize/sizeof(VALUE))
2835
2836#if STACK_GROW_DIRECTION < 0
2837# define STACK_LENGTH (size_t)(STACK_START - STACK_END)
2838#elif STACK_GROW_DIRECTION > 0
2839# define STACK_LENGTH (size_t)(STACK_END - STACK_START + 1)
2840#else
2841# define STACK_LENGTH ((STACK_END < STACK_START) ? (size_t)(STACK_START - STACK_END) \
2842 : (size_t)(STACK_END - STACK_START + 1))
2843#endif
2844#if !STACK_GROW_DIRECTION
2845int ruby_stack_grow_direction;
2846int
2847ruby_get_stack_grow_direction(volatile VALUE *addr)
2848{
2849 VALUE *end;
2850 SET_MACHINE_STACK_END(&end);
2851
2852 if (end > addr) return ruby_stack_grow_direction = 1;
2853 return ruby_stack_grow_direction = -1;
2854}
2855#endif
2856
2857size_t
2859{
2860 rb_execution_context_t *ec = GET_EC();
2861 SET_STACK_END;
2862 if (p) *p = STACK_UPPER(STACK_END, STACK_START, STACK_END);
2863 return STACK_LENGTH;
2864}
2865
2866#define PREVENT_STACK_OVERFLOW 1
2867#ifndef PREVENT_STACK_OVERFLOW
2868#if !(defined(POSIX_SIGNAL) && defined(SIGSEGV) && defined(HAVE_SIGALTSTACK))
2869# define PREVENT_STACK_OVERFLOW 1
2870#else
2871# define PREVENT_STACK_OVERFLOW 0
2872#endif
2873#endif
2874#if PREVENT_STACK_OVERFLOW && !defined(__EMSCRIPTEN__)
2875static int
2876stack_check(rb_execution_context_t *ec, int water_mark)
2877{
2878 SET_STACK_END;
2879
2880 size_t length = STACK_LENGTH;
2881 if (STACK_LEVEL_MAX == 0) return FALSE; /* unknown maxsize */
2882 if (STACK_LEVEL_MAX <= (size_t)water_mark) return TRUE;
2883 size_t maximum_length = STACK_LEVEL_MAX - water_mark;
2884
2885 return length > maximum_length;
2886}
2887#else
2888#define stack_check(ec, water_mark) FALSE
2889#endif
2890
2891#ifdef RUBY_ASAN_ENABLED
2892/* Unoptimized, instrumented VM frames can exceed the usual 16KB reserve. */
2893# define STACKFRAME_FOR_CALL_CFUNC (128 * 1024 / sizeof(VALUE))
2894#else
2895# define STACKFRAME_FOR_CALL_CFUNC 2048
2896#endif
2897
2898int
2899rb_ec_stack_check(rb_execution_context_t *ec)
2900{
2901 return stack_check(ec, STACKFRAME_FOR_CALL_CFUNC);
2902}
2903
2904int
2906{
2907 return stack_check(GET_EC(), STACKFRAME_FOR_CALL_CFUNC);
2908}
2909
2910/* ==================== Marking ==================== */
2911
2912/* The traversal mark redirect is per-Ractor so a real GC never observes a
2913 * foreign traversal's redirect (a VM-global slot would divert another Ractor's
2914 * concurrent GC mark into obj_traverse recursion). Only threads with no
2915 * current Ractor (modular GC's marking worker threads) fall back to the VM
2916 * slot, which no setter writes, so they always take the real mark path. */
2917static inline struct gc_mark_func_data_struct **
2918gc_mark_func_data_slotp_of(rb_ractor_t *const cr)
2919{
2920#if USE_MODULAR_GC
2921 return cr != NULL ? &cr->mark_func_data : &GET_VM()->gc.mark_func_data;
2922#else
2923 RUBY_ASSERT(cr != NULL);
2924 return &cr->mark_func_data;
2925#endif
2926}
2927#define GC_MARK_FUNC_DATA_SLOTP() gc_mark_func_data_slotp_of(rb_current_ractor_raw(false))
2928
2929/* Resolve the current Ractor once for a whole marking walk. rb_current_ractor_raw() is an
2930 * out-of-line rb_current_ec() call wherever RB_THREAD_CURRENT_EC_NOINLINE is set (arm64), so
2931 * the walk threads this ctx down rather than repeating the lookup per reference. */
2932static inline struct rb_gc_mark_ctx
2933gc_current_mark_ctx(void)
2934{
2935 rb_ractor_t *const cr = rb_current_ractor_raw(false);
2936 struct gc_mark_func_data_struct **const mfdp = gc_mark_func_data_slotp_of(cr);
2937
2938 return (struct rb_gc_mark_ctx){
2939 .objspace = gc_current_objspace_of(cr),
2940 .mfdp = mfdp,
2941 /* A walk's mfd is installed before it starts and restored after, so the flag cannot
2942 * change under us -- unlike *mfdp, which the redirect below clears and restores
2943 * around each mark_func call. */
2944 .checking_shareable = *mfdp != NULL && (*mfdp)->checking_shareable,
2945 };
2946}
2947
2948#define RB_GC_MARK_OR_TRAVERSE(ctx, func, obj_or_ptr, obj, check_obj) do { \
2949 if (!RB_SPECIAL_CONST_P(obj)) { \
2950 struct gc_mark_func_data_struct **mfdp = (ctx)->mfdp; \
2951 struct gc_mark_func_data_struct *mark_func_data = *mfdp; \
2952 void *objspace = (ctx)->objspace; \
2953 if (LIKELY(mark_func_data == NULL)) { \
2954 GC_ASSERT(rb_gc_impl_during_gc_p(objspace)); \
2955 (func)(objspace, (obj_or_ptr)); \
2956 } \
2957 else if (check_obj ? \
2958 rb_gc_impl_live_object_p(objspace, (const void *)obj) && \
2959 !rb_gc_impl_garbage_object_p(objspace, obj) : \
2960 true) { \
2961 GC_ASSERT(!rb_gc_impl_during_gc_p(objspace)); \
2962 *mfdp = NULL; \
2963 mark_func_data->mark_func((obj), mark_func_data->data); \
2964 *mfdp = mark_func_data; \
2965 } \
2966 } \
2967} while (0)
2968
2969static inline void
2970gc_mark_internal(const struct rb_gc_mark_ctx *ctx, VALUE obj)
2971{
2972 RB_GC_MARK_OR_TRAVERSE(ctx, rb_gc_impl_mark, obj, obj, false);
2973}
2974
2975static inline void
2976gc_mark_and_pin_internal(const struct rb_gc_mark_ctx *ctx, VALUE obj)
2977{
2978 RB_GC_MARK_OR_TRAVERSE(ctx, rb_gc_impl_mark_and_pin, obj, obj, false);
2979}
2980
2981static inline void
2982gc_mark_maybe_internal(const struct rb_gc_mark_ctx *ctx, VALUE obj)
2983{
2984 RB_GC_MARK_OR_TRAVERSE(ctx, rb_gc_impl_mark_maybe, obj, obj, true);
2985}
2986
2987static inline void
2988gc_mark_and_move_internal(const struct rb_gc_mark_ctx *ctx, VALUE *ptr)
2989{
2990 RB_GC_MARK_OR_TRAVERSE(ctx, rb_gc_impl_mark_and_move, ptr, *ptr, false);
2991}
2992
2993void
2994rb_gc_mark_movable(VALUE obj)
2995{
2996 if (RB_SPECIAL_CONST_P(obj)) return;
2997
2998 const struct rb_gc_mark_ctx ctx = gc_current_mark_ctx();
2999
3000 gc_mark_internal(&ctx, obj);
3001}
3002
3003void
3004rb_gc_mark_movable_ctx(const struct rb_gc_mark_ctx *ctx, VALUE obj)
3005{
3006 gc_mark_internal(ctx, obj);
3007}
3008
3009void
3010rb_gc_mark(VALUE obj)
3011{
3012 if (RB_SPECIAL_CONST_P(obj)) return;
3013
3014 const struct rb_gc_mark_ctx ctx = gc_current_mark_ctx();
3015
3016 gc_mark_and_pin_internal(&ctx, obj);
3017}
3018
3019void
3020rb_gc_mark_and_pin_ctx(const struct rb_gc_mark_ctx *ctx, VALUE obj)
3021{
3022 gc_mark_and_pin_internal(ctx, obj);
3023}
3024
3025void
3026rb_gc_mark_maybe(VALUE obj)
3027{
3028 if (RB_SPECIAL_CONST_P(obj)) return;
3029
3030 const struct rb_gc_mark_ctx ctx = gc_current_mark_ctx();
3031
3032 gc_mark_maybe_internal(&ctx, obj);
3033}
3034
3035void
3036rb_gc_mark_maybe_ctx(const struct rb_gc_mark_ctx *ctx, VALUE obj)
3037{
3038 gc_mark_maybe_internal(ctx, obj);
3039}
3040
3041void
3042rb_gc_mark_and_move(VALUE *ptr)
3043{
3044 if (RB_SPECIAL_CONST_P(*ptr)) return;
3045
3046 const struct rb_gc_mark_ctx ctx = gc_current_mark_ctx();
3047
3048 gc_mark_and_move_internal(&ctx, ptr);
3049}
3050
3051void
3052rb_gc_mark_and_move_ctx(const struct rb_gc_mark_ctx *ctx, VALUE *ptr)
3053{
3054 gc_mark_and_move_internal(ctx, ptr);
3055}
3056
3057typedef void each_location_func(const struct rb_gc_mark_ctx *ctx, VALUE obj, void *data);
3058
3059ATTRIBUTE_NO_ADDRESS_SAFETY_ANALYSIS(static void each_location(const struct rb_gc_mark_ctx *ctx, register const VALUE *x, register long n, each_location_func *cb, void *data));
3060static void
3061each_location(const struct rb_gc_mark_ctx *ctx, register const VALUE *x, register long n, each_location_func *cb, void *data)
3062{
3063 VALUE v;
3064 while (n--) {
3065 v = *x;
3066 cb(ctx, v, data);
3067 x++;
3068 }
3069}
3070
3071static void
3072each_location_ptr(const struct rb_gc_mark_ctx *ctx, const VALUE *start, const VALUE *end, each_location_func *cb, void *data)
3073{
3074 if (end <= start) return;
3075 each_location(ctx, start, end - start, cb, data);
3076}
3077
3078static void
3079gc_mark_maybe_each_location(const struct rb_gc_mark_ctx *ctx, VALUE obj, void *data)
3080{
3081 gc_mark_maybe_internal(ctx, obj);
3082}
3083
3084void
3085rb_gc_mark_locations(const VALUE *start, const VALUE *end)
3086{
3087 if (end <= start) return;
3088
3089 const struct rb_gc_mark_ctx ctx = gc_current_mark_ctx();
3090
3091 each_location_ptr(&ctx, start, end, gc_mark_maybe_each_location, NULL);
3092}
3093
3094void
3095rb_gc_mark_locations_ctx(const struct rb_gc_mark_ctx *ctx, const VALUE *start, const VALUE *end)
3096{
3097 each_location_ptr(ctx, start, end, gc_mark_maybe_each_location, NULL);
3098}
3099
3100void
3101rb_gc_mark_values(long n, const VALUE *values)
3102{
3103 if (n <= 0) return;
3104
3105 const struct rb_gc_mark_ctx ctx = gc_current_mark_ctx();
3106
3107 for (long i = 0; i < n; i++) {
3108 gc_mark_internal(&ctx, values[i]);
3109 }
3110}
3111
3112void
3113rb_gc_mark_vm_stack_values(long n, const VALUE *values)
3114{
3115 if (n <= 0) return;
3116
3117 const struct rb_gc_mark_ctx ctx = gc_current_mark_ctx();
3118
3119 for (long i = 0; i < n; i++) {
3120 gc_mark_and_pin_internal(&ctx, values[i]);
3121 }
3122}
3123
3124static int
3125mark_key(st_data_t key, st_data_t value, st_data_t data)
3126{
3127 gc_mark_and_pin_internal((const struct rb_gc_mark_ctx *)data, (VALUE)key);
3128
3129 return ST_CONTINUE;
3130}
3131
3132void
3133rb_mark_set(st_table *tbl)
3134{
3135 if (!tbl) return;
3136
3137 const struct rb_gc_mark_ctx ctx = gc_current_mark_ctx();
3138
3139 st_foreach(tbl, mark_key, (st_data_t)&ctx);
3140}
3141
3142static int
3143mark_keyvalue(st_data_t key, st_data_t value, st_data_t data)
3144{
3145 const struct rb_gc_mark_ctx *ctx = (const struct rb_gc_mark_ctx *)data;
3146
3147 gc_mark_internal(ctx, (VALUE)key);
3148 gc_mark_internal(ctx, (VALUE)value);
3149
3150 return ST_CONTINUE;
3151}
3152
3153static int
3154pin_key_pin_value(st_data_t key, st_data_t value, st_data_t data)
3155{
3156 const struct rb_gc_mark_ctx *ctx = (const struct rb_gc_mark_ctx *)data;
3157
3158 gc_mark_and_pin_internal(ctx, (VALUE)key);
3159 gc_mark_and_pin_internal(ctx, (VALUE)value);
3160
3161 return ST_CONTINUE;
3162}
3163
3164static int
3165pin_key_mark_value(st_data_t key, st_data_t value, st_data_t data)
3166{
3167 const struct rb_gc_mark_ctx *ctx = (const struct rb_gc_mark_ctx *)data;
3168
3169 gc_mark_and_pin_internal(ctx, (VALUE)key);
3170 gc_mark_internal(ctx, (VALUE)value);
3171
3172 return ST_CONTINUE;
3173}
3174
3175static int
3176gc_mark_tbl_no_pin_i(st_data_t key, st_data_t value, st_data_t data)
3177{
3178 gc_mark_internal((const struct rb_gc_mark_ctx *)data, (VALUE)value);
3179
3180 return ST_CONTINUE;
3181}
3182
3183static int
3184gc_mark_set_no_pin_i(st_data_t key, st_data_t value, st_data_t data)
3185{
3186 gc_mark_internal((const struct rb_gc_mark_ctx *)data, (VALUE)key);
3187
3188 return ST_CONTINUE;
3189}
3190
3191static void
3192mark_hash(const struct rb_gc_mark_ctx *ctx, VALUE hash)
3193{
3194 if (rb_hash_compare_by_id_p(hash)) {
3195 rb_hash_stlike_foreach(hash, pin_key_mark_value, (st_data_t)ctx);
3196 }
3197 else {
3198 rb_hash_stlike_foreach(hash, mark_keyvalue, (st_data_t)ctx);
3199 }
3200
3201 gc_mark_internal(ctx, RHASH(hash)->ifnone);
3202}
3203
3204void
3205rb_mark_hash(st_table *tbl)
3206{
3207 if (!tbl) return;
3208
3209 const struct rb_gc_mark_ctx ctx = gc_current_mark_ctx();
3210
3211 st_foreach(tbl, pin_key_pin_value, (st_data_t)&ctx);
3212}
3213
3214static enum rb_id_table_iterator_result
3215mark_method_entry_i(VALUE me, void *data)
3216{
3217 gc_mark_internal((const struct rb_gc_mark_ctx *)data, me);
3218
3219 return ID_TABLE_CONTINUE;
3220}
3221
3222static void
3223mark_m_tbl(const struct rb_gc_mark_ctx *ctx, struct rb_id_table *tbl)
3224{
3225 if (tbl) {
3226 rb_id_table_foreach_values(tbl, mark_method_entry_i, (void *)ctx);
3227 }
3228}
3229
3230static enum rb_id_table_iterator_result
3231mark_const_entry_i(VALUE value, void *data)
3232{
3233 const rb_const_entry_t *ce = (const rb_const_entry_t *)value;
3234 const struct rb_gc_mark_ctx *ctx = (const struct rb_gc_mark_ctx *)data;
3235
3236 gc_mark_internal(ctx, ce->value);
3237 gc_mark_internal(ctx, ce->file); // TODO: ce->file should be shareable?
3238
3239 return ID_TABLE_CONTINUE;
3240}
3241
3242static void
3243mark_const_tbl(const struct rb_gc_mark_ctx *ctx, struct rb_id_table *tbl)
3244{
3245 if (!tbl) return;
3246 rb_id_table_foreach_values(tbl, mark_const_entry_i, (void *)ctx);
3247}
3248
3249#if STACK_GROW_DIRECTION < 0
3250#define GET_STACK_BOUNDS(start, end, appendix) ((start) = STACK_END, (end) = STACK_START)
3251#elif STACK_GROW_DIRECTION > 0
3252#define GET_STACK_BOUNDS(start, end, appendix) ((start) = STACK_START, (end) = STACK_END+(appendix))
3253#else
3254#define GET_STACK_BOUNDS(start, end, appendix) \
3255 ((STACK_END < STACK_START) ? \
3256 ((start) = STACK_END, (end) = STACK_START) : ((start) = STACK_START, (end) = STACK_END+(appendix)))
3257#endif
3258
3259static void
3260gc_mark_machine_stack_location_maybe(const struct rb_gc_mark_ctx *ctx, VALUE obj, void *data)
3261{
3262 gc_mark_maybe_internal(ctx, obj);
3263
3264#ifdef RUBY_ASAN_ENABLED
3265 const rb_execution_context_t *ec = (const rb_execution_context_t *)data;
3266 void *fake_frame_start;
3267 void *fake_frame_end;
3268 bool is_fake_frame = asan_get_fake_stack_extents(
3269 ec->machine.asan_fake_stack_handle, obj,
3270 ec->machine.stack_start, ec->machine.stack_end,
3271 &fake_frame_start, &fake_frame_end
3272 );
3273 if (is_fake_frame) {
3274 each_location_ptr(ctx, fake_frame_start, fake_frame_end, gc_mark_maybe_each_location, NULL);
3275 }
3276#endif
3277}
3278
3279static bool
3280gc_object_moved_p_internal(void *objspace, VALUE obj)
3281{
3282 if (SPECIAL_CONST_P(obj)) {
3283 return false;
3284 }
3285
3286 return rb_gc_impl_object_moved_p(objspace, obj);
3287}
3288
3289static VALUE
3290gc_location_internal(void *objspace, VALUE value)
3291{
3292 if (SPECIAL_CONST_P(value)) {
3293 return value;
3294 }
3295
3296 return rb_gc_impl_location(objspace, value);
3297}
3298
3299VALUE
3300rb_gc_location(VALUE value)
3301{
3302 return gc_location_internal(rb_gc_get_objspace(), value);
3303}
3304
3305VALUE
3306rb_gc_location_ctx(const struct rb_gc_mark_ctx *ctx, VALUE value)
3307{
3308 return gc_location_internal(ctx->objspace, value);
3309}
3310
3311static inline void
3312gc_update_moved_internal(void *objspace, VALUE *ptr)
3313{
3314 VALUE destination = gc_location_internal(objspace, *ptr);
3315 if (destination != *ptr) {
3316 *ptr = destination;
3317 }
3318}
3319
3320void
3321rb_gc_update_moved(VALUE *ptr)
3322{
3323 gc_update_moved_internal(rb_gc_get_objspace(), ptr);
3324}
3325
3326void
3327rb_gc_update_moved_ctx(const struct rb_gc_mark_ctx *ctx, VALUE *ptr)
3328{
3329 gc_update_moved_internal(ctx->objspace, ptr);
3330}
3331
3332static void gc_mark_machine_context(const struct rb_gc_mark_ctx *ctx, const rb_execution_context_t *ec);
3333
3334#if defined(__wasm__)
3335
3336
3337static VALUE *rb_stack_range_tmp[2];
3338
3339static void
3340rb_mark_locations(void *begin, void *end)
3341{
3342 rb_stack_range_tmp[0] = begin;
3343 rb_stack_range_tmp[1] = end;
3344}
3345
3346void
3347rb_gc_save_machine_context(void)
3348{
3349 // no-op
3350}
3351
3352# if defined(__EMSCRIPTEN__)
3353
3354static void
3355mark_current_machine_context(const struct rb_gc_mark_ctx *ctx, const rb_execution_context_t *ec)
3356{
3357 emscripten_scan_stack(rb_mark_locations);
3358 each_location_ptr(ctx, rb_stack_range_tmp[0], rb_stack_range_tmp[1], gc_mark_maybe_each_location, NULL);
3359
3360 emscripten_scan_registers(rb_mark_locations);
3361 each_location_ptr(ctx, rb_stack_range_tmp[0], rb_stack_range_tmp[1], gc_mark_maybe_each_location, NULL);
3362}
3363# else // use Asyncify version
3364
3365static void
3366mark_current_machine_context(const struct rb_gc_mark_ctx *ctx, rb_execution_context_t *ec)
3367{
3368 VALUE *stack_start, *stack_end;
3369 SET_STACK_END;
3370 GET_STACK_BOUNDS(stack_start, stack_end, 1);
3371 each_location_ptr(ctx, stack_start, stack_end, gc_mark_maybe_each_location, NULL);
3372
3373 rb_wasm_scan_locals(rb_mark_locations);
3374 each_location_ptr(ctx, rb_stack_range_tmp[0], rb_stack_range_tmp[1], gc_mark_maybe_each_location, NULL);
3375}
3376
3377# endif
3378
3379#else // !defined(__wasm__)
3380
3381void
3382rb_gc_save_machine_context(void)
3383{
3384 rb_thread_t *thread = GET_THREAD();
3385
3386 RB_VM_SAVE_MACHINE_CONTEXT(thread);
3387}
3388
3389
3390static void
3391mark_current_machine_context(const struct rb_gc_mark_ctx *ctx, const rb_execution_context_t *ec)
3392{
3393 gc_mark_machine_context(ctx, ec);
3394}
3395#endif
3396
3397static void
3398gc_mark_machine_context(const struct rb_gc_mark_ctx *ctx, const rb_execution_context_t *ec)
3399{
3400 VALUE *stack_start, *stack_end;
3401
3402 GET_STACK_BOUNDS(stack_start, stack_end, 0);
3403 RUBY_DEBUG_LOG("ec->th:%u stack_start:%p stack_end:%p", rb_ec_thread_ptr(ec)->serial, stack_start, stack_end);
3404
3405 void *data =
3406#ifdef RUBY_ASAN_ENABLED
3407 /* gc_mark_machine_stack_location_maybe() uses data as const */
3409#else
3410 NULL;
3411#endif
3412
3413 each_location_ptr(ctx, stack_start, stack_end, gc_mark_machine_stack_location_maybe, data);
3414 int num_regs = sizeof(ec->machine.regs)/(sizeof(VALUE));
3415 each_location(ctx, (VALUE*)&ec->machine.regs, num_regs, gc_mark_machine_stack_location_maybe, data);
3416}
3417
3418void
3419rb_gc_mark_machine_context(const rb_execution_context_t *ec)
3420{
3421 const struct rb_gc_mark_ctx ctx = gc_current_mark_ctx();
3422
3423 gc_mark_machine_context(&ctx, ec);
3424}
3425
3426static int
3427rb_mark_tbl_i(st_data_t key, st_data_t value, st_data_t data)
3428{
3429 gc_mark_and_pin_internal((const struct rb_gc_mark_ctx *)data, (VALUE)value);
3430
3431 return ST_CONTINUE;
3432}
3433
3434void
3435rb_mark_tbl(st_table *tbl)
3436{
3437 if (!tbl || tbl->num_entries == 0) return;
3438
3439 const struct rb_gc_mark_ctx ctx = gc_current_mark_ctx();
3440
3441 st_foreach(tbl, rb_mark_tbl_i, (st_data_t)&ctx);
3442}
3443
3444static void
3445gc_mark_tbl_no_pin(const struct rb_gc_mark_ctx *ctx, st_table *tbl)
3446{
3447 if (!tbl || tbl->num_entries == 0) return;
3448
3449 st_foreach(tbl, gc_mark_tbl_no_pin_i, (st_data_t)ctx);
3450}
3451
3452void
3453rb_mark_tbl_no_pin(st_table *tbl)
3454{
3455 if (!tbl || tbl->num_entries == 0) return;
3456
3457 const struct rb_gc_mark_ctx ctx = gc_current_mark_ctx();
3458
3459 gc_mark_tbl_no_pin(&ctx, tbl);
3460}
3461
3462void
3463rb_mark_tbl_no_pin_ctx(const struct rb_gc_mark_ctx *ctx, st_table *tbl)
3464{
3465 gc_mark_tbl_no_pin(ctx, tbl);
3466}
3467
3468static void
3469gc_mark_set_no_pin(const struct rb_gc_mark_ctx *ctx, st_table *tbl)
3470{
3471 if (!tbl || tbl->num_entries == 0) return;
3472
3473 st_foreach(tbl, gc_mark_set_no_pin_i, (st_data_t)ctx);
3474}
3475
3476void
3477rb_gc_mark_set_no_pin(st_table *tbl)
3478{
3479 if (!tbl || tbl->num_entries == 0) return;
3480
3481 const struct rb_gc_mark_ctx ctx = gc_current_mark_ctx();
3482
3483 gc_mark_set_no_pin(&ctx, tbl);
3484}
3485
3486void
3487rb_gc_mark_set_no_pin_ctx(const struct rb_gc_mark_ctx *ctx, st_table *tbl)
3488{
3489 gc_mark_set_no_pin(ctx, tbl);
3490}
3491
3492static bool
3493gc_declarative_marking_p(const rb_data_type_t *type)
3494{
3495 return (type->flags & RUBY_TYPED_DECL_MARKING) != 0;
3496}
3497
3499rb_gc_get_ec(void)
3500{
3501 void *objspace = rb_gc_get_objspace();
3502
3503 if (RB_LIKELY(rb_gc_impl_during_gc_p(objspace))) {
3504 return rb_gc_impl_get_vm_context(objspace)->ec;
3505 }
3506 else {
3507 return GET_EC();
3508 }
3509}
3510
3511/* need_lock is false when the caller already holds vm->gc.registered_addrs.lock (the
3512 * terminated_set walk in rb_gc_mark_roots); the lock is not recursive, so both the
3513 * marking path and the traversal-API snapshot path below must honour it. */
3514void
3515rb_gc_mark_registered_addrs(rb_ractor_t *r, bool need_lock)
3516{
3517 if (r->registered_addrs_cnt == 0) return;
3518
3519 if (rb_gc_impl_during_gc_p(rb_gc_get_objspace())) {
3520 rb_vm_t *vm = GET_VM();
3521 if (need_lock) rb_native_mutex_lock(&vm->gc.registered_addrs.lock);
3522 for (size_t i = 0; i < r->registered_addrs_cnt; i++) {
3523 rb_gc_mark_maybe(*r->registered_addrs[i].addr);
3524 }
3525 if (need_lock) rb_native_mutex_unlock(&vm->gc.registered_addrs.lock);
3526 return;
3527 }
3528
3529 VALUE stack_snap[16];
3530 VALUE *snap = stack_snap;
3531 size_t capa = numberof(stack_snap);
3532
3533 rb_vm_t *vm = GET_VM();
3534 if (need_lock) rb_native_mutex_lock(&vm->gc.registered_addrs.lock);
3535 size_t cnt = r->registered_addrs_cnt;
3536 if (RB_UNLIKELY(cnt > capa)) {
3537 if (need_lock) rb_native_mutex_unlock(&vm->gc.registered_addrs.lock);
3538 rb_ractor_t *cr = rb_current_ractor_raw(false);
3539 bool saved_malloc_gc_disabled = cr ? cr->malloc_gc_disabled : false;
3540 if (cr) cr->malloc_gc_disabled = true;
3541 snap = ALLOC_N(VALUE, cnt);
3542 if (cr) cr->malloc_gc_disabled = saved_malloc_gc_disabled;
3543 capa = cnt;
3544 if (need_lock) rb_native_mutex_lock(&vm->gc.registered_addrs.lock);
3545 cnt = r->registered_addrs_cnt;
3546 VM_ASSERT(cnt <= capa);
3547 }
3548 for (size_t i = 0; i < cnt; i++) {
3549 snap[i] = *r->registered_addrs[i].addr;
3550 }
3551 if (need_lock) rb_native_mutex_unlock(&vm->gc.registered_addrs.lock);
3552
3553 for (size_t i = 0; i < cnt; i++) {
3554 rb_gc_mark_maybe(snap[i]);
3555 }
3556 if (snap != stack_snap) xfree(snap);
3557}
3558
3559static void
3560gc_mark_roots_ctx(const struct rb_gc_mark_ctx *ctx, void *objspace, const char **categoryp)
3561{
3562 rb_execution_context_t *ec = rb_gc_get_ec();
3563 rb_vm_t *vm = rb_ec_vm_ptr(ec);
3564
3565#define MARK_CHECKPOINT(category) do { \
3566 if (categoryp) *categoryp = category; \
3567} while (0)
3568
3569 /* A single-objspace impl (mmtk) only has stop-the-world global GCs and no
3570 * per-mutator root scan, so always walk every Ractor's local roots here. */
3571 const bool global_gc = rb_gc_impl_during_global_gc_p(objspace) ||
3572 !rb_gc_impl_multi_objspace_p();
3573
3574 /* Mark the current Ractor's roots from its C structs (a local GC must not depend on
3575 * heap wrapper traversal). A global GC does the same for every Ractor. */
3576 MARK_CHECKPOINT("ractor");
3577 if (global_gc) {
3578 rb_ractor_t *r;
3579 ccan_list_for_each(&vm->ractor.set, r, vmlr_node) {
3580 rb_ractor_mark_local_roots(r);
3581 MARK_CHECKPOINT("registered_addrs");
3582 rb_gc_mark_registered_addrs(r, true);
3583 MARK_CHECKPOINT("ractor");
3584 }
3585
3586 /* Early in boot (before rb_ractor_main_setup) main is not in vm->ractor.set
3587 * yet; do not drop its registered_marks in a single-objspace boot GC. */
3588 if (vm->ractor.cnt == 0 && vm->ractor.main_ractor) {
3589 rb_ractor_mark_local_roots(vm->ractor.main_ractor);
3590 MARK_CHECKPOINT("registered_addrs");
3591 rb_gc_mark_registered_addrs(vm->ractor.main_ractor, true);
3592 MARK_CHECKPOINT("ractor");
3593 }
3594 /* A Ractor that terminated (left vm->ractor.set) but whose struct is not freed
3595 * still owns rb_gc_register_mark_object pins. Keep them alive until
3596 * ractor_free hands them to main; an orphan (owner == NULL) was moved above.
3597 * The join value is not rooted here: ractor_mark marks it from the wrapper. */
3598 for (size_t i = 0; i < vm->gc.zombie_objspaces_count; i++) {
3599 rb_ractor_t *owner = vm->gc.zombie_objspaces[i].owner;
3600 if (owner) {
3601 rb_gc_mark_vm_stack_values((long)owner->registered_marks_cnt,
3602 owner->registered_marks);
3603 MARK_CHECKPOINT("registered_addrs");
3604 rb_gc_mark_registered_addrs(owner, true);
3605 MARK_CHECKPOINT("ractor");
3606 }
3607 }
3608
3609 /* Single-objspace impl: keep terminated-but-not-freed Ractors'
3610 * rb_gc_register_mark_object entries alive without depending on wrapper
3611 * reachability. With multiple objspaces zombie_objspaces covers this. */
3612 if (!rb_gc_impl_multi_objspace_p()) {
3613 rb_ractor_t *tr;
3614 rb_native_mutex_lock(&vm->gc.registered_addrs.lock);
3615 ccan_list_for_each(&vm->ractor.terminated_set, tr, vmlr_node) {
3616 rb_gc_mark_vm_stack_values((long)tr->registered_marks_cnt,
3617 tr->registered_marks);
3618 MARK_CHECKPOINT("registered_addrs");
3619 rb_gc_mark_registered_addrs(tr, false);
3620 MARK_CHECKPOINT("ractor");
3621 }
3622 rb_native_mutex_unlock(&vm->gc.registered_addrs.lock);
3623 }
3624 }
3625 else {
3626 rb_ractor_t *cr = rb_ec_ractor_ptr(ec);
3627 rb_ractor_mark_local_roots(cr);
3628 MARK_CHECKPOINT("registered_addrs");
3629 rb_gc_mark_registered_addrs(cr, true);
3630 }
3631
3632 /* Trap handlers live in the VM-global vm->trap_list.cmd[], a fixed array of aligned
3633 * VALUEs (signal.c uses ACCESS_ONCE): a racing walk reads either the old or the new
3634 * handler, both alive, so no lock. */
3635 MARK_CHECKPOINT("trap_list");
3636 rb_gc_mark_values(RUBY_NSIG, vm->trap_list.cmd);
3637
3638 /* VM-global roots belong to the main Ractor's objspace, since the boot objects
3639 * live there. A non-main Ractor's local GC skips them; a global GC walks all. */
3640 if (global_gc || objspace == vm->ractor.main_ractor->objspace) {
3641 /* Only the main Ractor can register at_exit/END procs (a non-main one gets an
3642 * IsolationError) so end_procs is a lock-free linked list */
3643 MARK_CHECKPOINT("end_proc");
3644 rb_mark_end_proc();
3645
3646 MARK_CHECKPOINT("vm");
3647 /* rb_vm_mark and the JIT root marks walk VM-global weak tables and shared singleton
3648 * JIT state that other Ractors rewrite under the VM lock, so main's otherwise
3649 * lock-free local GC takes the VM lock for this stretch */
3650 const bool vm_mark_needs_lock = rb_multi_ractor_p() && !global_gc;
3651 unsigned int vm_mark_lock_lev = 0;
3652 if (vm_mark_needs_lock) vm_mark_lock_lev = RB_GC_VM_LOCK_NO_BARRIER();
3653 rb_vm_mark(vm);
3654
3655 MARK_CHECKPOINT("global_tbl");
3656 rb_gc_mark_global_tbl();
3657
3658#if USE_YJIT
3659 void rb_yjit_root_mark(void); // in Rust
3660
3661 if (rb_yjit_enabled_p) {
3662 MARK_CHECKPOINT("YJIT");
3663 rb_yjit_root_mark();
3664 }
3665#endif
3666
3667#if USE_ZJIT
3668 void rb_zjit_root_mark(void);
3669 if (rb_zjit_enabled_p) {
3670 MARK_CHECKPOINT("ZJIT");
3671 rb_zjit_root_mark();
3672 }
3673#endif
3674 if (vm_mark_needs_lock) RB_GC_VM_UNLOCK_NO_BARRIER(vm_mark_lock_lev);
3675
3676 if (global_gc || rb_gc_single_objspace_p()) {
3677 MARK_CHECKPOINT("global_symbols");
3678 rb_sym_global_symbols_mark_and_move();
3679 }
3680 }
3681
3682 /* The dying thread's final collection of its own objspace runs after its stack
3683 * has been torn down (thread_cleanup_func), so there is no live machine context
3684 * to scan -- the join value and the pins are rooted explicitly. Scanning the
3685 * half-dead stack is not only useless but faults on some platforms. */
3686 if (!rb_gc_impl_during_postmortem_p(objspace)) {
3687 MARK_CHECKPOINT("machine_context");
3688 mark_current_machine_context(ctx, ec);
3689 }
3690
3691 MARK_CHECKPOINT("finish");
3692
3693#undef MARK_CHECKPOINT
3694}
3695
3696void
3697rb_gc_mark_roots(void *objspace, const char **categoryp)
3698{
3699 const struct rb_gc_mark_ctx ctx = gc_current_mark_ctx();
3700
3701 GC_ASSERT(ctx.objspace == objspace);
3702 gc_mark_roots_ctx(&ctx, objspace, categoryp);
3703}
3704
3706 const struct rb_gc_mark_ctx *ctx;
3707 VALUE obj;
3708};
3709
3710static void
3711gc_mark_classext_module(rb_classext_t *ext, bool prime, VALUE box_value, void *arg)
3712{
3714 const struct rb_gc_mark_ctx *ctx = foreach_arg->ctx;
3715
3716 if (RCLASSEXT_SUPER(ext)) {
3717 gc_mark_internal(ctx, RCLASSEXT_SUPER(ext));
3718 }
3719 mark_m_tbl(ctx, RCLASSEXT_M_TBL(ext));
3720
3721 gc_mark_internal(ctx, RCLASSEXT_FIELDS_OBJ(ext));
3722 gc_mark_internal(ctx, RCLASSEXT_CVC_TBL(ext));
3723
3724 if (!RCLASSEXT_SHARED_CONST_TBL(ext) && RCLASSEXT_CONST_TBL(ext)) {
3725 mark_const_tbl(ctx, RCLASSEXT_CONST_TBL(ext));
3726 }
3727 mark_m_tbl(ctx, RCLASSEXT_CALLABLE_M_TBL(ext));
3728 gc_mark_internal(ctx, RCLASSEXT_CC_TBL(ext));
3729 if (RCLASSEXT_SUBCLASSES(ext)) {
3730 gc_mark_internal(ctx, RCLASSEXT_SUBCLASSES(ext));
3731 }
3732 gc_mark_internal(ctx, RCLASSEXT_CLASSPATH(ext));
3733}
3734
3735static void
3736gc_mark_classext_iclass(rb_classext_t *ext, bool prime, VALUE box_value, void *arg)
3737{
3739 const struct rb_gc_mark_ctx *ctx = foreach_arg->ctx;
3740
3741 if (RCLASSEXT_SUPER(ext)) {
3742 gc_mark_internal(ctx, RCLASSEXT_SUPER(ext));
3743 }
3744 if (RCLASSEXT_ICLASS_IS_ORIGIN(ext) && !RCLASSEXT_ICLASS_ORIGIN_SHARED_MTBL(ext)) {
3745 mark_m_tbl(ctx, RCLASSEXT_M_TBL(ext));
3746 }
3747 if (RCLASSEXT_INCLUDER(ext)) {
3748 gc_mark_internal(ctx, RCLASSEXT_INCLUDER(ext));
3749 }
3750 mark_m_tbl(ctx, RCLASSEXT_CALLABLE_M_TBL(ext));
3751 gc_mark_internal(ctx, RCLASSEXT_CC_TBL(ext));
3752 if (RCLASSEXT_SUBCLASSES(ext)) {
3753 gc_mark_internal(ctx, RCLASSEXT_SUBCLASSES(ext));
3754 }
3755}
3756
3757#define TYPED_DATA_REFS_OFFSET_LIST(d) (size_t *)(uintptr_t)RTYPEDDATA_TYPE(d)->function.dmark
3758
3759static inline bool
3760rb_obj_using_gen_fields_table_p(VALUE obj)
3761{
3762 switch (BUILTIN_TYPE(obj)) {
3763 case T_STRUCT:
3764 case T_DATA:
3765 return false;
3766
3767 default:
3768 break;
3769 }
3770
3771 return rb_obj_gen_fields_p(obj);
3772}
3773
3774void
3775rb_gc_move_obj_during_marking(VALUE from, VALUE to)
3776{
3777 if (rb_obj_using_gen_fields_table_p(to)) {
3778 rb_mark_generic_ivar(from);
3779 }
3780}
3781
3782static void
3783gc_mark_children_ctx(const struct rb_gc_mark_ctx *ctx, VALUE obj)
3784{
3785 struct gc_mark_classext_foreach_arg foreach_args;
3786
3787 if (rb_obj_using_gen_fields_table_p(obj)) {
3788 rb_mark_generic_ivar(obj);
3789 }
3790
3791 switch (BUILTIN_TYPE(obj)) {
3792 case T_FLOAT:
3793 case T_BIGNUM:
3794 return;
3795
3796 case T_NIL:
3797 case T_FIXNUM:
3798 rb_bug("rb_gc_mark() called for broken object");
3799 break;
3800
3801 case T_NODE:
3802 UNEXPECTED_NODE(rb_gc_mark);
3803 break;
3804
3805 case T_IMEMO:
3806 rb_imemo_mark_and_move(ctx, obj, false);
3807 return;
3808
3809 default:
3810 break;
3811 }
3812
3813 gc_mark_internal(ctx, RBASIC(obj)->klass);
3814
3815 switch (BUILTIN_TYPE(obj)) {
3816 case T_CLASS:
3817 if (FL_TEST_RAW(obj, FL_SINGLETON)) {
3818 gc_mark_internal(ctx, RCLASS_ATTACHED_OBJECT(obj));
3819 }
3820 // Continue to the shared T_CLASS/T_MODULE
3821 case T_MODULE:
3822 foreach_args.ctx = ctx;
3823 foreach_args.obj = obj;
3824 rb_class_classext_foreach(obj, gc_mark_classext_module, (void *)&foreach_args);
3825 if (BOX_USER_P(RCLASS_PRIME_BOX(obj))) {
3826 gc_mark_internal(ctx, RCLASS_PRIME_BOX(obj)->box_object);
3827 }
3828 break;
3829
3830 case T_ICLASS:
3831 foreach_args.ctx = ctx;
3832 foreach_args.obj = obj;
3833 rb_class_classext_foreach(obj, gc_mark_classext_iclass, (void *)&foreach_args);
3834 if (BOX_USER_P(RCLASS_PRIME_BOX(obj))) {
3835 gc_mark_internal(ctx, RCLASS_PRIME_BOX(obj)->box_object);
3836 }
3837 break;
3838
3839 case T_ARRAY:
3840 if (ARY_SHARED_P(obj)) {
3841 VALUE root = ARY_SHARED_ROOT(obj);
3842 if (RB_TYPE_P(root, T_ARRAY)) {
3843 gc_mark_internal(ctx, root);
3844 }
3845 else {
3846 /* Ractor#send(move: true) hollowed the root out in place. If it was
3847 * embedded our elements are still in its slot, and nothing says so any
3848 * more, so it must not move (gc_ref_update_array cannot re-point us). */
3849 gc_mark_and_pin_internal(ctx, root);
3850 }
3851 }
3852 else {
3853 long len = RARRAY_LEN(obj);
3854 const VALUE *ptr = RARRAY_CONST_PTR(obj);
3855 for (long i = 0; i < len; i++) {
3856 gc_mark_internal(ctx, ptr[i]);
3857 }
3858 }
3859 break;
3860
3861 case T_HASH:
3862 mark_hash(ctx, obj);
3863 break;
3864
3865 case T_SYMBOL:
3866 gc_mark_internal(ctx, RSYMBOL(obj)->fstr);
3867 break;
3868
3869 case T_STRING:
3870 if (STR_SHARED_P(obj)) {
3871 if (STR_EMBED_P(RSTRING(obj)->as.heap.aux.shared)) {
3872 /* Embedded shared strings cannot be moved because this string
3873 * points into the slot of the shared string. There may be code
3874 * using the RSTRING_PTR on the stack, which would pin this
3875 * string but not pin the shared string, causing it to move. */
3876 gc_mark_and_pin_internal(ctx, RSTRING(obj)->as.heap.aux.shared);
3877 }
3878 else {
3879 gc_mark_internal(ctx, RSTRING(obj)->as.heap.aux.shared);
3880 }
3881 }
3882 break;
3883
3884 case T_DATA: {
3885 void *const ptr = RTYPEDDATA_GET_DATA(obj);
3886
3887 gc_mark_internal(ctx, RTYPEDDATA(obj)->fields_obj);
3888
3889 if (ptr) {
3890 if (gc_declarative_marking_p(RTYPEDDATA_TYPE(obj))) {
3891 size_t *offset_list = TYPED_DATA_REFS_OFFSET_LIST(obj);
3892
3893 for (size_t offset = *offset_list; offset != RUBY_REF_END; offset = *offset_list++) {
3894 gc_mark_internal(ctx, *(VALUE *)((char *)ptr + offset));
3895 }
3896 }
3897 else {
3898 RUBY_DATA_FUNC mark_func = RTYPEDDATA_TYPE(obj)->function.dmark;
3899 if (mark_func) (*mark_func)(ptr);
3900 }
3901 }
3902
3903 break;
3904 }
3905
3906 case T_OBJECT: {
3907 shape_id_t shape_id = RBASIC_SHAPE_ID(obj);
3908 if (rb_shape_embedded_p(shape_id)) {
3909 uint32_t len = RSHAPE_LEN(shape_id);
3910 const VALUE * const ptr = ROBJECT(obj)->as.ary;
3911
3912 for (uint32_t i = 0; i < len; i++) {
3913 gc_mark_internal(ctx, ptr[i]);
3914 }
3915 }
3916 else {
3917 if (!ctx->checking_shareable) {
3918 gc_mark_internal(ctx, ROBJECT(obj)->as.extended);
3919 }
3920 }
3921 break;
3922 }
3923
3924 case T_FILE:
3925 if (RFILE(obj)->fptr) {
3926 gc_mark_internal(ctx, RFILE(obj)->fptr->self);
3927 gc_mark_internal(ctx, RFILE(obj)->fptr->pathv);
3928 gc_mark_internal(ctx, RFILE(obj)->fptr->tied_io_for_writing);
3929 gc_mark_internal(ctx, RFILE(obj)->fptr->writeconv_asciicompat);
3930 gc_mark_internal(ctx, RFILE(obj)->fptr->writeconv_pre_ecopts);
3931 gc_mark_internal(ctx, RFILE(obj)->fptr->encs.ecopts);
3932 gc_mark_internal(ctx, RFILE(obj)->fptr->write_lock);
3933 gc_mark_internal(ctx, RFILE(obj)->fptr->timeout);
3934 gc_mark_internal(ctx, RFILE(obj)->fptr->wakeup_mutex);
3935 }
3936 break;
3937
3938 case T_REGEXP:
3939 gc_mark_internal(ctx, RREGEXP(obj)->src);
3940 break;
3941
3942 case T_MATCH:
3943 gc_mark_internal(ctx, RMATCH(obj)->regexp);
3944 if (RMATCH(obj)->str) {
3945 gc_mark_internal(ctx, RMATCH(obj)->str);
3946 }
3947 break;
3948
3949 case T_RATIONAL:
3950 gc_mark_internal(ctx, RRATIONAL(obj)->num);
3951 gc_mark_internal(ctx, RRATIONAL(obj)->den);
3952 break;
3953
3954 case T_COMPLEX:
3955 gc_mark_internal(ctx, RCOMPLEX(obj)->real);
3956 gc_mark_internal(ctx, RCOMPLEX(obj)->imag);
3957 break;
3958
3959 case T_STRUCT: {
3960 const long len = RSTRUCT_LEN(obj);
3961 const VALUE * const ptr = RSTRUCT_CONST_PTR(obj);
3962
3963 for (long i = 0; i < len; i++) {
3964 gc_mark_internal(ctx, ptr[i]);
3965 }
3966
3967 gc_mark_internal(ctx, RSTRUCT_FIELDS_OBJ(obj));
3968
3969 break;
3970 }
3971
3972 default:
3973 if (BUILTIN_TYPE(obj) == T_MOVED) rb_bug("rb_gc_mark(): %p is T_MOVED", (void *)obj);
3974 if (BUILTIN_TYPE(obj) == T_NONE) rb_bug("rb_gc_mark(): %p is T_NONE", (void *)obj);
3975 if (BUILTIN_TYPE(obj) == T_ZOMBIE) rb_bug("rb_gc_mark(): %p is T_ZOMBIE", (void *)obj);
3976 rb_bug("rb_gc_mark(): unknown data type 0x%x(%p) %s",
3977 BUILTIN_TYPE(obj), (void *)obj,
3978 rb_gc_impl_live_object_p(ctx->objspace, (void *)obj) ? "corrupted object" : "non object");
3979 }
3980}
3981
3982void
3983rb_gc_mark_children(void *objspace, VALUE obj)
3984{
3985 const struct rb_gc_mark_ctx ctx = gc_current_mark_ctx();
3986
3987 GC_ASSERT(ctx.objspace == objspace);
3988 gc_mark_children_ctx(&ctx, obj);
3989}
3990
3991size_t
3992rb_gc_obj_optimal_size(VALUE obj)
3993{
3994 switch (BUILTIN_TYPE(obj)) {
3995 case T_ARRAY:
3996 {
3997 size_t size = rb_ary_size_as_embedded(obj);
3998 if (rb_gc_size_allocatable_p(size)) {
3999 return size;
4000 }
4001 else {
4002 return sizeof(struct RArray);
4003 }
4004 }
4005
4006 case T_OBJECT:
4007 if (rb_obj_shape_complex_p(obj)) {
4008 return sizeof(struct RObject);
4009 }
4010 else {
4011 size_t size = rb_obj_embedded_size(RSHAPE_CAPACITY(RBASIC_SHAPE_ID(obj)));
4012 if (rb_gc_size_allocatable_p(size)) {
4013 return size;
4014 }
4015 else {
4016 return sizeof(struct RObject);
4017 }
4018 }
4019
4020 case T_STRING:
4021 {
4022 size_t size = rb_str_size_as_embedded(obj);
4023 if (rb_gc_size_allocatable_p(size)) {
4024 return size;
4025 }
4026 else {
4027 return sizeof(struct RString);
4028 }
4029 }
4030
4031 case T_HASH:
4032 {
4033 if (RHASH_AR_TABLE_P(obj)) {
4034 const unsigned bound = RHASH_AR_TABLE_BOUND(obj);
4035 const size_t ar_size = RHASH_AR_SLOT_SIZE(bound);
4036 if (ar_size > RHASH_ST_SLOT_SIZE || OBJ_FROZEN(obj)) {
4037 return ar_size;
4038 }
4039 }
4040
4041 return RHASH_ST_SLOT_SIZE;
4042 }
4043
4044 default:
4045 return 0;
4046 }
4047}
4048
4049void
4050rb_gc_writebarrier(VALUE a, VALUE b)
4051{
4052 rb_gc_impl_writebarrier(rb_gc_get_objspace(), a, b);
4053}
4054
4055void
4056rb_gc_writebarrier_unprotect(VALUE obj)
4057{
4058 rb_gc_impl_writebarrier_unprotect(rb_gc_get_objspace(), obj);
4059}
4060
4061/*
4062 * remember `obj' if needed.
4063 */
4064void
4065rb_gc_writebarrier_remember(VALUE obj)
4066{
4067 rb_gc_impl_writebarrier_remember(rb_gc_get_objspace(), obj);
4068}
4069
4070/* obj became shareable after it was created (FL_SHAREABLE was set). Tell the GC so it
4071 * updates the per-page shareable bitmap. */
4072void
4073rb_gc_obj_became_shareable(VALUE obj)
4074{
4075 rb_gc_impl_obj_became_shareable(rb_gc_get_objspace(), obj);
4076}
4077
4078/* Pin an in-flight message payload in its owner's (the sender's) objspace, so the
4079 * sender's local GC keeps it alive while it sits in a queue the sender does not walk. */
4080void
4081rb_gc_copy_attributes(VALUE dest, VALUE obj)
4082{
4083 rb_gc_impl_copy_attributes(rb_gc_get_objspace(), dest, obj);
4084}
4085
4086#if USE_MODULAR_GC
4087int
4088rb_gc_modular_gc_loaded_p(void)
4089{
4090 return rb_gc_functions.modular_gc_loaded_p;
4091}
4092
4093const char *
4094rb_gc_active_gc_name(void)
4095{
4096 const char *gc_name = rb_gc_impl_active_gc_name();
4097
4098 const size_t len = strlen(gc_name);
4099 if (len > RB_GC_MAX_NAME_LEN) {
4100 rb_bug("GC should have a name no more than %d chars long. Currently: %zu (%s)",
4101 RB_GC_MAX_NAME_LEN, len, gc_name);
4102 }
4103
4104 return gc_name;
4105}
4106#endif
4107
4109rb_gc_object_metadata(VALUE obj)
4110{
4111 return rb_gc_impl_object_metadata(rb_gc_get_objspace(), obj);
4112}
4113
4114/* GC */
4115
4116void *
4117rb_gc_ractor_cache_alloc(rb_ractor_t *ractor)
4118{
4119 return rb_gc_impl_ractor_cache_alloc(rb_gc_get_objspace(), ractor);
4120}
4121
4122void
4123rb_gc_ractor_cache_free(void *cache)
4124{
4125 rb_gc_impl_ractor_cache_free(rb_gc_get_objspace(), cache);
4126}
4127
4128bool
4129rb_gc_zjit_new_obj_fastpath(size_t alloc_size, VALUE flags, VALUE klass, struct rb_gc_zjit_fastpath *fastpath)
4130{
4131#if defined(RUBY_ASAN_ENABLED)
4132 (void)rb_gc_impl_zjit_new_obj_fastpath;
4133 return false;
4134#else
4135 return rb_gc_impl_zjit_new_obj_fastpath(rb_gc_get_objspace(), alloc_size, flags, klass, fastpath);
4136#endif
4137}
4138
4139void
4140rb_gc_register_mark_object(VALUE obj)
4141{
4142 /* rb_gc_impl_live_object_p() walks objspace->heap_pages.sorted, which
4143 * another ractor may mutate while allocating heap pages under the VM lock,
4144 * so the lookup must be done under the VM lock as well. */
4145 RB_VM_LOCKING() {
4146 if (rb_gc_impl_live_object_p(rb_gc_get_objspace(), (void *)obj)) {
4147 rb_vm_register_global_object(obj);
4148 }
4149 }
4150}
4151
4152static rb_ractor_t *
4153gc_registered_addrs_owner(rb_vm_t *vm)
4154{
4155 rb_ractor_t *cr = rb_current_ractor_raw(false);
4156 if (cr) return cr;
4157 RUBY_ASSERT(vm->ractor.main_ractor != NULL);
4158 return vm->ractor.main_ractor;
4159}
4160
4161/* Keep track of every ractor that owns registered addresses, so that a
4162 * rb_gc_unregister_address() call from a non-owning ractor can find the list
4163 * holding the address, and so GC can iterate every live registration list
4164 * without walking the whole ractor set. */
4165void
4166rb_gc_registered_addrs_enroll_without_gc(rb_vm_t *vm, rb_ractor_t *r)
4167{
4168 if (r->registered_addrs_listed) return;
4169 if (vm->gc.registered_addrs.registry_cnt == vm->gc.registered_addrs.registry_capa) {
4170 size_t nc = vm->gc.registered_addrs.registry_capa ? vm->gc.registered_addrs.registry_capa * 2 : 16;
4171 struct rb_ractor_struct **p = realloc(vm->gc.registered_addrs.registry,
4172 nc * sizeof(struct rb_ractor_struct *));
4173 if (!p) rb_bug("rb_gc_registered_addrs_enroll_without_gc: out of memory");
4174 vm->gc.registered_addrs.registry = p;
4175 vm->gc.registered_addrs.registry_capa = nc;
4176 }
4177 vm->gc.registered_addrs.registry[vm->gc.registered_addrs.registry_cnt++] = r;
4178 r->registered_addrs_listed = true;
4179}
4180
4181void
4182rb_gc_registered_addrs_unenroll_without_gc(rb_vm_t *vm, rb_ractor_t *r)
4183{
4184 if (!r->registered_addrs_listed) return;
4185 for (size_t i = 0; i < vm->gc.registered_addrs.registry_cnt; i++) {
4186 if (vm->gc.registered_addrs.registry[i] == r) {
4187 vm->gc.registered_addrs.registry[i] =
4188 vm->gc.registered_addrs.registry[--vm->gc.registered_addrs.registry_cnt];
4189 break;
4190 }
4191 }
4192 r->registered_addrs_listed = false;
4193}
4194
4195void
4196rb_gc_each_registered_addr(rb_gc_registered_addr_cb func, void *data)
4197{
4198#if !RB_GC_REGISTERED_ADDR_CHECK
4199 /* Production entries carry no provenance, so the verifier has nothing to check. */
4200 (void)func;
4201 (void)data;
4202 return;
4203#else
4204 rb_vm_t *vm = GET_VM();
4205 for (size_t i = 0; i < vm->gc.registered_addrs.registry_cnt; i++) {
4206 rb_ractor_t *r = vm->gc.registered_addrs.registry[i];
4207 for (size_t j = 0; j < r->registered_addrs_cnt; j++) {
4208 struct rb_ractor_registered_addr *entry = &r->registered_addrs[j];
4209 func(entry->addr, entry->initial_value, (void *)r->objspace, data);
4210 }
4211 }
4212#endif
4213}
4214
4215/* True if the same address is registered by a Ractor whose objspace is the given one;
4216 * that registrant's local GC can root the value, so the verifier accepts it. Called
4217 * from the consistency verifier with the world stopped, so no lock is taken here. */
4218bool
4219rb_gc_registered_addr_owned_by_registrant_p(VALUE *addr, void *objspace)
4220{
4221 rb_vm_t *vm = GET_VM();
4222 for (size_t i = 0; i < vm->gc.registered_addrs.registry_cnt; i++) {
4223 rb_ractor_t *r = vm->gc.registered_addrs.registry[i];
4224 if ((void *)r->objspace != objspace) continue;
4225 for (size_t j = 0; j < r->registered_addrs_cnt; j++) {
4226 if (r->registered_addrs[j].addr == addr) return true;
4227 }
4228 }
4229 return false;
4230}
4231
4232/* True while the objspace is a zombie pending merge. Registration ownership moves to
4233 * the inheritor before the zombie merge completes, so a value still owned by a zombie
4234 * is a safe transient for the verifier. */
4235bool
4236rb_gc_vm_zombie_objspace_p(void *objspace)
4237{
4238 rb_vm_t *vm = GET_VM();
4239 for (size_t i = 0; i < vm->gc.zombie_objspaces_count; i++) {
4240 if (vm->gc.zombie_objspaces[i].objspace == objspace) return true;
4241 }
4242 return false;
4243}
4244
4245static bool
4246gc_registered_addrs_remove(rb_ractor_t *r, VALUE *addr)
4247{
4248 for (size_t i = 0; i < r->registered_addrs_cnt; i++) {
4249 if (r->registered_addrs[i].addr == addr) {
4250 MEMMOVE(&r->registered_addrs[i], &r->registered_addrs[i + 1],
4251 struct rb_ractor_registered_addr, r->registered_addrs_cnt - i - 1);
4252 r->registered_addrs_cnt--;
4253 return true;
4254 }
4255 }
4256 return false;
4257}
4258
4259void
4260rb_gc_register_address(VALUE *addr)
4261{
4262 rb_vm_t *vm = GET_VM();
4263
4264 rb_native_mutex_lock(&vm->gc.registered_addrs.lock);
4265 rb_ractor_t *owner = gc_registered_addrs_owner(vm);
4266 if (owner->registered_addrs_cnt == owner->registered_addrs_capa) {
4267 size_t nc = owner->registered_addrs_capa ? owner->registered_addrs_capa * 2 : 64;
4268 struct rb_ractor_registered_addr *p =
4269 realloc(owner->registered_addrs, nc * sizeof(struct rb_ractor_registered_addr));
4270 if (!p) rb_bug("rb_gc_register_address: out of memory");
4271 owner->registered_addrs = p;
4272 owner->registered_addrs_capa = nc;
4273 }
4274 struct rb_ractor_registered_addr *entry = &owner->registered_addrs[owner->registered_addrs_cnt];
4275 entry->addr = addr;
4276#if RB_GC_REGISTERED_ADDR_CHECK
4277 entry->initial_value = *addr;
4278#endif
4279 owner->registered_addrs_cnt++;
4280 rb_gc_registered_addrs_enroll_without_gc(vm, owner);
4281 rb_native_mutex_unlock(&vm->gc.registered_addrs.lock);
4282
4283 /* Some C extensions register before assigning, so protect obj from GC here. */
4284 RB_GC_GUARD(*addr);
4285}
4286
4287void
4288rb_gc_unregister_address(VALUE *addr)
4289{
4290 rb_vm_t *vm = GET_VM();
4291
4292 rb_native_mutex_lock(&vm->gc.registered_addrs.lock);
4293 rb_ractor_t *cr = rb_current_ractor_raw(false);
4294 if (cr == NULL) cr = vm->ractor.main_ractor;
4295 if (cr && gc_registered_addrs_remove(cr, addr)) goto done;
4296 for (size_t i = 0; i < vm->gc.registered_addrs.registry_cnt; i++) {
4297 if (vm->gc.registered_addrs.registry[i] != cr &&
4298 gc_registered_addrs_remove(vm->gc.registered_addrs.registry[i], addr)) {
4299 break;
4300 }
4301 }
4302 done:
4303 rb_native_mutex_unlock(&vm->gc.registered_addrs.lock);
4304}
4305
4306void
4308{
4309 rb_gc_register_address(var);
4310}
4311
4312static VALUE
4313gc_start_internal(rb_execution_context_t *ec, VALUE self, VALUE full_mark, VALUE immediate_mark, VALUE immediate_sweep, VALUE compact, VALUE global)
4314{
4315 rb_gc_impl_start(rb_gc_get_objspace(), RTEST(full_mark), RTEST(immediate_mark), RTEST(immediate_sweep), RTEST(compact), RTEST(global));
4316
4317 return Qnil;
4318}
4319
4321 void *self;
4322 int (*callback)(void *, void *, size_t, void *);
4323 void *data;
4324};
4325
4326static void
4327each_objects_foreign_i(void *objspace, void *arg)
4328{
4329 struct each_objects_foreign_arg *a = (struct each_objects_foreign_arg *)arg;
4330 if (objspace == a->self) return;
4331 rb_gc_impl_each_objects_foreign(objspace, a->callback, a->data);
4332}
4333
4334/*
4335 * rb_objspace_each_objects() is special C API to walk through
4336 * Ruby object space. This C API is too difficult to use it.
4337 * To be frank, you should not use it. Or you need to read the
4338 * source code of this function and understand what this function does.
4339 *
4340 * 'callback' will be called several times (the number of heap page,
4341 * at current implementation) with:
4342 * vstart: a pointer to the first living object of the heap_page.
4343 * vend: a pointer to next to the valid heap_page area.
4344 * stride: a distance to next VALUE.
4345 *
4346 * If callback() returns non-zero, the iteration will be stopped.
4347 *
4348 * This takes the VM barrier for the whole walk, stopping every other
4349 * Ractor: the set of heap pages must not change under the callback, and a
4350 * GC is stop-the-world. Because of that, the callback must not wait on
4351 * another Ractor (e.g. send/receive) -- they are all suspended and it
4352 * would deadlock.
4353 *
4354 * This is a sample callback code to iterate liveness objects:
4355 *
4356 * static int
4357 * sample_callback(void *vstart, void *vend, int stride, void *data)
4358 * {
4359 * VALUE v = (VALUE)vstart;
4360 * for (; v != (VALUE)vend; v += stride) {
4361 * if (!rb_objspace_internal_object_p(v)) { // liveness check
4362 * // do something with live object 'v'
4363 * }
4364 * }
4365 * return 0; // continue to iteration
4366 * }
4367 *
4368 * Note: 'vstart' is not a top of heap_page. This point the first
4369 * living object to grasp at least one object to avoid GC issue.
4370 * This means that you can not walk through all Ruby object page
4371 * including freed object page.
4372 *
4373 * Note: On this implementation, 'stride' is the same as sizeof(RVALUE).
4374 * However, there are possibilities to pass variable values with
4375 * 'stride' with some reasons. You must use stride instead of
4376 * use some constant value in the iteration.
4377 */
4378void
4379rb_objspace_each_objects(int (*callback)(void *, void *, size_t, void *), void *data)
4380{
4381 RB_VM_LOCKING() {
4382 rb_vm_barrier();
4383
4384 void *self = rb_gc_get_objspace();
4385 rb_gc_impl_each_objects(self, callback, data);
4386
4387 /* Like upstream, cover every object in the process: walk the other live
4388 * Ractors' objspaces too, under the VM lock and barrier, with a pure-C callback.
4389 * A foreign objspace's stopped lazy sweep is not settled; the walk skips its
4390 * dead objects. Also covers zombie objspaces. */
4391 struct each_objects_foreign_arg arg = { self, callback, data };
4392 rb_gc_vm_each_objspace(each_objects_foreign_i, &arg);
4393 }
4394}
4395
4396/* Enumerate live, creating, and zombie objspaces under the VM lifetime lock.
4397 * Reading foreign mutable collector state also needs the barrier; independently
4398 * synchronized publications may be read under their own locks without a barrier. */
4399void
4400rb_gc_vm_each_objspace(void (*func)(void *objspace, void *data), void *data)
4401{
4402 ASSERT_vm_locking();
4403
4404 rb_vm_t *vm = GET_VM();
4405 rb_ractor_t *r;
4406 ccan_list_for_each(&vm->ractor.set, r, vmlr_node) {
4407 if (r->objspace) {
4408 func(r->objspace, data);
4409 }
4410 /* A child being created is not in the set yet but its objspace already holds
4411 * the Thread/Fiber wrappers; enumerate it through its creator so a global GC
4412 * cannot miss it and mark into an objspace it never cleared. */
4413 if (r->creating_child_objspace) {
4414 func(r->creating_child_objspace, data);
4415 }
4416 }
4417 for (size_t i = 0; i < vm->gc.zombie_objspaces_count; i++) {
4418 func(vm->gc.zombie_objspaces[i].objspace, data);
4419 }
4420}
4421
4422/* Merging an ownerless zombie objspace (its Ractor object was collected) into main
4423 * runs as a postponed job targeted at main, at main's next safepoint; never inside
4424 * the GC cycle that discovered the orphan. */
4425
4426static void gc_orphan_merge_job(void *unused);
4427
4428/* Grown with plain realloc: rb_gc_objspace_disown pushes from inside a global GC
4429 * sweep, where the accounting allocator is not allowed. This table is VM-lifetime
4430 * metadata with at most a few dozen entries. */
4431static void
4432zombie_objspaces_push(rb_vm_t *vm, void *objspace, void **owner_slot, struct rb_ractor_struct *owner)
4433{
4434 ASSERT_vm_locking();
4435 if (vm->gc.zombie_objspaces_count == vm->gc.zombie_objspaces_capa) {
4436 size_t new_capa = vm->gc.zombie_objspaces_capa ? vm->gc.zombie_objspaces_capa * 2 : 16;
4437 struct rb_objspace_zombie *grown =
4438 realloc(vm->gc.zombie_objspaces, new_capa * sizeof(struct rb_objspace_zombie));
4439 if (grown == NULL) rb_bug("zombie_objspaces_push: out of memory");
4440 vm->gc.zombie_objspaces = grown;
4441 vm->gc.zombie_objspaces_capa = new_capa;
4442 }
4443 size_t pages = rb_gc_impl_heap_page_count(objspace);
4444 vm->gc.zombie_objspaces[vm->gc.zombie_objspaces_count++] = (struct rb_objspace_zombie){
4445 .objspace = objspace,
4446 .owner_slot = owner_slot,
4447 .owner = owner,
4448 .pages = pages,
4449 };
4450 vm->gc.zombie_total_pages += pages;
4451}
4452
4453/* Called for a Ractor that terminated without being joined. Its objspace loses its
4454 * owning thread, but its pages still hold shareable objects other Ractors can reach,
4455 * so keep it enumerable until inheritance merges it. The owning r->objspace slot stays
4456 * until the inheriting path takes the objspace and clears it. */
4457/* Reserve the handle of the orphan-merge job if it is not registered yet. Shared by
4458 * every retire and disown path; a second preregister is idempotent (the same func and
4459 * data are deduplicated). */
4460static void
4461gc_orphan_merge_pjob_ensure(void)
4462{
4463 if (GET_VM()->gc.orphan_merge_pjob == POSTPONED_JOB_HANDLE_INVALID) {
4464 GET_VM()->gc.orphan_merge_pjob = rb_postponed_job_preregister(0, gc_orphan_merge_job, NULL);
4465 if (GET_VM()->gc.orphan_merge_pjob == POSTPONED_JOB_HANDLE_INVALID) {
4466 rb_bug("Could not preregister postponed job for GC");
4467 }
4468 }
4469}
4470
4471/* A terminating Ractor runs the last local GC of its own objspace; own thread only. */
4472void
4473rb_gc_objspace_retire_gc(void)
4474{
4475 rb_gc_impl_objspace_retire_gc(rb_gc_get_objspace());
4476}
4477
4478void
4479rb_gc_objspace_retire(void **objspace_slot)
4480{
4481 rb_vm_t *vm = GET_VM();
4482
4483 if (!rb_gc_impl_multi_objspace_p()) {
4484 /* It only aliased the shared objspace, so just drop it. */
4485 *objspace_slot = NULL;
4486 return;
4487 }
4488
4489 /* Return the hold if the Ractor exits with GC disabled: otherwise nobody can
4490 * enable it again and GC stays off. */
4491 if (rb_gc_impl_user_gc_disabled_set(*objspace_slot, false)) {
4492 RUBY_ATOMIC_DEC(vm->gc.disable_holders);
4493 }
4494
4495 RB_VM_LOCKING() {
4496 gc_orphan_merge_pjob_ensure();
4497 /* owner_slot is always &r->objspace of the retiring Ractor. owner is recorded so a
4498 * root scan can still reach the dead Ractor's registered_marks pins and its join
4499 * value; rb_gc_objspace_disown clears it when the zombie becomes an orphan. */
4500 struct rb_ractor_struct *owner =
4501 (struct rb_ractor_struct *)((char *)objspace_slot - offsetof(rb_ractor_t, objspace));
4502 zombie_objspaces_push(vm, *objspace_slot, objspace_slot, owner);
4503 }
4504}
4505
4506/* The owning Ractor object was collected, so nobody can join any more: drop the owner
4507 * slot in zombie_objspaces and hand the merge to main. Called from ractor_free (inside
4508 * a sweep), where the accounting allocator is unavailable; the table itself is stable. */
4509void
4510rb_gc_objspace_disown(void *objspace)
4511{
4512 if (!rb_gc_impl_multi_objspace_p()) return;
4513 ASSERT_vm_locking();
4514 rb_vm_t *vm = GET_VM();
4515 bool found = false;
4516
4517 for (size_t i = 0; i < vm->gc.zombie_objspaces_count; i++) {
4518 if (vm->gc.zombie_objspaces[i].objspace == objspace) {
4519 vm->gc.zombie_objspaces[i].owner_slot = NULL;
4520 /* The Ractor struct is being freed, so drop owner too: nothing may read its
4521 * registered_marks or join value after this. */
4522 vm->gc.zombie_objspaces[i].owner = NULL;
4523 found = true;
4524 break;
4525 }
4526 }
4527 if (!found) {
4528 zombie_objspaces_push(vm, objspace, NULL, NULL);
4529 }
4530
4531 /* The trigger is wait-free (an atomic bit plus an interrupt flag), so it is safe
4532 * inside a sweep, and it also covers a Ractor that never started. */
4533 gc_orphan_merge_pjob_ensure();
4534 rb_postponed_job_trigger_for_ractor(GET_VM()->gc.orphan_merge_pjob, vm->ractor.main_ractor->pub.self);
4535}
4536
4537/* Is a global (stop-the-world) GC cycle running? Only its driver runs during one, so
4538 * asking through the current objspace is exact. */
4539bool
4540rb_gc_during_global_gc_p(void)
4541{
4542 return rb_gc_impl_during_global_gc_p(rb_gc_get_objspace());
4543}
4544
4545static void
4546rb_gc_vm_forget_zombie(void *objspace)
4547{
4548 ASSERT_vm_locking();
4549 rb_vm_t *vm = GET_VM();
4550 size_t n = vm->gc.zombie_objspaces_count;
4551 for (size_t i = 0; i < n; i++) {
4552 if (vm->gc.zombie_objspaces[i].objspace == objspace) {
4553 vm->gc.zombie_total_pages -= vm->gc.zombie_objspaces[i].pages;
4554 vm->gc.zombie_objspaces[i] = vm->gc.zombie_objspaces[n - 1];
4555 vm->gc.zombie_objspaces_count = n - 1;
4556 break;
4557 }
4558 }
4559}
4560
4561/* Total zombie pages, deciding whether to start a global GC. An upper bound between
4562 * global cycles (each re-measures under the barrier), so a stale value cannot
4563 * re-trigger; a lock-free read at worst fires one cycle early or late. */
4564size_t
4565rb_gc_vm_zombie_total_pages(void)
4566{
4567 return GET_VM()->gc.zombie_total_pages;
4568}
4569
4570/* Number of live Ractors, for the heap growth heuristic (r_mul); a racy read is fine. */
4571unsigned int
4572rb_gc_vm_ractor_count(void)
4573{
4574 return GET_VM()->ractor.cnt;
4575}
4576
4577/* Called by a global cycle from inside the barrier. */
4578void
4579rb_gc_vm_refresh_zombie_pages(void)
4580{
4581 rb_vm_t *vm = GET_VM();
4582 size_t total = 0;
4583 for (size_t i = 0; i < vm->gc.zombie_objspaces_count; i++) {
4584 size_t pages = rb_gc_impl_heap_page_count(vm->gc.zombie_objspaces[i].objspace);
4585 vm->gc.zombie_objspaces[i].pages = pages;
4586 total += pages;
4587 }
4588 vm->gc.zombie_total_pages = total;
4589}
4590
4591void
4592rb_gc_rest(void)
4593{
4594 // Lock to keep assertions happy. This runs right after single-ractor mode is
4595 // cancelled, but we can still free shareables like fstrings because ractor.cnt is 1.
4596 RB_VM_LOCKING() {
4597 rb_gc_impl_gc_rest(rb_gc_get_objspace());
4598 }
4599}
4600
4601/* True while a zombie is being absorbed. The zombie's count is decremented before the
4602 * merge (see absorb below), so in that window its live objects still exist even though
4603 * the process looks single-objspace. */
4604static int gc_absorbing_zombie = 0;
4605
4606/* True once a zombie objspace was absorbed since the last global GC: until the unified
4607 * mark runs, a single-objspace local mark can miss absorbed shareable objects (a cc in
4608 * a class's cc_table, say), so stop treating the process as single until then. */
4609static bool gc_absorbed_since_global_gc = false;
4610
4611void
4612rb_gc_reset_absorbed_since_global_gc(void)
4613{
4614 gc_absorbed_since_global_gc = false;
4615}
4616
4617/* True when the process holds exactly one objspace (one live Ractor, no zombies) and
4618 * nothing was absorbed since the last global GC. Only then is a local GC the whole
4619 * world and the multi-objspace guards can be skipped. The child-creation window (the
4620 * child objspace exists while cnt is still 1) and both absorb windows, during (count
4621 * already decremented, merge unfinished) and after (merged, next global GC pending) --
4622 * count as multi: treating them as single would let a GC skip guards such as shareable
4623 * pinning and collect a live cc. */
4624/* False when the impl only supports one objspace (mmtk and friends); the VM then makes
4625 * its per-Ractor objspace machinery (retire, absorb, creation cover) a no-op. */
4626bool
4627rb_gc_multi_objspace_p(void)
4628{
4629 return rb_gc_impl_multi_objspace_p();
4630}
4631
4632/* Does obj belong to another Ractor's objspace rather than the current one? Always
4633 * false for a single-objspace impl, which cannot tell owners apart. */
4634bool
4635rb_gc_obj_foreign_p(VALUE obj)
4636{
4637 return rb_gc_impl_obj_foreign_p(rb_gc_get_objspace(), obj);
4638}
4639
4640bool
4641rb_gc_single_objspace_p(void)
4642{
4643 if (!rb_gc_impl_multi_objspace_p()) return true;
4644 rb_vm_t *vm = GET_VM();
4645 /* One Ractor is not one objspace: a forked child re-enters single-Ractor mode while
4646 * the pre-fork Ractors' objspaces are still parked in zombie_objspaces. */
4647 return (ruby_single_main_ractor != NULL || vm->ractor.cnt == 1) &&
4648 vm->gc.zombie_objspaces_count == 0 && gc_absorbing_zombie == 0 &&
4649 !gc_absorbed_since_global_gc &&
4650 (vm->ractor.main_ractor == NULL ||
4651 vm->ractor.main_ractor->creating_child_objspace == NULL);
4652}
4653
4654/* Inherit a dead Ractor's objspace into the calling Ractor. Going through the owner
4655 * slot clears it and releases the objspace in one VM-lock section; the merge runs with
4656 * the inheritor's GC disabled (moving the finalizer st table could trigger it). */
4657static void
4658objspace_absorb_merge(void *dst, void *src)
4659{
4660 ASSERT_vm_locking();
4661 rb_gc_impl_objspace_absorb(dst, src);
4662 gc_absorbed_since_global_gc = true;
4663}
4664
4665/* The dying thread's last collection of its own objspace, GVL still held; with
4666 * r->postmortem set, rb_ractor_mark_local_roots roots only the join value and the
4667 * registered_marks pins, so the scaffolding nobody needs any more dies here. */
4668void
4669rb_gc_objspace_postmortem_self(void)
4670{
4671 if (!rb_gc_impl_multi_objspace_p()) return;
4672
4673 rb_gc_impl_objspace_retire_gc(rb_gc_get_objspace());
4674}
4675
4676void
4677rb_gc_objspace_absorb_into_current(void **objspace_slot)
4678{
4679 if (!rb_gc_impl_multi_objspace_p()) {
4680 *objspace_slot = NULL;
4681 return;
4682 }
4683 RB_VM_LOCKING() {
4684 void *objspace = *objspace_slot;
4685 if (objspace != NULL) {
4686 *objspace_slot = NULL;
4687 gc_absorbing_zombie++;
4688 rb_gc_vm_forget_zombie(objspace);
4689 objspace_absorb_merge(rb_gc_get_objspace(), objspace);
4690 gc_absorbing_zombie--;
4691 }
4692 }
4693}
4694
4695/* Merge every ownerless zombie objspace (no owner slot, i.e. the Ractor object was
4696 * collected) into the current Ractor's objspace. Runs as a postponed job on the main
4697 * Ractor's thread; the VM teardown path calls it directly. */
4698static void
4699objspace_absorb_disowned_zombies(void)
4700{
4701 rb_vm_t *vm = GET_VM();
4702
4703 RB_VM_LOCKING() {
4704 size_t i = 0;
4705 while (i < vm->gc.zombie_objspaces_count) {
4706 if (vm->gc.zombie_objspaces[i].owner_slot == NULL) {
4707 void *zombie = vm->gc.zombie_objspaces[i].objspace;
4708 /* Remove via forget, which also subtracts the entry's pages from
4709 * zombie_total_pages; a hand-written swap-remove would leave a phantom
4710 * total that keeps starting stop-the-world global cycles. */
4711 gc_absorbing_zombie++;
4712 rb_gc_vm_forget_zombie(zombie);
4713 objspace_absorb_merge(rb_gc_get_objspace(), zombie);
4714 gc_absorbing_zombie--;
4715 }
4716 else {
4717 i++;
4718 }
4719 }
4720 }
4721}
4722
4723static void
4724gc_orphan_merge_job(void *unused)
4725{
4726 (void)unused;
4727 objspace_absorb_disowned_zombies();
4728}
4729
4730/* Re-target a pending orphan merge after fork. The job may target the parent's main
4731 * Ractor, whose per-Ractor trigger mask is not inherited unless that Ractor forked.
4732 * Called on the child side. */
4733/* Only main survives a fork, so rebuild the counter from main's own hold alone. */
4734void
4735rb_gc_disable_holders_atfork(void)
4736{
4737 RUBY_ATOMIC_SET(GET_VM()->gc.disable_holders,
4738 rb_gc_impl_user_gc_disabled_p(rb_gc_get_objspace()) ? 1 : 0);
4739}
4740
4741void
4742rb_gc_zombie_objspaces_atfork(void)
4743{
4744 rb_vm_t *vm = GET_VM();
4745
4746 for (size_t i = 0; i < vm->gc.zombie_objspaces_count; i++) {
4747 if (vm->gc.zombie_objspaces[i].owner_slot == NULL) {
4748 rb_postponed_job_trigger_for_ractor(GET_VM()->gc.orphan_merge_pjob, vm->ractor.main_ractor->pub.self);
4749 break;
4750 }
4751 }
4752}
4753
4754/* VM teardown, right after every other Ractor was killed: merge all uninherited
4755 * objspaces into main so at-exit processing covers every object and dead Ractors'
4756 * deferred finalizers run on main. The owner slot also covers collected wrappers. */
4757void
4758rb_gc_objspace_absorb_all_zombies(void)
4759{
4760 rb_vm_t *vm = GET_VM();
4761
4762 /* Entries whose Ractor object is already gone, i.e. the pending merge job itself,
4763 * which we run synchronously here. */
4764 objspace_absorb_disowned_zombies();
4765
4766 while (vm->gc.zombie_objspaces_count > 0) {
4767 size_t before = vm->gc.zombie_objspaces_count;
4768 GC_ASSERT(vm->gc.zombie_objspaces[0].owner_slot != NULL);
4769 /* Move the rb_gc_register_mark_object pins before the merge, so the objects
4770 * pinned in the owner's objspace do not lose their root in its sweep. */
4771 rb_ractor_t *owner = vm->gc.zombie_objspaces[0].owner;
4772 if (owner) {
4773 rb_ractor_absorb_registered_marks(GET_RACTOR(), owner);
4774 rb_ractor_absorb_registered_addrs_without_gc(GET_RACTOR(), owner);
4775 }
4776 rb_gc_objspace_absorb_into_current(vm->gc.zombie_objspaces[0].owner_slot);
4777 if (vm->gc.zombie_objspaces_count >= before) {
4778 rb_bug("rb_gc_objspace_absorb_all_zombies: zombie list did not shrink");
4779 }
4780 }
4781}
4782
4783static void
4784gc_ref_update_array(void *objspace, VALUE v)
4785{
4786 if (ARY_SHARED_P(v)) {
4787 VALUE old_root = RARRAY(v)->as.heap.aux.shared_root;
4788
4789 UPDATE_IF_MOVED(objspace, RARRAY(v)->as.heap.aux.shared_root);
4790
4791 VALUE new_root = RARRAY(v)->as.heap.aux.shared_root;
4792 // A root hollowed out by a move is no longer an array, and it is pinned rather
4793 // than re-pointed (see the marking of a shared root).
4794 // If the root is embedded and its location has changed
4795 if (RB_TYPE_P(new_root, T_ARRAY) && ARY_EMBED_P(new_root) && new_root != old_root) {
4796 size_t offset = (size_t)(RARRAY(v)->as.heap.ptr - RARRAY(old_root)->as.ary);
4797 GC_ASSERT(RARRAY(v)->as.heap.ptr >= RARRAY(old_root)->as.ary);
4798 RARRAY(v)->as.heap.ptr = RARRAY(new_root)->as.ary + offset;
4799 }
4800 }
4801 else {
4802 long len = RARRAY_LEN(v);
4803
4804 if (len > 0) {
4805 VALUE *ptr = (VALUE *)RARRAY_CONST_PTR(v);
4806 for (long i = 0; i < len; i++) {
4807 UPDATE_IF_MOVED(objspace, ptr[i]);
4808 }
4809 }
4810
4811 if (!ARY_EMBED_P(v) && rb_gc_obj_slot_size(v) >= rb_ary_size_as_embedded(v)) {
4812 /* Skip pinned arrays: a pinned array may be referenced from a
4813 * conservative root holding RARRAY_PTR across this compaction, so
4814 * freeing its heap buffer here would dangle that pointer. */
4815 if (rb_ary_embeddable_p(v) && !rb_gc_impl_pinned_p(objspace, v)) {
4816 rb_ary_make_embedded(v);
4817 }
4818 }
4819 }
4820}
4821
4822static void
4823gc_ref_update_object(void *objspace, VALUE v)
4824{
4825 RUBY_ASSERT(rb_gc_obj_slot_size(v) == rb_obj_shape_slot_size(v));
4826 shape_id_t shape_id = RBASIC_SHAPE_ID(v);
4827
4828 if (!rb_shape_embedded_p(shape_id)) {
4829 UPDATE_IF_MOVED(objspace, ROBJECT(v)->as.extended);
4830
4831 if (!rb_shape_complex_p(shape_id) && rb_shape_embedded_capacity(shape_id) >= RSHAPE_LEN(shape_id)) {
4832 VALUE *embedded_fields = ROBJECT_EMBEDDED_FIELDS(v);
4833 VALUE *extended_fields = ROBJECT_FIELDS(v);
4834 MEMCPY(embedded_fields, extended_fields, VALUE, RSHAPE_LEN(shape_id));
4835 shape_id = rb_shape_transition_robject(shape_id);
4836 RBASIC_SET_FULL_SHAPE_ID(v, shape_id);
4837 rb_gc_writebarrier_remember(v);
4838 }
4839 else {
4840 return;
4841 }
4842 }
4843
4844 VALUE *ptr = ROBJECT_FIELDS(v);
4845 attr_index_t len = RSHAPE_LEN(shape_id);
4846 for (attr_index_t i = 0; i < len; i++) {
4847 UPDATE_IF_MOVED(objspace, ptr[i]);
4848 }
4849}
4850
4851void
4852rb_gc_ref_update_table_values_only(st_table *tbl)
4853{
4854 gc_ref_update_table_values_only(tbl);
4855}
4856
4857/* Update MOVED references in a VALUE=>VALUE st_table */
4858void
4859rb_gc_update_tbl_refs(st_table *ptr)
4860{
4861 gc_update_table_refs(ptr);
4862}
4863
4864static int
4865rb_gc_update_set_refs_i(st_data_t key, st_data_t value, st_data_t argp, int error)
4866{
4867 if (rb_gc_location((VALUE)key) != (VALUE)key) {
4868 return ST_REPLACE;
4869 }
4870
4871 return ST_CONTINUE;
4872}
4873
4874static int
4875rb_gc_update_set_refs_replace_i(st_data_t *key, st_data_t *value, st_data_t argp, int existing)
4876{
4877 rb_gc_update_moved((VALUE *)key);
4878
4879 return ST_CONTINUE;
4880}
4881
4882void
4883rb_gc_update_set_refs(st_table *tbl)
4884{
4885 if (!tbl || tbl->num_entries == 0) return;
4886
4887 if (st_foreach_with_replace(tbl, rb_gc_update_set_refs_i, rb_gc_update_set_refs_replace_i, 0)) {
4888 rb_raise(rb_eRuntimeError, "hash modified during iteration");
4889 }
4890}
4891
4892static void
4893gc_ref_update_hash(void *objspace, VALUE v)
4894{
4895 rb_hash_stlike_foreach_with_replace(v, hash_foreach_replace, hash_replace_ref, (st_data_t)objspace);
4896}
4897
4898static void
4899gc_update_values(void *objspace, long n, VALUE *values)
4900{
4901 for (long i = 0; i < n; i++) {
4902 UPDATE_IF_MOVED(objspace, values[i]);
4903 }
4904}
4905
4906void
4907rb_gc_update_values(long n, VALUE *values)
4908{
4909 gc_update_values(rb_gc_get_objspace(), n, values);
4910}
4911
4912static enum rb_id_table_iterator_result
4913check_id_table_move(VALUE value, void *data)
4914{
4915 void *objspace = (void *)data;
4916
4917 if (gc_object_moved_p_internal(objspace, (VALUE)value)) {
4918 return ID_TABLE_REPLACE;
4919 }
4920
4921 return ID_TABLE_CONTINUE;
4922}
4923
4924void
4925rb_gc_prepare_heap_process_object(VALUE obj)
4926{
4927 switch (BUILTIN_TYPE(obj)) {
4928 case T_STRING:
4929 // Precompute the string coderange. This both save time for when it will be
4930 // eventually needed, and avoid mutating heap pages after a potential fork.
4931 rb_enc_str_coderange(obj);
4932 break;
4933 default:
4934 break;
4935 }
4936}
4937
4938void
4939rb_gc_prepare_heap(void)
4940{
4941 rb_gc_impl_prepare_heap(rb_gc_get_objspace());
4942}
4943
4944size_t
4945rb_gc_size_slot_size(size_t size)
4946{
4947 return rb_gc_impl_size_slot_size(rb_gc_get_objspace(), size);
4948}
4949
4950bool
4951rb_gc_size_allocatable_p(size_t size)
4952{
4953 return rb_gc_impl_size_allocatable_p(size);
4954}
4955
4956size_t
4957rb_gc_max_allocation_size(void)
4958{
4959 return rb_gc_impl_max_allocation_size();
4960}
4961
4962static enum rb_id_table_iterator_result
4963update_id_table(VALUE *value, void *data, int existing)
4964{
4965 void *objspace = (void *)data;
4966
4967 if (gc_object_moved_p_internal(objspace, (VALUE)*value)) {
4968 *value = gc_location_internal(objspace, (VALUE)*value);
4969 }
4970
4971 return ID_TABLE_CONTINUE;
4972}
4973
4974static void
4975update_m_tbl(void *objspace, struct rb_id_table *tbl)
4976{
4977 if (tbl) {
4978 rb_id_table_foreach_values_with_replace(tbl, check_id_table_move, update_id_table, objspace);
4979 }
4980}
4981
4982static enum rb_id_table_iterator_result
4983update_const_tbl_i(VALUE value, void *objspace)
4984{
4985 rb_const_entry_t *ce = (rb_const_entry_t *)value;
4986
4987 if (gc_object_moved_p_internal(objspace, ce->value)) {
4988 ce->value = gc_location_internal(objspace, ce->value);
4989 }
4990
4991 if (gc_object_moved_p_internal(objspace, ce->file)) {
4992 ce->file = gc_location_internal(objspace, ce->file);
4993 }
4994
4995 return ID_TABLE_CONTINUE;
4996}
4997
4998static void
4999update_const_tbl(void *objspace, struct rb_id_table *tbl)
5000{
5001 if (!tbl) return;
5002 rb_id_table_foreach_values(tbl, update_const_tbl_i, objspace);
5003}
5004
5005static void
5006update_superclasses(rb_objspace_t *objspace, rb_classext_t *ext)
5007{
5008 if (RCLASSEXT_SUPERCLASSES_WITH_SELF(ext)) {
5009 size_t array_size = RCLASSEXT_SUPERCLASS_DEPTH(ext) + 1;
5010 for (size_t i = 0; i < array_size; i++) {
5011 UPDATE_IF_MOVED(objspace, RCLASSEXT_SUPERCLASSES(ext)[i]);
5012 }
5013 }
5014}
5015
5016static void
5017update_classext_values(rb_objspace_t *objspace, rb_classext_t *ext, bool is_iclass)
5018{
5019 UPDATE_IF_MOVED(objspace, RCLASSEXT_ORIGIN(ext));
5020 UPDATE_IF_MOVED(objspace, RCLASSEXT_REFINED_CLASS(ext));
5021 UPDATE_IF_MOVED(objspace, RCLASSEXT_CLASSPATH(ext));
5022 if (is_iclass) {
5023 UPDATE_IF_MOVED(objspace, RCLASSEXT_INCLUDER(ext));
5024 }
5025}
5026
5027static void
5028update_classext(rb_classext_t *ext, bool is_prime, VALUE box_value, void *arg)
5029{
5030 struct classext_foreach_args *args = (struct classext_foreach_args *)arg;
5031 rb_objspace_t *objspace = args->objspace;
5032
5033 if (RCLASSEXT_SUPER(ext)) {
5034 UPDATE_IF_MOVED(objspace, RCLASSEXT_SUPER(ext));
5035 }
5036
5037 update_m_tbl(objspace, RCLASSEXT_M_TBL(ext));
5038
5039 UPDATE_IF_MOVED(objspace, ext->fields_obj);
5040 if (!RCLASSEXT_SHARED_CONST_TBL(ext)) {
5041 update_const_tbl(objspace, RCLASSEXT_CONST_TBL(ext));
5042 }
5043 UPDATE_IF_MOVED(objspace, RCLASSEXT_CC_TBL(ext));
5044 UPDATE_IF_MOVED(objspace, RCLASSEXT_CVC_TBL(ext));
5045 update_superclasses(objspace, ext);
5046 if (RCLASSEXT_SUBCLASSES(ext)) {
5047 UPDATE_IF_MOVED(objspace, RCLASSEXT_SUBCLASSES(ext));
5048 }
5049
5050 update_classext_values(objspace, ext, false);
5051}
5052
5053static void
5054update_iclass_classext(rb_classext_t *ext, bool is_prime, VALUE box_value, void *arg)
5055{
5056 struct classext_foreach_args *args = (struct classext_foreach_args *)arg;
5057 rb_objspace_t *objspace = args->objspace;
5058
5059 if (RCLASSEXT_SUPER(ext)) {
5060 UPDATE_IF_MOVED(objspace, RCLASSEXT_SUPER(ext));
5061 }
5062 update_m_tbl(objspace, RCLASSEXT_M_TBL(ext));
5063 update_m_tbl(objspace, RCLASSEXT_CALLABLE_M_TBL(ext));
5064 UPDATE_IF_MOVED(objspace, RCLASSEXT_CC_TBL(ext));
5065 UPDATE_IF_MOVED(objspace, RCLASSEXT_CVC_TBL(ext));
5066 if (RCLASSEXT_SUBCLASSES(ext)) {
5067 UPDATE_IF_MOVED(objspace, RCLASSEXT_SUBCLASSES(ext));
5068 }
5069
5070 update_classext_values(objspace, ext, true);
5071}
5072
5074 vm_table_foreach_callback_func callback;
5075 vm_table_update_callback_func update_callback;
5076 void *data;
5077 bool weak_only;
5078 /* The generic_fields table being walked, so compaction can re-insert a moved key
5079 * into it (rb_generic_fields_tables_foreach hands the table to the callback). */
5080 struct st_table *gen_fields_current_tbl;
5081 /* Re-inserting a moved key adds an entry, which can rehash and break the running
5082 * iterator, so collect them and insert after the walk (raw realloc: we are in GC). */
5083 struct gen_fields_deferred_insert { st_data_t k, v; } *gf_deferred;
5084 size_t gf_deferred_cnt, gf_deferred_capa;
5085};
5086
5087static int
5088vm_weak_table_foreach_weak_key(st_data_t key, st_data_t value, st_data_t data, int error)
5089{
5090 struct global_vm_table_foreach_data *iter_data = (struct global_vm_table_foreach_data *)data;
5091
5092 int ret = iter_data->callback((VALUE)key, iter_data->data);
5093
5094 if (!iter_data->weak_only) {
5095 if (ret != ST_CONTINUE) return ret;
5096
5097 ret = iter_data->callback((VALUE)value, iter_data->data);
5098 }
5099
5100 return ret;
5101}
5102
5103static int
5104vm_weak_table_foreach_update_weak_key(st_data_t *key, st_data_t *value, st_data_t data, int existing)
5105{
5106 struct global_vm_table_foreach_data *iter_data = (struct global_vm_table_foreach_data *)data;
5107
5108 int ret = iter_data->update_callback((VALUE *)key, iter_data->data);
5109
5110 if (!iter_data->weak_only) {
5111 if (ret != ST_CONTINUE) return ret;
5112
5113 ret = iter_data->update_callback((VALUE *)value, iter_data->data);
5114 }
5115
5116 return ret;
5117}
5118
5119static int
5120vm_weak_table_sym_set_foreach(VALUE *sym_ptr, void *data)
5121{
5122 VALUE sym = *sym_ptr;
5123 struct global_vm_table_foreach_data *iter_data = (struct global_vm_table_foreach_data *)data;
5124
5125 if (RB_SPECIAL_CONST_P(sym)) return ST_CONTINUE;
5126
5127 int ret = iter_data->callback(sym, iter_data->data);
5128
5129 if (ret == ST_REPLACE) {
5130 ret = iter_data->update_callback(sym_ptr, iter_data->data);
5131 }
5132
5133 return ret;
5134}
5135
5136struct st_table *rb_generic_fields_tbl_get(void);
5137
5138static int
5139vm_weak_table_gen_fields_foreach(st_data_t key, st_data_t value, st_data_t data)
5140{
5141 struct global_vm_table_foreach_data *iter_data = (struct global_vm_table_foreach_data *)data;
5142
5143 int ret = iter_data->callback((VALUE)key, iter_data->data);
5144
5145 VALUE new_value = (VALUE)value;
5146 VALUE new_key = (VALUE)key;
5147
5148 switch (ret) {
5149 case ST_CONTINUE:
5150 break;
5151
5152 case ST_DELETE:
5153 // When we're removing an object from the weak ref table, we need to
5154 // set the shape on it so that the GC finalizer won't try to remove
5155 // it again. A "root shape" indicates to the GC that this object
5156 // has no fields on it, hence it won't be in the gen fields table.
5157 if (BUILTIN_TYPE((VALUE)key) != T_NONE) {
5158 RBASIC_SET_SHAPE_ID((VALUE)key, ROOT_SHAPE_ID);
5159 }
5160 return ST_DELETE;
5161
5162 case ST_REPLACE: {
5163 ret = iter_data->update_callback(&new_key, iter_data->data);
5164 if (key != new_key) {
5165 ret = ST_DELETE;
5166 }
5167 break;
5168 }
5169
5170 default:
5171 rb_bug("vm_weak_table_gen_fields_foreach: return value %d not supported", ret);
5172 }
5173
5174 if (!iter_data->weak_only) {
5175 int ivar_ret = iter_data->callback(new_value, iter_data->data);
5176 switch (ivar_ret) {
5177 case ST_CONTINUE:
5178 break;
5179
5180 case ST_REPLACE:
5181 iter_data->update_callback(&new_value, iter_data->data);
5182 break;
5183
5184 case ST_DELETE:
5185 /* Leftover entry of a moved host: even if the key is alive, nobody can
5186 * read these fields once fields_obj is unreachable, so clean up as if the
5187 * key had died. */
5188 RBASIC_SET_SHAPE_ID((VALUE)key, ROOT_SHAPE_ID);
5189 return ST_DELETE;
5190
5191 default:
5192 rb_bug("vm_weak_table_gen_fields_foreach: return value %d not supported", ivar_ret);
5193 }
5194 }
5195
5196 if (key != new_key) {
5197 /* Inserting the new key adds an entry and may rehash, so defer it. */
5198 if (iter_data->gf_deferred_cnt == iter_data->gf_deferred_capa) {
5199 size_t nc = iter_data->gf_deferred_capa ? iter_data->gf_deferred_capa * 2 : 64;
5200 struct gen_fields_deferred_insert *p =
5201 realloc(iter_data->gf_deferred, nc * sizeof(*p));
5202 if (!p) rb_bug("vm_weak_table_gen_fields_foreach: out of memory");
5203 iter_data->gf_deferred = p;
5204 iter_data->gf_deferred_capa = nc;
5205 }
5206 iter_data->gf_deferred[iter_data->gf_deferred_cnt++] =
5207 (struct gen_fields_deferred_insert){ .k = (st_data_t)new_key, .v = (st_data_t)new_value };
5208 }
5209 else if (value != new_value) {
5210 DURING_GC_COULD_MALLOC_REGION_START();
5211 {
5212 /* Updating an existing key's value adds no entry and cannot rehash. */
5213 st_insert(iter_data->gen_fields_current_tbl, (st_data_t)new_key, new_value);
5214 }
5215 DURING_GC_COULD_MALLOC_REGION_END();
5216 }
5217
5218 return ret;
5219}
5220
5221static int
5222vm_weak_table_frozen_strings_foreach(VALUE *str, void *data)
5223{
5224 // int retval = vm_weak_table_foreach_weak_key(key, value, data, error);
5225 struct global_vm_table_foreach_data *iter_data = (struct global_vm_table_foreach_data *)data;
5226 int retval = iter_data->callback(*str, iter_data->data);
5227
5228 if (retval == ST_REPLACE) {
5229 retval = iter_data->update_callback(str, iter_data->data);
5230 }
5231
5232 if (retval == ST_DELETE) {
5233 FL_UNSET(*str, RSTRING_FSTR);
5234 }
5235
5236 return retval;
5237}
5238
5239void rb_fstring_foreach_with_replace(int (*callback)(VALUE *str, void *data), void *data);
5240
5241/* Callback of rb_generic_fields_tables_foreach: walk one generic_fields table with the
5242 * gen_fields foreach used by compaction, recording the current table in foreach_data so
5243 * a moved key is re-inserted into the right one. */
5244static void
5245vm_weak_table_gen_fields_tbl_cb(struct st_table *tbl, void *arg)
5246{
5247 struct global_vm_table_foreach_data *foreach_data = (struct global_vm_table_foreach_data *)arg;
5248 foreach_data->gen_fields_current_tbl = tbl;
5249 st_foreach(tbl, vm_weak_table_gen_fields_foreach, (st_data_t)foreach_data);
5250}
5251
5252void
5253rb_gc_vm_weak_table_foreach(vm_table_foreach_callback_func callback,
5254 vm_table_update_callback_func update_callback,
5255 void *data,
5256 bool weak_only,
5257 enum rb_gc_vm_weak_tables table)
5258{
5259 rb_vm_t *vm = GET_VM();
5260
5261 struct global_vm_table_foreach_data foreach_data = {
5262 .callback = callback,
5263 .update_callback = update_callback,
5264 .data = data,
5265 .weak_only = weak_only,
5266 };
5267
5268 switch (table) {
5269 case RB_GC_VM_CI_TABLE: {
5270 st_foreach_with_replace(
5271 &vm->ci_table,
5272 vm_weak_table_foreach_weak_key,
5273 vm_weak_table_foreach_update_weak_key,
5274 (st_data_t)&foreach_data
5275 );
5276 break;
5277 }
5278 case RB_GC_VM_OVERLOADED_CME_TABLE: {
5279 st_foreach_with_replace(
5280 &vm->overloaded_cme_table,
5281 vm_weak_table_foreach_weak_key,
5282 vm_weak_table_foreach_update_weak_key,
5283 (st_data_t)&foreach_data
5284 );
5285 break;
5286 }
5287 case RB_GC_VM_GLOBAL_SYMBOLS_TABLE: {
5288 rb_sym_global_symbol_table_foreach_weak_reference(
5289 vm_weak_table_sym_set_foreach,
5290 &foreach_data
5291 );
5292 break;
5293 }
5294 case RB_GC_VM_GENERIC_FIELDS_TABLE: {
5295 /* There is one table. A global GC walks it without a lock under the
5296 * stop-the-world barrier; a local compaction holds the barrier VM lock taken in
5297 * gc_enter, so foreign keys cannot move and fall through the moved check. The
5298 * table's mutex (taken by shared_table_foreach) excludes mutator inserts. */
5299 if (rb_gc_during_global_gc_p()) {
5300 rb_generic_fields_tables_foreach(vm_weak_table_gen_fields_tbl_cb, (void *)&foreach_data);
5301 }
5302 else if (!weak_only) {
5303 rb_generic_fields_shared_table_foreach(vm_weak_table_gen_fields_tbl_cb, (void *)&foreach_data);
5304 }
5305 if (foreach_data.gf_deferred != NULL) {
5306 DURING_GC_COULD_MALLOC_REGION_START();
5307 {
5308 for (size_t i = 0; i < foreach_data.gf_deferred_cnt; i++) {
5309 struct gen_fields_deferred_insert *const d = &foreach_data.gf_deferred[i];
5310 st_insert(foreach_data.gen_fields_current_tbl, d->k, d->v);
5311 }
5312 }
5313 DURING_GC_COULD_MALLOC_REGION_END();
5314 free(foreach_data.gf_deferred);
5315 }
5316 break;
5317 }
5318 case RB_GC_VM_FROZEN_STRINGS_TABLE: {
5319 rb_fstring_foreach_with_replace(
5320 vm_weak_table_frozen_strings_foreach,
5321 &foreach_data
5322 );
5323 break;
5324 }
5325 case RB_GC_VM_WEAK_TABLE_COUNT:
5326 rb_bug("Unreachable");
5327 default:
5328 rb_bug("rb_gc_vm_weak_table_foreach: unknown table %d", table);
5329 }
5330}
5331
5332/* The global GC's weak pass over the generic_fields table; under the barrier, so the
5333 * walk needs no lock. */
5335 int (*cb)(VALUE key, VALUE val, void *arg);
5336 void *arg;
5337};
5338
5339static int
5340gf_mark_foreach_i(st_data_t key, st_data_t val, st_data_t data)
5341{
5342 struct gf_mark_foreach_ctx *ctx = (struct gf_mark_foreach_ctx *)data;
5343 return ctx->cb((VALUE)key, (VALUE)val, ctx->arg);
5344}
5345
5346static void
5347gf_mark_foreach_table_cb(struct st_table *tbl, void *arg)
5348{
5349 st_foreach(tbl, gf_mark_foreach_i, (st_data_t)arg);
5350}
5351
5352void
5353rb_gc_vm_generic_fields_mark_foreach(int (*cb)(VALUE key, VALUE val, void *arg), void *arg)
5354{
5355 struct gf_mark_foreach_ctx ctx = { cb, arg };
5356 rb_generic_fields_tables_foreach(gf_mark_foreach_table_cb, &ctx);
5357}
5358
5360 bool (*is_dead)(VALUE key);
5361};
5362
5363static int
5364gf_drain_i(st_data_t key, st_data_t val, st_data_t data)
5365{
5366 struct gf_drain_ctx *ctx = (struct gf_drain_ctx *)data;
5367 if (ctx->is_dead((VALUE)key)) {
5368 /* The weak pass only drains dead keys' entries, never touching the key itself:
5369 * after the global GC settled another objspace's lazy sweep the key may already
5370 * be freed (poisoned), and writing a shape there would be a use-after-poison. */
5371 return ST_DELETE;
5372 }
5373 return ST_CONTINUE;
5374}
5375
5376static void
5377gf_drain_table_cb(struct st_table *tbl, void *arg)
5378{
5379 st_foreach(tbl, gf_drain_i, (st_data_t)arg);
5380}
5381
5382void
5383rb_gc_vm_generic_fields_drain_dead(bool (*is_dead)(VALUE key))
5384{
5385 struct gf_drain_ctx ctx = { is_dead };
5386 rb_generic_fields_tables_foreach(gf_drain_table_cb, &ctx);
5387}
5388
5389VALUE
5390rb_gc_vm_top_self(void)
5391{
5392 return rb_vm_top_self();
5393}
5394
5395void
5396rb_gc_update_vm_references(void *objspace)
5397{
5398 rb_execution_context_t *ec = GET_EC();
5399 rb_vm_t *vm = rb_ec_vm_ptr(ec);
5400
5401 rb_vm_update_references(vm);
5402 rb_gc_update_global_tbl();
5403 rb_sym_global_symbols_mark_and_move();
5404
5405#if USE_YJIT
5406 void rb_yjit_root_update_references(void); // in Rust
5407
5408 if (rb_yjit_enabled_p) {
5409 rb_yjit_root_update_references();
5410 }
5411#endif
5412
5413#if USE_ZJIT
5414 void rb_zjit_root_update_references(void); // in Rust
5415
5416 if (rb_zjit_enabled_p) {
5417 rb_zjit_root_update_references();
5418 }
5419#endif
5420}
5421
5422void
5423rb_gc_update_object_references(void *objspace, VALUE obj)
5424{
5425 struct classext_foreach_args args;
5426
5427 switch (BUILTIN_TYPE(obj)) {
5428 case T_CLASS:
5429 if (FL_TEST_RAW(obj, FL_SINGLETON)) {
5430 UPDATE_IF_MOVED(objspace, RCLASS_ATTACHED_OBJECT(obj));
5431 }
5432 // Continue to the shared T_CLASS/T_MODULE
5433 case T_MODULE:
5434 args.klass = obj;
5435 args.objspace = objspace;
5436 rb_class_classext_foreach(obj, update_classext, (void *)&args);
5437 break;
5438
5439 case T_ICLASS:
5440 args.objspace = objspace;
5441 rb_class_classext_foreach(obj, update_iclass_classext, (void *)&args);
5442 break;
5443
5444 case T_IMEMO: {
5445 /* Not derived from `objspace`: a global compaction runs this pass over every
5446 * objspace in turn, while rb_gc_impl_mark_and_move has always resolved through the
5447 * current Ractor here (which is also what sets during_reference_updating on all of
5448 * them). Keep that resolution, just hoisted out of the per-reference path. */
5449 const struct rb_gc_mark_ctx ctx = gc_current_mark_ctx();
5450
5451 rb_imemo_mark_and_move(&ctx, obj, true);
5452 return;
5453 }
5454
5455 case T_NIL:
5456 case T_FIXNUM:
5457 case T_NODE:
5458 case T_MOVED:
5459 case T_NONE:
5460 /* These can't move */
5461 return;
5462
5463 case T_ARRAY:
5464 gc_ref_update_array(objspace, obj);
5465 break;
5466
5467 case T_HASH:
5468 gc_ref_update_hash(objspace, obj);
5469 UPDATE_IF_MOVED(objspace, RHASH(obj)->ifnone);
5470 break;
5471
5472 case T_STRING:
5473 {
5474 if (STR_SHARED_P(obj)) {
5475 UPDATE_IF_MOVED(objspace, RSTRING(obj)->as.heap.aux.shared);
5476 }
5477
5478 /* If, after move the string is not embedded, and can fit in the
5479 * slot it's been placed in, then re-embed it. Skip pinned objects:
5480 * a local holding RSTRING_PTR across this compaction could otherwise
5481 * point to freed memory even if the String is marked and pinned. */
5482 if (rb_gc_obj_slot_size(obj) >= rb_str_size_as_embedded(obj)) {
5483 if (!STR_EMBED_P(obj) && rb_str_reembeddable_p(obj)
5484 && !rb_gc_impl_pinned_p(objspace, obj)) {
5485 rb_str_make_embedded(obj);
5486 }
5487 }
5488
5489 break;
5490 }
5491 case T_DATA:
5492 /* Call the compaction callback, if it exists */
5493 {
5494 void *const ptr = RTYPEDDATA_GET_DATA(obj);
5495
5496 UPDATE_IF_MOVED(objspace, RTYPEDDATA(obj)->fields_obj);
5497
5498 if (ptr) {
5499 if (gc_declarative_marking_p(RTYPEDDATA_TYPE(obj))) {
5500 size_t *offset_list = TYPED_DATA_REFS_OFFSET_LIST(obj);
5501
5502 for (size_t offset = *offset_list; offset != RUBY_REF_END; offset = *offset_list++) {
5503 VALUE *ref = (VALUE *)((char *)ptr + offset);
5504 *ref = gc_location_internal(objspace, *ref);
5505 }
5506 }
5507 else {
5508 RUBY_DATA_FUNC compact_func = RTYPEDDATA_TYPE(obj)->function.dcompact;
5509 if (compact_func) (*compact_func)(ptr);
5510 }
5511 }
5512 }
5513 break;
5514
5515 case T_OBJECT:
5516 gc_ref_update_object(objspace, obj);
5517 break;
5518
5519 case T_FILE:
5520 if (RFILE(obj)->fptr) {
5521 UPDATE_IF_MOVED(objspace, RFILE(obj)->fptr->self);
5522 UPDATE_IF_MOVED(objspace, RFILE(obj)->fptr->pathv);
5523 UPDATE_IF_MOVED(objspace, RFILE(obj)->fptr->tied_io_for_writing);
5524 UPDATE_IF_MOVED(objspace, RFILE(obj)->fptr->writeconv_asciicompat);
5525 UPDATE_IF_MOVED(objspace, RFILE(obj)->fptr->writeconv_pre_ecopts);
5526 UPDATE_IF_MOVED(objspace, RFILE(obj)->fptr->encs.ecopts);
5527 UPDATE_IF_MOVED(objspace, RFILE(obj)->fptr->write_lock);
5528 UPDATE_IF_MOVED(objspace, RFILE(obj)->fptr->timeout);
5529 UPDATE_IF_MOVED(objspace, RFILE(obj)->fptr->wakeup_mutex);
5530 }
5531 break;
5532 case T_REGEXP:
5533 UPDATE_IF_MOVED(objspace, RREGEXP(obj)->src);
5534 break;
5535
5536 case T_SYMBOL:
5537 UPDATE_IF_MOVED(objspace, RSYMBOL(obj)->fstr);
5538 break;
5539
5540 case T_FLOAT:
5541 case T_BIGNUM:
5542 break;
5543
5544 case T_MATCH:
5545 UPDATE_IF_MOVED(objspace, RMATCH(obj)->regexp);
5546
5547 if (RMATCH(obj)->str) {
5548 UPDATE_IF_MOVED(objspace, RMATCH(obj)->str);
5549 }
5550 break;
5551
5552 case T_RATIONAL:
5553 UPDATE_IF_MOVED(objspace, RRATIONAL(obj)->num);
5554 UPDATE_IF_MOVED(objspace, RRATIONAL(obj)->den);
5555 break;
5556
5557 case T_COMPLEX:
5558 UPDATE_IF_MOVED(objspace, RCOMPLEX(obj)->real);
5559 UPDATE_IF_MOVED(objspace, RCOMPLEX(obj)->imag);
5560
5561 break;
5562
5563 case T_STRUCT:
5564 {
5565 long i, len = RSTRUCT_LEN(obj);
5566 VALUE *ptr = (VALUE *)RSTRUCT_CONST_PTR(obj);
5567
5568 for (i = 0; i < len; i++) {
5569 UPDATE_IF_MOVED(objspace, ptr[i]);
5570 }
5571
5572 UPDATE_IF_MOVED(objspace, RSTRUCT(obj)->fields_obj);
5573 }
5574 break;
5575 default:
5576 rb_bug("unreachable");
5577 break;
5578 }
5579
5580 UPDATE_IF_MOVED(objspace, RBASIC(obj)->klass);
5581}
5582
5583VALUE
5584rb_gc_start(void)
5585{
5586 rb_gc();
5587 return Qnil;
5588}
5589
5590void
5591rb_gc(void)
5592{
5593 unless_objspace(objspace) { return; }
5594
5595 rb_gc_impl_start(objspace, true, true, true, false, true);
5596}
5597
5598int
5599rb_during_gc(void)
5600{
5601 unless_objspace(objspace) { return FALSE; }
5602
5603 return rb_gc_impl_during_gc_p(objspace);
5604}
5605
5606size_t
5607rb_gc_count(void)
5608{
5609 return rb_gc_impl_gc_count(rb_gc_get_objspace());
5610}
5611
5612static VALUE
5613gc_count(rb_execution_context_t *ec, VALUE self)
5614{
5615 return SIZET2NUM(rb_gc_count());
5616}
5617
5618VALUE
5619rb_gc_latest_gc_info(VALUE key)
5620{
5621 if (!SYMBOL_P(key) && !RB_TYPE_P(key, T_HASH)) {
5622 rb_raise(rb_eTypeError, "non-hash or symbol given");
5623 }
5624
5625 VALUE val = rb_gc_impl_latest_gc_info(rb_gc_get_objspace(), key);
5626
5627 if (val == Qundef) {
5628 rb_raise(rb_eArgError, "unknown key: %"PRIsVALUE, rb_sym2str(key));
5629 }
5630
5631 return val;
5632}
5633
5634static VALUE
5635gc_stat(rb_execution_context_t *ec, VALUE self, VALUE arg, VALUE global_scope)
5636{
5637 if (NIL_P(arg)) {
5638 arg = rb_hash_new();
5639 }
5640 else if (!RB_TYPE_P(arg, T_HASH) && !SYMBOL_P(arg)) {
5641 rb_raise(rb_eTypeError, "non-hash or symbol given");
5642 }
5643
5644 VALUE ret = rb_gc_impl_stat(RTEST(global_scope) ? NULL : rb_gc_get_objspace(), arg);
5645
5646 if (ret == Qundef) {
5647 GC_ASSERT(SYMBOL_P(arg));
5648
5649 rb_raise(rb_eArgError, "unknown key: %"PRIsVALUE, rb_sym2str(arg));
5650 }
5651
5652 return ret;
5653}
5654
5655size_t
5656rb_gc_stat(VALUE arg)
5657{
5658 if (!RB_TYPE_P(arg, T_HASH) && !SYMBOL_P(arg)) {
5659 rb_raise(rb_eTypeError, "non-hash or symbol given");
5660 }
5661
5662 VALUE ret = rb_gc_impl_stat(rb_gc_get_objspace(), arg);
5663
5664 if (ret == Qundef) {
5665 GC_ASSERT(SYMBOL_P(arg));
5666
5667 rb_raise(rb_eArgError, "unknown key: %"PRIsVALUE, rb_sym2str(arg));
5668 }
5669
5670 if (SYMBOL_P(arg)) {
5671 return NUM2SIZET(ret);
5672 }
5673 else {
5674 return 0;
5675 }
5676}
5677
5678static VALUE
5679gc_stat_heap(rb_execution_context_t *ec, VALUE self, VALUE heap_name, VALUE arg)
5680{
5681 if (NIL_P(arg)) {
5682 arg = rb_hash_new();
5683 }
5684
5685 if (NIL_P(heap_name)) {
5686 if (!RB_TYPE_P(arg, T_HASH)) {
5687 rb_raise(rb_eTypeError, "non-hash given");
5688 }
5689 }
5690 else if (FIXNUM_P(heap_name)) {
5691 if (!SYMBOL_P(arg) && !RB_TYPE_P(arg, T_HASH)) {
5692 rb_raise(rb_eTypeError, "non-hash or symbol given");
5693 }
5694 }
5695 else {
5696 rb_raise(rb_eTypeError, "heap_name must be nil or an Integer");
5697 }
5698
5699 VALUE ret = rb_gc_impl_stat_heap(rb_gc_get_objspace(), heap_name, arg);
5700
5701 if (ret == Qundef) {
5702 GC_ASSERT(SYMBOL_P(arg));
5703
5704 rb_raise(rb_eArgError, "unknown key: %"PRIsVALUE, rb_sym2str(arg));
5705 }
5706
5707 return ret;
5708}
5709
5710static VALUE
5711gc_config_get(rb_execution_context_t *ec, VALUE self)
5712{
5713 VALUE cfg_hash = rb_gc_impl_config_get(rb_gc_get_objspace());
5714 rb_hash_aset(cfg_hash, sym("implementation"), rb_fstring_cstr(rb_gc_impl_active_gc_name()));
5715
5716 return cfg_hash;
5717}
5718
5719static VALUE
5720gc_config_set(rb_execution_context_t *ec, VALUE self, VALUE hash)
5721{
5722 void *objspace = rb_gc_get_objspace();
5723
5724 rb_gc_impl_config_set(objspace, hash);
5725
5726 return Qnil;
5727}
5728
5729static VALUE
5730gc_stress_get(rb_execution_context_t *ec, VALUE self)
5731{
5732 return rb_gc_impl_stress_get(rb_gc_get_objspace());
5733}
5734
5735static VALUE
5736gc_stress_set_m(rb_execution_context_t *ec, VALUE self, VALUE flag)
5737{
5738 rb_gc_impl_stress_set(rb_gc_get_objspace(), flag);
5739
5740 return flag;
5741}
5742
5743void
5744rb_gc_initial_stress_set(VALUE flag)
5745{
5746 initial_stress = flag;
5747}
5748
5749/* Add or drop a GC-disable holder (vm->gc.disable_holders; see vm_core.h). critical
5750 * is the anonymous holder used by internal sections that must not be interrupted by a
5751 * GC, such as collecting under the barrier. */
5752
5753static void
5754rb_gc_critical_disable(void)
5755{
5756 rb_gc_impl_gc_rest(rb_gc_get_objspace());
5757 RUBY_ATOMIC_INC(GET_VM()->gc.disable_holders);
5758}
5759
5760static void
5761rb_gc_critical_enable(void)
5762{
5763 RUBY_ATOMIC_DEC(GET_VM()->gc.disable_holders);
5764}
5765
5766bool
5767rb_gc_gc_disabled_global_p(void)
5768{
5769 return RUBY_ATOMIC_LOAD(GET_VM()->gc.disable_holders) != 0;
5770}
5771
5772/* GC.disable/enable set and clear this objspace's flag and only move the holder count
5773 * when the flag actually changes. The returned previous state is this objspace's. */
5774static bool
5775gc_ractor_disable_set(bool disable)
5776{
5777 const bool was = rb_gc_impl_user_gc_disabled_set(rb_gc_get_objspace(), disable);
5778 if (was != disable) {
5779 if (disable) {
5780 RUBY_ATOMIC_INC(GET_VM()->gc.disable_holders);
5781 }
5782 else {
5783 RUBY_ATOMIC_DEC(GET_VM()->gc.disable_holders);
5784 }
5785 }
5786 return was;
5787}
5788
5789VALUE
5790rb_gc_enable(void)
5791{
5792 return RBOOL(gc_ractor_disable_set(false));
5793}
5794
5795VALUE
5796rb_gc_disable_no_rest(void)
5797{
5798 return RBOOL(gc_ractor_disable_set(true));
5799}
5800
5801VALUE
5802rb_gc_disable(void)
5803{
5804 const bool was_disabled = gc_ractor_disable_set(true);
5805 if (!was_disabled) {
5806 rb_gc_impl_gc_rest(rb_gc_get_objspace());
5807 }
5808 return RBOOL(was_disabled);
5809}
5810
5811VALUE
5812rb_objspace_gc_enable(void *objspace)
5813{
5814 bool disabled = !rb_gc_impl_gc_enabled_p(objspace);
5815 rb_gc_impl_gc_enable(objspace);
5816 return RBOOL(disabled);
5817}
5818
5819VALUE
5820rb_objspace_gc_disable(void *objspace)
5821{
5822 bool disabled = !rb_gc_impl_gc_enabled_p(objspace);
5823 rb_gc_impl_gc_disable(objspace, true);
5824 return RBOOL(disabled);
5825}
5826
5827VALUE
5828rb_gc_objspace_enable(void *objspace)
5829{
5830 return rb_objspace_gc_enable(objspace);
5831}
5832
5833VALUE
5834rb_gc_local_enable(void)
5835{
5836 return rb_gc_objspace_enable(rb_gc_get_objspace());
5837}
5838
5839
5840VALUE
5841rb_gc_objspace_disable_no_rest(void *objspace)
5842{
5843 bool disabled = !rb_gc_impl_gc_enabled_p(objspace);
5844 rb_gc_impl_gc_disable(objspace, false);
5845 return RBOOL(disabled);
5846}
5847
5848VALUE
5849rb_gc_local_disable_no_rest(void)
5850{
5851 return rb_gc_objspace_disable_no_rest(rb_gc_get_objspace());
5852}
5853
5854static VALUE
5855gc_enable(rb_execution_context_t *ec, VALUE _)
5856{
5857 return rb_gc_enable();
5858}
5859
5860static VALUE
5861gc_disable(rb_execution_context_t *ec, VALUE _)
5862{
5863 return rb_gc_disable();
5864}
5865
5866// TODO: think about moving ruby_gc_set_params into Init_heap or Init_gc
5867void
5868ruby_gc_set_params(void)
5869{
5870 rb_gc_impl_set_params(rb_gc_get_objspace());
5871}
5872
5873void
5874rb_objspace_reachable_objects_from(VALUE obj, void (func)(VALUE, void *), void *data)
5875{
5876 RB_VM_LOCKING() {
5877 if (rb_gc_impl_during_gc_p(rb_gc_get_objspace())) rb_bug("rb_objspace_reachable_objects_from() is not supported while during GC");
5878
5879 if (!RB_SPECIAL_CONST_P(obj)) {
5880 struct gc_mark_func_data_struct **mfdp = GC_MARK_FUNC_DATA_SLOTP();
5881 struct gc_mark_func_data_struct *prev_mfd = *mfdp;
5882 struct gc_mark_func_data_struct mfd = {
5883 .mark_func = func,
5884 .data = data,
5885 };
5886
5887 *mfdp = &mfd;
5888 rb_gc_mark_children(rb_gc_get_objspace(), obj);
5889 *mfdp = prev_mfd;
5890 }
5891 }
5892}
5893
5895 const char *category;
5896 void (*func)(const char *category, VALUE, void *);
5897 void *data;
5898};
5899
5900static void
5901root_objects_from(VALUE obj, void *ptr)
5902{
5903 const struct root_objects_data *data = (struct root_objects_data *)ptr;
5904 (*data->func)(data->category, obj, data->data);
5905}
5906
5907void
5908rb_objspace_reachable_objects_from_root(void (func)(const char *category, VALUE, void *), void *passing_data)
5909{
5910 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");
5911
5912 struct root_objects_data data = {
5913 .func = func,
5914 .data = passing_data,
5915 };
5916
5917 struct gc_mark_func_data_struct **mfdp = GC_MARK_FUNC_DATA_SLOTP();
5918 struct gc_mark_func_data_struct *prev_mfd = *mfdp;
5919 struct gc_mark_func_data_struct mfd = {
5920 .mark_func = root_objects_from,
5921 .data = &data,
5922 };
5923
5924 *mfdp = &mfd;
5925 rb_gc_save_machine_context();
5926 rb_gc_mark_roots(rb_gc_get_objspace(), &data.category);
5927 *mfdp = prev_mfd;
5928}
5929
5930/*
5931 ------------------------------ DEBUG ------------------------------
5932*/
5933
5934static const char *
5935type_name(int type, VALUE obj)
5936{
5937 switch (type) {
5938#define TYPE_NAME(t) case (t): return #t;
5939 TYPE_NAME(T_NONE);
5940 TYPE_NAME(T_OBJECT);
5941 TYPE_NAME(T_CLASS);
5942 TYPE_NAME(T_MODULE);
5943 TYPE_NAME(T_FLOAT);
5944 TYPE_NAME(T_STRING);
5945 TYPE_NAME(T_REGEXP);
5946 TYPE_NAME(T_ARRAY);
5947 TYPE_NAME(T_HASH);
5948 TYPE_NAME(T_STRUCT);
5949 TYPE_NAME(T_BIGNUM);
5950 TYPE_NAME(T_FILE);
5951 TYPE_NAME(T_MATCH);
5952 TYPE_NAME(T_COMPLEX);
5953 TYPE_NAME(T_RATIONAL);
5954 TYPE_NAME(T_NIL);
5955 TYPE_NAME(T_TRUE);
5956 TYPE_NAME(T_FALSE);
5957 TYPE_NAME(T_SYMBOL);
5958 TYPE_NAME(T_FIXNUM);
5959 TYPE_NAME(T_UNDEF);
5960 TYPE_NAME(T_IMEMO);
5961 TYPE_NAME(T_ICLASS);
5962 TYPE_NAME(T_MOVED);
5963 TYPE_NAME(T_ZOMBIE);
5964 case T_DATA:
5965 if (obj && rb_objspace_data_type_name(obj)) {
5966 return rb_objspace_data_type_name(obj);
5967 }
5968 return "T_DATA";
5969#undef TYPE_NAME
5970 }
5971 return "unknown";
5972}
5973
5974static const char *
5975obj_type_name(VALUE obj)
5976{
5977 return type_name(TYPE(obj), obj);
5978}
5979
5980const char *
5981rb_method_type_name(rb_method_type_t type)
5982{
5983 switch (type) {
5984 case VM_METHOD_TYPE_ISEQ: return "iseq";
5985 case VM_METHOD_TYPE_ATTRSET: return "attrset";
5986 case VM_METHOD_TYPE_IVAR: return "ivar";
5987 case VM_METHOD_TYPE_BMETHOD: return "bmethod";
5988 case VM_METHOD_TYPE_ALIAS: return "alias";
5989 case VM_METHOD_TYPE_REFINED: return "refined";
5990 case VM_METHOD_TYPE_CFUNC: return "cfunc";
5991 case VM_METHOD_TYPE_ZSUPER: return "zsuper";
5992 case VM_METHOD_TYPE_MISSING: return "missing";
5993 case VM_METHOD_TYPE_OPTIMIZED: return "optimized";
5994 case VM_METHOD_TYPE_UNDEF: return "undef";
5995 case VM_METHOD_TYPE_NOTIMPLEMENTED: return "notimplemented";
5996 }
5997 rb_bug("rb_method_type_name: unreachable (type: %d)", type);
5998}
5999
6000static void
6001rb_raw_iseq_info(char *const buff, const size_t buff_size, const rb_iseq_t *iseq)
6002{
6003 if (buff_size > 0 && ISEQ_BODY(iseq) && ISEQ_BODY(iseq)->location.label && !RB_TYPE_P(ISEQ_BODY(iseq)->location.pathobj, T_MOVED)) {
6004 VALUE path = rb_iseq_path(iseq);
6005 int n = ISEQ_BODY(iseq)->location.first_lineno;
6006 VALUE label = ISEQ_BODY(iseq)->location.label;
6007 snprintf(buff, buff_size, " %.*s@%.*s:%d",
6008 RSTRING_LENINT(label), RSTRING_PTR(label),
6009 RSTRING_LENINT(path), RSTRING_PTR(path), n);
6010 }
6011}
6012
6013static int
6014str_len_no_raise(VALUE str)
6015{
6016 long len = RSTRING_LEN(str);
6017 if (len < 0) return 0;
6018 if (len > INT_MAX) return INT_MAX;
6019 return (int)len;
6020}
6021
6022#define BUFF_ARGS buff + pos, buff_size - pos
6023#define APPEND_F(...) if ((pos += snprintf(BUFF_ARGS, "" __VA_ARGS__)) >= buff_size) goto end
6024#define APPEND_S(s) do { \
6025 if ((pos + (int)rb_strlen_lit(s)) >= buff_size) { \
6026 goto end; \
6027 } \
6028 else { \
6029 memcpy(buff + pos, (s), rb_strlen_lit(s) + 1); \
6030 } \
6031 } while (0)
6032#define C(c, s) ((c) != 0 ? (s) : " ")
6033
6034static size_t
6035rb_raw_obj_info_common(char *const buff, const size_t buff_size, const VALUE obj)
6036{
6037 size_t pos = 0;
6038
6039 if (SPECIAL_CONST_P(obj)) {
6040 APPEND_F("%s", obj_type_name(obj));
6041
6042 if (FIXNUM_P(obj)) {
6043 APPEND_F(" %ld", FIX2LONG(obj));
6044 }
6045 else if (SYMBOL_P(obj)) {
6046 APPEND_F(" %s", rb_id2name(SYM2ID(obj)));
6047 }
6048 }
6049 else {
6050 // const int age = RVALUE_AGE_GET(obj);
6051
6052 if (rb_gc_impl_live_object_p(rb_gc_get_objspace(), (void *)obj)) {
6053 APPEND_F("%p %s/", (void *)obj, obj_type_name(obj));
6054 // TODO: fixme
6055 // APPEND_F("%p [%d%s%s%s%s%s%s] %s ",
6056 // (void *)obj, age,
6057 // C(RVALUE_UNCOLLECTIBLE_BITMAP(obj), "L"),
6058 // C(RVALUE_MARK_BITMAP(obj), "M"),
6059 // C(RVALUE_PIN_BITMAP(obj), "P"),
6060 // C(RVALUE_MARKING_BITMAP(obj), "R"),
6061 // C(RVALUE_WB_UNPROTECTED_BITMAP(obj), "U"),
6062 // C(rb_objspace_garbage_object_p(obj), "G"),
6063 // obj_type_name(obj));
6064 }
6065 else {
6066 /* fake */
6067 // APPEND_F("%p [%dXXXX] %s",
6068 // (void *)obj, age,
6069 // obj_type_name(obj));
6070 }
6071
6072 if (internal_object_p(obj)) {
6073 /* ignore */
6074 }
6075 else if (RBASIC(obj)->klass == 0) {
6076 APPEND_S("(temporary internal)");
6077 }
6078 else if (RTEST(RBASIC(obj)->klass)) {
6079 VALUE class_path = rb_mod_name(RBASIC(obj)->klass);
6080 if (!NIL_P(class_path)) {
6081 APPEND_F("%.*s ", str_len_no_raise(class_path), RSTRING_PTR(class_path));
6082 }
6083 }
6084 }
6085 end:
6086
6087 return pos;
6088}
6089
6090const char *rb_raw_obj_info(char *const buff, const size_t buff_size, VALUE obj);
6091
6092static size_t
6093rb_raw_obj_info_buitin_type(char *const buff, const size_t buff_size, const VALUE obj, size_t pos)
6094{
6095 if (LIKELY(pos < buff_size) && !SPECIAL_CONST_P(obj)) {
6096 const enum ruby_value_type type = BUILTIN_TYPE(obj);
6097
6098 switch (type) {
6099 case T_NODE:
6100 UNEXPECTED_NODE(rb_raw_obj_info);
6101 break;
6102 case T_ARRAY:
6103 if (ARY_SHARED_P(obj)) {
6104 APPEND_S("shared -> ");
6105 rb_raw_obj_info(BUFF_ARGS, ARY_SHARED_ROOT(obj));
6106 }
6107 else {
6108 APPEND_F("[%s%s%s] ",
6109 C(ARY_EMBED_P(obj), "E"),
6110 C(ARY_SHARED_P(obj), "S"),
6111 C(ARY_SHARED_ROOT_P(obj), "R"));
6112
6113 if (ARY_EMBED_P(obj)) {
6114 APPEND_F("len: %ld (embed)",
6115 RARRAY_LEN(obj));
6116 }
6117 else {
6118 APPEND_F("len: %ld, capa:%ld ptr:%p",
6119 RARRAY_LEN(obj),
6120 RARRAY(obj)->as.heap.aux.capa,
6121 (void *)RARRAY_CONST_PTR(obj));
6122 }
6123 }
6124 break;
6125 case T_STRING: {
6126 APPEND_F("[%s%s] ",
6127 C(FL_TEST(obj, RSTRING_FSTR), "F"),
6128 C(RB_OBJ_FROZEN(obj), "R"));
6129
6130 if (STR_SHARED_P(obj)) {
6131 APPEND_F(" [shared] len: %ld", RSTRING_LEN(obj));
6132 }
6133 else {
6134 if (STR_EMBED_P(obj)) APPEND_S(" [embed]");
6135
6136 APPEND_F(" len: %ld, capa: %" PRIdSIZE, RSTRING_LEN(obj), rb_str_capacity(obj));
6137 }
6138 APPEND_F(" \"%.*s\"", str_len_no_raise(obj), RSTRING_PTR(obj));
6139 break;
6140 }
6141 case T_SYMBOL: {
6142 VALUE fstr = RSYMBOL(obj)->fstr;
6143 ID id = RSYMBOL(obj)->id;
6144 if (RB_TYPE_P(fstr, T_STRING)) {
6145 APPEND_F(":%.*s id:%d", str_len_no_raise(fstr), RSTRING_PTR(fstr), (unsigned int)id);
6146 }
6147 else {
6148 APPEND_F("(%p) id:%d", (void *)fstr, (unsigned int)id);
6149 }
6150 break;
6151 }
6152 case T_MOVED: {
6153 APPEND_F("-> %p", (void*)gc_location_internal(rb_gc_get_objspace(), obj));
6154 break;
6155 }
6156 case T_HASH: {
6157 APPEND_F("[%c] %"PRIdSIZE,
6158 RHASH_AR_TABLE_P(obj) ? 'A' : 'S',
6159 RHASH_SIZE(obj));
6160 break;
6161 }
6162 case T_CLASS:
6163 case T_MODULE:
6164 {
6165 VALUE class_path = rb_mod_name(obj);
6166 if (!NIL_P(class_path)) {
6167 APPEND_F("%.*s", str_len_no_raise(class_path), RSTRING_PTR(class_path));
6168 }
6169 else {
6170 APPEND_S("(anon)");
6171 }
6172 break;
6173 }
6174 case T_ICLASS:
6175 {
6176 VALUE class_path = rb_mod_name(RBASIC_CLASS(obj));
6177 if (!NIL_P(class_path)) {
6178 APPEND_F("src:%.*s", str_len_no_raise(class_path), RSTRING_PTR(class_path));
6179 }
6180 break;
6181 }
6182 case T_OBJECT:
6183 {
6184 shape_id_t shape_id = RBASIC_SHAPE_ID(obj);
6185 if (rb_shape_embedded_p(shape_id)) {
6186 APPEND_F("(embed) len:%d capa:%d", RSHAPE_LEN(shape_id), RSHAPE_CAPACITY(shape_id));
6187 }
6188 else {
6189 VALUE fields_obj = ROBJECT_FIELDS_OBJ(obj);
6190 if (rb_shape_complex_p(shape_id)) {
6191 size_t hash_len = rb_st_table_size(rb_imemo_fields_complex_tbl(fields_obj));
6192 APPEND_F("(complex) len:%zu extended:%p", hash_len, (void *)fields_obj);
6193 }
6194 else {
6195 APPEND_F("(extended) len:%d capa:%d extended:%p", RSHAPE_LEN(shape_id), RSHAPE_CAPACITY(shape_id), (void *)fields_obj);
6196 }
6197 }
6198 }
6199 break;
6200 case T_DATA: {
6201 const struct rb_block *block;
6202 const rb_iseq_t *iseq;
6203 if (rb_obj_is_proc(obj) &&
6204 (block = vm_proc_block(obj)) != NULL &&
6205 (vm_block_type(block) == block_type_iseq) &&
6206 (iseq = vm_block_iseq(block)) != NULL) {
6207 rb_raw_iseq_info(BUFF_ARGS, iseq);
6208 }
6209 else if (rb_ractor_p(obj)) {
6210 rb_ractor_t *r = (void *)DATA_PTR(obj);
6211 if (r) {
6212 APPEND_F("r:%"PRI_SERIALT_PREFIX"u", r->pub.id);
6213 }
6214 }
6215 break;
6216 }
6217 case T_IMEMO: {
6218 APPEND_F("<%s> ", rb_imemo_name(imemo_type(obj)));
6219
6220 switch (imemo_type(obj)) {
6221 case imemo_fields:
6222 {
6223 shape_id_t shape_id = RBASIC_SHAPE_ID(obj);
6224 if (rb_shape_complex_p(shape_id)) {
6225 size_t hash_len = rb_st_table_size(rb_imemo_fields_complex_tbl(obj));
6226 APPEND_F("(complex) len:%zu", hash_len);
6227 }
6228 else {
6229 APPEND_F("(embed) len:%d capa:%d", RSHAPE_LEN(shape_id), RSHAPE_CAPACITY(shape_id));
6230 }
6231
6232 APPEND_S("owner -> ");
6233 rb_raw_obj_info(BUFF_ARGS, CLASS_OF(obj));
6234
6235 break;
6236 }
6237 case imemo_ment:
6238 {
6239 const rb_method_entry_t *me = (const rb_method_entry_t *)obj;
6240
6241 APPEND_F(":%s (%s%s%s%s) type:%s aliased:%d owner:%p defined_class:%p",
6242 rb_id2name(me->called_id),
6243 METHOD_ENTRY_VISI(me) == METHOD_VISI_PUBLIC ? "pub" :
6244 METHOD_ENTRY_VISI(me) == METHOD_VISI_PRIVATE ? "pri" : "pro",
6245 METHOD_ENTRY_COMPLEMENTED(me) ? ",cmp" : "",
6246 METHOD_ENTRY_CACHED(me) ? ",cc" : "",
6247 METHOD_ENTRY_INVALIDATED(me) ? ",inv" : "",
6248 me->def ? rb_method_type_name(me->def->type) : "NULL",
6249 me->def ? me->def->aliased : -1,
6250 (void *)me->owner, // obj_info(me->owner),
6251 (void *)me->defined_class); //obj_info(me->defined_class)));
6252
6253 if (me->def) {
6254 switch (me->def->type) {
6255 case VM_METHOD_TYPE_ISEQ:
6256 APPEND_S(" (iseq:");
6257 rb_raw_obj_info(BUFF_ARGS, (VALUE)me->def->body.iseq.iseqptr);
6258 APPEND_S(")");
6259 break;
6260 default:
6261 break;
6262 }
6263 }
6264
6265 break;
6266 }
6267 case imemo_iseq: {
6268 const rb_iseq_t *iseq = (const rb_iseq_t *)obj;
6269 rb_raw_iseq_info(BUFF_ARGS, iseq);
6270 break;
6271 }
6272 case imemo_callinfo:
6273 {
6274 const struct rb_callinfo *ci = (const struct rb_callinfo *)obj;
6275 APPEND_F("(mid:%s, flag:%x argc:%d, kwarg:%s)",
6276 rb_id2name(vm_ci_mid(ci)),
6277 vm_ci_flag(ci),
6278 vm_ci_argc(ci),
6279 vm_ci_kwarg(ci) ? "available" : "NULL");
6280 break;
6281 }
6282 case imemo_callcache:
6283 {
6284 const struct rb_callcache *cc = (const struct rb_callcache *)obj;
6285 VALUE class_path = vm_cc_valid(cc) ? rb_mod_name(cc->klass) : Qnil;
6286 const rb_callable_method_entry_t *cme = vm_cc_cme(cc);
6287 const char *class_name;
6288 int class_name_len;
6289
6290 if (NIL_P(class_path)) {
6291 class_name = vm_cc_valid(cc) ? "??" : "<NULL>";
6292 class_name_len = vm_cc_valid(cc) ? 2 : 6;
6293 }
6294 else {
6295 class_name = RSTRING_PTR(class_path);
6296 class_name_len = str_len_no_raise(class_path);
6297 }
6298
6299 APPEND_F("(klass:%.*s cme:%s%s (%p) call:%p",
6300 class_name_len, class_name,
6301 cme ? rb_id2name(cme->called_id) : "<NULL>",
6302 cme ? (METHOD_ENTRY_INVALIDATED(cme) ? " [inv]" : "") : "",
6303 (void *)cme,
6304 (void *)(uintptr_t)vm_cc_call(cc));
6305 break;
6306 }
6307 default:
6308 break;
6309 }
6310 }
6311 default:
6312 break;
6313 }
6314 }
6315 end:
6316
6317 return pos;
6318}
6319
6320#undef C
6321
6322#ifdef RUBY_ASAN_ENABLED
6323void
6324rb_asan_poison_object(VALUE obj)
6325{
6326 MAYBE_UNUSED(struct RVALUE *) ptr = (void *)obj;
6327 asan_poison_memory_region(ptr, rb_gc_obj_slot_size(obj));
6328}
6329
6330void
6331rb_asan_unpoison_object(VALUE obj, bool newobj_p)
6332{
6333 MAYBE_UNUSED(struct RVALUE *) ptr = (void *)obj;
6334 asan_unpoison_memory_region(ptr, rb_gc_obj_slot_size(obj), newobj_p);
6335}
6336
6337void *
6338rb_asan_poisoned_object_p(VALUE obj)
6339{
6340 MAYBE_UNUSED(struct RVALUE *) ptr = (void *)obj;
6341 return __asan_region_is_poisoned(ptr, rb_gc_obj_slot_size(obj));
6342}
6343#endif
6344
6345static void
6346raw_obj_info(char *const buff, const size_t buff_size, VALUE obj)
6347{
6348 size_t pos = rb_raw_obj_info_common(buff, buff_size, obj);
6349 pos = rb_raw_obj_info_buitin_type(buff, buff_size, obj, pos);
6350 if (pos >= buff_size) {} // truncated
6351}
6352
6353const char *
6354rb_raw_obj_info(char *const buff, const size_t buff_size, VALUE obj)
6355{
6356 void *objspace = rb_gc_get_objspace();
6357
6358 if (SPECIAL_CONST_P(obj)) {
6359 raw_obj_info(buff, buff_size, obj);
6360 }
6361 else if (!rb_gc_impl_live_object_p(objspace, (const void *)obj)) {
6362 snprintf(buff, buff_size, "out-of-heap:%p", (void *)obj);
6363 }
6364#if 0 // maybe no need to check it?
6365 else if (0 && rb_gc_impl_garbage_object_p(objspace, obj)) {
6366 snprintf(buff, buff_size, "garbage:%p", (void *)obj);
6367 }
6368#endif
6369 else {
6370 asan_unpoisoning_object(obj) {
6371 raw_obj_info(buff, buff_size, obj);
6372 }
6373 }
6374 return buff;
6375}
6376
6377#undef APPEND_S
6378#undef APPEND_F
6379#undef BUFF_ARGS
6380
6381/* Increments *var atomically and resets *var to 0 when maxval is
6382 * reached. Returns the wraparound old *var value (0...maxval). */
6383static rb_atomic_t
6384atomic_inc_wraparound(rb_atomic_t *var, const rb_atomic_t maxval)
6385{
6386 rb_atomic_t oldval = RUBY_ATOMIC_FETCH_ADD(*var, 1);
6387 if (RB_UNLIKELY(oldval >= maxval - 1)) { // wraparound *var
6388 const rb_atomic_t newval = oldval + 1;
6389 RUBY_ATOMIC_CAS(*var, newval, newval % maxval);
6390 oldval %= maxval;
6391 }
6392 return oldval;
6393}
6394
6395static const char *
6396obj_info(VALUE obj)
6397{
6398 if (RGENGC_OBJ_INFO) {
6399 static struct {
6400 rb_atomic_t index;
6401 char buffers[10][0x100];
6402 } info = {0};
6403
6404 rb_atomic_t index = atomic_inc_wraparound(&info.index, numberof(info.buffers));
6405 char *const buff = info.buffers[index];
6406 return rb_raw_obj_info(buff, sizeof(info.buffers[0]), obj);
6407 }
6408 return obj_type_name(obj);
6409}
6410
6411/*
6412 ------------------------ Extended allocator ------------------------
6413*/
6414
6416 VALUE exc;
6417 const char *fmt;
6418 va_list *ap;
6419};
6420
6421static void *
6422gc_vraise(void *ptr)
6423{
6424 struct gc_raise_tag *argv = ptr;
6425 rb_vraise(argv->exc, argv->fmt, *argv->ap);
6426 UNREACHABLE_RETURN(NULL);
6427}
6428
6429static void
6430gc_raise(VALUE exc, const char *fmt, ...)
6431{
6432 va_list ap;
6433 va_start(ap, fmt);
6434 struct gc_raise_tag argv = {
6435 exc, fmt, &ap,
6436 };
6437
6438 if (ruby_native_thread_p()) {
6439 rb_thread_call_with_gvl(gc_vraise, &argv);
6441 }
6442 else {
6443 /* Not in a ruby thread */
6444 fprintf(stderr, "%s", "[FATAL] ");
6445 vfprintf(stderr, fmt, ap);
6446 }
6447
6448 va_end(ap);
6449 abort();
6450}
6451
6452NORETURN(static void negative_size_allocation_error(const char *));
6453static void
6454negative_size_allocation_error(const char *msg)
6455{
6456 gc_raise(rb_eNoMemError, "%s", msg);
6457}
6458
6459static void *
6460ruby_memerror_body(void *dummy)
6461{
6462 rb_memerror();
6463 return 0;
6464}
6465
6466NORETURN(static void ruby_memerror(void));
6468static void
6469ruby_memerror(void)
6470{
6471 if (ruby_thread_has_gvl_p()) {
6472 rb_memerror();
6473 }
6474 else {
6475 if (ruby_native_thread_p()) {
6476 rb_thread_call_with_gvl(ruby_memerror_body, 0);
6477 }
6478 else {
6479 /* no ruby thread */
6480 fprintf(stderr, "[FATAL] failed to allocate memory\n");
6481 }
6482 }
6483
6484 /* We have discussions whether we should die here; */
6485 /* We might rethink about it later. */
6486 exit(EXIT_FAILURE);
6487}
6488
6489void
6490rb_memerror(void)
6491{
6492 /* the `GET_VM()->special_exceptions` below assumes that
6493 * the VM is reachable from the current thread. We should
6494 * definitely make sure of that. */
6495 RUBY_ASSERT_ALWAYS(ruby_thread_has_gvl_p());
6496
6497 rb_execution_context_t *ec = GET_EC();
6498 VALUE exc = GET_VM()->special_exceptions[ruby_error_nomemory];
6499
6500 if (!exc ||
6501 rb_ec_raised_p(ec, RAISED_NOMEMORY) ||
6502 rb_ec_vm_lock_rec(ec) != ec->tag->lock_rec) {
6503 fprintf(stderr, "[FATAL] failed to allocate memory\n");
6504 exit(EXIT_FAILURE);
6505 }
6506 if (rb_ec_raised_p(ec, RAISED_NOMEMORY)) {
6507 rb_ec_raised_clear(ec);
6508 }
6509 else {
6510 rb_ec_raised_set(ec, RAISED_NOMEMORY);
6511 exc = ruby_vm_special_exception_copy(exc);
6512 }
6513 ec->errinfo = exc;
6514 EC_JUMP_TAG(ec, TAG_RAISE);
6515}
6516
6517bool
6518rb_memerror_reentered(void)
6519{
6520 rb_execution_context_t *ec = GET_EC();
6521 return (ec && rb_ec_raised_p(ec, RAISED_NOMEMORY));
6522}
6523
6524static void *
6525handle_malloc_failure(void *ptr)
6526{
6527 if (LIKELY(ptr)) {
6528 return ptr;
6529 }
6530 else {
6531 ruby_memerror();
6532 UNREACHABLE_RETURN(ptr);
6533 }
6534}
6535
6536static void *ruby_xmalloc_body(size_t size);
6537
6538void *
6539ruby_xmalloc(size_t size)
6540{
6541 if (RUBY_DTRACE_GC_XMALLOC_ENABLED()) {
6542 RUBY_DTRACE_GC_XMALLOC(1, size);
6543 }
6544
6545 return handle_malloc_failure(ruby_xmalloc_body(size));
6546}
6547
6548static bool
6549malloc_gc_allowed(void)
6550{
6551 rb_ractor_t *r = rb_current_ractor_raw(false);
6552
6553 return r == NULL || !r->malloc_gc_disabled;
6554}
6555
6556static void *
6557ruby_xmalloc_body(size_t size)
6558{
6559 if ((ssize_t)size < 0) {
6560 negative_size_allocation_error("too large allocation size");
6561 }
6562
6563 return rb_gc_impl_malloc(rb_gc_get_objspace(), size, malloc_gc_allowed());
6564}
6565
6566void
6567ruby_malloc_size_overflow(size_t count, size_t elsize)
6568{
6569 rb_raise(rb_eArgError,
6570 "malloc: possible integer overflow (%"PRIuSIZE"*%"PRIuSIZE")",
6571 count, elsize);
6572}
6573
6574void
6575ruby_malloc_add_size_overflow(size_t x, size_t y)
6576{
6577 rb_raise(rb_eArgError,
6578 "malloc: possible integer overflow (%"PRIuSIZE"+%"PRIuSIZE")",
6579 x, y);
6580}
6581
6582static void *ruby_xmalloc2_body(size_t n, size_t size);
6583
6584void *
6585ruby_xmalloc2(size_t n, size_t size)
6586{
6587 if (RUBY_DTRACE_GC_XMALLOC_ENABLED()) {
6588 RUBY_DTRACE_GC_XMALLOC(n, size);
6589 }
6590
6591 return handle_malloc_failure(ruby_xmalloc2_body(n, size));
6592}
6593
6594static void *
6595ruby_xmalloc2_body(size_t n, size_t size)
6596{
6597 return rb_gc_impl_malloc(rb_gc_get_objspace(), xmalloc2_size(n, size), malloc_gc_allowed());
6598}
6599
6600static void *ruby_xcalloc_body(size_t n, size_t size);
6601
6602void *
6603ruby_xcalloc(size_t n, size_t size)
6604{
6605 if (RUBY_DTRACE_GC_XCALLOC_ENABLED()) {
6606 RUBY_DTRACE_GC_XCALLOC(n, size);
6607 }
6608
6609 return handle_malloc_failure(ruby_xcalloc_body(n, size));
6610}
6611
6612static void *
6613ruby_xcalloc_body(size_t n, size_t size)
6614{
6615 return rb_gc_impl_calloc(rb_gc_get_objspace(), xmalloc2_size(n, size), malloc_gc_allowed());
6616}
6617
6618static void *ruby_xrealloc_sized_body(void *ptr, size_t new_size, size_t old_size);
6619
6620#ifdef ruby_xrealloc_sized
6621#undef ruby_xrealloc_sized
6622#endif
6623void *
6624ruby_xrealloc_sized(void *ptr, size_t new_size, size_t old_size)
6625{
6626 return handle_malloc_failure(ruby_xrealloc_sized_body(ptr, new_size, old_size));
6627}
6628
6629static void *
6630ruby_xrealloc_sized_body(void *ptr, size_t new_size, size_t old_size)
6631{
6632 if ((ssize_t)new_size < 0) {
6633 negative_size_allocation_error("too large allocation size");
6634 }
6635
6636 return rb_gc_impl_realloc(rb_gc_get_objspace(), ptr, new_size, old_size, malloc_gc_allowed());
6637}
6638
6639void *
6640ruby_xrealloc(void *ptr, size_t new_size)
6641{
6642 return ruby_xrealloc_sized(ptr, new_size, 0);
6643}
6644
6645static void *ruby_xrealloc2_sized_body(void *ptr, size_t n, size_t size, size_t old_n);
6646
6647#ifdef ruby_xrealloc2_sized
6648#undef ruby_xrealloc2_sized
6649#endif
6650void *
6651ruby_xrealloc2_sized(void *ptr, size_t n, size_t size, size_t old_n)
6652{
6653 return handle_malloc_failure(ruby_xrealloc2_sized_body(ptr, n, size, old_n));
6654}
6655
6656static void *
6657ruby_xrealloc2_sized_body(void *ptr, size_t n, size_t size, size_t old_n)
6658{
6659 size_t len = xmalloc2_size(n, size);
6660 return rb_gc_impl_realloc(rb_gc_get_objspace(), ptr, len, old_n * size, malloc_gc_allowed());
6661}
6662
6663void *
6664ruby_xrealloc2(void *ptr, size_t n, size_t size)
6665{
6666 return ruby_xrealloc2_sized(ptr, n, size, 0);
6667}
6668
6669#ifdef ruby_xfree_sized
6670#undef ruby_xfree_sized
6671#endif
6672
6673/*
6674 * This is a debugging flag for measuring the cost of `xfree`.
6675 * It can be enabled at compile time using `-DRUBY_NO_FREE`.
6676 * At run time, if the `RUBY_NO_FREE` environment variable is set to "1",
6677 * then `xfree` will not free any memory.
6678 */
6679#ifdef RUBY_NO_FREE
6680static bool g_nofree = false;
6681#endif
6682
6683void
6684ruby_xfree_sized(void *x, size_t size)
6685{
6686#ifdef RUBY_NO_FREE
6687 if (g_nofree) {
6688 return;
6689 }
6690#endif
6691
6692 if (RUBY_DTRACE_GC_XFREE_ENABLED()) {
6693 RUBY_DTRACE_GC_XFREE(x, size);
6694 }
6695
6696 if (LIKELY(x)) {
6697 /* It's possible for a C extension's pthread destructor function set by pthread_key_create
6698 * to be called after ruby_vm_destruct and attempt to free memory. Fall back to mimfree in
6699 * that case. */
6700 if (LIKELY(GET_VM())) {
6701 rb_gc_impl_free(rb_gc_get_objspace(), x, size);
6702 }
6703 else {
6704 ruby_mimfree(x);
6705 }
6706 }
6707}
6708
6709void
6710ruby_xfree(void *x)
6711{
6712 ruby_xfree_sized(x, 0);
6713}
6714
6715void *
6716rb_xmalloc_mul_add(size_t x, size_t y, size_t z) /* x * y + z */
6717{
6718 size_t w = size_mul_add_or_raise(x, y, z, rb_eArgError);
6719 return ruby_xmalloc(w);
6720}
6721
6722void *
6723rb_xcalloc_mul_add(size_t x, size_t y, size_t z) /* x * y + z */
6724{
6725 size_t w = size_mul_add_or_raise(x, y, z, rb_eArgError);
6726 return ruby_xcalloc(w, 1);
6727}
6728
6729void *
6730rb_xrealloc_mul_add(const void *p, size_t x, size_t y, size_t z) /* x * y + z */
6731{
6732 size_t w = size_mul_add_or_raise(x, y, z, rb_eArgError);
6733 return ruby_xrealloc((void *)p, w);
6734}
6735
6736void *
6737rb_xmalloc_mul_add_mul(size_t x, size_t y, size_t z, size_t w) /* x * y + z * w */
6738{
6739 size_t u = size_mul_add_mul_or_raise(x, y, z, w, rb_eArgError);
6740 return ruby_xmalloc(u);
6741}
6742
6743void *
6744rb_xcalloc_mul_add_mul(size_t x, size_t y, size_t z, size_t w) /* x * y + z * w */
6745{
6746 size_t u = size_mul_add_mul_or_raise(x, y, z, w, rb_eArgError);
6747 return ruby_xcalloc(u, 1);
6748}
6749
6750/* Mimic ruby_xmalloc, but need not rb_objspace.
6751 * should return pointer suitable for ruby_xfree
6752 */
6753void *
6754ruby_mimmalloc(size_t size)
6755{
6756 void *mem;
6757#if CALC_EXACT_MALLOC_SIZE
6758 size += sizeof(struct malloc_obj_info);
6759#endif
6760 mem = malloc(size);
6761#if CALC_EXACT_MALLOC_SIZE
6762 if (!mem) {
6763 return NULL;
6764 }
6765 else
6766 /* set 0 for consistency of allocated_size/allocations */
6767 {
6768 struct malloc_obj_info *info = mem;
6769 info->size = 0;
6770 mem = info + 1;
6771 }
6772#endif
6773 return mem;
6774}
6775
6776void *
6777ruby_mimcalloc(size_t num, size_t size)
6778{
6779 void *mem;
6780#if CALC_EXACT_MALLOC_SIZE
6781 struct rbimpl_size_overflow_tag t = rbimpl_size_mul_overflow(num, size);
6782 if (UNLIKELY(t.overflowed)) {
6783 return NULL;
6784 }
6785 size = t.result + sizeof(struct malloc_obj_info);
6786 mem = calloc1(size);
6787 if (!mem) {
6788 return NULL;
6789 }
6790 else
6791 /* set 0 for consistency of allocated_size/allocations */
6792 {
6793 struct malloc_obj_info *info = mem;
6794 info->size = 0;
6795 mem = info + 1;
6796 }
6797#else
6798 mem = calloc(num, size);
6799#endif
6800 return mem;
6801}
6802
6803void
6804ruby_mimfree(void *ptr)
6805{
6806#if CALC_EXACT_MALLOC_SIZE
6807 struct malloc_obj_info *info = (struct malloc_obj_info *)ptr - 1;
6808 ptr = info;
6809#endif
6810 free(ptr);
6811}
6812
6813void
6814rb_gc_adjust_memory_usage(ssize_t diff)
6815{
6816 unless_objspace(objspace) { return; }
6817
6818 rb_gc_impl_adjust_memory_usage(objspace, diff);
6819}
6820
6821const char *
6822rb_obj_info(VALUE obj)
6823{
6824 return obj_info(obj);
6825}
6826
6827void
6828rb_obj_info_dump(VALUE obj)
6829{
6830 char buff[0x100];
6831 fprintf(stderr, "rb_obj_info_dump: %s\n", rb_raw_obj_info(buff, 0x100, obj));
6832}
6833
6834void
6835rb_obj_info_dump_loc(VALUE obj, const char *file, int line, const char *func)
6836{
6837 char buff[0x100];
6838 fprintf(stderr, "<OBJ_INFO:%s@%s:%d> %s\n", func, file, line, rb_raw_obj_info(buff, 0x100, obj));
6839}
6840
6841void
6842rb_gc_before_fork(void)
6843{
6844 rb_gc_impl_before_fork(rb_gc_get_objspace());
6845}
6846
6847void
6848rb_gc_after_fork(rb_pid_t pid)
6849{
6850 rb_gc_impl_after_fork(rb_gc_get_objspace(), pid);
6851}
6852
6853bool
6854rb_gc_obj_shareable_p(VALUE obj)
6855{
6856 return RB_OBJ_SHAREABLE_P(obj);
6857}
6858
6859void
6860rb_gc_rp(VALUE obj)
6861{
6862 rp(obj);
6863}
6864
6866 VALUE parent;
6867 long err_count;
6868};
6869
6870static void
6871check_shareable_i(const VALUE child, void *ptr)
6872{
6873 struct check_shareable_data *data = (struct check_shareable_data *)ptr;
6874
6875 if (!rb_gc_obj_shareable_p(child)) {
6876 /* A shareable object may reference an unshareable one only if the write barrier
6877 * recorded the edge in the target's shref bit (keeping it alive past its owner's
6878 * local GC). Root-like exceptions (Ractor private fields, cref, JIT) are hidden
6879 * while checking_shareable is set. */
6880 if (rb_gc_impl_shref_marked_p(rb_gc_get_objspace(), child)) {
6881 return;
6882 }
6883
6884 fprintf(stderr, "(a) ");
6885 rb_gc_rp(data->parent);
6886 fprintf(stderr, "(b) ");
6887 rb_gc_rp(child);
6888 fprintf(stderr, "check_shareable_i: shareable (a) -> unshareable (b) without a shref record\n");
6889
6890 data->err_count++;
6891 rb_bug("!! violate shareable constraint !!");
6892 }
6893}
6894
6895/* List obj's direct children one level deep through the traversal API and check the
6896 * shareable constraint: a shareable object's child is either shareable or an
6897 * unshareable one with a recorded shref. The "verification walk in progress" marker
6898 * lives in the per-Ractor mark_func_data slot: a process-global flag would make the
6899 * lock-free local GC of an unrelated Ractor hit the mark gate too, skip marking a live
6900 * object's children (its fields imemo, say) and let the sweep collect them. (Upstream
6901 * could use a global flag, since its GC always runs under the VM lock.) The slot is
6902 * private to this Ractor and the walk is synchronous, so no lock is needed. */
6903void
6904rb_gc_verify_shareable(VALUE obj)
6905{
6906 struct check_shareable_data data = {
6907 .parent = obj,
6908 .err_count = 0,
6909 };
6910
6911 if (!RB_SPECIAL_CONST_P(obj)) {
6912 struct gc_mark_func_data_struct **mfdp = GC_MARK_FUNC_DATA_SLOTP();
6913 struct gc_mark_func_data_struct *prev_mfd = *mfdp;
6914 struct gc_mark_func_data_struct mfd = {
6915 .mark_func = check_shareable_i,
6916 .data = &data,
6917 .checking_shareable = true,
6918 };
6919
6920 *mfdp = &mfd;
6921 rb_gc_mark_children(rb_gc_get_objspace(), obj);
6922 *mfdp = prev_mfd;
6923 }
6924
6925 if (data.err_count > 0) {
6926 rb_bug("rb_gc_verify_shareable");
6927 }
6928}
6929
6930bool
6931rb_gc_checking_shareable(void)
6932{
6933 const struct gc_mark_func_data_struct *mfd = *GC_MARK_FUNC_DATA_SLOTP();
6934 return mfd && mfd->checking_shareable;
6935}
6936
6937/*
6938 * Document-module: ObjectSpace
6939 *
6940 * The ObjectSpace module contains a number of routines
6941 * that interact with the garbage collection facility and allow you to
6942 * traverse all living objects with an iterator.
6943 *
6944 * ObjectSpace also provides support for object finalizers, procs that will be
6945 * called after a specific object was destroyed by garbage collection. See
6946 * the documentation for +ObjectSpace.define_finalizer+ for important
6947 * information on how to use this method correctly.
6948 *
6949 * a = "A"
6950 * b = "B"
6951 *
6952 * ObjectSpace.define_finalizer(a, proc {|id| puts "Finalizer one on #{id}" })
6953 * ObjectSpace.define_finalizer(b, proc {|id| puts "Finalizer two on #{id}" })
6954 *
6955 * a = nil
6956 * b = nil
6957 *
6958 * _produces:_
6959 *
6960 * Finalizer two on 537763470
6961 * Finalizer one on 537763480
6962 */
6963
6964#include "gc.rbinc"
6965
6966void
6967Init_GC(void)
6968{
6969#ifdef RUBY_NO_FREE
6970 const char* nofree_str = getenv("RUBY_NO_FREE");
6971 if (nofree_str && strcmp(nofree_str, "1") == 0) {
6972 fprintf(stderr, "WARNING: Enabling no-free mode! xfree() will never free anything!\n");
6973 g_nofree = true;
6974 }
6975#endif
6976
6977#undef rb_intern
6978 malloc_offset = gc_compute_malloc_offset();
6979
6980 rb_mGC = rb_define_module("GC");
6981
6982 VALUE rb_mObjSpace = rb_define_module("ObjectSpace");
6983
6984 rb_define_module_function(rb_mObjSpace, "each_object", os_each_obj, -1);
6985
6986 rb_define_module_function(rb_mObjSpace, "define_finalizer", define_final, -1);
6987 rb_define_module_function(rb_mObjSpace, "undefine_finalizer", undefine_final, 1);
6988
6989 rb_vm_register_special_exception(ruby_error_nomemory, rb_eNoMemError, "failed to allocate memory");
6990
6991 rb_define_method(rb_cBasicObject, "__id__", rb_obj_id, 0);
6992 rb_define_method(rb_mKernel, "object_id", rb_obj_id, 0);
6993
6994 rb_define_module_function(rb_mObjSpace, "count_objects", count_objects, -1);
6995
6996 rb_gc_impl_init();
6997}
6998
6999// Set a name for the anonymous virtual memory area. `addr` is the starting
7000// address of the area and `size` is its length in bytes. `name` is a
7001// NUL-terminated human-readable string.
7002//
7003// This function is usually called after calling `mmap()`. The human-readable
7004// annotation helps developers identify the call site of `mmap()` that created
7005// the memory mapping.
7006//
7007// This function currently only works on Linux 5.17 or higher. After calling
7008// this function, we can see annotations in the form of "[anon:...]" in
7009// `/proc/self/maps`, where `...` is the content of `name`. This function has
7010// no effect when called on other platforms.
7011void
7012ruby_annotate_mmap(const void *addr, unsigned long size, const char *name)
7013{
7014#if defined(HAVE_SYS_PRCTL_H) && defined(PR_SET_VMA) && defined(PR_SET_VMA_ANON_NAME)
7015 // The name length cannot exceed 80 (including the '\0').
7016 RUBY_ASSERT(strlen(name) < 80);
7017 prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME, (unsigned long)addr, size, name);
7018 // We ignore errors in prctl. prctl may set errno to EINVAL for several
7019 // reasons.
7020 // 1. The attr (PR_SET_VMA_ANON_NAME) is not a valid attribute.
7021 // 2. addr is an invalid address.
7022 // 3. The string pointed by name is too long.
7023 // The first error indicates PR_SET_VMA_ANON_NAME is not available, and may
7024 // happen if we run the compiled binary on an old kernel. In theory, all
7025 // other errors should result in a failure. But since EINVAL cannot tell
7026 // the first error from others, and this function is mainly used for
7027 // debugging, we silently ignore the error.
7028 errno = 0;
7029#endif
7030}
#define RUBY_ASSERT_ALWAYS(expr,...)
A variant of RUBY_ASSERT that does not interface with RUBY_DEBUG.
Definition assert.h:199
#define RUBY_ASSERT(...)
Asserts that the given expression is truthy if and only if RUBY_DEBUG is truthy.
Definition assert.h:219
#define RUBY_ATOMIC_VALUE_CAS(var, oldval, newval)
Identical to RUBY_ATOMIC_CAS, except it expects its arguments are VALUE.
Definition atomic.h:406
#define RUBY_ATOMIC_SIZE_FETCH_ADD(var, val)
Identical to RUBY_ATOMIC_FETCH_ADD, except it expects its arguments to be size_t.
Definition atomic.h:235
#define RUBY_ATOMIC_INC(var)
Atomically increments the value pointed by var.
Definition atomic.h:214
#define RUBY_ATOMIC_CAS(var, oldval, newval)
Atomic compare-and-swap.
Definition atomic.h:165
std::atomic< unsigned > rb_atomic_t
Type that is eligible for atomic operations.
Definition atomic.h:69
#define RUBY_ATOMIC_FETCH_ADD(var, val)
Atomically replaces the value pointed by var with the result of addition of val to the old value of v...
Definition atomic.h:118
#define RUBY_ATOMIC_DEC(var)
Atomically decrements the value pointed by var.
Definition atomic.h:223
#define RUBY_ATOMIC_LOAD(var)
Atomic load.
Definition atomic.h:175
#define RUBY_ATOMIC_SET(var, val)
Identical to RUBY_ATOMIC_EXCHANGE, except for the return type.
Definition atomic.h:185
#define rb_define_method(klass, mid, func, arity)
Defines klass#mid.
#define rb_define_module_function(klass, mid, func, arity)
Defines klass#mid and makes it a module function.
unsigned int rb_postponed_job_handle_t
The type of a handle returned from rb_postponed_job_preregister and passed to rb_postponed_job_trigge...
Definition debug.h:703
void rb_postponed_job_trigger(rb_postponed_job_handle_t h)
Triggers a pre-registered job registered with rb_postponed_job_preregister, scheduling it for executi...
Definition vm_trace.c:1899
rb_postponed_job_handle_t rb_postponed_job_preregister(unsigned int flags, rb_postponed_job_func_t func, void *data)
Pre-registers a func in Ruby's postponed job preregistration table, returning an opaque handle which ...
Definition vm_trace.c:1865
uint32_t rb_event_flag_t
Represents event(s).
Definition event.h:108
#define RUBY_INTERNAL_EVENT_NEWOBJ
Object allocated.
Definition event.h:93
static bool RB_OBJ_FROZEN(VALUE obj)
Checks if an object is frozen.
Definition fl_type.h:714
@ RUBY_FL_WB_PROTECTED
Definition fl_type.h:186
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:3384
#define T_COMPLEX
Old name of RUBY_T_COMPLEX.
Definition value_type.h:59
#define TYPE(_)
Old name of rb_type.
Definition value_type.h:108
#define FL_SINGLETON
Old name of RUBY_FL_SINGLETON.
Definition fl_type.h:58
#define T_FILE
Old name of RUBY_T_FILE.
Definition value_type.h:62
#define T_STRING
Old name of RUBY_T_STRING.
Definition value_type.h:78
#define xfree
Old name of ruby_xfree.
Definition xmalloc.h:58
#define T_MASK
Old name of RUBY_T_MASK.
Definition value_type.h:68
#define Qundef
Old name of RUBY_Qundef.
#define INT2FIX
Old name of RB_INT2FIX.
Definition long.h:48
#define OBJ_FROZEN
Old name of RB_OBJ_FROZEN.
Definition fl_type.h:133
#define T_NIL
Old name of RUBY_T_NIL.
Definition value_type.h:72
#define UNREACHABLE
Old name of RBIMPL_UNREACHABLE.
Definition assume.h:28
#define T_FLOAT
Old name of RUBY_T_FLOAT.
Definition value_type.h:64
#define T_IMEMO
Old name of RUBY_T_IMEMO.
Definition value_type.h:67
#define ID2SYM
Old name of RB_ID2SYM.
Definition symbol.h:44
#define T_BIGNUM
Old name of RUBY_T_BIGNUM.
Definition value_type.h:57
#define SPECIAL_CONST_P
Old name of RB_SPECIAL_CONST_P.
#define T_STRUCT
Old name of RUBY_T_STRUCT.
Definition value_type.h:79
#define OBJ_FREEZE
Old name of RB_OBJ_FREEZE.
Definition fl_type.h:131
#define T_FIXNUM
Old name of RUBY_T_FIXNUM.
Definition value_type.h:63
#define UNREACHABLE_RETURN
Old name of RBIMPL_UNREACHABLE_RETURN.
Definition assume.h:29
#define SYM2ID
Old name of RB_SYM2ID.
Definition symbol.h:45
#define T_DATA
Old name of RUBY_T_DATA.
Definition value_type.h:60
#define FIXNUM_FLAG
Old name of RUBY_FIXNUM_FLAG.
#define LL2NUM
Old name of RB_LL2NUM.
Definition long_long.h:30
#define CLASS_OF
Old name of rb_class_of.
Definition globals.h:205
#define T_NONE
Old name of RUBY_T_NONE.
Definition value_type.h:74
#define T_NODE
Old name of RUBY_T_NODE.
Definition value_type.h:73
#define SIZET2NUM
Old name of RB_SIZE2NUM.
Definition size_t.h:62
#define FL_FINALIZE
Old name of RUBY_FL_FINALIZE.
Definition fl_type.h:61
#define T_MODULE
Old name of RUBY_T_MODULE.
Definition value_type.h:70
#define ASSUME
Old name of RBIMPL_ASSUME.
Definition assume.h:27
#define T_TRUE
Old name of RUBY_T_TRUE.
Definition value_type.h:81
#define T_RATIONAL
Old name of RUBY_T_RATIONAL.
Definition value_type.h:76
#define T_ICLASS
Old name of RUBY_T_ICLASS.
Definition value_type.h:66
#define T_HASH
Old name of RUBY_T_HASH.
Definition value_type.h:65
#define ALLOC_N
Old name of RB_ALLOC_N.
Definition memory.h:399
#define FL_ABLE
Old name of RB_FL_ABLE.
Definition fl_type.h:118
#define FL_TEST_RAW
Old name of RB_FL_TEST_RAW.
Definition fl_type.h:128
#define rb_ary_new3
Old name of rb_ary_new_from_args.
Definition array.h:658
#define LONG2NUM
Old name of RB_LONG2NUM.
Definition long.h:50
#define T_FALSE
Old name of RUBY_T_FALSE.
Definition value_type.h:61
#define ULL2NUM
Old name of RB_ULL2NUM.
Definition long_long.h:31
#define T_UNDEF
Old name of RUBY_T_UNDEF.
Definition value_type.h:82
#define T_ZOMBIE
Old name of RUBY_T_ZOMBIE.
Definition value_type.h:83
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#define FIX2LONG
Old name of RB_FIX2LONG.
Definition long.h:46
#define T_ARRAY
Old name of RUBY_T_ARRAY.
Definition value_type.h:56
#define T_OBJECT
Old name of RUBY_T_OBJECT.
Definition value_type.h:75
#define NIL_P
Old name of RB_NIL_P.
#define FL_WB_PROTECTED
Old name of RUBY_FL_WB_PROTECTED.
Definition fl_type.h:59
#define T_SYMBOL
Old name of RUBY_T_SYMBOL.
Definition value_type.h:80
#define T_MATCH
Old name of RUBY_T_MATCH.
Definition value_type.h:69
#define T_CLASS
Old name of RUBY_T_CLASS.
Definition value_type.h:58
#define BUILTIN_TYPE
Old name of RB_BUILTIN_TYPE.
Definition value_type.h:85
#define T_MOVED
Old name of RUBY_T_MOVED.
Definition value_type.h:71
#define FL_TEST
Old name of RB_FL_TEST.
Definition fl_type.h:127
#define xcalloc
Old name of ruby_xcalloc.
Definition xmalloc.h:55
#define FL_UNSET
Old name of RB_FL_UNSET.
Definition fl_type.h:129
#define FIXNUM_P
Old name of RB_FIXNUM_P.
#define NUM2SIZET
Old name of RB_NUM2SIZE.
Definition size_t.h:61
#define SYMBOL_P
Old name of RB_SYMBOL_P.
Definition value_type.h:88
#define T_REGEXP
Old name of RUBY_T_REGEXP.
Definition value_type.h:77
size_t ruby_stack_length(VALUE **p)
Queries what Ruby thinks is the machine stack.
Definition gc.c:2858
int ruby_stack_check(void)
Checks for stack overflow.
Definition gc.c:2905
VALUE rb_eNoMemError
NoMemoryError exception.
Definition error.c:1484
#define ruby_verbose
This variable controls whether the interpreter is in debug mode.
Definition error.h:476
VALUE rb_eTypeError
TypeError exception.
Definition error.c:1473
VALUE rb_eRuntimeError
RuntimeError exception.
Definition error.c:1471
void rb_warn(const char *fmt,...)
Identical to rb_warning(), except it reports unless $VERBOSE is nil.
Definition error.c:468
VALUE rb_mKernel
Kernel module.
Definition object.c:59
VALUE rb_cObject
Object class.
Definition object.c:60
VALUE rb_mGC
GC module.
Definition gc.c:468
VALUE rb_obj_class(VALUE obj)
Queries the class of an object.
Definition object.c:234
VALUE rb_cBasicObject
BasicObject class.
Definition object.c:58
VALUE rb_class_real(VALUE klass)
Finds a "real" class.
Definition object.c:225
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:906
Defines RBIMPL_HAS_BUILTIN.
void rb_ary_free(VALUE ary)
Destroys the given array for no reason.
VALUE rb_ary_new(void)
Allocates a new, empty array.
VALUE rb_ary_push(VALUE ary, VALUE elem)
Special case of rb_ary_cat() that it adds only one element.
#define RETURN_ENUMERATOR(obj, argc, argv)
Identical to RETURN_SIZED_ENUMERATOR(), except its size is unknown.
Definition enumerator.h:242
static int rb_check_arity(int argc, int min, int max)
Ensures that the passed integer is in the passed range.
Definition error.h:284
VALUE rb_block_proc(void)
Constructs a Proc object from implicitly passed components.
Definition proc.c:1575
VALUE rb_obj_is_proc(VALUE recv)
Queries if the given object is a proc.
Definition proc.c:386
void rb_str_free(VALUE str)
Destroys the given string for no reason.
Definition string.c:1803
size_t rb_str_capacity(VALUE str)
Queries the capacity of the given string.
Definition string.c:1023
VALUE rb_mod_name(VALUE mod)
Queries the name of a module.
Definition variable.c:152
void rb_free_generic_ivar(VALUE obj)
Frees the list of instance variables.
Definition variable.c:1444
void rb_undef_alloc_func(VALUE klass)
Deletes the allocator function of a class.
Definition vm_method.c:1846
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:691
rb_alloc_func_t rb_get_alloc_func(VALUE klass)
Queries the allocator function of a class.
Definition vm_method.c:1855
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:3677
VALUE rb_sym2str(VALUE symbol)
Obtain a frozen string representation of a symbol (not including the leading colon).
Definition symbol.c:1148
int capa
Designed capacity of the buffer.
Definition io.h:11
int rb_io_fptr_finalize(rb_io_t *fptr)
Destroys the given IO.
Definition io.c:5941
int len
Length of the buffer.
Definition io.h:8
static bool rb_ractor_shareable_p(VALUE obj)
Queries if multiple Ractors can share the passed object or not.
Definition ractor.h:269
#define RB_OBJ_SHAREABLE_P(obj)
Queries if the passed object has previously classified as shareable or not.
Definition ractor.h:255
void * rb_thread_call_with_gvl(void *(*func)(void *), void *data1)
(Re-)acquires the GVL.
Definition thread.c:2319
VALUE rb_yield(VALUE val)
Yields the block.
Definition vm_eval.c:1378
#define RBIMPL_ATTR_MAYBE_UNUSED()
Wraps (or simulates) [[maybe_unused]]
#define MEMCPY(p1, p2, type, n)
Handy macro to call memcpy.
Definition memory.h:372
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
Definition memory.h:167
#define MEMMOVE(p1, p2, type, n)
Handy macro to call memmove.
Definition memory.h:384
VALUE type(ANYARGS)
ANYARGS-ed function type.
#define RARRAY_LEN
Just another name of rb_array_len.
Definition rarray.h:50
#define RARRAY(obj)
Convenient casting macro.
Definition rarray.h:44
#define RARRAY_AREF(a, i)
Definition rarray.h:402
#define RARRAY_CONST_PTR
Just another name of rb_array_const_ptr.
Definition rarray.h:51
static VALUE RBASIC_CLASS(VALUE obj)
Queries the class of an object.
Definition rbasic.h:166
#define RBASIC(obj)
Convenient casting macro.
Definition rbasic.h:40
#define RCLASS(obj)
Convenient casting macro.
Definition rclass.h:38
#define RUBY_DEFAULT_FREE
This is a value you can set to RData::dfree.
Definition rdata.h:56
void(* RUBY_DATA_FUNC)(void *)
This is the type of callbacks registered to RData.
Definition rdata.h:69
#define RUBY_NEVER_FREE
This is a value you can set to RData::dfree.
Definition rdata.h:63
#define RFILE(obj)
Convenient casting macro.
Definition rfile.h:50
#define RHASH_SIZE(h)
Queries the size of the hash.
Definition rhash.h:57
#define RHASH_EMPTY_P(h)
Checks if the hash is empty.
Definition rhash.h:67
#define RMATCH(obj)
Convenient casting macro.
Definition rmatch.h:37
#define ROBJECT(obj)
Convenient casting macro.
Definition robject.h:43
#define RREGEXP(obj)
Convenient casting macro.
Definition rregexp.h:37
static struct re_pattern_buffer * RREGEXP_PTR(VALUE rexp)
Convenient getter function.
Definition rregexp.h:86
static int RSTRING_LENINT(VALUE str)
Identical to RSTRING_LEN(), except it differs for the return type.
Definition rstring.h:438
#define RSTRING(obj)
Convenient casting macro.
Definition rstring.h:41
static long RSTRUCT_LEN(VALUE st)
Returns the number of struct members.
Definition rstruct.h:82
#define RUBY_TYPED_DEFAULT_FREE
This is a value you can set to rb_data_type_struct::dfree.
Definition rtypeddata.h:81
VALUE rb_data_typed_object_wrap(VALUE klass, void *datap, const rb_data_type_t *type)
This is the primitive way to wrap an existing C struct into RTypedData.
Definition gc.c:1405
VALUE rb_data_typed_object_zalloc(VALUE klass, size_t size, const rb_data_type_t *type)
Identical to rb_data_typed_object_wrap(), except it allocates a new data region internally instead of...
Definition gc.c:1442
#define RUBY_TYPED_FREE_IMMEDIATELY
Macros to see if each corresponding flag is defined.
Definition rtypeddata.h:122
#define DATA_PTR(obj)
Convenient casting macro for backward compatibility.
Definition rtypeddata.h:439
static const rb_data_type_t * RTYPEDDATA_TYPE(VALUE obj)
Queries for the type of given object.
Definition rtypeddata.h:692
#define RDATA(obj)
Convenient casting macro for backward compatibility.
Definition rtypeddata.h:431
#define RTYPEDDATA(obj)
Convenient casting macro.
Definition rtypeddata.h:96
const char * rb_obj_classname(VALUE obj)
Queries the name of the class of the passed object.
Definition variable.c:533
void rb_p(VALUE obj)
Inspects an object.
Definition io.c:9314
#define errno
Ractor-aware version of errno.
Definition ruby.h:388
int ruby_native_thread_p(void)
Queries if the thread which calls this function is a ruby's thread.
Definition thread.c:6157
static bool RB_SPECIAL_CONST_P(VALUE obj)
Checks if the given object is of enum ruby_special_consts.
#define RTEST
This is an old name of RB_TEST.
Defines old _.
#define _(args)
This was a transition path from K&R to ANSI.
Definition stdarg.h:35
Ruby's array.
Definition rarray.h:127
Ruby object's base components.
Definition rbasic.h:69
Regular expression execution context.
Definition rmatch.h:79
union RMatch::@58 as
"Registers" of a match.
struct rmatch_offset * char_offset
Capture group offsets, in C array.
Definition rmatch.h:98
int char_offset_num_allocated
Number of rmatch_offset that ::rmatch::char_offset holds.
Definition rmatch.h:95
int num_regs
Number of capture-group registers.
Definition rmatch.h:101
Ruby's ordinal objects.
Definition robject.h:51
Ruby's String.
Definition rstring.h:196
"Typed" user data.
Definition rtypeddata.h:397
void * data
Pointer to the actual C level struct that you want to wrap.
Definition rtypeddata.h:417
VALUE fields_obj
Direct reference to the slots that holds instance variables, if any.
Definition rtypeddata.h:403
Definition method.h:63
Definition constant.h:33
This is the struct that holds necessary info for a struct.
Definition rtypeddata.h:242
struct rb_data_type_struct::@64 function
Function pointers.
RUBY_DATA_FUNC dcompact
This function is called when the object is relocated.
Definition rtypeddata.h:293
const char * wrap_struct_name
Name of structs of this kind.
Definition rtypeddata.h:249
RUBY_DATA_FUNC dmark
This function is called when the object is experiencing GC marks.
Definition rtypeddata.h:263
Definition gc_impl.h:34
Ruby's IO, metadata and buffers.
Definition io.h:295
Definition method.h:55
const rb_iseq_t * iseqptr
iseq pointer, should be separated from iseqval
Definition method.h:143
Represents the region of a capture group.
Definition rmatch.h:65
Definition st.h:79
Definition string.c:9192
void rb_native_mutex_lock(rb_nativethread_lock_t *lock)
Just another name of rb_nativethread_lock_lock.
void rb_native_mutex_initialize(rb_nativethread_lock_t *lock)
Just another name of rb_nativethread_lock_initialize.
void rb_native_mutex_unlock(rb_nativethread_lock_t *lock)
Just another name of rb_nativethread_lock_unlock.
intptr_t SIGNED_VALUE
A signed integer type that has the same width with VALUE.
Definition value.h:63
uintptr_t ID
Type that represents a Ruby identifier such as a variable name.
Definition value.h:52
uintptr_t VALUE
Type that represents a Ruby object.
Definition value.h:40
static bool RB_TYPE_P(VALUE obj, enum ruby_value_type t)
Queries if the given object is of given type.
Definition value_type.h:376
ruby_value_type
C-level type of an object.
Definition value_type.h:113
@ RUBY_T_MASK
Bitmask of ruby_value_type.
Definition value_type.h:145