Ruby 4.1.0dev (2026-09-26 revision 57213d44ce7b1a31fc9648e9cd5eb0c4507f4a49)
gc.c (57213d44ce7b1a31fc9648e9cd5eb0c4507f4a49)
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_globals.lock (every Ractor's root scan takes
640 * it); inheriting it locked would make the child's first GC wait forever, so rebuild
641 * it, like the generic_fields lock. */
642void
643rb_gc_atfork_global_locks(void)
644{
645 rb_vm_t *vm = GET_VM();
646 rb_native_mutex_initialize(&vm->gc.registered_globals.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
3348void
3349rb_gc_mark_roots(void *objspace, const char **categoryp)
3350{
3351 rb_execution_context_t *ec = rb_gc_get_ec();
3352 rb_vm_t *vm = rb_ec_vm_ptr(ec);
3353
3354#define MARK_CHECKPOINT(category) do { \
3355 if (categoryp) *categoryp = category; \
3356} while (0)
3357
3358 /* A single-objspace impl (mmtk) only has stop-the-world global GCs and no
3359 * per-mutator root scan, so always walk every Ractor's local roots here. */
3360 const bool global_gc = rb_gc_impl_during_global_gc_p(objspace) ||
3361 !rb_gc_impl_multi_objspace_p();
3362
3363 /* Mark the current Ractor's roots from its C structs (a local GC must not depend on
3364 * heap wrapper traversal). A global GC does the same for every Ractor. */
3365 MARK_CHECKPOINT("ractor");
3366 if (global_gc) {
3367 rb_ractor_t *r;
3368 ccan_list_for_each(&vm->ractor.set, r, vmlr_node) {
3369 rb_ractor_mark_local_roots(r);
3370 }
3371
3372 /* Early in boot (before rb_ractor_main_setup) main is not in vm->ractor.set
3373 * yet; do not drop its registered_marks in a single-objspace boot GC. */
3374 if (vm->ractor.cnt == 0 && vm->ractor.main_ractor) {
3375 rb_ractor_mark_local_roots(vm->ractor.main_ractor);
3376 }
3377 /* A Ractor that terminated (left vm->ractor.set) but whose struct is not freed
3378 * still owns rb_gc_register_mark_object pins. Keep them alive until
3379 * ractor_free hands them to main; an orphan (owner == NULL) was moved above.
3380 * The join value is not rooted here: ractor_mark marks it from the wrapper. */
3381 for (size_t i = 0; i < vm->gc.zombie_objspaces_count; i++) {
3382 rb_ractor_t *owner = vm->gc.zombie_objspaces[i].owner;
3383 if (owner) {
3384 rb_gc_mark_vm_stack_values((long)owner->registered_marks_cnt,
3385 owner->registered_marks);
3386 }
3387 }
3388
3389 /* Single-objspace impl: keep terminated-but-not-freed Ractors'
3390 * rb_gc_register_mark_object entries alive without depending on wrapper
3391 * reachability. With multiple objspaces zombie_objspaces covers this. */
3392 if (!rb_gc_impl_multi_objspace_p()) {
3393 rb_ractor_t *tr;
3394 rb_native_mutex_lock(&vm->gc.registered_globals.lock);
3395 ccan_list_for_each(&vm->ractor.terminated_set, tr, vmlr_node) {
3396 rb_gc_mark_vm_stack_values((long)tr->registered_marks_cnt,
3397 tr->registered_marks);
3398 }
3399 rb_native_mutex_unlock(&vm->gc.registered_globals.lock);
3400 }
3401 }
3402 else {
3403 rb_ractor_mark_local_roots(rb_ec_ractor_ptr(ec));
3404 }
3405
3406 /* rb_gc_register_address slots live in one VM-wide list: *addr can later hold
3407 * another objspace's value, so every Ractor's GC scans all slots conservatively,
3408 * marking only its own residents. */
3409 MARK_CHECKPOINT("registered_globals");
3410 rb_native_mutex_lock(&vm->gc.registered_globals.lock);
3411 for (size_t i = 0; i < vm->gc.registered_globals.addrs_cnt; i++) {
3412 rb_gc_mark_maybe(*vm->gc.registered_globals.addrs[i]);
3413 }
3414 rb_native_mutex_unlock(&vm->gc.registered_globals.lock);
3415
3416 /* Trap handlers live in the VM-global vm->trap_list.cmd[], a fixed array of aligned
3417 * VALUEs (signal.c uses ACCESS_ONCE): a racing walk reads either the old or the new
3418 * handler, both alive, so no lock. */
3419 MARK_CHECKPOINT("trap_list");
3420 rb_gc_mark_values(RUBY_NSIG, vm->trap_list.cmd);
3421
3422 /* VM-global roots belong to the main Ractor's objspace, since the boot objects
3423 * live there. A non-main Ractor's local GC skips them; a global GC walks all. */
3424 if (global_gc || objspace == vm->ractor.main_ractor->objspace) {
3425 /* Only the main Ractor can register at_exit/END procs (a non-main one gets an
3426 * IsolationError) so end_procs is a lock-free linked list */
3427 MARK_CHECKPOINT("end_proc");
3428 rb_mark_end_proc();
3429
3430 MARK_CHECKPOINT("vm");
3431 /* rb_vm_mark and the JIT root marks walk VM-global weak tables and shared singleton
3432 * JIT state that other Ractors rewrite under the VM lock, so main's otherwise
3433 * lock-free local GC takes the VM lock for this stretch */
3434 const bool vm_mark_needs_lock = rb_multi_ractor_p() && !global_gc;
3435 unsigned int vm_mark_lock_lev = 0;
3436 if (vm_mark_needs_lock) vm_mark_lock_lev = RB_GC_VM_LOCK_NO_BARRIER();
3437 rb_vm_mark(vm);
3438
3439 MARK_CHECKPOINT("global_tbl");
3440 rb_gc_mark_global_tbl();
3441
3442#if USE_YJIT
3443 void rb_yjit_root_mark(void); // in Rust
3444
3445 if (rb_yjit_enabled_p) {
3446 MARK_CHECKPOINT("YJIT");
3447 rb_yjit_root_mark();
3448 }
3449#endif
3450
3451#if USE_ZJIT
3452 void rb_zjit_root_mark(void);
3453 if (rb_zjit_enabled_p) {
3454 MARK_CHECKPOINT("ZJIT");
3455 rb_zjit_root_mark();
3456 }
3457#endif
3458 if (vm_mark_needs_lock) RB_GC_VM_UNLOCK_NO_BARRIER(vm_mark_lock_lev);
3459
3460 if (global_gc || rb_gc_single_objspace_p()) {
3461 MARK_CHECKPOINT("global_symbols");
3462 rb_sym_global_symbols_mark_and_move();
3463 }
3464 }
3465
3466 /* The dying thread's final collection of its own objspace runs after its stack
3467 * has been torn down (thread_cleanup_func), so there is no live machine context
3468 * to scan -- the join value and the pins are rooted explicitly. Scanning the
3469 * half-dead stack is not only useless but faults on some platforms. */
3470 if (!rb_gc_impl_during_postmortem_p(objspace)) {
3471 MARK_CHECKPOINT("machine_context");
3472 mark_current_machine_context(ec);
3473 }
3474
3475 MARK_CHECKPOINT("finish");
3476
3477#undef MARK_CHECKPOINT
3478}
3479
3484
3485static void
3486gc_mark_classext_module(rb_classext_t *ext, bool prime, VALUE box_value, void *arg)
3487{
3489 rb_objspace_t *objspace = foreach_arg->objspace;
3490
3491 if (RCLASSEXT_SUPER(ext)) {
3492 gc_mark_internal(RCLASSEXT_SUPER(ext));
3493 }
3494 mark_m_tbl(objspace, RCLASSEXT_M_TBL(ext));
3495
3496 gc_mark_internal(RCLASSEXT_FIELDS_OBJ(ext));
3497 gc_mark_internal(RCLASSEXT_CVC_TBL(ext));
3498
3499 if (!RCLASSEXT_SHARED_CONST_TBL(ext) && RCLASSEXT_CONST_TBL(ext)) {
3500 mark_const_tbl(objspace, RCLASSEXT_CONST_TBL(ext));
3501 }
3502 mark_m_tbl(objspace, RCLASSEXT_CALLABLE_M_TBL(ext));
3503 gc_mark_internal(RCLASSEXT_CC_TBL(ext));
3504 if (RCLASSEXT_SUBCLASSES(ext)) {
3505 gc_mark_internal(RCLASSEXT_SUBCLASSES(ext));
3506 }
3507 gc_mark_internal(RCLASSEXT_CLASSPATH(ext));
3508}
3509
3510static void
3511gc_mark_classext_iclass(rb_classext_t *ext, bool prime, VALUE box_value, void *arg)
3512{
3514 rb_objspace_t *objspace = foreach_arg->objspace;
3515
3516 if (RCLASSEXT_SUPER(ext)) {
3517 gc_mark_internal(RCLASSEXT_SUPER(ext));
3518 }
3519 if (RCLASSEXT_ICLASS_IS_ORIGIN(ext) && !RCLASSEXT_ICLASS_ORIGIN_SHARED_MTBL(ext)) {
3520 mark_m_tbl(objspace, RCLASSEXT_M_TBL(ext));
3521 }
3522 if (RCLASSEXT_INCLUDER(ext)) {
3523 gc_mark_internal(RCLASSEXT_INCLUDER(ext));
3524 }
3525 mark_m_tbl(objspace, RCLASSEXT_CALLABLE_M_TBL(ext));
3526 gc_mark_internal(RCLASSEXT_CC_TBL(ext));
3527 if (RCLASSEXT_SUBCLASSES(ext)) {
3528 gc_mark_internal(RCLASSEXT_SUBCLASSES(ext));
3529 }
3530}
3531
3532#define TYPED_DATA_REFS_OFFSET_LIST(d) (size_t *)(uintptr_t)RTYPEDDATA_TYPE(d)->function.dmark
3533
3534static inline bool
3535rb_obj_using_gen_fields_table_p(VALUE obj)
3536{
3537 switch (BUILTIN_TYPE(obj)) {
3538 case T_STRUCT:
3539 case T_DATA:
3540 return false;
3541
3542 default:
3543 break;
3544 }
3545
3546 return rb_obj_gen_fields_p(obj);
3547}
3548
3549void
3550rb_gc_move_obj_during_marking(VALUE from, VALUE to)
3551{
3552 if (rb_obj_using_gen_fields_table_p(to)) {
3553 rb_mark_generic_ivar(from);
3554 }
3555}
3556
3557void
3558rb_gc_mark_children(void *objspace, VALUE obj)
3559{
3560 struct gc_mark_classext_foreach_arg foreach_args;
3561
3562 if (rb_obj_using_gen_fields_table_p(obj)) {
3563 rb_mark_generic_ivar(obj);
3564 }
3565
3566 switch (BUILTIN_TYPE(obj)) {
3567 case T_FLOAT:
3568 case T_BIGNUM:
3569 return;
3570
3571 case T_NIL:
3572 case T_FIXNUM:
3573 rb_bug("rb_gc_mark() called for broken object");
3574 break;
3575
3576 case T_NODE:
3577 UNEXPECTED_NODE(rb_gc_mark);
3578 break;
3579
3580 case T_IMEMO:
3581 rb_imemo_mark_and_move(obj, false);
3582 return;
3583
3584 default:
3585 break;
3586 }
3587
3588 gc_mark_internal(RBASIC(obj)->klass);
3589
3590 switch (BUILTIN_TYPE(obj)) {
3591 case T_CLASS:
3592 if (FL_TEST_RAW(obj, FL_SINGLETON)) {
3593 gc_mark_internal(RCLASS_ATTACHED_OBJECT(obj));
3594 }
3595 // Continue to the shared T_CLASS/T_MODULE
3596 case T_MODULE:
3597 foreach_args.objspace = objspace;
3598 foreach_args.obj = obj;
3599 rb_class_classext_foreach(obj, gc_mark_classext_module, (void *)&foreach_args);
3600 if (BOX_USER_P(RCLASS_PRIME_BOX(obj))) {
3601 gc_mark_internal(RCLASS_PRIME_BOX(obj)->box_object);
3602 }
3603 break;
3604
3605 case T_ICLASS:
3606 foreach_args.objspace = objspace;
3607 foreach_args.obj = obj;
3608 rb_class_classext_foreach(obj, gc_mark_classext_iclass, (void *)&foreach_args);
3609 if (BOX_USER_P(RCLASS_PRIME_BOX(obj))) {
3610 gc_mark_internal(RCLASS_PRIME_BOX(obj)->box_object);
3611 }
3612 break;
3613
3614 case T_ARRAY:
3615 if (ARY_SHARED_P(obj)) {
3616 VALUE root = ARY_SHARED_ROOT(obj);
3617 if (RB_TYPE_P(root, T_ARRAY)) {
3618 gc_mark_internal(root);
3619 }
3620 else {
3621 /* Ractor#send(move: true) hollowed the root out in place. If it was
3622 * embedded our elements are still in its slot, and nothing says so any
3623 * more, so it must not move (gc_ref_update_array cannot re-point us). */
3624 gc_mark_and_pin_internal(root);
3625 }
3626 }
3627 else {
3628 long len = RARRAY_LEN(obj);
3629 const VALUE *ptr = RARRAY_CONST_PTR(obj);
3630 for (long i = 0; i < len; i++) {
3631 gc_mark_internal(ptr[i]);
3632 }
3633 }
3634 break;
3635
3636 case T_HASH:
3637 mark_hash(obj);
3638 break;
3639
3640 case T_SYMBOL:
3641 gc_mark_internal(RSYMBOL(obj)->fstr);
3642 break;
3643
3644 case T_STRING:
3645 if (STR_SHARED_P(obj)) {
3646 if (STR_EMBED_P(RSTRING(obj)->as.heap.aux.shared)) {
3647 /* Embedded shared strings cannot be moved because this string
3648 * points into the slot of the shared string. There may be code
3649 * using the RSTRING_PTR on the stack, which would pin this
3650 * string but not pin the shared string, causing it to move. */
3651 gc_mark_and_pin_internal(RSTRING(obj)->as.heap.aux.shared);
3652 }
3653 else {
3654 gc_mark_internal(RSTRING(obj)->as.heap.aux.shared);
3655 }
3656 }
3657 break;
3658
3659 case T_DATA: {
3660 void *const ptr = RTYPEDDATA_GET_DATA(obj);
3661
3662 gc_mark_internal(RTYPEDDATA(obj)->fields_obj);
3663
3664 if (ptr) {
3665 if (gc_declarative_marking_p(RTYPEDDATA_TYPE(obj))) {
3666 size_t *offset_list = TYPED_DATA_REFS_OFFSET_LIST(obj);
3667
3668 for (size_t offset = *offset_list; offset != RUBY_REF_END; offset = *offset_list++) {
3669 gc_mark_internal(*(VALUE *)((char *)ptr + offset));
3670 }
3671 }
3672 else {
3673 RUBY_DATA_FUNC mark_func = RTYPEDDATA_TYPE(obj)->function.dmark;
3674 if (mark_func) (*mark_func)(ptr);
3675 }
3676 }
3677
3678 break;
3679 }
3680
3681 case T_OBJECT: {
3682 shape_id_t shape_id = RBASIC_SHAPE_ID(obj);
3683 if (rb_shape_embedded_p(shape_id)) {
3684 uint32_t len = RSHAPE_LEN(shape_id);
3685 const VALUE * const ptr = ROBJECT(obj)->as.ary;
3686
3687 for (uint32_t i = 0; i < len; i++) {
3688 gc_mark_internal(ptr[i]);
3689 }
3690 }
3691 else {
3692 if (!rb_gc_checking_shareable()) {
3693 gc_mark_internal(ROBJECT(obj)->as.extended);
3694 }
3695 }
3696 break;
3697 }
3698
3699 case T_FILE:
3700 if (RFILE(obj)->fptr) {
3701 gc_mark_internal(RFILE(obj)->fptr->self);
3702 gc_mark_internal(RFILE(obj)->fptr->pathv);
3703 gc_mark_internal(RFILE(obj)->fptr->tied_io_for_writing);
3704 gc_mark_internal(RFILE(obj)->fptr->writeconv_asciicompat);
3705 gc_mark_internal(RFILE(obj)->fptr->writeconv_pre_ecopts);
3706 gc_mark_internal(RFILE(obj)->fptr->encs.ecopts);
3707 gc_mark_internal(RFILE(obj)->fptr->write_lock);
3708 gc_mark_internal(RFILE(obj)->fptr->timeout);
3709 gc_mark_internal(RFILE(obj)->fptr->wakeup_mutex);
3710 }
3711 break;
3712
3713 case T_REGEXP:
3714 gc_mark_internal(RREGEXP(obj)->src);
3715 break;
3716
3717 case T_MATCH:
3718 gc_mark_internal(RMATCH(obj)->regexp);
3719 if (RMATCH(obj)->str) {
3720 gc_mark_internal(RMATCH(obj)->str);
3721 }
3722 break;
3723
3724 case T_RATIONAL:
3725 gc_mark_internal(RRATIONAL(obj)->num);
3726 gc_mark_internal(RRATIONAL(obj)->den);
3727 break;
3728
3729 case T_COMPLEX:
3730 gc_mark_internal(RCOMPLEX(obj)->real);
3731 gc_mark_internal(RCOMPLEX(obj)->imag);
3732 break;
3733
3734 case T_STRUCT: {
3735 const long len = RSTRUCT_LEN(obj);
3736 const VALUE * const ptr = RSTRUCT_CONST_PTR(obj);
3737
3738 for (long i = 0; i < len; i++) {
3739 gc_mark_internal(ptr[i]);
3740 }
3741
3742 gc_mark_internal(RSTRUCT_FIELDS_OBJ(obj));
3743
3744 break;
3745 }
3746
3747 default:
3748 if (BUILTIN_TYPE(obj) == T_MOVED) rb_bug("rb_gc_mark(): %p is T_MOVED", (void *)obj);
3749 if (BUILTIN_TYPE(obj) == T_NONE) rb_bug("rb_gc_mark(): %p is T_NONE", (void *)obj);
3750 if (BUILTIN_TYPE(obj) == T_ZOMBIE) rb_bug("rb_gc_mark(): %p is T_ZOMBIE", (void *)obj);
3751 rb_bug("rb_gc_mark(): unknown data type 0x%x(%p) %s",
3752 BUILTIN_TYPE(obj), (void *)obj,
3753 rb_gc_impl_live_object_p(objspace, (void *)obj) ? "corrupted object" : "non object");
3754 }
3755}
3756
3757size_t
3758rb_gc_obj_optimal_size(VALUE obj)
3759{
3760 switch (BUILTIN_TYPE(obj)) {
3761 case T_ARRAY:
3762 {
3763 size_t size = rb_ary_size_as_embedded(obj);
3764 if (rb_gc_size_allocatable_p(size)) {
3765 return size;
3766 }
3767 else {
3768 return sizeof(struct RArray);
3769 }
3770 }
3771
3772 case T_OBJECT:
3773 if (rb_obj_shape_complex_p(obj)) {
3774 return sizeof(struct RObject);
3775 }
3776 else {
3777 size_t size = rb_obj_embedded_size(RSHAPE_CAPACITY(RBASIC_SHAPE_ID(obj)));
3778 if (rb_gc_size_allocatable_p(size)) {
3779 return size;
3780 }
3781 else {
3782 return sizeof(struct RObject);
3783 }
3784 }
3785
3786 case T_STRING:
3787 {
3788 size_t size = rb_str_size_as_embedded(obj);
3789 if (rb_gc_size_allocatable_p(size)) {
3790 return size;
3791 }
3792 else {
3793 return sizeof(struct RString);
3794 }
3795 }
3796
3797 case T_HASH:
3798 {
3799 if (RHASH_AR_TABLE_P(obj)) {
3800 const unsigned bound = RHASH_AR_TABLE_BOUND(obj);
3801 const size_t ar_size = RHASH_AR_SLOT_SIZE(bound);
3802 if (ar_size > RHASH_ST_SLOT_SIZE || OBJ_FROZEN(obj)) {
3803 return ar_size;
3804 }
3805 }
3806
3807 return RHASH_ST_SLOT_SIZE;
3808 }
3809
3810 default:
3811 return 0;
3812 }
3813}
3814
3815void
3816rb_gc_writebarrier(VALUE a, VALUE b)
3817{
3818 rb_gc_impl_writebarrier(rb_gc_get_objspace(), a, b);
3819}
3820
3821void
3822rb_gc_writebarrier_unprotect(VALUE obj)
3823{
3824 rb_gc_impl_writebarrier_unprotect(rb_gc_get_objspace(), obj);
3825}
3826
3827/*
3828 * remember `obj' if needed.
3829 */
3830void
3831rb_gc_writebarrier_remember(VALUE obj)
3832{
3833 rb_gc_impl_writebarrier_remember(rb_gc_get_objspace(), obj);
3834}
3835
3836/* obj became shareable after it was created (FL_SHAREABLE was set). Tell the GC so it
3837 * updates the per-page shareable bitmap. */
3838void
3839rb_gc_obj_became_shareable(VALUE obj)
3840{
3841 rb_gc_impl_obj_became_shareable(rb_gc_get_objspace(), obj);
3842}
3843
3844/* Pin an in-flight message payload in its owner's (the sender's) objspace, so the
3845 * sender's local GC keeps it alive while it sits in a queue the sender does not walk. */
3846void
3847rb_gc_copy_attributes(VALUE dest, VALUE obj)
3848{
3849 rb_gc_impl_copy_attributes(rb_gc_get_objspace(), dest, obj);
3850}
3851
3852#if USE_MODULAR_GC
3853int
3854rb_gc_modular_gc_loaded_p(void)
3855{
3856 return rb_gc_functions.modular_gc_loaded_p;
3857}
3858
3859const char *
3860rb_gc_active_gc_name(void)
3861{
3862 const char *gc_name = rb_gc_impl_active_gc_name();
3863
3864 const size_t len = strlen(gc_name);
3865 if (len > RB_GC_MAX_NAME_LEN) {
3866 rb_bug("GC should have a name no more than %d chars long. Currently: %zu (%s)",
3867 RB_GC_MAX_NAME_LEN, len, gc_name);
3868 }
3869
3870 return gc_name;
3871}
3872#endif
3873
3875rb_gc_object_metadata(VALUE obj)
3876{
3877 return rb_gc_impl_object_metadata(rb_gc_get_objspace(), obj);
3878}
3879
3880/* GC */
3881
3882void *
3883rb_gc_ractor_cache_alloc(rb_ractor_t *ractor)
3884{
3885 return rb_gc_impl_ractor_cache_alloc(rb_gc_get_objspace(), ractor);
3886}
3887
3888void
3889rb_gc_ractor_cache_free(void *cache)
3890{
3891 rb_gc_impl_ractor_cache_free(rb_gc_get_objspace(), cache);
3892}
3893
3894bool
3895rb_gc_zjit_new_obj_fastpath(size_t alloc_size, VALUE flags, VALUE klass, struct rb_gc_zjit_fastpath *fastpath)
3896{
3897#if defined(RUBY_ASAN_ENABLED)
3898 (void)rb_gc_impl_zjit_new_obj_fastpath;
3899 return false;
3900#else
3901 return rb_gc_impl_zjit_new_obj_fastpath(rb_gc_get_objspace(), alloc_size, flags, klass, fastpath);
3902#endif
3903}
3904
3905void
3906rb_gc_register_mark_object(VALUE obj)
3907{
3908 /* rb_gc_impl_live_object_p() walks objspace->heap_pages.sorted, which
3909 * another ractor may mutate while allocating heap pages under the VM lock,
3910 * so the lookup must be done under the VM lock as well. */
3911 RB_VM_LOCKING() {
3912 if (rb_gc_impl_live_object_p(rb_gc_get_objspace(), (void *)obj)) {
3913 rb_vm_register_global_object(obj);
3914 }
3915 }
3916}
3917
3918void
3919rb_gc_register_address(VALUE *addr)
3920{
3921 rb_vm_t *vm = GET_VM();
3922
3923 rb_native_mutex_lock(&vm->gc.registered_globals.lock);
3924 if (vm->gc.registered_globals.addrs_cnt == vm->gc.registered_globals.addrs_capa) {
3925 size_t nc = vm->gc.registered_globals.addrs_capa ? vm->gc.registered_globals.addrs_capa * 2 : 64;
3926 VALUE **p = realloc(vm->gc.registered_globals.addrs, nc * sizeof(VALUE *));
3927 if (!p) rb_bug("rb_gc_register_address: out of memory");
3928 vm->gc.registered_globals.addrs = p;
3929 vm->gc.registered_globals.addrs_capa = nc;
3930 }
3931 vm->gc.registered_globals.addrs[vm->gc.registered_globals.addrs_cnt++] = addr;
3932 rb_native_mutex_unlock(&vm->gc.registered_globals.lock);
3933
3934 /* Some C extensions register before assigning, so protect obj from GC here. */
3935 RB_GC_GUARD(*addr);
3936}
3937
3938void
3939rb_gc_unregister_address(VALUE *addr)
3940{
3941 rb_vm_t *vm = GET_VM();
3942
3943 /* One VM-wide list, so a register and unregister from different Ractors (Init on
3944 * main, dfree elsewhere) still pair up. Silently a no-op when not found: upstream
3945 * tolerates a double unregister too. */
3946 rb_native_mutex_lock(&vm->gc.registered_globals.lock);
3947 for (size_t i = 0; i < vm->gc.registered_globals.addrs_cnt; i++) {
3948 if (vm->gc.registered_globals.addrs[i] == addr) {
3949 MEMMOVE(&vm->gc.registered_globals.addrs[i], &vm->gc.registered_globals.addrs[i + 1],
3950 VALUE *, vm->gc.registered_globals.addrs_cnt - i - 1);
3951 vm->gc.registered_globals.addrs_cnt--;
3952 break;
3953 }
3954 }
3955 rb_native_mutex_unlock(&vm->gc.registered_globals.lock);
3956}
3957
3958void
3960{
3961 rb_gc_register_address(var);
3962}
3963
3964static VALUE
3965gc_start_internal(rb_execution_context_t *ec, VALUE self, VALUE full_mark, VALUE immediate_mark, VALUE immediate_sweep, VALUE compact, VALUE global)
3966{
3967 rb_gc_impl_start(rb_gc_get_objspace(), RTEST(full_mark), RTEST(immediate_mark), RTEST(immediate_sweep), RTEST(compact), RTEST(global));
3968
3969 return Qnil;
3970}
3971
3973 void *self;
3974 int (*callback)(void *, void *, size_t, void *);
3975 void *data;
3976};
3977
3978static void
3979each_objects_foreign_i(void *objspace, void *arg)
3980{
3981 struct each_objects_foreign_arg *a = (struct each_objects_foreign_arg *)arg;
3982 if (objspace == a->self) return;
3983 rb_gc_impl_each_objects_foreign(objspace, a->callback, a->data);
3984}
3985
3986/*
3987 * rb_objspace_each_objects() is special C API to walk through
3988 * Ruby object space. This C API is too difficult to use it.
3989 * To be frank, you should not use it. Or you need to read the
3990 * source code of this function and understand what this function does.
3991 *
3992 * 'callback' will be called several times (the number of heap page,
3993 * at current implementation) with:
3994 * vstart: a pointer to the first living object of the heap_page.
3995 * vend: a pointer to next to the valid heap_page area.
3996 * stride: a distance to next VALUE.
3997 *
3998 * If callback() returns non-zero, the iteration will be stopped.
3999 *
4000 * This takes the VM barrier for the whole walk, stopping every other
4001 * Ractor: the set of heap pages must not change under the callback, and a
4002 * GC is stop-the-world. Because of that, the callback must not wait on
4003 * another Ractor (e.g. send/receive) -- they are all suspended and it
4004 * would deadlock.
4005 *
4006 * This is a sample callback code to iterate liveness objects:
4007 *
4008 * static int
4009 * sample_callback(void *vstart, void *vend, int stride, void *data)
4010 * {
4011 * VALUE v = (VALUE)vstart;
4012 * for (; v != (VALUE)vend; v += stride) {
4013 * if (!rb_objspace_internal_object_p(v)) { // liveness check
4014 * // do something with live object 'v'
4015 * }
4016 * }
4017 * return 0; // continue to iteration
4018 * }
4019 *
4020 * Note: 'vstart' is not a top of heap_page. This point the first
4021 * living object to grasp at least one object to avoid GC issue.
4022 * This means that you can not walk through all Ruby object page
4023 * including freed object page.
4024 *
4025 * Note: On this implementation, 'stride' is the same as sizeof(RVALUE).
4026 * However, there are possibilities to pass variable values with
4027 * 'stride' with some reasons. You must use stride instead of
4028 * use some constant value in the iteration.
4029 */
4030void
4031rb_objspace_each_objects(int (*callback)(void *, void *, size_t, void *), void *data)
4032{
4033 RB_VM_LOCKING() {
4034 rb_vm_barrier();
4035
4036 void *self = rb_gc_get_objspace();
4037 rb_gc_impl_each_objects(self, callback, data);
4038
4039 /* Like upstream, cover every object in the process: walk the other live
4040 * Ractors' objspaces too, under the VM lock and barrier, with a pure-C callback.
4041 * A foreign objspace's stopped lazy sweep is not settled; the walk skips its
4042 * dead objects. Also covers zombie objspaces. */
4043 struct each_objects_foreign_arg arg = { self, callback, data };
4044 rb_gc_vm_each_objspace(each_objects_foreign_i, &arg);
4045 }
4046}
4047
4048/* Enumerate live, creating, and zombie objspaces under the VM lifetime lock.
4049 * Reading foreign mutable collector state also needs the barrier; independently
4050 * synchronized publications may be read under their own locks without a barrier. */
4051void
4052rb_gc_vm_each_objspace(void (*func)(void *objspace, void *data), void *data)
4053{
4054 ASSERT_vm_locking();
4055
4056 rb_vm_t *vm = GET_VM();
4057 rb_ractor_t *r;
4058 ccan_list_for_each(&vm->ractor.set, r, vmlr_node) {
4059 if (r->objspace) {
4060 func(r->objspace, data);
4061 }
4062 /* A child being created is not in the set yet but its objspace already holds
4063 * the Thread/Fiber wrappers; enumerate it through its creator so a global GC
4064 * cannot miss it and mark into an objspace it never cleared. */
4065 if (r->creating_child_objspace) {
4066 func(r->creating_child_objspace, data);
4067 }
4068 }
4069 for (size_t i = 0; i < vm->gc.zombie_objspaces_count; i++) {
4070 func(vm->gc.zombie_objspaces[i].objspace, data);
4071 }
4072}
4073
4074/* Merging an ownerless zombie objspace (its Ractor object was collected) into main
4075 * runs as a postponed job targeted at main, at main's next safepoint; never inside
4076 * the GC cycle that discovered the orphan. */
4077
4078static void gc_orphan_merge_job(void *unused);
4079
4080/* Grown with plain realloc: rb_gc_objspace_disown pushes from inside a global GC
4081 * sweep, where the accounting allocator is not allowed. This table is VM-lifetime
4082 * metadata with at most a few dozen entries. */
4083static void
4084zombie_objspaces_push(rb_vm_t *vm, void *objspace, void **owner_slot, struct rb_ractor_struct *owner)
4085{
4086 ASSERT_vm_locking();
4087 if (vm->gc.zombie_objspaces_count == vm->gc.zombie_objspaces_capa) {
4088 size_t new_capa = vm->gc.zombie_objspaces_capa ? vm->gc.zombie_objspaces_capa * 2 : 16;
4089 struct rb_objspace_zombie *grown =
4090 realloc(vm->gc.zombie_objspaces, new_capa * sizeof(struct rb_objspace_zombie));
4091 if (grown == NULL) rb_bug("zombie_objspaces_push: out of memory");
4092 vm->gc.zombie_objspaces = grown;
4093 vm->gc.zombie_objspaces_capa = new_capa;
4094 }
4095 size_t pages = rb_gc_impl_heap_page_count(objspace);
4096 vm->gc.zombie_objspaces[vm->gc.zombie_objspaces_count++] = (struct rb_objspace_zombie){
4097 .objspace = objspace,
4098 .owner_slot = owner_slot,
4099 .owner = owner,
4100 .pages = pages,
4101 };
4102 vm->gc.zombie_total_pages += pages;
4103}
4104
4105/* Called for a Ractor that terminated without being joined. Its objspace loses its
4106 * owning thread, but its pages still hold shareable objects other Ractors can reach,
4107 * so keep it enumerable until inheritance merges it. The owning r->objspace slot stays
4108 * until the inheriting path takes the objspace and clears it. */
4109/* Reserve the handle of the orphan-merge job if it is not registered yet. Shared by
4110 * every retire and disown path; a second preregister is idempotent (the same func and
4111 * data are deduplicated). */
4112static void
4113gc_orphan_merge_pjob_ensure(void)
4114{
4115 if (GET_VM()->gc.orphan_merge_pjob == POSTPONED_JOB_HANDLE_INVALID) {
4116 GET_VM()->gc.orphan_merge_pjob = rb_postponed_job_preregister(0, gc_orphan_merge_job, NULL);
4117 if (GET_VM()->gc.orphan_merge_pjob == POSTPONED_JOB_HANDLE_INVALID) {
4118 rb_bug("Could not preregister postponed job for GC");
4119 }
4120 }
4121}
4122
4123/* A terminating Ractor runs the last local GC of its own objspace; own thread only. */
4124void
4125rb_gc_objspace_retire_gc(void)
4126{
4127 rb_gc_impl_objspace_retire_gc(rb_gc_get_objspace());
4128}
4129
4130void
4131rb_gc_objspace_retire(void **objspace_slot)
4132{
4133 rb_vm_t *vm = GET_VM();
4134
4135 if (!rb_gc_impl_multi_objspace_p()) {
4136 /* It only aliased the shared objspace, so just drop it. */
4137 *objspace_slot = NULL;
4138 return;
4139 }
4140
4141 /* Return the hold if the Ractor exits with GC disabled: otherwise nobody can
4142 * enable it again and GC stays off. */
4143 if (rb_gc_impl_user_gc_disabled_set(*objspace_slot, false)) {
4144 RUBY_ATOMIC_DEC(vm->gc.disable_holders);
4145 }
4146
4147 RB_VM_LOCKING() {
4148 gc_orphan_merge_pjob_ensure();
4149 /* owner_slot is always &r->objspace of the retiring Ractor. owner is recorded so a
4150 * root scan can still reach the dead Ractor's registered_marks pins and its join
4151 * value; rb_gc_objspace_disown clears it when the zombie becomes an orphan. */
4152 struct rb_ractor_struct *owner =
4153 (struct rb_ractor_struct *)((char *)objspace_slot - offsetof(rb_ractor_t, objspace));
4154 zombie_objspaces_push(vm, *objspace_slot, objspace_slot, owner);
4155 }
4156}
4157
4158/* The owning Ractor object was collected, so nobody can join any more: drop the owner
4159 * slot in zombie_objspaces and hand the merge to main. Called from ractor_free (inside
4160 * a sweep), where the accounting allocator is unavailable; the table itself is stable. */
4161void
4162rb_gc_objspace_disown(void *objspace)
4163{
4164 if (!rb_gc_impl_multi_objspace_p()) return;
4165 ASSERT_vm_locking();
4166 rb_vm_t *vm = GET_VM();
4167 bool found = false;
4168
4169 for (size_t i = 0; i < vm->gc.zombie_objspaces_count; i++) {
4170 if (vm->gc.zombie_objspaces[i].objspace == objspace) {
4171 vm->gc.zombie_objspaces[i].owner_slot = NULL;
4172 /* The Ractor struct is being freed, so drop owner too: nothing may read its
4173 * registered_marks or join value after this. */
4174 vm->gc.zombie_objspaces[i].owner = NULL;
4175 found = true;
4176 break;
4177 }
4178 }
4179 if (!found) {
4180 zombie_objspaces_push(vm, objspace, NULL, NULL);
4181 }
4182
4183 /* The trigger is wait-free (an atomic bit plus an interrupt flag), so it is safe
4184 * inside a sweep, and it also covers a Ractor that never started. */
4185 gc_orphan_merge_pjob_ensure();
4186 rb_postponed_job_trigger_for_ractor(GET_VM()->gc.orphan_merge_pjob, vm->ractor.main_ractor->pub.self);
4187}
4188
4189/* Is a global (stop-the-world) GC cycle running? Only its driver runs during one, so
4190 * asking through the current objspace is exact. */
4191bool
4192rb_gc_during_global_gc_p(void)
4193{
4194 return rb_gc_impl_during_global_gc_p(rb_gc_get_objspace());
4195}
4196
4197static void
4198rb_gc_vm_forget_zombie(void *objspace)
4199{
4200 ASSERT_vm_locking();
4201 rb_vm_t *vm = GET_VM();
4202 size_t n = vm->gc.zombie_objspaces_count;
4203 for (size_t i = 0; i < n; i++) {
4204 if (vm->gc.zombie_objspaces[i].objspace == objspace) {
4205 vm->gc.zombie_total_pages -= vm->gc.zombie_objspaces[i].pages;
4206 vm->gc.zombie_objspaces[i] = vm->gc.zombie_objspaces[n - 1];
4207 vm->gc.zombie_objspaces_count = n - 1;
4208 break;
4209 }
4210 }
4211}
4212
4213/* Total zombie pages, deciding whether to start a global GC. An upper bound between
4214 * global cycles (each re-measures under the barrier), so a stale value cannot
4215 * re-trigger; a lock-free read at worst fires one cycle early or late. */
4216size_t
4217rb_gc_vm_zombie_total_pages(void)
4218{
4219 return GET_VM()->gc.zombie_total_pages;
4220}
4221
4222/* Number of live Ractors, for the heap growth heuristic (r_mul); a racy read is fine. */
4223unsigned int
4224rb_gc_vm_ractor_count(void)
4225{
4226 return GET_VM()->ractor.cnt;
4227}
4228
4229/* Called by a global cycle from inside the barrier. */
4230void
4231rb_gc_vm_refresh_zombie_pages(void)
4232{
4233 rb_vm_t *vm = GET_VM();
4234 size_t total = 0;
4235 for (size_t i = 0; i < vm->gc.zombie_objspaces_count; i++) {
4236 size_t pages = rb_gc_impl_heap_page_count(vm->gc.zombie_objspaces[i].objspace);
4237 vm->gc.zombie_objspaces[i].pages = pages;
4238 total += pages;
4239 }
4240 vm->gc.zombie_total_pages = total;
4241}
4242
4243void
4244rb_gc_rest(void)
4245{
4246 // Lock to keep assertions happy. This runs right after single-ractor mode is
4247 // cancelled, but we can still free shareables like fstrings because ractor.cnt is 1.
4248 RB_VM_LOCKING() {
4249 rb_gc_impl_gc_rest(rb_gc_get_objspace());
4250 }
4251}
4252
4253/* True while a zombie is being absorbed. The zombie's count is decremented before the
4254 * merge (see absorb below), so in that window its live objects still exist even though
4255 * the process looks single-objspace. */
4256static int gc_absorbing_zombie = 0;
4257
4258/* True once a zombie objspace was absorbed since the last global GC: until the unified
4259 * mark runs, a single-objspace local mark can miss absorbed shareable objects (a cc in
4260 * a class's cc_table, say), so stop treating the process as single until then. */
4261static bool gc_absorbed_since_global_gc = false;
4262
4263void
4264rb_gc_reset_absorbed_since_global_gc(void)
4265{
4266 gc_absorbed_since_global_gc = false;
4267}
4268
4269/* True when the process holds exactly one objspace (one live Ractor, no zombies) and
4270 * nothing was absorbed since the last global GC. Only then is a local GC the whole
4271 * world and the multi-objspace guards can be skipped. The child-creation window (the
4272 * child objspace exists while cnt is still 1) and both absorb windows, during (count
4273 * already decremented, merge unfinished) and after (merged, next global GC pending) --
4274 * count as multi: treating them as single would let a GC skip guards such as shareable
4275 * pinning and collect a live cc. */
4276/* False when the impl only supports one objspace (mmtk and friends); the VM then makes
4277 * its per-Ractor objspace machinery (retire, absorb, creation cover) a no-op. */
4278bool
4279rb_gc_multi_objspace_p(void)
4280{
4281 return rb_gc_impl_multi_objspace_p();
4282}
4283
4284/* Does obj belong to another Ractor's objspace rather than the current one? Always
4285 * false for a single-objspace impl, which cannot tell owners apart. */
4286bool
4287rb_gc_obj_foreign_p(VALUE obj)
4288{
4289 return rb_gc_impl_obj_foreign_p(rb_gc_get_objspace(), obj);
4290}
4291
4292bool
4293rb_gc_single_objspace_p(void)
4294{
4295 if (!rb_gc_impl_multi_objspace_p()) return true;
4296 rb_vm_t *vm = GET_VM();
4297 /* One Ractor is not one objspace: a forked child re-enters single-Ractor mode while
4298 * the pre-fork Ractors' objspaces are still parked in zombie_objspaces. */
4299 return (ruby_single_main_ractor != NULL || vm->ractor.cnt == 1) &&
4300 vm->gc.zombie_objspaces_count == 0 && gc_absorbing_zombie == 0 &&
4301 !gc_absorbed_since_global_gc &&
4302 (vm->ractor.main_ractor == NULL ||
4303 vm->ractor.main_ractor->creating_child_objspace == NULL);
4304}
4305
4306/* Inherit a dead Ractor's objspace into the calling Ractor. Going through the owner
4307 * slot clears it and releases the objspace in one VM-lock section; the merge runs with
4308 * the inheritor's GC disabled (moving the finalizer st table could trigger it). */
4309static void
4310objspace_absorb_merge(void *dst, void *src)
4311{
4312 ASSERT_vm_locking();
4313 rb_gc_impl_objspace_absorb(dst, src);
4314 gc_absorbed_since_global_gc = true;
4315}
4316
4317/* The dying thread's last collection of its own objspace, GVL still held; with
4318 * r->postmortem set, rb_ractor_mark_local_roots roots only the join value and the
4319 * registered_marks pins, so the scaffolding nobody needs any more dies here. */
4320void
4321rb_gc_objspace_postmortem_self(void)
4322{
4323 if (!rb_gc_impl_multi_objspace_p()) return;
4324
4325 rb_gc_impl_objspace_retire_gc(rb_gc_get_objspace());
4326}
4327
4328void
4329rb_gc_objspace_absorb_into_current(void **objspace_slot)
4330{
4331 if (!rb_gc_impl_multi_objspace_p()) {
4332 *objspace_slot = NULL;
4333 return;
4334 }
4335 RB_VM_LOCKING() {
4336 void *objspace = *objspace_slot;
4337 if (objspace != NULL) {
4338 *objspace_slot = NULL;
4339 gc_absorbing_zombie++;
4340 rb_gc_vm_forget_zombie(objspace);
4341 objspace_absorb_merge(rb_gc_get_objspace(), objspace);
4342 gc_absorbing_zombie--;
4343 }
4344 }
4345}
4346
4347/* Merge every ownerless zombie objspace (no owner slot, i.e. the Ractor object was
4348 * collected) into the current Ractor's objspace. Runs as a postponed job on the main
4349 * Ractor's thread; the VM teardown path calls it directly. */
4350static void
4351objspace_absorb_disowned_zombies(void)
4352{
4353 rb_vm_t *vm = GET_VM();
4354
4355 RB_VM_LOCKING() {
4356 size_t i = 0;
4357 while (i < vm->gc.zombie_objspaces_count) {
4358 if (vm->gc.zombie_objspaces[i].owner_slot == NULL) {
4359 void *zombie = vm->gc.zombie_objspaces[i].objspace;
4360 /* Remove via forget, which also subtracts the entry's pages from
4361 * zombie_total_pages; a hand-written swap-remove would leave a phantom
4362 * total that keeps starting stop-the-world global cycles. */
4363 gc_absorbing_zombie++;
4364 rb_gc_vm_forget_zombie(zombie);
4365 objspace_absorb_merge(rb_gc_get_objspace(), zombie);
4366 gc_absorbing_zombie--;
4367 }
4368 else {
4369 i++;
4370 }
4371 }
4372 }
4373}
4374
4375static void
4376gc_orphan_merge_job(void *unused)
4377{
4378 (void)unused;
4379 objspace_absorb_disowned_zombies();
4380}
4381
4382/* Re-target a pending orphan merge after fork. The job may target the parent's main
4383 * Ractor, whose per-Ractor trigger mask is not inherited unless that Ractor forked.
4384 * Called on the child side. */
4385/* Only main survives a fork, so rebuild the counter from main's own hold alone. */
4386void
4387rb_gc_disable_holders_atfork(void)
4388{
4389 RUBY_ATOMIC_SET(GET_VM()->gc.disable_holders,
4390 rb_gc_impl_user_gc_disabled_p(rb_gc_get_objspace()) ? 1 : 0);
4391}
4392
4393void
4394rb_gc_zombie_objspaces_atfork(void)
4395{
4396 rb_vm_t *vm = GET_VM();
4397
4398 for (size_t i = 0; i < vm->gc.zombie_objspaces_count; i++) {
4399 if (vm->gc.zombie_objspaces[i].owner_slot == NULL) {
4400 rb_postponed_job_trigger_for_ractor(GET_VM()->gc.orphan_merge_pjob, vm->ractor.main_ractor->pub.self);
4401 break;
4402 }
4403 }
4404}
4405
4406/* VM teardown, right after every other Ractor was killed: merge all uninherited
4407 * objspaces into main so at-exit processing covers every object and dead Ractors'
4408 * deferred finalizers run on main. The owner slot also covers collected wrappers. */
4409void
4410rb_gc_objspace_absorb_all_zombies(void)
4411{
4412 rb_vm_t *vm = GET_VM();
4413
4414 /* Entries whose Ractor object is already gone, i.e. the pending merge job itself,
4415 * which we run synchronously here. */
4416 objspace_absorb_disowned_zombies();
4417
4418 while (vm->gc.zombie_objspaces_count > 0) {
4419 size_t before = vm->gc.zombie_objspaces_count;
4420 GC_ASSERT(vm->gc.zombie_objspaces[0].owner_slot != NULL);
4421 /* Move the rb_gc_register_mark_object pins before the merge, so the objects
4422 * pinned in the owner's objspace do not lose their root in its sweep. */
4423 rb_ractor_t *owner = vm->gc.zombie_objspaces[0].owner;
4424 if (owner) {
4425 rb_ractor_absorb_registered_marks(GET_RACTOR(), owner);
4426 }
4427 rb_gc_objspace_absorb_into_current(vm->gc.zombie_objspaces[0].owner_slot);
4428 if (vm->gc.zombie_objspaces_count >= before) {
4429 rb_bug("rb_gc_objspace_absorb_all_zombies: zombie list did not shrink");
4430 }
4431 }
4432}
4433
4434static void
4435gc_ref_update_array(void *objspace, VALUE v)
4436{
4437 if (ARY_SHARED_P(v)) {
4438 VALUE old_root = RARRAY(v)->as.heap.aux.shared_root;
4439
4440 UPDATE_IF_MOVED(objspace, RARRAY(v)->as.heap.aux.shared_root);
4441
4442 VALUE new_root = RARRAY(v)->as.heap.aux.shared_root;
4443 // A root hollowed out by a move is no longer an array, and it is pinned rather
4444 // than re-pointed (see the marking of a shared root).
4445 // If the root is embedded and its location has changed
4446 if (RB_TYPE_P(new_root, T_ARRAY) && ARY_EMBED_P(new_root) && new_root != old_root) {
4447 size_t offset = (size_t)(RARRAY(v)->as.heap.ptr - RARRAY(old_root)->as.ary);
4448 GC_ASSERT(RARRAY(v)->as.heap.ptr >= RARRAY(old_root)->as.ary);
4449 RARRAY(v)->as.heap.ptr = RARRAY(new_root)->as.ary + offset;
4450 }
4451 }
4452 else {
4453 long len = RARRAY_LEN(v);
4454
4455 if (len > 0) {
4456 VALUE *ptr = (VALUE *)RARRAY_CONST_PTR(v);
4457 for (long i = 0; i < len; i++) {
4458 UPDATE_IF_MOVED(objspace, ptr[i]);
4459 }
4460 }
4461
4462 if (rb_gc_obj_slot_size(v) >= rb_ary_size_as_embedded(v)) {
4463 /* Skip pinned arrays: a pinned array may be referenced from a
4464 * conservative root holding RARRAY_PTR across this compaction, so
4465 * freeing its heap buffer here would dangle that pointer. */
4466 if (rb_ary_embeddable_p(v) && !rb_gc_impl_pinned_p(objspace, v)) {
4467 rb_ary_make_embedded(v);
4468 }
4469 }
4470 }
4471}
4472
4473static void
4474gc_ref_update_object(void *objspace, VALUE v)
4475{
4476 RUBY_ASSERT(rb_gc_obj_slot_size(v) == rb_obj_shape_slot_size(v));
4477 shape_id_t shape_id = RBASIC_SHAPE_ID(v);
4478
4479 if (!rb_shape_embedded_p(shape_id)) {
4480 UPDATE_IF_MOVED(objspace, ROBJECT(v)->as.extended);
4481
4482 if (!rb_shape_complex_p(shape_id) && rb_shape_embedded_capacity(shape_id) >= RSHAPE_LEN(shape_id)) {
4483 VALUE *embedded_fields = ROBJECT_EMBEDDED_FIELDS(v);
4484 VALUE *extended_fields = ROBJECT_FIELDS(v);
4485 MEMCPY(embedded_fields, extended_fields, VALUE, RSHAPE_LEN(shape_id));
4486 shape_id = rb_shape_transition_robject(shape_id);
4487 RBASIC_SET_FULL_SHAPE_ID(v, shape_id);
4488 rb_gc_writebarrier_remember(v);
4489 }
4490 else {
4491 return;
4492 }
4493 }
4494
4495 VALUE *ptr = ROBJECT_FIELDS(v);
4496 attr_index_t len = RSHAPE_LEN(shape_id);
4497 for (attr_index_t i = 0; i < len; i++) {
4498 UPDATE_IF_MOVED(objspace, ptr[i]);
4499 }
4500}
4501
4502void
4503rb_gc_ref_update_table_values_only(st_table *tbl)
4504{
4505 gc_ref_update_table_values_only(tbl);
4506}
4507
4508/* Update MOVED references in a VALUE=>VALUE st_table */
4509void
4510rb_gc_update_tbl_refs(st_table *ptr)
4511{
4512 gc_update_table_refs(ptr);
4513}
4514
4515static int
4516rb_gc_update_set_refs_i(st_data_t key, st_data_t value, st_data_t argp, int error)
4517{
4518 if (rb_gc_location((VALUE)key) != (VALUE)key) {
4519 return ST_REPLACE;
4520 }
4521
4522 return ST_CONTINUE;
4523}
4524
4525static int
4526rb_gc_update_set_refs_replace_i(st_data_t *key, st_data_t *value, st_data_t argp, int existing)
4527{
4528 rb_gc_update_moved((VALUE *)key);
4529
4530 return ST_CONTINUE;
4531}
4532
4533void
4534rb_gc_update_set_refs(st_table *tbl)
4535{
4536 if (!tbl || tbl->num_entries == 0) return;
4537
4538 if (st_foreach_with_replace(tbl, rb_gc_update_set_refs_i, rb_gc_update_set_refs_replace_i, 0)) {
4539 rb_raise(rb_eRuntimeError, "hash modified during iteration");
4540 }
4541}
4542
4543static void
4544gc_ref_update_hash(void *objspace, VALUE v)
4545{
4546 rb_hash_stlike_foreach_with_replace(v, hash_foreach_replace, hash_replace_ref, (st_data_t)objspace);
4547}
4548
4549static void
4550gc_update_values(void *objspace, long n, VALUE *values)
4551{
4552 for (long i = 0; i < n; i++) {
4553 UPDATE_IF_MOVED(objspace, values[i]);
4554 }
4555}
4556
4557void
4558rb_gc_update_values(long n, VALUE *values)
4559{
4560 gc_update_values(rb_gc_get_objspace(), n, values);
4561}
4562
4563static enum rb_id_table_iterator_result
4564check_id_table_move(VALUE value, void *data)
4565{
4566 void *objspace = (void *)data;
4567
4568 if (gc_object_moved_p_internal(objspace, (VALUE)value)) {
4569 return ID_TABLE_REPLACE;
4570 }
4571
4572 return ID_TABLE_CONTINUE;
4573}
4574
4575void
4576rb_gc_prepare_heap_process_object(VALUE obj)
4577{
4578 switch (BUILTIN_TYPE(obj)) {
4579 case T_STRING:
4580 // Precompute the string coderange. This both save time for when it will be
4581 // eventually needed, and avoid mutating heap pages after a potential fork.
4582 rb_enc_str_coderange(obj);
4583 break;
4584 default:
4585 break;
4586 }
4587}
4588
4589void
4590rb_gc_prepare_heap(void)
4591{
4592 rb_gc_impl_prepare_heap(rb_gc_get_objspace());
4593}
4594
4595size_t
4596rb_gc_size_slot_size(size_t size)
4597{
4598 return rb_gc_impl_size_slot_size(rb_gc_get_objspace(), size);
4599}
4600
4601bool
4602rb_gc_size_allocatable_p(size_t size)
4603{
4604 return rb_gc_impl_size_allocatable_p(size);
4605}
4606
4607size_t
4608rb_gc_max_allocation_size(void)
4609{
4610 return rb_gc_impl_max_allocation_size();
4611}
4612
4613static enum rb_id_table_iterator_result
4614update_id_table(VALUE *value, void *data, int existing)
4615{
4616 void *objspace = (void *)data;
4617
4618 if (gc_object_moved_p_internal(objspace, (VALUE)*value)) {
4619 *value = gc_location_internal(objspace, (VALUE)*value);
4620 }
4621
4622 return ID_TABLE_CONTINUE;
4623}
4624
4625static void
4626update_m_tbl(void *objspace, struct rb_id_table *tbl)
4627{
4628 if (tbl) {
4629 rb_id_table_foreach_values_with_replace(tbl, check_id_table_move, update_id_table, objspace);
4630 }
4631}
4632
4633static enum rb_id_table_iterator_result
4634update_const_tbl_i(VALUE value, void *objspace)
4635{
4636 rb_const_entry_t *ce = (rb_const_entry_t *)value;
4637
4638 if (gc_object_moved_p_internal(objspace, ce->value)) {
4639 ce->value = gc_location_internal(objspace, ce->value);
4640 }
4641
4642 if (gc_object_moved_p_internal(objspace, ce->file)) {
4643 ce->file = gc_location_internal(objspace, ce->file);
4644 }
4645
4646 return ID_TABLE_CONTINUE;
4647}
4648
4649static void
4650update_const_tbl(void *objspace, struct rb_id_table *tbl)
4651{
4652 if (!tbl) return;
4653 rb_id_table_foreach_values(tbl, update_const_tbl_i, objspace);
4654}
4655
4656static void
4657update_superclasses(rb_objspace_t *objspace, rb_classext_t *ext)
4658{
4659 if (RCLASSEXT_SUPERCLASSES_WITH_SELF(ext)) {
4660 size_t array_size = RCLASSEXT_SUPERCLASS_DEPTH(ext) + 1;
4661 for (size_t i = 0; i < array_size; i++) {
4662 UPDATE_IF_MOVED(objspace, RCLASSEXT_SUPERCLASSES(ext)[i]);
4663 }
4664 }
4665}
4666
4667static void
4668update_classext_values(rb_objspace_t *objspace, rb_classext_t *ext, bool is_iclass)
4669{
4670 UPDATE_IF_MOVED(objspace, RCLASSEXT_ORIGIN(ext));
4671 UPDATE_IF_MOVED(objspace, RCLASSEXT_REFINED_CLASS(ext));
4672 UPDATE_IF_MOVED(objspace, RCLASSEXT_CLASSPATH(ext));
4673 if (is_iclass) {
4674 UPDATE_IF_MOVED(objspace, RCLASSEXT_INCLUDER(ext));
4675 }
4676}
4677
4678static void
4679update_classext(rb_classext_t *ext, bool is_prime, VALUE box_value, void *arg)
4680{
4681 struct classext_foreach_args *args = (struct classext_foreach_args *)arg;
4682 rb_objspace_t *objspace = args->objspace;
4683
4684 if (RCLASSEXT_SUPER(ext)) {
4685 UPDATE_IF_MOVED(objspace, RCLASSEXT_SUPER(ext));
4686 }
4687
4688 update_m_tbl(objspace, RCLASSEXT_M_TBL(ext));
4689
4690 UPDATE_IF_MOVED(objspace, ext->fields_obj);
4691 if (!RCLASSEXT_SHARED_CONST_TBL(ext)) {
4692 update_const_tbl(objspace, RCLASSEXT_CONST_TBL(ext));
4693 }
4694 UPDATE_IF_MOVED(objspace, RCLASSEXT_CC_TBL(ext));
4695 UPDATE_IF_MOVED(objspace, RCLASSEXT_CVC_TBL(ext));
4696 update_superclasses(objspace, ext);
4697 if (RCLASSEXT_SUBCLASSES(ext)) {
4698 UPDATE_IF_MOVED(objspace, RCLASSEXT_SUBCLASSES(ext));
4699 }
4700
4701 update_classext_values(objspace, ext, false);
4702}
4703
4704static void
4705update_iclass_classext(rb_classext_t *ext, bool is_prime, VALUE box_value, void *arg)
4706{
4707 struct classext_foreach_args *args = (struct classext_foreach_args *)arg;
4708 rb_objspace_t *objspace = args->objspace;
4709
4710 if (RCLASSEXT_SUPER(ext)) {
4711 UPDATE_IF_MOVED(objspace, RCLASSEXT_SUPER(ext));
4712 }
4713 update_m_tbl(objspace, RCLASSEXT_M_TBL(ext));
4714 update_m_tbl(objspace, RCLASSEXT_CALLABLE_M_TBL(ext));
4715 UPDATE_IF_MOVED(objspace, RCLASSEXT_CC_TBL(ext));
4716 UPDATE_IF_MOVED(objspace, RCLASSEXT_CVC_TBL(ext));
4717 if (RCLASSEXT_SUBCLASSES(ext)) {
4718 UPDATE_IF_MOVED(objspace, RCLASSEXT_SUBCLASSES(ext));
4719 }
4720
4721 update_classext_values(objspace, ext, true);
4722}
4723
4725 vm_table_foreach_callback_func callback;
4726 vm_table_update_callback_func update_callback;
4727 void *data;
4728 bool weak_only;
4729 /* The generic_fields table being walked, so compaction can re-insert a moved key
4730 * into it (rb_generic_fields_tables_foreach hands the table to the callback). */
4731 struct st_table *gen_fields_current_tbl;
4732 /* Re-inserting a moved key adds an entry, which can rehash and break the running
4733 * iterator, so collect them and insert after the walk (raw realloc: we are in GC). */
4734 struct gen_fields_deferred_insert { st_data_t k, v; } *gf_deferred;
4735 size_t gf_deferred_cnt, gf_deferred_capa;
4736};
4737
4738static int
4739vm_weak_table_foreach_weak_key(st_data_t key, st_data_t value, st_data_t data, int error)
4740{
4741 struct global_vm_table_foreach_data *iter_data = (struct global_vm_table_foreach_data *)data;
4742
4743 int ret = iter_data->callback((VALUE)key, iter_data->data);
4744
4745 if (!iter_data->weak_only) {
4746 if (ret != ST_CONTINUE) return ret;
4747
4748 ret = iter_data->callback((VALUE)value, iter_data->data);
4749 }
4750
4751 return ret;
4752}
4753
4754static int
4755vm_weak_table_foreach_update_weak_key(st_data_t *key, st_data_t *value, st_data_t data, int existing)
4756{
4757 struct global_vm_table_foreach_data *iter_data = (struct global_vm_table_foreach_data *)data;
4758
4759 int ret = iter_data->update_callback((VALUE *)key, iter_data->data);
4760
4761 if (!iter_data->weak_only) {
4762 if (ret != ST_CONTINUE) return ret;
4763
4764 ret = iter_data->update_callback((VALUE *)value, iter_data->data);
4765 }
4766
4767 return ret;
4768}
4769
4770static int
4771vm_weak_table_sym_set_foreach(VALUE *sym_ptr, void *data)
4772{
4773 VALUE sym = *sym_ptr;
4774 struct global_vm_table_foreach_data *iter_data = (struct global_vm_table_foreach_data *)data;
4775
4776 if (RB_SPECIAL_CONST_P(sym)) return ST_CONTINUE;
4777
4778 int ret = iter_data->callback(sym, iter_data->data);
4779
4780 if (ret == ST_REPLACE) {
4781 ret = iter_data->update_callback(sym_ptr, iter_data->data);
4782 }
4783
4784 return ret;
4785}
4786
4787struct st_table *rb_generic_fields_tbl_get(void);
4788
4789static int
4790vm_weak_table_gen_fields_foreach(st_data_t key, st_data_t value, st_data_t data)
4791{
4792 struct global_vm_table_foreach_data *iter_data = (struct global_vm_table_foreach_data *)data;
4793
4794 int ret = iter_data->callback((VALUE)key, iter_data->data);
4795
4796 VALUE new_value = (VALUE)value;
4797 VALUE new_key = (VALUE)key;
4798
4799 switch (ret) {
4800 case ST_CONTINUE:
4801 break;
4802
4803 case ST_DELETE:
4804 // When we're removing an object from the weak ref table, we need to
4805 // set the shape on it so that the GC finalizer won't try to remove
4806 // it again. A "root shape" indicates to the GC that this object
4807 // has no fields on it, hence it won't be in the gen fields table.
4808 if (BUILTIN_TYPE((VALUE)key) != T_NONE) {
4809 RBASIC_SET_SHAPE_ID((VALUE)key, ROOT_SHAPE_ID);
4810 }
4811 return ST_DELETE;
4812
4813 case ST_REPLACE: {
4814 ret = iter_data->update_callback(&new_key, iter_data->data);
4815 if (key != new_key) {
4816 ret = ST_DELETE;
4817 }
4818 break;
4819 }
4820
4821 default:
4822 rb_bug("vm_weak_table_gen_fields_foreach: return value %d not supported", ret);
4823 }
4824
4825 if (!iter_data->weak_only) {
4826 int ivar_ret = iter_data->callback(new_value, iter_data->data);
4827 switch (ivar_ret) {
4828 case ST_CONTINUE:
4829 break;
4830
4831 case ST_REPLACE:
4832 iter_data->update_callback(&new_value, iter_data->data);
4833 break;
4834
4835 case ST_DELETE:
4836 /* Leftover entry of a moved host: even if the key is alive, nobody can
4837 * read these fields once fields_obj is unreachable, so clean up as if the
4838 * key had died. */
4839 RBASIC_SET_SHAPE_ID((VALUE)key, ROOT_SHAPE_ID);
4840 return ST_DELETE;
4841
4842 default:
4843 rb_bug("vm_weak_table_gen_fields_foreach: return value %d not supported", ivar_ret);
4844 }
4845 }
4846
4847 if (key != new_key) {
4848 /* Inserting the new key adds an entry and may rehash, so defer it. */
4849 if (iter_data->gf_deferred_cnt == iter_data->gf_deferred_capa) {
4850 size_t nc = iter_data->gf_deferred_capa ? iter_data->gf_deferred_capa * 2 : 64;
4851 struct gen_fields_deferred_insert *p =
4852 realloc(iter_data->gf_deferred, nc * sizeof(*p));
4853 if (!p) rb_bug("vm_weak_table_gen_fields_foreach: out of memory");
4854 iter_data->gf_deferred = p;
4855 iter_data->gf_deferred_capa = nc;
4856 }
4857 iter_data->gf_deferred[iter_data->gf_deferred_cnt++] =
4858 (struct gen_fields_deferred_insert){ .k = (st_data_t)new_key, .v = (st_data_t)new_value };
4859 }
4860 else if (value != new_value) {
4861 DURING_GC_COULD_MALLOC_REGION_START();
4862 {
4863 /* Updating an existing key's value adds no entry and cannot rehash. */
4864 st_insert(iter_data->gen_fields_current_tbl, (st_data_t)new_key, new_value);
4865 }
4866 DURING_GC_COULD_MALLOC_REGION_END();
4867 }
4868
4869 return ret;
4870}
4871
4872static int
4873vm_weak_table_frozen_strings_foreach(VALUE *str, void *data)
4874{
4875 // int retval = vm_weak_table_foreach_weak_key(key, value, data, error);
4876 struct global_vm_table_foreach_data *iter_data = (struct global_vm_table_foreach_data *)data;
4877 int retval = iter_data->callback(*str, iter_data->data);
4878
4879 if (retval == ST_REPLACE) {
4880 retval = iter_data->update_callback(str, iter_data->data);
4881 }
4882
4883 if (retval == ST_DELETE) {
4884 FL_UNSET(*str, RSTRING_FSTR);
4885 }
4886
4887 return retval;
4888}
4889
4890void rb_fstring_foreach_with_replace(int (*callback)(VALUE *str, void *data), void *data);
4891
4892/* Callback of rb_generic_fields_tables_foreach: walk one generic_fields table with the
4893 * gen_fields foreach used by compaction, recording the current table in foreach_data so
4894 * a moved key is re-inserted into the right one. */
4895static void
4896vm_weak_table_gen_fields_tbl_cb(struct st_table *tbl, void *arg)
4897{
4898 struct global_vm_table_foreach_data *foreach_data = (struct global_vm_table_foreach_data *)arg;
4899 foreach_data->gen_fields_current_tbl = tbl;
4900 st_foreach(tbl, vm_weak_table_gen_fields_foreach, (st_data_t)foreach_data);
4901}
4902
4903void
4904rb_gc_vm_weak_table_foreach(vm_table_foreach_callback_func callback,
4905 vm_table_update_callback_func update_callback,
4906 void *data,
4907 bool weak_only,
4908 enum rb_gc_vm_weak_tables table)
4909{
4910 rb_vm_t *vm = GET_VM();
4911
4912 struct global_vm_table_foreach_data foreach_data = {
4913 .callback = callback,
4914 .update_callback = update_callback,
4915 .data = data,
4916 .weak_only = weak_only,
4917 };
4918
4919 switch (table) {
4920 case RB_GC_VM_CI_TABLE: {
4921 st_foreach_with_replace(
4922 &vm->ci_table,
4923 vm_weak_table_foreach_weak_key,
4924 vm_weak_table_foreach_update_weak_key,
4925 (st_data_t)&foreach_data
4926 );
4927 break;
4928 }
4929 case RB_GC_VM_OVERLOADED_CME_TABLE: {
4930 st_foreach_with_replace(
4931 &vm->overloaded_cme_table,
4932 vm_weak_table_foreach_weak_key,
4933 vm_weak_table_foreach_update_weak_key,
4934 (st_data_t)&foreach_data
4935 );
4936 break;
4937 }
4938 case RB_GC_VM_GLOBAL_SYMBOLS_TABLE: {
4939 rb_sym_global_symbol_table_foreach_weak_reference(
4940 vm_weak_table_sym_set_foreach,
4941 &foreach_data
4942 );
4943 break;
4944 }
4945 case RB_GC_VM_GENERIC_FIELDS_TABLE: {
4946 /* There is one table. A global GC walks it without a lock under the
4947 * stop-the-world barrier; a local compaction holds the barrier VM lock taken in
4948 * gc_enter, so foreign keys cannot move and fall through the moved check. The
4949 * table's mutex (taken by shared_table_foreach) excludes mutator inserts. */
4950 if (rb_gc_during_global_gc_p()) {
4951 rb_generic_fields_tables_foreach(vm_weak_table_gen_fields_tbl_cb, (void *)&foreach_data);
4952 }
4953 else if (!weak_only) {
4954 rb_generic_fields_shared_table_foreach(vm_weak_table_gen_fields_tbl_cb, (void *)&foreach_data);
4955 }
4956 if (foreach_data.gf_deferred != NULL) {
4957 DURING_GC_COULD_MALLOC_REGION_START();
4958 {
4959 for (size_t i = 0; i < foreach_data.gf_deferred_cnt; i++) {
4960 struct gen_fields_deferred_insert *const d = &foreach_data.gf_deferred[i];
4961 st_insert(foreach_data.gen_fields_current_tbl, d->k, d->v);
4962 }
4963 }
4964 DURING_GC_COULD_MALLOC_REGION_END();
4965 free(foreach_data.gf_deferred);
4966 }
4967 break;
4968 }
4969 case RB_GC_VM_FROZEN_STRINGS_TABLE: {
4970 rb_fstring_foreach_with_replace(
4971 vm_weak_table_frozen_strings_foreach,
4972 &foreach_data
4973 );
4974 break;
4975 }
4976 case RB_GC_VM_WEAK_TABLE_COUNT:
4977 rb_bug("Unreachable");
4978 default:
4979 rb_bug("rb_gc_vm_weak_table_foreach: unknown table %d", table);
4980 }
4981}
4982
4983/* The global GC's weak pass over the generic_fields table; under the barrier, so the
4984 * walk needs no lock. */
4986 int (*cb)(VALUE key, VALUE val, void *arg);
4987 void *arg;
4988};
4989
4990static int
4991gf_mark_foreach_i(st_data_t key, st_data_t val, st_data_t data)
4992{
4993 struct gf_mark_foreach_ctx *ctx = (struct gf_mark_foreach_ctx *)data;
4994 return ctx->cb((VALUE)key, (VALUE)val, ctx->arg);
4995}
4996
4997static void
4998gf_mark_foreach_table_cb(struct st_table *tbl, void *arg)
4999{
5000 st_foreach(tbl, gf_mark_foreach_i, (st_data_t)arg);
5001}
5002
5003void
5004rb_gc_vm_generic_fields_mark_foreach(int (*cb)(VALUE key, VALUE val, void *arg), void *arg)
5005{
5006 struct gf_mark_foreach_ctx ctx = { cb, arg };
5007 rb_generic_fields_tables_foreach(gf_mark_foreach_table_cb, &ctx);
5008}
5009
5011 bool (*is_dead)(VALUE key);
5012};
5013
5014static int
5015gf_drain_i(st_data_t key, st_data_t val, st_data_t data)
5016{
5017 struct gf_drain_ctx *ctx = (struct gf_drain_ctx *)data;
5018 if (ctx->is_dead((VALUE)key)) {
5019 /* The weak pass only drains dead keys' entries, never touching the key itself:
5020 * after the global GC settled another objspace's lazy sweep the key may already
5021 * be freed (poisoned), and writing a shape there would be a use-after-poison. */
5022 return ST_DELETE;
5023 }
5024 return ST_CONTINUE;
5025}
5026
5027static void
5028gf_drain_table_cb(struct st_table *tbl, void *arg)
5029{
5030 st_foreach(tbl, gf_drain_i, (st_data_t)arg);
5031}
5032
5033void
5034rb_gc_vm_generic_fields_drain_dead(bool (*is_dead)(VALUE key))
5035{
5036 struct gf_drain_ctx ctx = { is_dead };
5037 rb_generic_fields_tables_foreach(gf_drain_table_cb, &ctx);
5038}
5039
5040VALUE
5041rb_gc_vm_top_self(void)
5042{
5043 return rb_vm_top_self();
5044}
5045
5046void
5047rb_gc_update_vm_references(void *objspace)
5048{
5049 rb_execution_context_t *ec = GET_EC();
5050 rb_vm_t *vm = rb_ec_vm_ptr(ec);
5051
5052 rb_vm_update_references(vm);
5053 rb_gc_update_global_tbl();
5054 rb_sym_global_symbols_mark_and_move();
5055
5056#if USE_YJIT
5057 void rb_yjit_root_update_references(void); // in Rust
5058
5059 if (rb_yjit_enabled_p) {
5060 rb_yjit_root_update_references();
5061 }
5062#endif
5063
5064#if USE_ZJIT
5065 void rb_zjit_root_update_references(void); // in Rust
5066
5067 if (rb_zjit_enabled_p) {
5068 rb_zjit_root_update_references();
5069 }
5070#endif
5071}
5072
5073void
5074rb_gc_update_object_references(void *objspace, VALUE obj)
5075{
5076 struct classext_foreach_args args;
5077
5078 switch (BUILTIN_TYPE(obj)) {
5079 case T_CLASS:
5080 if (FL_TEST_RAW(obj, FL_SINGLETON)) {
5081 UPDATE_IF_MOVED(objspace, RCLASS_ATTACHED_OBJECT(obj));
5082 }
5083 // Continue to the shared T_CLASS/T_MODULE
5084 case T_MODULE:
5085 args.klass = obj;
5086 args.objspace = objspace;
5087 rb_class_classext_foreach(obj, update_classext, (void *)&args);
5088 break;
5089
5090 case T_ICLASS:
5091 args.objspace = objspace;
5092 rb_class_classext_foreach(obj, update_iclass_classext, (void *)&args);
5093 break;
5094
5095 case T_IMEMO:
5096 rb_imemo_mark_and_move(obj, true);
5097 return;
5098
5099 case T_NIL:
5100 case T_FIXNUM:
5101 case T_NODE:
5102 case T_MOVED:
5103 case T_NONE:
5104 /* These can't move */
5105 return;
5106
5107 case T_ARRAY:
5108 gc_ref_update_array(objspace, obj);
5109 break;
5110
5111 case T_HASH:
5112 gc_ref_update_hash(objspace, obj);
5113 UPDATE_IF_MOVED(objspace, RHASH(obj)->ifnone);
5114 break;
5115
5116 case T_STRING:
5117 {
5118 if (STR_SHARED_P(obj)) {
5119 UPDATE_IF_MOVED(objspace, RSTRING(obj)->as.heap.aux.shared);
5120 }
5121
5122 /* If, after move the string is not embedded, and can fit in the
5123 * slot it's been placed in, then re-embed it. Skip pinned objects:
5124 * a local holding RSTRING_PTR across this compaction could otherwise
5125 * point to freed memory even if the String is marked and pinned. */
5126 if (rb_gc_obj_slot_size(obj) >= rb_str_size_as_embedded(obj)) {
5127 if (!STR_EMBED_P(obj) && rb_str_reembeddable_p(obj)
5128 && !rb_gc_impl_pinned_p(objspace, obj)) {
5129 rb_str_make_embedded(obj);
5130 }
5131 }
5132
5133 break;
5134 }
5135 case T_DATA:
5136 /* Call the compaction callback, if it exists */
5137 {
5138 void *const ptr = RTYPEDDATA_GET_DATA(obj);
5139
5140 UPDATE_IF_MOVED(objspace, RTYPEDDATA(obj)->fields_obj);
5141
5142 if (ptr) {
5143 if (gc_declarative_marking_p(RTYPEDDATA_TYPE(obj))) {
5144 size_t *offset_list = TYPED_DATA_REFS_OFFSET_LIST(obj);
5145
5146 for (size_t offset = *offset_list; offset != RUBY_REF_END; offset = *offset_list++) {
5147 VALUE *ref = (VALUE *)((char *)ptr + offset);
5148 *ref = gc_location_internal(objspace, *ref);
5149 }
5150 }
5151 else {
5152 RUBY_DATA_FUNC compact_func = RTYPEDDATA_TYPE(obj)->function.dcompact;
5153 if (compact_func) (*compact_func)(ptr);
5154 }
5155 }
5156 }
5157 break;
5158
5159 case T_OBJECT:
5160 gc_ref_update_object(objspace, obj);
5161 break;
5162
5163 case T_FILE:
5164 if (RFILE(obj)->fptr) {
5165 UPDATE_IF_MOVED(objspace, RFILE(obj)->fptr->self);
5166 UPDATE_IF_MOVED(objspace, RFILE(obj)->fptr->pathv);
5167 UPDATE_IF_MOVED(objspace, RFILE(obj)->fptr->tied_io_for_writing);
5168 UPDATE_IF_MOVED(objspace, RFILE(obj)->fptr->writeconv_asciicompat);
5169 UPDATE_IF_MOVED(objspace, RFILE(obj)->fptr->writeconv_pre_ecopts);
5170 UPDATE_IF_MOVED(objspace, RFILE(obj)->fptr->encs.ecopts);
5171 UPDATE_IF_MOVED(objspace, RFILE(obj)->fptr->write_lock);
5172 UPDATE_IF_MOVED(objspace, RFILE(obj)->fptr->timeout);
5173 UPDATE_IF_MOVED(objspace, RFILE(obj)->fptr->wakeup_mutex);
5174 }
5175 break;
5176 case T_REGEXP:
5177 UPDATE_IF_MOVED(objspace, RREGEXP(obj)->src);
5178 break;
5179
5180 case T_SYMBOL:
5181 UPDATE_IF_MOVED(objspace, RSYMBOL(obj)->fstr);
5182 break;
5183
5184 case T_FLOAT:
5185 case T_BIGNUM:
5186 break;
5187
5188 case T_MATCH:
5189 UPDATE_IF_MOVED(objspace, RMATCH(obj)->regexp);
5190
5191 if (RMATCH(obj)->str) {
5192 UPDATE_IF_MOVED(objspace, RMATCH(obj)->str);
5193 }
5194 break;
5195
5196 case T_RATIONAL:
5197 UPDATE_IF_MOVED(objspace, RRATIONAL(obj)->num);
5198 UPDATE_IF_MOVED(objspace, RRATIONAL(obj)->den);
5199 break;
5200
5201 case T_COMPLEX:
5202 UPDATE_IF_MOVED(objspace, RCOMPLEX(obj)->real);
5203 UPDATE_IF_MOVED(objspace, RCOMPLEX(obj)->imag);
5204
5205 break;
5206
5207 case T_STRUCT:
5208 {
5209 long i, len = RSTRUCT_LEN(obj);
5210 VALUE *ptr = (VALUE *)RSTRUCT_CONST_PTR(obj);
5211
5212 for (i = 0; i < len; i++) {
5213 UPDATE_IF_MOVED(objspace, ptr[i]);
5214 }
5215
5216 UPDATE_IF_MOVED(objspace, RSTRUCT(obj)->fields_obj);
5217 }
5218 break;
5219 default:
5220 rb_bug("unreachable");
5221 break;
5222 }
5223
5224 UPDATE_IF_MOVED(objspace, RBASIC(obj)->klass);
5225}
5226
5227VALUE
5228rb_gc_start(void)
5229{
5230 rb_gc();
5231 return Qnil;
5232}
5233
5234void
5235rb_gc(void)
5236{
5237 unless_objspace(objspace) { return; }
5238
5239 rb_gc_impl_start(objspace, true, true, true, false, true);
5240}
5241
5242int
5243rb_during_gc(void)
5244{
5245 unless_objspace(objspace) { return FALSE; }
5246
5247 return rb_gc_impl_during_gc_p(objspace);
5248}
5249
5250size_t
5251rb_gc_count(void)
5252{
5253 return rb_gc_impl_gc_count(rb_gc_get_objspace());
5254}
5255
5256static VALUE
5257gc_count(rb_execution_context_t *ec, VALUE self)
5258{
5259 return SIZET2NUM(rb_gc_count());
5260}
5261
5262VALUE
5263rb_gc_latest_gc_info(VALUE key)
5264{
5265 if (!SYMBOL_P(key) && !RB_TYPE_P(key, T_HASH)) {
5266 rb_raise(rb_eTypeError, "non-hash or symbol given");
5267 }
5268
5269 VALUE val = rb_gc_impl_latest_gc_info(rb_gc_get_objspace(), key);
5270
5271 if (val == Qundef) {
5272 rb_raise(rb_eArgError, "unknown key: %"PRIsVALUE, rb_sym2str(key));
5273 }
5274
5275 return val;
5276}
5277
5278static VALUE
5279gc_stat(rb_execution_context_t *ec, VALUE self, VALUE arg, VALUE global_scope)
5280{
5281 if (NIL_P(arg)) {
5282 arg = rb_hash_new();
5283 }
5284 else if (!RB_TYPE_P(arg, T_HASH) && !SYMBOL_P(arg)) {
5285 rb_raise(rb_eTypeError, "non-hash or symbol given");
5286 }
5287
5288 VALUE ret = rb_gc_impl_stat(RTEST(global_scope) ? NULL : rb_gc_get_objspace(), arg);
5289
5290 if (ret == Qundef) {
5291 GC_ASSERT(SYMBOL_P(arg));
5292
5293 rb_raise(rb_eArgError, "unknown key: %"PRIsVALUE, rb_sym2str(arg));
5294 }
5295
5296 return ret;
5297}
5298
5299size_t
5300rb_gc_stat(VALUE arg)
5301{
5302 if (!RB_TYPE_P(arg, T_HASH) && !SYMBOL_P(arg)) {
5303 rb_raise(rb_eTypeError, "non-hash or symbol given");
5304 }
5305
5306 VALUE ret = rb_gc_impl_stat(rb_gc_get_objspace(), arg);
5307
5308 if (ret == Qundef) {
5309 GC_ASSERT(SYMBOL_P(arg));
5310
5311 rb_raise(rb_eArgError, "unknown key: %"PRIsVALUE, rb_sym2str(arg));
5312 }
5313
5314 if (SYMBOL_P(arg)) {
5315 return NUM2SIZET(ret);
5316 }
5317 else {
5318 return 0;
5319 }
5320}
5321
5322static VALUE
5323gc_stat_heap(rb_execution_context_t *ec, VALUE self, VALUE heap_name, VALUE arg)
5324{
5325 if (NIL_P(arg)) {
5326 arg = rb_hash_new();
5327 }
5328
5329 if (NIL_P(heap_name)) {
5330 if (!RB_TYPE_P(arg, T_HASH)) {
5331 rb_raise(rb_eTypeError, "non-hash given");
5332 }
5333 }
5334 else if (FIXNUM_P(heap_name)) {
5335 if (!SYMBOL_P(arg) && !RB_TYPE_P(arg, T_HASH)) {
5336 rb_raise(rb_eTypeError, "non-hash or symbol given");
5337 }
5338 }
5339 else {
5340 rb_raise(rb_eTypeError, "heap_name must be nil or an Integer");
5341 }
5342
5343 VALUE ret = rb_gc_impl_stat_heap(rb_gc_get_objspace(), heap_name, arg);
5344
5345 if (ret == Qundef) {
5346 GC_ASSERT(SYMBOL_P(arg));
5347
5348 rb_raise(rb_eArgError, "unknown key: %"PRIsVALUE, rb_sym2str(arg));
5349 }
5350
5351 return ret;
5352}
5353
5354static VALUE
5355gc_config_get(rb_execution_context_t *ec, VALUE self)
5356{
5357 VALUE cfg_hash = rb_gc_impl_config_get(rb_gc_get_objspace());
5358 rb_hash_aset(cfg_hash, sym("implementation"), rb_fstring_cstr(rb_gc_impl_active_gc_name()));
5359
5360 return cfg_hash;
5361}
5362
5363static VALUE
5364gc_config_set(rb_execution_context_t *ec, VALUE self, VALUE hash)
5365{
5366 void *objspace = rb_gc_get_objspace();
5367
5368 rb_gc_impl_config_set(objspace, hash);
5369
5370 return Qnil;
5371}
5372
5373static VALUE
5374gc_stress_get(rb_execution_context_t *ec, VALUE self)
5375{
5376 return rb_gc_impl_stress_get(rb_gc_get_objspace());
5377}
5378
5379static VALUE
5380gc_stress_set_m(rb_execution_context_t *ec, VALUE self, VALUE flag)
5381{
5382 rb_gc_impl_stress_set(rb_gc_get_objspace(), flag);
5383
5384 return flag;
5385}
5386
5387void
5388rb_gc_initial_stress_set(VALUE flag)
5389{
5390 initial_stress = flag;
5391}
5392
5393/* Add or drop a GC-disable holder (vm->gc.disable_holders; see vm_core.h). critical
5394 * is the anonymous holder used by internal sections that must not be interrupted by a
5395 * GC, such as collecting under the barrier. */
5396
5397static void
5398rb_gc_critical_disable(void)
5399{
5400 rb_gc_impl_gc_rest(rb_gc_get_objspace());
5401 RUBY_ATOMIC_INC(GET_VM()->gc.disable_holders);
5402}
5403
5404static void
5405rb_gc_critical_enable(void)
5406{
5407 RUBY_ATOMIC_DEC(GET_VM()->gc.disable_holders);
5408}
5409
5410bool
5411rb_gc_gc_disabled_global_p(void)
5412{
5413 return RUBY_ATOMIC_LOAD(GET_VM()->gc.disable_holders) != 0;
5414}
5415
5416/* GC.disable/enable set and clear this objspace's flag and only move the holder count
5417 * when the flag actually changes. The returned previous state is this objspace's. */
5418static bool
5419gc_ractor_disable_set(bool disable)
5420{
5421 const bool was = rb_gc_impl_user_gc_disabled_set(rb_gc_get_objspace(), disable);
5422 if (was != disable) {
5423 if (disable) {
5424 RUBY_ATOMIC_INC(GET_VM()->gc.disable_holders);
5425 }
5426 else {
5427 RUBY_ATOMIC_DEC(GET_VM()->gc.disable_holders);
5428 }
5429 }
5430 return was;
5431}
5432
5433VALUE
5434rb_gc_enable(void)
5435{
5436 return RBOOL(gc_ractor_disable_set(false));
5437}
5438
5439VALUE
5440rb_gc_disable_no_rest(void)
5441{
5442 return RBOOL(gc_ractor_disable_set(true));
5443}
5444
5445VALUE
5446rb_gc_disable(void)
5447{
5448 const bool was_disabled = gc_ractor_disable_set(true);
5449 if (!was_disabled) {
5450 rb_gc_impl_gc_rest(rb_gc_get_objspace());
5451 }
5452 return RBOOL(was_disabled);
5453}
5454
5455VALUE
5456rb_objspace_gc_enable(void *objspace)
5457{
5458 bool disabled = !rb_gc_impl_gc_enabled_p(objspace);
5459 rb_gc_impl_gc_enable(objspace);
5460 return RBOOL(disabled);
5461}
5462
5463VALUE
5464rb_objspace_gc_disable(void *objspace)
5465{
5466 bool disabled = !rb_gc_impl_gc_enabled_p(objspace);
5467 rb_gc_impl_gc_disable(objspace, true);
5468 return RBOOL(disabled);
5469}
5470
5471VALUE
5472rb_gc_objspace_enable(void *objspace)
5473{
5474 return rb_objspace_gc_enable(objspace);
5475}
5476
5477VALUE
5478rb_gc_local_enable(void)
5479{
5480 return rb_gc_objspace_enable(rb_gc_get_objspace());
5481}
5482
5483
5484VALUE
5485rb_gc_objspace_disable_no_rest(void *objspace)
5486{
5487 bool disabled = !rb_gc_impl_gc_enabled_p(objspace);
5488 rb_gc_impl_gc_disable(objspace, false);
5489 return RBOOL(disabled);
5490}
5491
5492VALUE
5493rb_gc_local_disable_no_rest(void)
5494{
5495 return rb_gc_objspace_disable_no_rest(rb_gc_get_objspace());
5496}
5497
5498static VALUE
5499gc_enable(rb_execution_context_t *ec, VALUE _)
5500{
5501 return rb_gc_enable();
5502}
5503
5504static VALUE
5505gc_disable(rb_execution_context_t *ec, VALUE _)
5506{
5507 return rb_gc_disable();
5508}
5509
5510// TODO: think about moving ruby_gc_set_params into Init_heap or Init_gc
5511void
5512ruby_gc_set_params(void)
5513{
5514 rb_gc_impl_set_params(rb_gc_get_objspace());
5515}
5516
5517void
5518rb_objspace_reachable_objects_from(VALUE obj, void (func)(VALUE, void *), void *data)
5519{
5520 RB_VM_LOCKING() {
5521 if (rb_gc_impl_during_gc_p(rb_gc_get_objspace())) rb_bug("rb_objspace_reachable_objects_from() is not supported while during GC");
5522
5523 if (!RB_SPECIAL_CONST_P(obj)) {
5524 struct gc_mark_func_data_struct **mfdp = GC_MARK_FUNC_DATA_SLOTP();
5525 struct gc_mark_func_data_struct *prev_mfd = *mfdp;
5526 struct gc_mark_func_data_struct mfd = {
5527 .mark_func = func,
5528 .data = data,
5529 };
5530
5531 *mfdp = &mfd;
5532 rb_gc_mark_children(rb_gc_get_objspace(), obj);
5533 *mfdp = prev_mfd;
5534 }
5535 }
5536}
5537
5539 const char *category;
5540 void (*func)(const char *category, VALUE, void *);
5541 void *data;
5542};
5543
5544static void
5545root_objects_from(VALUE obj, void *ptr)
5546{
5547 const struct root_objects_data *data = (struct root_objects_data *)ptr;
5548 (*data->func)(data->category, obj, data->data);
5549}
5550
5551void
5552rb_objspace_reachable_objects_from_root(void (func)(const char *category, VALUE, void *), void *passing_data)
5553{
5554 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");
5555
5556 struct root_objects_data data = {
5557 .func = func,
5558 .data = passing_data,
5559 };
5560
5561 struct gc_mark_func_data_struct **mfdp = GC_MARK_FUNC_DATA_SLOTP();
5562 struct gc_mark_func_data_struct *prev_mfd = *mfdp;
5563 struct gc_mark_func_data_struct mfd = {
5564 .mark_func = root_objects_from,
5565 .data = &data,
5566 };
5567
5568 *mfdp = &mfd;
5569 rb_gc_save_machine_context();
5570 rb_gc_mark_roots(rb_gc_get_objspace(), &data.category);
5571 *mfdp = prev_mfd;
5572}
5573
5574/*
5575 ------------------------------ DEBUG ------------------------------
5576*/
5577
5578static const char *
5579type_name(int type, VALUE obj)
5580{
5581 switch (type) {
5582#define TYPE_NAME(t) case (t): return #t;
5583 TYPE_NAME(T_NONE);
5584 TYPE_NAME(T_OBJECT);
5585 TYPE_NAME(T_CLASS);
5586 TYPE_NAME(T_MODULE);
5587 TYPE_NAME(T_FLOAT);
5588 TYPE_NAME(T_STRING);
5589 TYPE_NAME(T_REGEXP);
5590 TYPE_NAME(T_ARRAY);
5591 TYPE_NAME(T_HASH);
5592 TYPE_NAME(T_STRUCT);
5593 TYPE_NAME(T_BIGNUM);
5594 TYPE_NAME(T_FILE);
5595 TYPE_NAME(T_MATCH);
5596 TYPE_NAME(T_COMPLEX);
5597 TYPE_NAME(T_RATIONAL);
5598 TYPE_NAME(T_NIL);
5599 TYPE_NAME(T_TRUE);
5600 TYPE_NAME(T_FALSE);
5601 TYPE_NAME(T_SYMBOL);
5602 TYPE_NAME(T_FIXNUM);
5603 TYPE_NAME(T_UNDEF);
5604 TYPE_NAME(T_IMEMO);
5605 TYPE_NAME(T_ICLASS);
5606 TYPE_NAME(T_MOVED);
5607 TYPE_NAME(T_ZOMBIE);
5608 case T_DATA:
5609 if (obj && rb_objspace_data_type_name(obj)) {
5610 return rb_objspace_data_type_name(obj);
5611 }
5612 return "T_DATA";
5613#undef TYPE_NAME
5614 }
5615 return "unknown";
5616}
5617
5618static const char *
5619obj_type_name(VALUE obj)
5620{
5621 return type_name(TYPE(obj), obj);
5622}
5623
5624const char *
5625rb_method_type_name(rb_method_type_t type)
5626{
5627 switch (type) {
5628 case VM_METHOD_TYPE_ISEQ: return "iseq";
5629 case VM_METHOD_TYPE_ATTRSET: return "attrset";
5630 case VM_METHOD_TYPE_IVAR: return "ivar";
5631 case VM_METHOD_TYPE_BMETHOD: return "bmethod";
5632 case VM_METHOD_TYPE_ALIAS: return "alias";
5633 case VM_METHOD_TYPE_REFINED: return "refined";
5634 case VM_METHOD_TYPE_CFUNC: return "cfunc";
5635 case VM_METHOD_TYPE_ZSUPER: return "zsuper";
5636 case VM_METHOD_TYPE_MISSING: return "missing";
5637 case VM_METHOD_TYPE_OPTIMIZED: return "optimized";
5638 case VM_METHOD_TYPE_UNDEF: return "undef";
5639 case VM_METHOD_TYPE_NOTIMPLEMENTED: return "notimplemented";
5640 }
5641 rb_bug("rb_method_type_name: unreachable (type: %d)", type);
5642}
5643
5644static void
5645rb_raw_iseq_info(char *const buff, const size_t buff_size, const rb_iseq_t *iseq)
5646{
5647 if (buff_size > 0 && ISEQ_BODY(iseq) && ISEQ_BODY(iseq)->location.label && !RB_TYPE_P(ISEQ_BODY(iseq)->location.pathobj, T_MOVED)) {
5648 VALUE path = rb_iseq_path(iseq);
5649 int n = ISEQ_BODY(iseq)->location.first_lineno;
5650 VALUE label = ISEQ_BODY(iseq)->location.label;
5651 snprintf(buff, buff_size, " %.*s@%.*s:%d",
5652 RSTRING_LENINT(label), RSTRING_PTR(label),
5653 RSTRING_LENINT(path), RSTRING_PTR(path), n);
5654 }
5655}
5656
5657static int
5658str_len_no_raise(VALUE str)
5659{
5660 long len = RSTRING_LEN(str);
5661 if (len < 0) return 0;
5662 if (len > INT_MAX) return INT_MAX;
5663 return (int)len;
5664}
5665
5666#define BUFF_ARGS buff + pos, buff_size - pos
5667#define APPEND_F(...) if ((pos += snprintf(BUFF_ARGS, "" __VA_ARGS__)) >= buff_size) goto end
5668#define APPEND_S(s) do { \
5669 if ((pos + (int)rb_strlen_lit(s)) >= buff_size) { \
5670 goto end; \
5671 } \
5672 else { \
5673 memcpy(buff + pos, (s), rb_strlen_lit(s) + 1); \
5674 } \
5675 } while (0)
5676#define C(c, s) ((c) != 0 ? (s) : " ")
5677
5678static size_t
5679rb_raw_obj_info_common(char *const buff, const size_t buff_size, const VALUE obj)
5680{
5681 size_t pos = 0;
5682
5683 if (SPECIAL_CONST_P(obj)) {
5684 APPEND_F("%s", obj_type_name(obj));
5685
5686 if (FIXNUM_P(obj)) {
5687 APPEND_F(" %ld", FIX2LONG(obj));
5688 }
5689 else if (SYMBOL_P(obj)) {
5690 APPEND_F(" %s", rb_id2name(SYM2ID(obj)));
5691 }
5692 }
5693 else {
5694 // const int age = RVALUE_AGE_GET(obj);
5695
5696 if (rb_gc_impl_live_object_p(rb_gc_get_objspace(), (void *)obj)) {
5697 APPEND_F("%p %s/", (void *)obj, obj_type_name(obj));
5698 // TODO: fixme
5699 // APPEND_F("%p [%d%s%s%s%s%s%s] %s ",
5700 // (void *)obj, age,
5701 // C(RVALUE_UNCOLLECTIBLE_BITMAP(obj), "L"),
5702 // C(RVALUE_MARK_BITMAP(obj), "M"),
5703 // C(RVALUE_PIN_BITMAP(obj), "P"),
5704 // C(RVALUE_MARKING_BITMAP(obj), "R"),
5705 // C(RVALUE_WB_UNPROTECTED_BITMAP(obj), "U"),
5706 // C(rb_objspace_garbage_object_p(obj), "G"),
5707 // obj_type_name(obj));
5708 }
5709 else {
5710 /* fake */
5711 // APPEND_F("%p [%dXXXX] %s",
5712 // (void *)obj, age,
5713 // obj_type_name(obj));
5714 }
5715
5716 if (internal_object_p(obj)) {
5717 /* ignore */
5718 }
5719 else if (RBASIC(obj)->klass == 0) {
5720 APPEND_S("(temporary internal)");
5721 }
5722 else if (RTEST(RBASIC(obj)->klass)) {
5723 VALUE class_path = rb_mod_name(RBASIC(obj)->klass);
5724 if (!NIL_P(class_path)) {
5725 APPEND_F("%.*s ", str_len_no_raise(class_path), RSTRING_PTR(class_path));
5726 }
5727 }
5728 }
5729 end:
5730
5731 return pos;
5732}
5733
5734const char *rb_raw_obj_info(char *const buff, const size_t buff_size, VALUE obj);
5735
5736static size_t
5737rb_raw_obj_info_buitin_type(char *const buff, const size_t buff_size, const VALUE obj, size_t pos)
5738{
5739 if (LIKELY(pos < buff_size) && !SPECIAL_CONST_P(obj)) {
5740 const enum ruby_value_type type = BUILTIN_TYPE(obj);
5741
5742 switch (type) {
5743 case T_NODE:
5744 UNEXPECTED_NODE(rb_raw_obj_info);
5745 break;
5746 case T_ARRAY:
5747 if (ARY_SHARED_P(obj)) {
5748 APPEND_S("shared -> ");
5749 rb_raw_obj_info(BUFF_ARGS, ARY_SHARED_ROOT(obj));
5750 }
5751 else {
5752 APPEND_F("[%s%s%s] ",
5753 C(ARY_EMBED_P(obj), "E"),
5754 C(ARY_SHARED_P(obj), "S"),
5755 C(ARY_SHARED_ROOT_P(obj), "R"));
5756
5757 if (ARY_EMBED_P(obj)) {
5758 APPEND_F("len: %ld (embed)",
5759 RARRAY_LEN(obj));
5760 }
5761 else {
5762 APPEND_F("len: %ld, capa:%ld ptr:%p",
5763 RARRAY_LEN(obj),
5764 RARRAY(obj)->as.heap.aux.capa,
5765 (void *)RARRAY_CONST_PTR(obj));
5766 }
5767 }
5768 break;
5769 case T_STRING: {
5770 APPEND_F("[%s%s] ",
5771 C(FL_TEST(obj, RSTRING_FSTR), "F"),
5772 C(RB_OBJ_FROZEN(obj), "R"));
5773
5774 if (STR_SHARED_P(obj)) {
5775 APPEND_F(" [shared] len: %ld", RSTRING_LEN(obj));
5776 }
5777 else {
5778 if (STR_EMBED_P(obj)) APPEND_S(" [embed]");
5779
5780 APPEND_F(" len: %ld, capa: %" PRIdSIZE, RSTRING_LEN(obj), rb_str_capacity(obj));
5781 }
5782 APPEND_F(" \"%.*s\"", str_len_no_raise(obj), RSTRING_PTR(obj));
5783 break;
5784 }
5785 case T_SYMBOL: {
5786 VALUE fstr = RSYMBOL(obj)->fstr;
5787 ID id = RSYMBOL(obj)->id;
5788 if (RB_TYPE_P(fstr, T_STRING)) {
5789 APPEND_F(":%.*s id:%d", str_len_no_raise(fstr), RSTRING_PTR(fstr), (unsigned int)id);
5790 }
5791 else {
5792 APPEND_F("(%p) id:%d", (void *)fstr, (unsigned int)id);
5793 }
5794 break;
5795 }
5796 case T_MOVED: {
5797 APPEND_F("-> %p", (void*)gc_location_internal(rb_gc_get_objspace(), obj));
5798 break;
5799 }
5800 case T_HASH: {
5801 APPEND_F("[%c] %"PRIdSIZE,
5802 RHASH_AR_TABLE_P(obj) ? 'A' : 'S',
5803 RHASH_SIZE(obj));
5804 break;
5805 }
5806 case T_CLASS:
5807 case T_MODULE:
5808 {
5809 VALUE class_path = rb_mod_name(obj);
5810 if (!NIL_P(class_path)) {
5811 APPEND_F("%.*s", str_len_no_raise(class_path), RSTRING_PTR(class_path));
5812 }
5813 else {
5814 APPEND_S("(anon)");
5815 }
5816 break;
5817 }
5818 case T_ICLASS:
5819 {
5820 VALUE class_path = rb_mod_name(RBASIC_CLASS(obj));
5821 if (!NIL_P(class_path)) {
5822 APPEND_F("src:%.*s", str_len_no_raise(class_path), RSTRING_PTR(class_path));
5823 }
5824 break;
5825 }
5826 case T_OBJECT:
5827 {
5828 shape_id_t shape_id = RBASIC_SHAPE_ID(obj);
5829 if (rb_shape_embedded_p(shape_id)) {
5830 APPEND_F("(embed) len:%d capa:%d", RSHAPE_LEN(shape_id), RSHAPE_CAPACITY(shape_id));
5831 }
5832 else {
5833 VALUE fields_obj = ROBJECT_FIELDS_OBJ(obj);
5834 if (rb_shape_complex_p(shape_id)) {
5835 size_t hash_len = rb_st_table_size(rb_imemo_fields_complex_tbl(fields_obj));
5836 APPEND_F("(complex) len:%zu extended:%p", hash_len, (void *)fields_obj);
5837 }
5838 else {
5839 APPEND_F("(extended) len:%d capa:%d extended:%p", RSHAPE_LEN(shape_id), RSHAPE_CAPACITY(shape_id), (void *)fields_obj);
5840 }
5841 }
5842 }
5843 break;
5844 case T_DATA: {
5845 const struct rb_block *block;
5846 const rb_iseq_t *iseq;
5847 if (rb_obj_is_proc(obj) &&
5848 (block = vm_proc_block(obj)) != NULL &&
5849 (vm_block_type(block) == block_type_iseq) &&
5850 (iseq = vm_block_iseq(block)) != NULL) {
5851 rb_raw_iseq_info(BUFF_ARGS, iseq);
5852 }
5853 else if (rb_ractor_p(obj)) {
5854 rb_ractor_t *r = (void *)DATA_PTR(obj);
5855 if (r) {
5856 APPEND_F("r:%"PRI_SERIALT_PREFIX"u", r->pub.id);
5857 }
5858 }
5859 break;
5860 }
5861 case T_IMEMO: {
5862 APPEND_F("<%s> ", rb_imemo_name(imemo_type(obj)));
5863
5864 switch (imemo_type(obj)) {
5865 case imemo_fields:
5866 {
5867 shape_id_t shape_id = RBASIC_SHAPE_ID(obj);
5868 if (rb_shape_complex_p(shape_id)) {
5869 size_t hash_len = rb_st_table_size(rb_imemo_fields_complex_tbl(obj));
5870 APPEND_F("(complex) len:%zu", hash_len);
5871 }
5872 else {
5873 APPEND_F("(embed) len:%d capa:%d", RSHAPE_LEN(shape_id), RSHAPE_CAPACITY(shape_id));
5874 }
5875
5876 APPEND_S("owner -> ");
5877 rb_raw_obj_info(BUFF_ARGS, CLASS_OF(obj));
5878
5879 break;
5880 }
5881 case imemo_ment:
5882 {
5883 const rb_method_entry_t *me = (const rb_method_entry_t *)obj;
5884
5885 APPEND_F(":%s (%s%s%s%s) type:%s aliased:%d owner:%p defined_class:%p",
5886 rb_id2name(me->called_id),
5887 METHOD_ENTRY_VISI(me) == METHOD_VISI_PUBLIC ? "pub" :
5888 METHOD_ENTRY_VISI(me) == METHOD_VISI_PRIVATE ? "pri" : "pro",
5889 METHOD_ENTRY_COMPLEMENTED(me) ? ",cmp" : "",
5890 METHOD_ENTRY_CACHED(me) ? ",cc" : "",
5891 METHOD_ENTRY_INVALIDATED(me) ? ",inv" : "",
5892 me->def ? rb_method_type_name(me->def->type) : "NULL",
5893 me->def ? me->def->aliased : -1,
5894 (void *)me->owner, // obj_info(me->owner),
5895 (void *)me->defined_class); //obj_info(me->defined_class)));
5896
5897 if (me->def) {
5898 switch (me->def->type) {
5899 case VM_METHOD_TYPE_ISEQ:
5900 APPEND_S(" (iseq:");
5901 rb_raw_obj_info(BUFF_ARGS, (VALUE)me->def->body.iseq.iseqptr);
5902 APPEND_S(")");
5903 break;
5904 default:
5905 break;
5906 }
5907 }
5908
5909 break;
5910 }
5911 case imemo_iseq: {
5912 const rb_iseq_t *iseq = (const rb_iseq_t *)obj;
5913 rb_raw_iseq_info(BUFF_ARGS, iseq);
5914 break;
5915 }
5916 case imemo_callinfo:
5917 {
5918 const struct rb_callinfo *ci = (const struct rb_callinfo *)obj;
5919 APPEND_F("(mid:%s, flag:%x argc:%d, kwarg:%s)",
5920 rb_id2name(vm_ci_mid(ci)),
5921 vm_ci_flag(ci),
5922 vm_ci_argc(ci),
5923 vm_ci_kwarg(ci) ? "available" : "NULL");
5924 break;
5925 }
5926 case imemo_callcache:
5927 {
5928 const struct rb_callcache *cc = (const struct rb_callcache *)obj;
5929 VALUE class_path = vm_cc_valid(cc) ? rb_mod_name(cc->klass) : Qnil;
5930 const rb_callable_method_entry_t *cme = vm_cc_cme(cc);
5931 const char *class_name;
5932 int class_name_len;
5933
5934 if (NIL_P(class_path)) {
5935 class_name = vm_cc_valid(cc) ? "??" : "<NULL>";
5936 class_name_len = vm_cc_valid(cc) ? 2 : 6;
5937 }
5938 else {
5939 class_name = RSTRING_PTR(class_path);
5940 class_name_len = str_len_no_raise(class_path);
5941 }
5942
5943 APPEND_F("(klass:%.*s cme:%s%s (%p) call:%p",
5944 class_name_len, class_name,
5945 cme ? rb_id2name(cme->called_id) : "<NULL>",
5946 cme ? (METHOD_ENTRY_INVALIDATED(cme) ? " [inv]" : "") : "",
5947 (void *)cme,
5948 (void *)(uintptr_t)vm_cc_call(cc));
5949 break;
5950 }
5951 default:
5952 break;
5953 }
5954 }
5955 default:
5956 break;
5957 }
5958 }
5959 end:
5960
5961 return pos;
5962}
5963
5964#undef C
5965
5966#ifdef RUBY_ASAN_ENABLED
5967void
5968rb_asan_poison_object(VALUE obj)
5969{
5970 MAYBE_UNUSED(struct RVALUE *) ptr = (void *)obj;
5971 asan_poison_memory_region(ptr, rb_gc_obj_slot_size(obj));
5972}
5973
5974void
5975rb_asan_unpoison_object(VALUE obj, bool newobj_p)
5976{
5977 MAYBE_UNUSED(struct RVALUE *) ptr = (void *)obj;
5978 asan_unpoison_memory_region(ptr, rb_gc_obj_slot_size(obj), newobj_p);
5979}
5980
5981void *
5982rb_asan_poisoned_object_p(VALUE obj)
5983{
5984 MAYBE_UNUSED(struct RVALUE *) ptr = (void *)obj;
5985 return __asan_region_is_poisoned(ptr, rb_gc_obj_slot_size(obj));
5986}
5987#endif
5988
5989static void
5990raw_obj_info(char *const buff, const size_t buff_size, VALUE obj)
5991{
5992 size_t pos = rb_raw_obj_info_common(buff, buff_size, obj);
5993 pos = rb_raw_obj_info_buitin_type(buff, buff_size, obj, pos);
5994 if (pos >= buff_size) {} // truncated
5995}
5996
5997const char *
5998rb_raw_obj_info(char *const buff, const size_t buff_size, VALUE obj)
5999{
6000 void *objspace = rb_gc_get_objspace();
6001
6002 if (SPECIAL_CONST_P(obj)) {
6003 raw_obj_info(buff, buff_size, obj);
6004 }
6005 else if (!rb_gc_impl_live_object_p(objspace, (const void *)obj)) {
6006 snprintf(buff, buff_size, "out-of-heap:%p", (void *)obj);
6007 }
6008#if 0 // maybe no need to check it?
6009 else if (0 && rb_gc_impl_garbage_object_p(objspace, obj)) {
6010 snprintf(buff, buff_size, "garbage:%p", (void *)obj);
6011 }
6012#endif
6013 else {
6014 asan_unpoisoning_object(obj) {
6015 raw_obj_info(buff, buff_size, obj);
6016 }
6017 }
6018 return buff;
6019}
6020
6021#undef APPEND_S
6022#undef APPEND_F
6023#undef BUFF_ARGS
6024
6025/* Increments *var atomically and resets *var to 0 when maxval is
6026 * reached. Returns the wraparound old *var value (0...maxval). */
6027static rb_atomic_t
6028atomic_inc_wraparound(rb_atomic_t *var, const rb_atomic_t maxval)
6029{
6030 rb_atomic_t oldval = RUBY_ATOMIC_FETCH_ADD(*var, 1);
6031 if (RB_UNLIKELY(oldval >= maxval - 1)) { // wraparound *var
6032 const rb_atomic_t newval = oldval + 1;
6033 RUBY_ATOMIC_CAS(*var, newval, newval % maxval);
6034 oldval %= maxval;
6035 }
6036 return oldval;
6037}
6038
6039static const char *
6040obj_info(VALUE obj)
6041{
6042 if (RGENGC_OBJ_INFO) {
6043 static struct {
6044 rb_atomic_t index;
6045 char buffers[10][0x100];
6046 } info = {0};
6047
6048 rb_atomic_t index = atomic_inc_wraparound(&info.index, numberof(info.buffers));
6049 char *const buff = info.buffers[index];
6050 return rb_raw_obj_info(buff, sizeof(info.buffers[0]), obj);
6051 }
6052 return obj_type_name(obj);
6053}
6054
6055/*
6056 ------------------------ Extended allocator ------------------------
6057*/
6058
6060 VALUE exc;
6061 const char *fmt;
6062 va_list *ap;
6063};
6064
6065static void *
6066gc_vraise(void *ptr)
6067{
6068 struct gc_raise_tag *argv = ptr;
6069 rb_vraise(argv->exc, argv->fmt, *argv->ap);
6070 UNREACHABLE_RETURN(NULL);
6071}
6072
6073static void
6074gc_raise(VALUE exc, const char *fmt, ...)
6075{
6076 va_list ap;
6077 va_start(ap, fmt);
6078 struct gc_raise_tag argv = {
6079 exc, fmt, &ap,
6080 };
6081
6082 if (ruby_native_thread_p()) {
6083 rb_thread_call_with_gvl(gc_vraise, &argv);
6085 }
6086 else {
6087 /* Not in a ruby thread */
6088 fprintf(stderr, "%s", "[FATAL] ");
6089 vfprintf(stderr, fmt, ap);
6090 }
6091
6092 va_end(ap);
6093 abort();
6094}
6095
6096NORETURN(static void negative_size_allocation_error(const char *));
6097static void
6098negative_size_allocation_error(const char *msg)
6099{
6100 gc_raise(rb_eNoMemError, "%s", msg);
6101}
6102
6103static void *
6104ruby_memerror_body(void *dummy)
6105{
6106 rb_memerror();
6107 return 0;
6108}
6109
6110NORETURN(static void ruby_memerror(void));
6112static void
6113ruby_memerror(void)
6114{
6115 if (ruby_thread_has_gvl_p()) {
6116 rb_memerror();
6117 }
6118 else {
6119 if (ruby_native_thread_p()) {
6120 rb_thread_call_with_gvl(ruby_memerror_body, 0);
6121 }
6122 else {
6123 /* no ruby thread */
6124 fprintf(stderr, "[FATAL] failed to allocate memory\n");
6125 }
6126 }
6127
6128 /* We have discussions whether we should die here; */
6129 /* We might rethink about it later. */
6130 exit(EXIT_FAILURE);
6131}
6132
6133void
6134rb_memerror(void)
6135{
6136 /* the `GET_VM()->special_exceptions` below assumes that
6137 * the VM is reachable from the current thread. We should
6138 * definitely make sure of that. */
6139 RUBY_ASSERT_ALWAYS(ruby_thread_has_gvl_p());
6140
6141 rb_execution_context_t *ec = GET_EC();
6142 VALUE exc = GET_VM()->special_exceptions[ruby_error_nomemory];
6143
6144 if (!exc ||
6145 rb_ec_raised_p(ec, RAISED_NOMEMORY) ||
6146 rb_ec_vm_lock_rec(ec) != ec->tag->lock_rec) {
6147 fprintf(stderr, "[FATAL] failed to allocate memory\n");
6148 exit(EXIT_FAILURE);
6149 }
6150 if (rb_ec_raised_p(ec, RAISED_NOMEMORY)) {
6151 rb_ec_raised_clear(ec);
6152 }
6153 else {
6154 rb_ec_raised_set(ec, RAISED_NOMEMORY);
6155 exc = ruby_vm_special_exception_copy(exc);
6156 }
6157 ec->errinfo = exc;
6158 EC_JUMP_TAG(ec, TAG_RAISE);
6159}
6160
6161bool
6162rb_memerror_reentered(void)
6163{
6164 rb_execution_context_t *ec = GET_EC();
6165 return (ec && rb_ec_raised_p(ec, RAISED_NOMEMORY));
6166}
6167
6168static void *
6169handle_malloc_failure(void *ptr)
6170{
6171 if (LIKELY(ptr)) {
6172 return ptr;
6173 }
6174 else {
6175 ruby_memerror();
6176 UNREACHABLE_RETURN(ptr);
6177 }
6178}
6179
6180static void *ruby_xmalloc_body(size_t size);
6181
6182void *
6183ruby_xmalloc(size_t size)
6184{
6185 if (RUBY_DTRACE_GC_XMALLOC_ENABLED()) {
6186 RUBY_DTRACE_GC_XMALLOC(1, size);
6187 }
6188
6189 return handle_malloc_failure(ruby_xmalloc_body(size));
6190}
6191
6192static bool
6193malloc_gc_allowed(void)
6194{
6195 rb_ractor_t *r = rb_current_ractor_raw(false);
6196
6197 return r == NULL || !r->malloc_gc_disabled;
6198}
6199
6200static void *
6201ruby_xmalloc_body(size_t size)
6202{
6203 if ((ssize_t)size < 0) {
6204 negative_size_allocation_error("too large allocation size");
6205 }
6206
6207 return rb_gc_impl_malloc(rb_gc_get_objspace(), size, malloc_gc_allowed());
6208}
6209
6210void
6211ruby_malloc_size_overflow(size_t count, size_t elsize)
6212{
6213 rb_raise(rb_eArgError,
6214 "malloc: possible integer overflow (%"PRIuSIZE"*%"PRIuSIZE")",
6215 count, elsize);
6216}
6217
6218void
6219ruby_malloc_add_size_overflow(size_t x, size_t y)
6220{
6221 rb_raise(rb_eArgError,
6222 "malloc: possible integer overflow (%"PRIuSIZE"+%"PRIuSIZE")",
6223 x, y);
6224}
6225
6226static void *ruby_xmalloc2_body(size_t n, size_t size);
6227
6228void *
6229ruby_xmalloc2(size_t n, size_t size)
6230{
6231 if (RUBY_DTRACE_GC_XMALLOC_ENABLED()) {
6232 RUBY_DTRACE_GC_XMALLOC(n, size);
6233 }
6234
6235 return handle_malloc_failure(ruby_xmalloc2_body(n, size));
6236}
6237
6238static void *
6239ruby_xmalloc2_body(size_t n, size_t size)
6240{
6241 return rb_gc_impl_malloc(rb_gc_get_objspace(), xmalloc2_size(n, size), malloc_gc_allowed());
6242}
6243
6244static void *ruby_xcalloc_body(size_t n, size_t size);
6245
6246void *
6247ruby_xcalloc(size_t n, size_t size)
6248{
6249 if (RUBY_DTRACE_GC_XCALLOC_ENABLED()) {
6250 RUBY_DTRACE_GC_XCALLOC(n, size);
6251 }
6252
6253 return handle_malloc_failure(ruby_xcalloc_body(n, size));
6254}
6255
6256static void *
6257ruby_xcalloc_body(size_t n, size_t size)
6258{
6259 return rb_gc_impl_calloc(rb_gc_get_objspace(), xmalloc2_size(n, size), malloc_gc_allowed());
6260}
6261
6262static void *ruby_xrealloc_sized_body(void *ptr, size_t new_size, size_t old_size);
6263
6264#ifdef ruby_xrealloc_sized
6265#undef ruby_xrealloc_sized
6266#endif
6267void *
6268ruby_xrealloc_sized(void *ptr, size_t new_size, size_t old_size)
6269{
6270 return handle_malloc_failure(ruby_xrealloc_sized_body(ptr, new_size, old_size));
6271}
6272
6273static void *
6274ruby_xrealloc_sized_body(void *ptr, size_t new_size, size_t old_size)
6275{
6276 if ((ssize_t)new_size < 0) {
6277 negative_size_allocation_error("too large allocation size");
6278 }
6279
6280 return rb_gc_impl_realloc(rb_gc_get_objspace(), ptr, new_size, old_size, malloc_gc_allowed());
6281}
6282
6283void *
6284ruby_xrealloc(void *ptr, size_t new_size)
6285{
6286 return ruby_xrealloc_sized(ptr, new_size, 0);
6287}
6288
6289static void *ruby_xrealloc2_sized_body(void *ptr, size_t n, size_t size, size_t old_n);
6290
6291#ifdef ruby_xrealloc2_sized
6292#undef ruby_xrealloc2_sized
6293#endif
6294void *
6295ruby_xrealloc2_sized(void *ptr, size_t n, size_t size, size_t old_n)
6296{
6297 return handle_malloc_failure(ruby_xrealloc2_sized_body(ptr, n, size, old_n));
6298}
6299
6300static void *
6301ruby_xrealloc2_sized_body(void *ptr, size_t n, size_t size, size_t old_n)
6302{
6303 size_t len = xmalloc2_size(n, size);
6304 return rb_gc_impl_realloc(rb_gc_get_objspace(), ptr, len, old_n * size, malloc_gc_allowed());
6305}
6306
6307void *
6308ruby_xrealloc2(void *ptr, size_t n, size_t size)
6309{
6310 return ruby_xrealloc2_sized(ptr, n, size, 0);
6311}
6312
6313#ifdef ruby_xfree_sized
6314#undef ruby_xfree_sized
6315#endif
6316
6317/*
6318 * This is a debugging flag for measuring the cost of `xfree`.
6319 * It can be enabled at compile time using `-DRUBY_NO_FREE`.
6320 * At run time, if the `RUBY_NO_FREE` environment variable is set to "1",
6321 * then `xfree` will not free any memory.
6322 */
6323#ifdef RUBY_NO_FREE
6324static bool g_nofree = false;
6325#endif
6326
6327void
6328ruby_xfree_sized(void *x, size_t size)
6329{
6330#ifdef RUBY_NO_FREE
6331 if (g_nofree) {
6332 return;
6333 }
6334#endif
6335
6336 if (RUBY_DTRACE_GC_XFREE_ENABLED()) {
6337 RUBY_DTRACE_GC_XFREE(x, size);
6338 }
6339
6340 if (LIKELY(x)) {
6341 /* It's possible for a C extension's pthread destructor function set by pthread_key_create
6342 * to be called after ruby_vm_destruct and attempt to free memory. Fall back to mimfree in
6343 * that case. */
6344 if (LIKELY(GET_VM())) {
6345 rb_gc_impl_free(rb_gc_get_objspace(), x, size);
6346 }
6347 else {
6348 ruby_mimfree(x);
6349 }
6350 }
6351}
6352
6353void
6354ruby_xfree(void *x)
6355{
6356 ruby_xfree_sized(x, 0);
6357}
6358
6359void *
6360rb_xmalloc_mul_add(size_t x, size_t y, size_t z) /* x * y + z */
6361{
6362 size_t w = size_mul_add_or_raise(x, y, z, rb_eArgError);
6363 return ruby_xmalloc(w);
6364}
6365
6366void *
6367rb_xcalloc_mul_add(size_t x, size_t y, size_t z) /* x * y + z */
6368{
6369 size_t w = size_mul_add_or_raise(x, y, z, rb_eArgError);
6370 return ruby_xcalloc(w, 1);
6371}
6372
6373void *
6374rb_xrealloc_mul_add(const void *p, size_t x, size_t y, size_t z) /* x * y + z */
6375{
6376 size_t w = size_mul_add_or_raise(x, y, z, rb_eArgError);
6377 return ruby_xrealloc((void *)p, w);
6378}
6379
6380void *
6381rb_xmalloc_mul_add_mul(size_t x, size_t y, size_t z, size_t w) /* x * y + z * w */
6382{
6383 size_t u = size_mul_add_mul_or_raise(x, y, z, w, rb_eArgError);
6384 return ruby_xmalloc(u);
6385}
6386
6387void *
6388rb_xcalloc_mul_add_mul(size_t x, size_t y, size_t z, size_t w) /* x * y + z * w */
6389{
6390 size_t u = size_mul_add_mul_or_raise(x, y, z, w, rb_eArgError);
6391 return ruby_xcalloc(u, 1);
6392}
6393
6394/* Mimic ruby_xmalloc, but need not rb_objspace.
6395 * should return pointer suitable for ruby_xfree
6396 */
6397void *
6398ruby_mimmalloc(size_t size)
6399{
6400 void *mem;
6401#if CALC_EXACT_MALLOC_SIZE
6402 size += sizeof(struct malloc_obj_info);
6403#endif
6404 mem = malloc(size);
6405#if CALC_EXACT_MALLOC_SIZE
6406 if (!mem) {
6407 return NULL;
6408 }
6409 else
6410 /* set 0 for consistency of allocated_size/allocations */
6411 {
6412 struct malloc_obj_info *info = mem;
6413 info->size = 0;
6414 mem = info + 1;
6415 }
6416#endif
6417 return mem;
6418}
6419
6420void *
6421ruby_mimcalloc(size_t num, size_t size)
6422{
6423 void *mem;
6424#if CALC_EXACT_MALLOC_SIZE
6425 struct rbimpl_size_overflow_tag t = rbimpl_size_mul_overflow(num, size);
6426 if (UNLIKELY(t.overflowed)) {
6427 return NULL;
6428 }
6429 size = t.result + sizeof(struct malloc_obj_info);
6430 mem = calloc1(size);
6431 if (!mem) {
6432 return NULL;
6433 }
6434 else
6435 /* set 0 for consistency of allocated_size/allocations */
6436 {
6437 struct malloc_obj_info *info = mem;
6438 info->size = 0;
6439 mem = info + 1;
6440 }
6441#else
6442 mem = calloc(num, size);
6443#endif
6444 return mem;
6445}
6446
6447void
6448ruby_mimfree(void *ptr)
6449{
6450#if CALC_EXACT_MALLOC_SIZE
6451 struct malloc_obj_info *info = (struct malloc_obj_info *)ptr - 1;
6452 ptr = info;
6453#endif
6454 free(ptr);
6455}
6456
6457void
6458rb_gc_adjust_memory_usage(ssize_t diff)
6459{
6460 unless_objspace(objspace) { return; }
6461
6462 rb_gc_impl_adjust_memory_usage(objspace, diff);
6463}
6464
6465const char *
6466rb_obj_info(VALUE obj)
6467{
6468 return obj_info(obj);
6469}
6470
6471void
6472rb_obj_info_dump(VALUE obj)
6473{
6474 char buff[0x100];
6475 fprintf(stderr, "rb_obj_info_dump: %s\n", rb_raw_obj_info(buff, 0x100, obj));
6476}
6477
6478void
6479rb_obj_info_dump_loc(VALUE obj, const char *file, int line, const char *func)
6480{
6481 char buff[0x100];
6482 fprintf(stderr, "<OBJ_INFO:%s@%s:%d> %s\n", func, file, line, rb_raw_obj_info(buff, 0x100, obj));
6483}
6484
6485void
6486rb_gc_before_fork(void)
6487{
6488 rb_gc_impl_before_fork(rb_gc_get_objspace());
6489}
6490
6491void
6492rb_gc_after_fork(rb_pid_t pid)
6493{
6494 rb_gc_impl_after_fork(rb_gc_get_objspace(), pid);
6495}
6496
6497bool
6498rb_gc_obj_shareable_p(VALUE obj)
6499{
6500 return RB_OBJ_SHAREABLE_P(obj);
6501}
6502
6503void
6504rb_gc_rp(VALUE obj)
6505{
6506 rp(obj);
6507}
6508
6510 VALUE parent;
6511 long err_count;
6512};
6513
6514static void
6515check_shareable_i(const VALUE child, void *ptr)
6516{
6517 struct check_shareable_data *data = (struct check_shareable_data *)ptr;
6518
6519 if (!rb_gc_obj_shareable_p(child)) {
6520 /* A shareable object may reference an unshareable one only if the write barrier
6521 * recorded the edge in the target's shref bit (keeping it alive past its owner's
6522 * local GC). Root-like exceptions (Ractor private fields, cref, JIT) are hidden
6523 * while checking_shareable is set. */
6524 if (rb_gc_impl_shref_marked_p(rb_gc_get_objspace(), child)) {
6525 return;
6526 }
6527
6528 fprintf(stderr, "(a) ");
6529 rb_gc_rp(data->parent);
6530 fprintf(stderr, "(b) ");
6531 rb_gc_rp(child);
6532 fprintf(stderr, "check_shareable_i: shareable (a) -> unshareable (b) without a shref record\n");
6533
6534 data->err_count++;
6535 rb_bug("!! violate shareable constraint !!");
6536 }
6537}
6538
6539/* List obj's direct children one level deep through the traversal API and check the
6540 * shareable constraint: a shareable object's child is either shareable or an
6541 * unshareable one with a recorded shref. The "verification walk in progress" marker
6542 * lives in the per-Ractor mark_func_data slot: a process-global flag would make the
6543 * lock-free local GC of an unrelated Ractor hit the mark gate too, skip marking a live
6544 * object's children (its fields imemo, say) and let the sweep collect them. (Upstream
6545 * could use a global flag, since its GC always runs under the VM lock.) The slot is
6546 * private to this Ractor and the walk is synchronous, so no lock is needed. */
6547void
6548rb_gc_verify_shareable(VALUE obj)
6549{
6550 struct check_shareable_data data = {
6551 .parent = obj,
6552 .err_count = 0,
6553 };
6554
6555 if (!RB_SPECIAL_CONST_P(obj)) {
6556 struct gc_mark_func_data_struct **mfdp = GC_MARK_FUNC_DATA_SLOTP();
6557 struct gc_mark_func_data_struct *prev_mfd = *mfdp;
6558 struct gc_mark_func_data_struct mfd = {
6559 .mark_func = check_shareable_i,
6560 .data = &data,
6561 .checking_shareable = true,
6562 };
6563
6564 *mfdp = &mfd;
6565 rb_gc_mark_children(rb_gc_get_objspace(), obj);
6566 *mfdp = prev_mfd;
6567 }
6568
6569 if (data.err_count > 0) {
6570 rb_bug("rb_gc_verify_shareable");
6571 }
6572}
6573
6574bool
6575rb_gc_checking_shareable(void)
6576{
6577 const struct gc_mark_func_data_struct *mfd = *GC_MARK_FUNC_DATA_SLOTP();
6578 return mfd && mfd->checking_shareable;
6579}
6580
6581/*
6582 * Document-module: ObjectSpace
6583 *
6584 * The ObjectSpace module contains a number of routines
6585 * that interact with the garbage collection facility and allow you to
6586 * traverse all living objects with an iterator.
6587 *
6588 * ObjectSpace also provides support for object finalizers, procs that will be
6589 * called after a specific object was destroyed by garbage collection. See
6590 * the documentation for +ObjectSpace.define_finalizer+ for important
6591 * information on how to use this method correctly.
6592 *
6593 * a = "A"
6594 * b = "B"
6595 *
6596 * ObjectSpace.define_finalizer(a, proc {|id| puts "Finalizer one on #{id}" })
6597 * ObjectSpace.define_finalizer(b, proc {|id| puts "Finalizer two on #{id}" })
6598 *
6599 * a = nil
6600 * b = nil
6601 *
6602 * _produces:_
6603 *
6604 * Finalizer two on 537763470
6605 * Finalizer one on 537763480
6606 */
6607
6608#include "gc.rbinc"
6609
6610void
6611Init_GC(void)
6612{
6613#ifdef RUBY_NO_FREE
6614 const char* nofree_str = getenv("RUBY_NO_FREE");
6615 if (nofree_str && strcmp(nofree_str, "1") == 0) {
6616 fprintf(stderr, "WARNING: Enabling no-free mode! xfree() will never free anything!\n");
6617 g_nofree = true;
6618 }
6619#endif
6620
6621#undef rb_intern
6622 malloc_offset = gc_compute_malloc_offset();
6623
6624 rb_mGC = rb_define_module("GC");
6625
6626 VALUE rb_mObjSpace = rb_define_module("ObjectSpace");
6627
6628 rb_define_module_function(rb_mObjSpace, "each_object", os_each_obj, -1);
6629
6630 rb_define_module_function(rb_mObjSpace, "define_finalizer", define_final, -1);
6631 rb_define_module_function(rb_mObjSpace, "undefine_finalizer", undefine_final, 1);
6632
6633 rb_vm_register_special_exception(ruby_error_nomemory, rb_eNoMemError, "failed to allocate memory");
6634
6635 rb_define_method(rb_cBasicObject, "__id__", rb_obj_id, 0);
6636 rb_define_method(rb_mKernel, "object_id", rb_obj_id, 0);
6637
6638 rb_define_module_function(rb_mObjSpace, "count_objects", count_objects, -1);
6639
6640 rb_gc_impl_init();
6641}
6642
6643// Set a name for the anonymous virtual memory area. `addr` is the starting
6644// address of the area and `size` is its length in bytes. `name` is a
6645// NUL-terminated human-readable string.
6646//
6647// This function is usually called after calling `mmap()`. The human-readable
6648// annotation helps developers identify the call site of `mmap()` that created
6649// the memory mapping.
6650//
6651// This function currently only works on Linux 5.17 or higher. After calling
6652// this function, we can see annotations in the form of "[anon:...]" in
6653// `/proc/self/maps`, where `...` is the content of `name`. This function has
6654// no effect when called on other platforms.
6655void
6656ruby_annotate_mmap(const void *addr, unsigned long size, const char *name)
6657{
6658#if defined(HAVE_SYS_PRCTL_H) && defined(PR_SET_VMA) && defined(PR_SET_VMA_ANON_NAME)
6659 // The name length cannot exceed 80 (including the '\0').
6660 RUBY_ASSERT(strlen(name) < 80);
6661 prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME, (unsigned long)addr, size, name);
6662 // We ignore errors in prctl. prctl may set errno to EINVAL for several
6663 // reasons.
6664 // 1. The attr (PR_SET_VMA_ANON_NAME) is not a valid attribute.
6665 // 2. addr is an invalid address.
6666 // 3. The string pointed by name is too long.
6667 // The first error indicates PR_SET_VMA_ANON_NAME is not available, and may
6668 // happen if we run the compiled binary on an old kernel. In theory, all
6669 // other errors should result in a failure. But since EINVAL cannot tell
6670 // the first error from others, and this function is mainly used for
6671 // debugging, we silently ignore the error.
6672 errno = 0;
6673#endif
6674}
#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:3380
#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 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:905
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 rb_io_fptr_finalize(rb_io_t *fptr)
Destroys the given IO.
Definition io.c:5789
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:9158
#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:6155
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