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