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