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