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