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