Ruby 4.1.0dev (2026-09-27 revision f6ff9e7d02e46360f8930b280a3dd921cccbda29)
ractor.c (f6ff9e7d02e46360f8930b280a3dd921cccbda29)
1// Ractor implementation
2
3#include "ruby/ruby.h"
4#include "ruby/thread.h"
5#include "ruby/ractor.h"
6#include "ruby/re.h"
8#include "vm_core.h"
9#include "vm_sync.h"
10#include "ractor_core.h"
11#include "internal/array.h"
12#include "internal/class.h"
13#include "internal/complex.h"
14#include "internal/cont.h"
15#include "internal/error.h"
16#include "internal/gc.h"
17#include "internal/hash.h"
18#include "internal/object.h"
19#include "internal/array.h"
20#include "internal/string.h"
21#include "internal/variable.h"
22#include "eval_intern.h"
23#include "internal/io.h"
24#include "internal/marshal.h"
25#include "internal/ractor.h"
26#include "internal/rational.h"
27#include "internal/re.h"
28#include "internal/struct.h"
29#include "internal/st.h"
30#include "internal/thread.h"
31#include "internal/vm.h"
32#include "ruby/encoding.h"
33#include "variable.h"
34#include "shape.h"
35#include "yjit.h"
36#include "zjit.h"
37
39static VALUE rb_cRactorSelector;
40
41VALUE rb_eRactorUnsafeError;
42VALUE rb_eRactorIsolationError;
43static VALUE rb_eRactorError;
44static VALUE rb_eRactorRemoteError;
45static VALUE rb_eRactorMovedError;
46static VALUE rb_eRactorClosedError;
47static VALUE rb_cRactorMovedObject;
48
49static ID id_marshal_dump, id_marshal_load;
50static ID id_dump, id_load, id_dump_data, id_load_data;
51
52static void vm_ractor_blocking_cnt_inc(rb_vm_t *vm, rb_ractor_t *r, const char *file, int line);
53
54
55#if RACTOR_CHECK_MODE > 0
56bool rb_ractor_ignore_belonging_flag = false;
57#endif
58
59// Ractor locking
60
61static void
62ASSERT_ractor_unlocking(rb_ractor_t *r)
63{
64#if RACTOR_CHECK_MODE > 0
65 const rb_execution_context_t *ec = rb_current_ec_noinline();
66 if (ec != NULL && r->sync.locked_by == rb_ractor_self(rb_ec_ractor_ptr(ec))) {
67 rb_bug("recursive ractor locking");
68 }
69#endif
70}
71
72static void
73ASSERT_ractor_locking(rb_ractor_t *r)
74{
75#if RACTOR_CHECK_MODE > 0
76 const rb_execution_context_t *ec = rb_current_ec_noinline();
77 if (ec != NULL && r->sync.locked_by != rb_ractor_self(rb_ec_ractor_ptr(ec))) {
78 rp(r->sync.locked_by);
79 rb_bug("ractor lock is not acquired.");
80 }
81#endif
82}
83
84static void
85ractor_lock(rb_ractor_t *r, const char *file, int line)
86{
87 RUBY_DEBUG_LOG2(file, line, "locking r:%"PRI_SERIALT_PREFIX"u%s", r->pub.id, rb_current_ractor_raw(false) == r ? " (self)" : "");
88
89 ASSERT_ractor_unlocking(r);
90 rb_native_mutex_lock(&r->sync.lock);
91
92 const rb_execution_context_t *ec = rb_current_ec_noinline();
93 if (ec) {
94 rb_ractor_t *cr = rb_ec_ractor_ptr(ec);
95 VM_ASSERT(!cr->malloc_gc_disabled);
96 cr->malloc_gc_disabled = true;
97 }
98
99#if RACTOR_CHECK_MODE > 0
100 if (ec != NULL) {
101 rb_ractor_t *cr = rb_ec_ractor_ptr(ec);
102 r->sync.locked_by = rb_ractor_self(cr);
103 }
104#endif
105
106 RUBY_DEBUG_LOG2(file, line, "locked r:%"PRI_SERIALT_PREFIX"u%s", r->pub.id, rb_current_ractor_raw(false) == r ? " (self)" : "");
107}
108
109static void
110ractor_lock_self(rb_ractor_t *cr, const char *file, int line)
111{
112 VM_ASSERT(cr == rb_ec_ractor_ptr(rb_current_ec_noinline()));
113#if RACTOR_CHECK_MODE > 0
114 VM_ASSERT(cr->sync.locked_by != cr->pub.self);
115#endif
116 ractor_lock(cr, file, line);
117}
118
119static void
120ractor_unlock(rb_ractor_t *r, const char *file, int line)
121{
122 ASSERT_ractor_locking(r);
123#if RACTOR_CHECK_MODE > 0
124 r->sync.locked_by = Qnil;
125#endif
126
127 const rb_execution_context_t *ec = rb_current_ec_noinline();
128 if (ec) {
129 rb_ractor_t *cr = rb_ec_ractor_ptr(ec);
130 VM_ASSERT(cr->malloc_gc_disabled);
131 cr->malloc_gc_disabled = false;
132 }
133
134 rb_native_mutex_unlock(&r->sync.lock);
135
136 RUBY_DEBUG_LOG2(file, line, "r:%"PRI_SERIALT_PREFIX"u%s", r->pub.id, rb_current_ractor_raw(false) == r ? " (self)" : "");
137}
138
139static void
140ractor_unlock_self(rb_ractor_t *cr, const char *file, int line)
141{
142 VM_ASSERT(cr == rb_ec_ractor_ptr(rb_current_ec_noinline()));
143#if RACTOR_CHECK_MODE > 0
144 VM_ASSERT(cr->sync.locked_by == cr->pub.self);
145#endif
146 ractor_unlock(cr, file, line);
147}
148
149#define RACTOR_LOCK(r) ractor_lock(r, __FILE__, __LINE__)
150#define RACTOR_UNLOCK(r) ractor_unlock(r, __FILE__, __LINE__)
151#define RACTOR_LOCK_SELF(r) ractor_lock_self(r, __FILE__, __LINE__)
152#define RACTOR_UNLOCK_SELF(r) ractor_unlock_self(r, __FILE__, __LINE__)
153
154void
155rb_ractor_lock_self(rb_ractor_t *r)
156{
157 RACTOR_LOCK_SELF(r);
158}
159
160void
161rb_ractor_unlock_self(rb_ractor_t *r)
162{
163 RACTOR_UNLOCK_SELF(r);
164}
165
166// Ractor status
167
168static const char *
169ractor_status_str(enum ractor_status status)
170{
171 switch (status) {
172 case ractor_created: return "created";
173 case ractor_running: return "running";
174 case ractor_blocking: return "blocking";
175 case ractor_terminated: return "terminated";
176 }
177 rb_bug("unreachable");
178}
179
180static void
181ractor_status_set(rb_ractor_t *r, enum ractor_status status)
182{
183 RUBY_DEBUG_LOG("r:%"PRI_SERIALT_PREFIX"u [%s]->[%s]", r->pub.id, ractor_status_str(r->status_), ractor_status_str(status));
184
185 // check 1
186 if (r->status_ != ractor_created) {
187 VM_ASSERT(r == GET_RACTOR()); // only self-modification is allowed.
188 ASSERT_vm_locking();
189 }
190
191 // check2: transition check. assume it will be vanished on non-debug build.
192 switch (r->status_) {
193 case ractor_created:
194 VM_ASSERT(status == ractor_blocking);
195 break;
196 case ractor_running:
197 VM_ASSERT(status == ractor_blocking||
198 status == ractor_terminated);
199 break;
200 case ractor_blocking:
201 VM_ASSERT(status == ractor_running);
202 break;
203 case ractor_terminated:
204 rb_bug("unreachable");
205 break;
206 }
207
208 r->status_ = status;
209}
210
211static bool
212ractor_status_p(rb_ractor_t *r, enum ractor_status status)
213{
214 return rb_ractor_status_p(r, status);
215}
216
217// Ractor data/mark/free
218
219static void ractor_local_storage_mark(rb_ractor_t *r);
220static void ractor_local_storage_free(rb_ractor_t *r);
221
222static void ractor_sync_mark(rb_ractor_t *r);
223static void ractor_sync_free(rb_ractor_t *r);
224static size_t ractor_sync_memsize(const rb_ractor_t *r);
225static void ractor_sync_init(rb_ractor_t *r);
226
227static int
228mark_targeted_hook_list(st_data_t key, st_data_t value, st_data_t _arg)
229{
230 rb_hook_list_t *hook_list = (rb_hook_list_t*)value;
231
232 if (hook_list->type == hook_list_type_targeted_iseq) {
233 rb_gc_mark((VALUE)key);
234 }
235 else {
237 RUBY_ASSERT(hook_list->type == hook_list_type_targeted_def);
238 rb_gc_mark(def->body.bmethod.proc);
239 }
240 rb_hook_list_mark(hook_list);
241
242 return ST_CONTINUE;
243}
244
245static void
246ractor_mark_thread(rb_thread_t *th)
247{
248 rb_gc_mark(th->self);
249
250 /* A thread's ec lives inside the root fiber struct and is freed with that
251 * fiber's wrapper object, so keep the fiber wrappers alive from here too. */
252 if (th->root_fiber) {
253 VALUE root_fiber_self = rb_fiberptr_self(th->root_fiber);
254 if (root_fiber_self) rb_gc_mark(root_fiber_self);
255 }
256 /* The ec sits inside its fiber, so marking that fiber's wrapper scans the ec
257 * as well. Only when there is no wrapper yet (mid-creation, teardown) does
258 * the ec need marking of its own. */
259 VALUE ec_fiber_self = (th->ec && th->ec->fiber_ptr) ? rb_fiberptr_self(th->ec->fiber_ptr) : 0;
260 if (ec_fiber_self) {
261 rb_gc_mark(ec_fiber_self);
262 }
263 else if (th->ec) {
264 rb_execution_context_mark(th->ec);
265 }
266
267 /* Root the thread's remaining possessions directly as well; thgroup in
268 * particular has no other root. */
269 rb_thread_mark_owned_roots(th);
270}
271
272static void
273ractor_mark_unshareable_parts(rb_ractor_t *r)
274{
275 /* A single VALUE slot written by the owner in one word, so any GC reads it safely.
276 * Its target belongs to another Ractor, so containment makes a foreign marker skip
277 * it. */
278 rb_gc_mark(r->r_stdin);
279 rb_gc_mark(r->r_stdout);
280 rb_gc_mark(r->r_stderr);
281 rb_gc_mark(r->verbose);
282 rb_gc_mark(r->debug);
283
284 // mark the received messages (the structures the owner mutates guard themselves)
285 ractor_sync_mark(r);
286
287 /* Structures the owner mutates while running follow. */
288
289 rb_hook_list_mark(&r->pub.hooks);
290 if (r->pub.targeted_hooks.num_entries) {
291 st_foreach(&r->pub.targeted_hooks, mark_targeted_hook_list, 0);
292 }
293
294 if (r->threads.cnt > 0) {
295 rb_thread_t *th = 0;
296 ccan_list_for_each(&r->threads.set, th, lt_node) {
297 VM_ASSERT(th != NULL);
298 ractor_mark_thread(th);
299 }
300 }
301
302 /* A thread in the MN termination epilogue has left the set but is still
303 * running on its coroutine stack; it stays a root until its last use.
304 * Read once: the epilogue clears the slot concurrently. The thread is
305 * past rb_fiber_close/thread_cleanup_func by then -- the same state
306 * thread_mark walks whenever a terminated Thread's wrapper is still
307 * referenced, and ractor_mark_thread performs the same marks. */
308 rb_thread_t *dying_th = RUBY_ATOMIC_PTR_LOAD(r->threads.dying_th);
309 if (dying_th) ractor_mark_thread(dying_th);
310
311 ractor_local_storage_mark(r);
312}
313
314static void
315ractor_mark(void *ptr)
316{
317 rb_ractor_t *r = (rb_ractor_t *)ptr;
318
319 /* Only the wrapper's direct references: following an unshareable object from the
320 * shareable wrapper would break the shref rule. Unshareable roots are marked by the
321 * root scan (rb_ractor_mark_local_roots); zombie_objspaces covers the terminated. */
322 rb_gc_mark(r->loc);
323 rb_gc_mark(r->name);
324 /* The default port is shareable, so following it breaks no rule. Other Ractors
325 * still send/value through it after termination, and once a terminated Ractor left
326 * both the set and zombie_objspaces (orphan-merged) this marker is its only cover. */
327 rb_gc_mark(r->sync.default_port_value);
328 /* A single-objspace impl (mmtk) has no zombie_objspaces and no pin/shref bits, so
329 * the root scan cannot reach a terminated Ractor's queue, in-flight payloads or
330 * join value; and no shref rule forbids following them from the wrapper. */
331 if (!rb_gc_multi_objspace_p()) {
332 ractor_mark_unshareable_parts(r);
333 rb_ractor_mark_terminated_join_value(r);
334 }
335 else if (rb_gc_during_global_gc_p()) {
336 /* The join value is only of use to whoever can still call Ractor#value, which
337 * means holding this wrapper, so mark it as the wrapper's child rather than as a
338 * root. A global GC stops the world and marks every objspace together, which is
339 * what lets the shareable wrapper reach an unshareable value at all. */
340 rb_ractor_mark_terminated_join_value(r);
341 }
342}
343
344/* Mark the GC roots reachable from Ractor r's C structs. A local GC cannot rely on the
345 * heap Ractor and Thread wrapper objects, which may live in another objspace, so this
346 * Ractor's own possessions are rooted directly from here. */
347void
348rb_ractor_mark_local_roots(rb_ractor_t *r)
349{
350 if (r->postmortem) {
351 /* The final self collection: everything else -- the Thread and Fiber
352 * wrappers, stdio, stack leftovers -- is what it exists to reclaim.
353 * Skipping the walk below cannot drop dying_th: postmortem runs on the
354 * Ractor's last thread, which can only run after any predecessor's
355 * epilogue cleared the slot (under the same scheduler lock). */
356 VM_ASSERT(RUBY_ATOMIC_PTR_LOAD(r->threads.dying_th) == NULL);
357 rb_ractor_mark_terminated_join_value(r);
358 rb_gc_mark_vm_stack_values((long)r->registered_marks_cnt, r->registered_marks);
359 rb_gc_mark_registered_addrs(r, true);
360 return;
361 }
362
363 rb_gc_mark(r->loc);
364 rb_gc_mark(r->name);
365 /* Only the root scan calls this: a local GC for itself, a global GC for the whole
366 * set under the barrier. A terminated Ractor has left the set; zombie_objspaces
367 * covers it instead. */
368 VM_ASSERT(r == rb_current_ractor_raw(false) || rb_gc_during_global_gc_p());
369 VM_ASSERT(!rb_ractor_status_p(r, ractor_terminated));
370 ractor_mark_unshareable_parts(r);
371
372 /* This Ractor's rb_gc_register_mark_object pins, treated conservatively: a local GC
373 * marks only its own residents and leaves foreign or shareable entries to their
374 * owner or to the global GC. */
375 rb_gc_mark_vm_stack_values((long)r->registered_marks_cnt, r->registered_marks);
376}
377
378/* Mark and pin a terminated, unfreed Ractor's return value (legacy); the global GC
379 * calls this via zombie_objspaces. Pinned because compaction does not update C-struct
380 * slots. The default port is covered by the mutual wrapper/port marking instead. */
381void
382rb_ractor_mark_terminated_join_value(rb_ractor_t *r)
383{
384 VALUE slots[] = {
385 r->sync.legacy,
386 };
387 rb_gc_mark_vm_stack_values((long)numberof(slots), slots);
388}
389
390/* Move src's rb_gc_register_mark_object pins to dst. Called before merging src's
391 * objspace into dst, so a pinned object never loses its root in between. An absorb can
392 * run during a GC sweep, so plain realloc keeps it from re-entering GC. */
393void
394rb_ractor_absorb_registered_marks(rb_ractor_t *dst, rb_ractor_t *src)
395{
396 if (src->registered_marks_cnt == 0) return;
397 size_t need = dst->registered_marks_cnt + src->registered_marks_cnt;
398 if (need > dst->registered_marks_capa) {
399 size_t nc = dst->registered_marks_capa ? dst->registered_marks_capa : 64;
400 while (nc < need) nc *= 2;
401 VALUE *p = realloc(dst->registered_marks, nc * sizeof(VALUE));
402 if (!p) rb_bug("rb_ractor_absorb_registered_marks: out of memory");
403 dst->registered_marks = p;
404 dst->registered_marks_capa = nc;
405 }
406 MEMCPY(dst->registered_marks + dst->registered_marks_cnt,
407 src->registered_marks, VALUE, src->registered_marks_cnt);
408 dst->registered_marks_cnt = need;
409 src->registered_marks_cnt = 0;
410}
411
412void
413rb_ractor_absorb_registered_addrs_without_gc(rb_ractor_t *dst, rb_ractor_t *src)
414{
415 rb_vm_t *vm = GET_VM();
416
417 rb_native_mutex_lock(&vm->gc.registered_addrs.lock);
418 if (src->registered_addrs_cnt > 0) {
419 size_t need = dst->registered_addrs_cnt + src->registered_addrs_cnt;
420 if (need > dst->registered_addrs_capa) {
421 size_t nc = dst->registered_addrs_capa ? dst->registered_addrs_capa : 64;
422 while (nc < need) nc *= 2;
423 struct rb_ractor_registered_addr *p =
424 realloc(dst->registered_addrs, nc * sizeof(struct rb_ractor_registered_addr));
425 if (!p) rb_bug("rb_ractor_absorb_registered_addrs_without_gc: out of memory");
426 dst->registered_addrs = p;
427 dst->registered_addrs_capa = nc;
428 }
429 MEMCPY(dst->registered_addrs + dst->registered_addrs_cnt,
430 src->registered_addrs, struct rb_ractor_registered_addr, src->registered_addrs_cnt);
431 dst->registered_addrs_cnt = need;
432 src->registered_addrs_cnt = 0;
433 rb_gc_registered_addrs_enroll_without_gc(vm, dst);
434 }
435 rb_gc_registered_addrs_unenroll_without_gc(vm, src);
436 rb_native_mutex_unlock(&vm->gc.registered_addrs.lock);
437}
438
439static int
440free_targeted_hook_lists(st_data_t key, st_data_t val, st_data_t _arg)
441{
442 rb_hook_list_t *hook_list = (rb_hook_list_t*)val;
443 rb_hook_list_free(hook_list);
444 return ST_DELETE;
445}
446
447static void
448free_targeted_hooks(st_table *hooks_tbl)
449{
450 st_foreach(hooks_tbl, free_targeted_hook_lists, 0);
451}
452
453void rb_thread_sched_destroy(struct rb_thread_sched *);
454
455static void
456ractor_free(void *ptr)
457{
458 rb_ractor_t *r = (rb_ractor_t *)ptr;
459 RUBY_DEBUG_LOG("free r:%"PRI_SERIALT_PREFIX"u", rb_ractor_id(r));
460
461 free_targeted_hooks(&r->pub.targeted_hooks);
462 rb_thread_sched_destroy(&r->threads.sched);
463 rb_native_mutex_destroy(&r->sync.lock);
464 ractor_local_storage_free(r);
465 rb_hook_list_free(&r->pub.hooks);
466 rb_st_free_embedded_table(&r->pub.targeted_hooks);
467
468 if (r->newobj_cache) {
469 RUBY_ASSERT(r == ruby_single_main_ractor);
470
471 rb_gc_ractor_cache_free(r->newobj_cache);
472 r->newobj_cache = NULL;
473 }
474
475 /* Died unjoined and the handle is collected: nobody can inherit it. We are in a
476 * sweep under the global GC barrier, so disown the zombie_objspaces entry and post
477 * the merge to main. main itself only gets here in the free-at-exit walk: leave it
478 * and its objspace to VM destruct. */
479 if (r->objspace && !r->main_ractor) {
480 rb_gc_objspace_disown(r->objspace);
481 r->objspace = NULL;
482 }
483
484 ractor_sync_free(r);
485
486 if (r->in_terminated_set) {
487 rb_native_mutex_lock(&GET_VM()->gc.registered_addrs.lock);
488 ccan_list_del(&r->vmlr_node);
489 r->in_terminated_set = false;
490 rb_native_mutex_unlock(&GET_VM()->gc.registered_addrs.lock);
491 }
492
493 /* An orphan (unjoined) Ractor hands its rb_gc_register_mark_object pins to main
494 * before its objspace is absorbed; the join path does the same for the joiner.
495 * Both happen before the objspace merge, so no window has unmoved registrations. */
496 if (!r->main_ractor) {
497 rb_ractor_absorb_registered_marks(GET_VM()->ractor.main_ractor, r);
498 rb_ractor_absorb_registered_addrs_without_gc(GET_VM()->ractor.main_ractor, r);
499 }
500 else {
501 rb_native_mutex_lock(&GET_VM()->gc.registered_addrs.lock);
502 rb_gc_registered_addrs_unenroll_without_gc(GET_VM(), r);
503 rb_native_mutex_unlock(&GET_VM()->gc.registered_addrs.lock);
504 }
505 free(r->registered_marks);
506 r->registered_marks = NULL;
507 r->registered_marks_cnt = r->registered_marks_capa = 0;
508
509 free(r->registered_addrs);
510 r->registered_addrs = NULL;
511 r->registered_addrs_cnt = r->registered_addrs_capa = 0;
512
513 if (!r->main_ractor) {
514 SIZED_FREE(r);
515 }
516}
517
518static size_t
519ractor_memsize(const void *ptr)
520{
521 rb_ractor_t *r = (rb_ractor_t *)ptr;
522
523 // TODO: more correct?
524 return sizeof(rb_ractor_t) + ractor_sync_memsize(r);
525}
526
527static void
528ractor_update_references(void *ptr)
529{
530 /* registered_marks are pinned (marked by rb_gc_mark_vm_stack_values), so
531 * compaction does not need to update them. */
532}
533
534static const rb_data_type_t ractor_data_type = {
535 "ractor",
536 {
537 ractor_mark,
538 ractor_free,
539 ractor_memsize,
540 ractor_update_references,
541 },
542 0, 0, RUBY_TYPED_FREE_IMMEDIATELY /* | RUBY_TYPED_WB_PROTECTED */
543};
544
545bool
546rb_ractor_p(VALUE gv)
547{
548 if (rb_typeddata_is_kind_of(gv, &ractor_data_type)) {
549 return true;
550 }
551 else {
552 return false;
553 }
554}
555
556static inline rb_ractor_t *
557RACTOR_PTR(VALUE self)
558{
559 VM_ASSERT(rb_ractor_p(self));
560 rb_ractor_t *r = DATA_PTR(self);
561 return r;
562}
563
564#define MAIN_RACTOR_ID 1
565static rb_serial_t ractor_last_id = MAIN_RACTOR_ID;
566
567#include "ractor_sync.c"
568
569// creation/termination
570
571/* Ids are never reused, so they must not wrap either: 64 bits, which rules out an
572 * atomic (there is no portable 64-bit one). Serialized by the VM lock, or by the
573 * GVL before there is a second Ractor to take it against -- the same condition
574 * vm_insert_ractor0 asserts. */
575static rb_serial_t
576ractor_next_id(void)
577{
578 VM_ASSERT(RB_VM_LOCKED_P() || !rb_multi_ractor_p());
579 return ++ractor_last_id;
580}
581
582static void
583vm_insert_ractor0(rb_vm_t *vm, rb_ractor_t *r, bool single_ractor_mode)
584{
585 RUBY_DEBUG_LOG("r:%"PRI_SERIALT_PREFIX"u ractor.cnt:%u++", r->pub.id, vm->ractor.cnt);
586 VM_ASSERT(single_ractor_mode || RB_VM_LOCKED_P());
587
588 /* End main's cycle before a second Ractor becomes visible: the collection was
589 * planned for a single-objspace world (a local GC is a whole-world GC there and may
590 * free shareable objects), so it must not straddle the transition. */
591 if (vm->ractor.cnt == 1) {
592 rb_gc_rest();
593 }
594
595 ccan_list_add_tail(&vm->ractor.set, &r->vmlr_node);
596 vm->ractor.cnt++;
597
598 if (r->newobj_cache) {
599 VM_ASSERT(r == ruby_single_main_ractor);
600 }
601 else {
602 r->newobj_cache = rb_gc_ractor_cache_alloc(r);
603 }
604}
605
606static void
607cancel_single_ractor_mode(void)
608{
609 // enable multi-ractor mode
610 RUBY_DEBUG_LOG("enable multi-ractor mode");
611
612 ruby_single_main_ractor = NULL;
613 rb_yjit_invalidate_single_ractor();
614 rb_zjit_invalidate_single_ractor();
615
616 ASSERT_vm_unlocking();
617 rb_funcall(rb_cRactor, rb_intern("_activated"), 0);
618}
619
620static void
621vm_insert_ractor(rb_vm_t *vm, rb_ractor_t *r)
622{
623 VM_ASSERT(ractor_status_p(r, ractor_created));
624
625 if (rb_multi_ractor_p()) {
626 RB_VM_LOCK();
627 {
628 vm_insert_ractor0(vm, r, false);
629 vm_ractor_blocking_cnt_inc(vm, r, __FILE__, __LINE__);
630 /* The child is in the set and enumerated on its own now, so drop the cover
631 * through its creator and avoid enumerating it twice. Cleared under the
632 * same VM lock that added it, so no whole-VM walk sees both. */
633 rb_ractor_t *cur = rb_current_ractor_raw(false);
634 if (cur && cur->creating_child_objspace == r->objspace) {
635 cur->creating_child_objspace = NULL;
636 }
637 }
638 RB_VM_UNLOCK();
639 }
640 else {
641 if (vm->ractor.cnt == 0) {
642 // main ractor
643 vm_insert_ractor0(vm, r, true);
644 ractor_status_set(r, ractor_blocking);
645 ractor_status_set(r, ractor_running);
646 }
647 else {
648 cancel_single_ractor_mode();
649 vm_insert_ractor0(vm, r, true);
650 vm_ractor_blocking_cnt_inc(vm, r, __FILE__, __LINE__);
651 /* As in the multi-Ractor branch: the child joined the set, so drop the
652 * creator's cover, or a global GC enumerates the child's objspace twice and
653 * sweeps its live main Thread and root Fiber. */
654 rb_ractor_t *cur = rb_current_ractor_raw(false);
655 if (cur && cur->creating_child_objspace == r->objspace) {
656 cur->creating_child_objspace = NULL;
657 }
658 }
659 }
660}
661
662static void
663vm_remove_ractor(rb_vm_t *vm, rb_ractor_t *cr)
664{
665 VM_ASSERT(ractor_status_p(cr, ractor_running));
666 VM_ASSERT(vm->ractor.cnt > 1);
667 VM_ASSERT(cr->threads.cnt == 1);
668
669 RB_VM_LOCK();
670 {
671 RUBY_DEBUG_LOG("ractor.cnt:%u-- terminate_waiting:%d",
672 vm->ractor.cnt, vm->ractor.sync.terminate_waiting);
673
674 VM_ASSERT(vm->ractor.cnt > 0);
675 ccan_list_del(&cr->vmlr_node);
676
677 /* A single-objspace impl has no zombie_objspaces, so nothing roots the
678 * registered_marks of a Ractor that left the set; track it in a separate list
679 * until ractor_free. */
680 if (!rb_gc_multi_objspace_p()) {
681 rb_native_mutex_lock(&vm->gc.registered_addrs.lock);
682 ccan_list_add(&vm->ractor.terminated_set, &cr->vmlr_node);
683 cr->in_terminated_set = true;
684 rb_native_mutex_unlock(&vm->gc.registered_addrs.lock);
685 }
686
687 if (vm->ractor.cnt <= 2 && vm->ractor.sync.terminate_waiting) {
688 rb_native_cond_signal(&vm->ractor.sync.terminate_cond);
689 }
690
691 rb_gc_ractor_cache_free(cr->newobj_cache);
692 cr->newobj_cache = NULL;
693
694 /* The objspace loses its owning thread: keep it enumerable until inheritance
695 * merges it. Register in zombie_objspaces BEFORE decrementing cnt: other
696 * Ractors read rb_gc_single_objspace_p lock-free, and the other order opens a
697 * cnt==1-no-zombie window where a GC skips shareable pinning and collects
698 * objects (a cc, say) reachable only through this objspace. */
699 if (cr->objspace) {
700 /* The final self collection already ran (ractor_postmortem_collect),
701 * so the entry measures exactly the pages the joiner will inherit. */
702 rb_gc_objspace_retire(&cr->objspace);
703 }
704 vm->ractor.cnt--;
705
706 ractor_status_set(cr, ractor_terminated);
707 }
708 RB_VM_UNLOCK();
709}
710
711/* The dying thread's final collection of its own objspace, and the capture of what it
712 * must free itself. Called with the GVL still held: a concurrent global GC waits for
713 * this thread's safepoint, so the collection is lock-free like any local GC. */
714static void
715ractor_postmortem_collect(rb_thread_t *th, struct rb_ractor_postmortem_frees *pf)
716{
717 rb_ractor_t *const cr = th->ractor;
718 VM_ASSERT(cr != GET_VM()->ractor.main_ractor);
719 VM_ASSERT(th->ec != NULL);
720
721 struct rb_fiber_struct *const fiber = th->ec->fiber_ptr;
722 const bool fiber_wrapped = fiber && rb_fiberptr_self(fiber) != 0;
723
724 /* With a thread-event hook registered the callbacks may retain any Ractor's Thread
725 * object (rb_internal_thread_event_hook_t), and such references are invisible to
726 * the reduced roots: keep the ordinary retire roots, wrappers survive to absorb. */
727 cr->postmortem = rb_gc_multi_objspace_p() && !rb_thread_event_hooks_registered_p();
728 rb_gc_objspace_postmortem_self();
729
730 /* Only what this collection provably swept (wrapper gone, struct deferred with an
731 * in-band mark) may be touched after vm_remove_ractor unlinks the Ractor. */
732 pf->th = (th->self == 0) ? th : NULL;
733 pf->fiber = (fiber_wrapped && rb_fiberptr_self(fiber) == 0) ? fiber : NULL;
734}
735
736void
737rb_ractor_postmortem_free(const struct rb_ractor_postmortem_frees *pf)
738{
739 if (pf->fiber == NULL && pf->th == NULL) return;
740
741 /* The frees below resolve their objspace through the TLS ec, which sits inside
742 * pf->fiber and leads to the retired Ractor: cut the resolution off so they fall
743 * back to the main objspace. (The MN epilogue has already done this.) */
744#ifdef RB_THREAD_LOCAL_SPECIFIER
745 rb_current_ec_set(NULL);
746#else
747 native_tls_set(ruby_current_ec_key, NULL);
748#endif
749
750 /* the fiber struct embeds the thread's final ec, so free it first */
751 if (pf->fiber) rb_fiber_free_body(pf->fiber);
752 if (pf->th) rb_thread_free_body(pf->th);
753}
754
755static VALUE
756ractor_alloc(VALUE klass)
757{
758 rb_ractor_t *r;
759 VALUE rv = TypedData_Make_Struct(klass, rb_ractor_t, &ractor_data_type, r);
761 r->pub.self = rv;
762 r->next_ec_serial = 1;
763 VM_ASSERT(ractor_status_p(r, ractor_created));
764 return rv;
765}
766
767static rb_ractor_t _main_ractor = {
768 .loc = Qnil,
769 .name = Qnil,
770 .pub.id = MAIN_RACTOR_ID,
771 .pub.self = Qnil,
772 .next_ec_serial = 1,
773 .main_ractor = true,
774};
775
777rb_ractor_main_alloc(void)
778{
779 rb_ractor_t *r = &_main_ractor;
780 /* The main Ractor is allocated before its objspace exists, so its newobj cache is
781 * created later in Init_BareVM, once rb_gc_init_objspaces has set r->objspace. */
782 ruby_single_main_ractor = r;
783
784 return r;
785}
786
787#if defined(HAVE_WORKING_FORK)
788// Set up the main Ractor for the VM after fork.
789// Puts us in "single Ractor mode"
790void
791rb_ractor_atfork(rb_vm_t *vm, rb_thread_t *th)
792{
793 // initialize as a main ractor
794 vm->ractor.cnt = 0;
795 vm->ractor.blocking_cnt = 0;
796 /* Only main survives a fork: the holds of dead Ractors and of critical sections are
797 * gone, leaving main's own disable. */
798 rb_gc_disable_holders_atfork();
799 /* Only the main Ractor survives a fork, so drop the creation cover. The set was
800 * just emptied by rb_vm_living_threads_init, and zombie_objspaces still holds the
801 * non-main objspaces that terminate_atfork parked there for the orphan merge. */
802 th->ractor->creating_child_objspace = NULL;
803 ruby_single_main_ractor = th->ractor;
804 th->ractor->status_ = ractor_created;
805
806 rb_ractor_living_threads_init(th->ractor);
807 rb_ractor_living_threads_insert(th->ractor, th);
808
809 VM_ASSERT(vm->ractor.blocking_cnt == 0);
810 VM_ASSERT(vm->ractor.cnt == 1);
811}
812
813void
814rb_ractor_terminate_atfork(rb_vm_t *vm, rb_ractor_t *r)
815{
816 rb_gc_ractor_cache_free(r->newobj_cache);
817 r->newobj_cache = NULL;
818 r->status_ = ractor_terminated;
819 // a termination epilogue in the parent did not survive the fork
820 r->threads.dying_th = NULL;
821 if (!rb_gc_multi_objspace_p()) {
822 ccan_list_del(&r->vmlr_node);
823 ccan_list_add(&vm->ractor.terminated_set, &r->vmlr_node);
824 r->in_terminated_set = true;
825 }
826
827 /* In a forked child every other Ractor is terminated-unjoined, so keep its objspace
828 * enumerable until a join or a global GC merges it. */
829 if (r->objspace) {
830 rb_gc_objspace_retire(&r->objspace);
831 }
832 ractor_sync_terminate_atfork(vm, r);
833}
834#endif
835
836void rb_thread_sched_init(struct rb_thread_sched *, bool atfork);
837
838void
839rb_ractor_living_threads_init(rb_ractor_t *r)
840{
841 ccan_list_head_init(&r->threads.set);
842 r->threads.cnt = 0;
843 r->threads.blocking_cnt = 0;
844 r->threads.terminating = false;
845 // atfork: a sibling's termination epilogue did not survive the fork
846 r->threads.dying_th = NULL;
847}
848
849static void
850ractor_init(rb_ractor_t *r, VALUE name, VALUE loc)
851{
852 ractor_sync_init(r);
853 st_init_existing_numtable_with_size(&r->pub.targeted_hooks, 0);
854 r->pub.hooks.type = hook_list_type_ractor_local;
855
856 // thread management
857 rb_thread_sched_init(&r->threads.sched, false);
858 rb_ractor_living_threads_init(r);
859
860 // naming
861 if (!NIL_P(name)) {
862 rb_encoding *enc;
863 StringValueCStr(name);
864 enc = rb_enc_get(name);
865 if (!rb_enc_asciicompat(enc)) {
866 rb_raise(rb_eArgError, "ASCII incompatible encoding (%s)",
867 rb_enc_name(enc));
868 }
870 }
871
873 r->loc = loc;
874 r->name = name;
875}
876
877void
878rb_ractor_main_setup(rb_vm_t *vm, rb_ractor_t *r, rb_thread_t *th)
879{
880 VALUE rv = r->pub.self = TypedData_Wrap_Struct(rb_cRactor, &ractor_data_type, r);
881 RB_OBJ_SET_SHAREABLE(r->pub.self);
882 ractor_init(r, Qnil, Qnil);
883 r->threads.main = th;
884 rb_ractor_living_threads_insert(r, th);
885 rb_ractor_setup_default_port(r);
886
887 RB_GC_GUARD(rv);
888}
889
890static VALUE
891ractor_create(rb_execution_context_t *ec, VALUE self, VALUE loc, VALUE name, VALUE args, VALUE block)
892{
893 VALUE rv = ractor_alloc(self);
894 rb_ractor_t *r = RACTOR_PTR(rv);
895 ractor_init(r, name, loc);
896
897 RB_VM_LOCKING() {
898 r->pub.id = ractor_next_id();
899 }
900 RUBY_DEBUG_LOG("r:%"PRI_SERIALT_PREFIX"u", r->pub.id);
901
902 rb_ractor_t *cr = rb_ec_ractor_ptr(ec);
903 r->verbose = cr->verbose;
904 r->debug = cr->debug;
905
906 /* Every Ractor has an objspace, and it must exist before its thread runs: the
907 * first allocation goes there through rb_gc_get_objspace. */
908 r->objspace = rb_gc_objspace_alloc();
909
910 rb_thread_create_ractor(r, args, block);
911
912 RB_GC_GUARD(rv);
913 return rv;
914}
915
916#if 0
917static VALUE
918ractor_create_func(VALUE klass, VALUE loc, VALUE name, VALUE args, rb_block_call_func_t func)
919{
920 VALUE block = rb_proc_new(func, Qnil);
921 return ractor_create(rb_current_ec_noinline(), klass, loc, name, args, block);
922}
923#endif
924
925static void
926ractor_atexit(rb_execution_context_t *ec, rb_ractor_t *cr, VALUE result, bool exc)
927{
928 ractor_notify_exit(ec, cr, result, exc);
929}
930
931/* The dying thread's last work inside its Ractor. The order is the point: a joiner woken
932 * before the collection spins in ractor_value for the whole of it. */
933void
934rb_ractor_postmortem(rb_thread_t *th, struct rb_ractor_postmortem_frees *pf)
935{
936 ractor_postmortem_collect(th, pf);
937 ractor_send_exit_tokens(th->ec, th->ractor);
938}
939
940void
941rb_ractor_atexit(rb_execution_context_t *ec, VALUE result)
942{
943 rb_ractor_t *cr = rb_ec_ractor_ptr(ec);
944 ractor_atexit(ec, cr, result, false);
945}
946
947void
948rb_ractor_atexit_exception(rb_execution_context_t *ec)
949{
950 rb_ractor_t *cr = rb_ec_ractor_ptr(ec);
951 ractor_atexit(ec, cr, ec->errinfo, true);
952}
953
954void
955rb_ractor_teardown(rb_execution_context_t *ec)
956{
957 rb_ractor_t *cr = rb_ec_ractor_ptr(ec);
958
959 // sync with rb_ractor_terminate_interrupt_main_thread()
960 RB_VM_LOCKING() {
961 VM_ASSERT(cr->threads.main != NULL);
962 cr->threads.main = NULL;
963 }
964}
965
966void
967rb_ractor_receive_parameters(rb_execution_context_t *ec, rb_ractor_t *r, int len, VALUE *ptr)
968{
969 for (int i=0; i<len; i++) {
970 ptr[i] = ractor_receive(ec, ractor_default_port(r), NULL);
971 }
972}
973
974void
975rb_ractor_send_parameters(rb_execution_context_t *ec, rb_ractor_t *r, VALUE args)
976{
977 int len = RARRAY_LENINT(args);
978 for (int i=0; i<len; i++) {
979 ractor_send(ec, ractor_default_port(r), RARRAY_AREF(args, i), false);
980 }
981}
982
983bool
984rb_ractor_main_p_(void)
985{
986 VM_ASSERT(rb_multi_ractor_p());
987 rb_execution_context_t *ec = GET_EC();
988 return rb_ec_ractor_ptr(ec) == rb_ec_vm_ptr(ec)->ractor.main_ractor;
989}
990
991int
992rb_ractor_living_thread_num(const rb_ractor_t *r)
993{
994 return r->threads.cnt;
995}
996
997// only for current ractor
998VALUE
999rb_ractor_thread_list(void)
1000{
1001 rb_ractor_t *r = GET_RACTOR();
1002 rb_thread_t *th = 0;
1003 VALUE ary = rb_ary_new();
1004
1005 ccan_list_for_each(&r->threads.set, th, lt_node) {
1006 switch (th->status) {
1007 case THREAD_RUNNABLE:
1008 case THREAD_STOPPED:
1009 case THREAD_STOPPED_FOREVER:
1010 rb_ary_push(ary, th->self);
1011 default:
1012 break;
1013 }
1014 }
1015
1016 return ary;
1017}
1018
1019void
1020rb_ractor_living_threads_insert(rb_ractor_t *r, rb_thread_t *th)
1021{
1022 VM_ASSERT(th != NULL);
1023
1024 RACTOR_LOCK(r);
1025 {
1026 RUBY_DEBUG_LOG("r(%"PRI_SERIALT_PREFIX"u)->threads.cnt:%d++", r->pub.id, r->threads.cnt);
1027 ccan_list_add_tail(&r->threads.set, &th->lt_node);
1028 r->threads.cnt++;
1029 }
1030 RACTOR_UNLOCK(r);
1031
1032 // first thread for a ractor
1033 if (r->threads.cnt == 1) {
1034 VM_ASSERT(ractor_status_p(r, ractor_created));
1035 vm_insert_ractor(th->vm, r);
1036 }
1037}
1038
1039static void
1040vm_ractor_blocking_cnt_inc(rb_vm_t *vm, rb_ractor_t *r, const char *file, int line)
1041{
1042 ractor_status_set(r, ractor_blocking);
1043
1044 RUBY_DEBUG_LOG2(file, line, "vm->ractor.blocking_cnt:%d++", vm->ractor.blocking_cnt);
1045 vm->ractor.blocking_cnt++;
1046 VM_ASSERT(vm->ractor.blocking_cnt <= vm->ractor.cnt);
1047}
1048
1049void
1050rb_vm_ractor_blocking_cnt_inc(rb_vm_t *vm, rb_ractor_t *cr, const char *file, int line)
1051{
1052 ASSERT_vm_locking();
1053 VM_ASSERT(GET_RACTOR() == cr);
1054 vm_ractor_blocking_cnt_inc(vm, cr, file, line);
1055}
1056
1057void
1058rb_vm_ractor_blocking_cnt_dec(rb_vm_t *vm, rb_ractor_t *cr, const char *file, int line)
1059{
1060 ASSERT_vm_locking();
1061 VM_ASSERT(GET_RACTOR() == cr);
1062
1063 RUBY_DEBUG_LOG2(file, line, "vm->ractor.blocking_cnt:%d--", vm->ractor.blocking_cnt);
1064 VM_ASSERT(vm->ractor.blocking_cnt > 0);
1065 vm->ractor.blocking_cnt--;
1066
1067 ractor_status_set(cr, ractor_running);
1068}
1069
1070/* Remove a child that never started (send_parameters failed during creation). The
1071 * creator calls this (rb_ractor_living_threads_remove assumes the current Ractor);
1072 * leaving the set and disowning the objspace share one VM-lock section, no window. */
1073void
1074rb_ractor_cancel_creation(rb_ractor_t *r, rb_thread_t *th)
1075{
1076 RACTOR_LOCK(r);
1077 {
1078 ccan_list_del(&th->lt_node);
1079 r->threads.cnt--;
1080 }
1081 RACTOR_UNLOCK(r);
1082
1083 RB_VM_LOCK();
1084 {
1085 rb_vm_t *vm = th->vm;
1086 VM_ASSERT(vm->ractor.cnt > 1);
1087 ccan_list_del(&r->vmlr_node);
1088 vm->ractor.cnt--;
1089 /* Give back the blocking count vm_insert_ractor took at insert time. A child
1090 * that never ran has no chance to decrement it, and without this the
1091 * blocking_cnt <= cnt invariant breaks on the next insert. */
1092 VM_ASSERT(r->status_ == ractor_blocking);
1093 VM_ASSERT(vm->ractor.blocking_cnt > 0);
1094 vm->ractor.blocking_cnt--;
1095
1096 rb_gc_ractor_cache_free(r->newobj_cache);
1097 r->newobj_cache = NULL;
1098
1099 if (r->objspace) {
1100 rb_gc_objspace_disown(r->objspace);
1101 r->objspace = NULL;
1102 }
1103 r->status_ = ractor_terminated;
1104 }
1105 RB_VM_UNLOCK();
1106}
1107
1108void
1109rb_ractor_living_threads_remove(rb_ractor_t *cr, rb_thread_t *th)
1110{
1111 VM_ASSERT(cr == GET_RACTOR());
1112 RUBY_DEBUG_LOG("r->threads.cnt:%d--", cr->threads.cnt);
1113
1114 if (cr->threads.cnt == 1) {
1115 vm_remove_ractor(th->vm, cr);
1116 }
1117 else {
1118 RACTOR_LOCK(cr);
1119 {
1120 ccan_list_del(&th->lt_node);
1121 cr->threads.cnt--;
1122 }
1123 RACTOR_UNLOCK(cr);
1124 }
1125}
1126
1127void
1128rb_ractor_blocking_threads_inc(rb_ractor_t *cr, const char *file, int line)
1129{
1130 RUBY_DEBUG_LOG2(file, line, "cr->threads.blocking_cnt:%d++", cr->threads.blocking_cnt);
1131
1132 VM_ASSERT(cr->threads.cnt > 0);
1133 VM_ASSERT(cr == GET_RACTOR());
1134
1135 cr->threads.blocking_cnt++;
1136}
1137
1138void
1139rb_ractor_blocking_threads_dec(rb_ractor_t *cr, const char *file, int line)
1140{
1141 RUBY_DEBUG_LOG2(file, line,
1142 "r->threads.blocking_cnt:%d--, r->threads.cnt:%u",
1143 cr->threads.blocking_cnt, cr->threads.cnt);
1144
1145 VM_ASSERT(cr == GET_RACTOR());
1146
1147 cr->threads.blocking_cnt--;
1148}
1149
1150void
1151rb_ractor_vm_barrier_interrupt_running_thread(rb_ractor_t *r)
1152{
1153 VM_ASSERT(r != GET_RACTOR());
1154 ASSERT_ractor_unlocking(r);
1155 ASSERT_vm_locking();
1156
1157 RACTOR_LOCK(r);
1158 {
1159 if (ractor_status_p(r, ractor_running)) {
1160 rb_execution_context_t *ec = r->threads.running_ec;
1161 if (ec) {
1162 RUBY_VM_SET_VM_BARRIER_INTERRUPT(ec);
1163 }
1164 }
1165 }
1166 RACTOR_UNLOCK(r);
1167}
1168
1169void
1170rb_ractor_terminate_interrupt_main_thread(rb_ractor_t *r)
1171{
1172 VM_ASSERT(r != GET_RACTOR());
1173 ASSERT_ractor_unlocking(r);
1174 ASSERT_vm_locking();
1175
1176 rb_thread_t *main_th = r->threads.main;
1177 if (main_th) {
1178 if (main_th->status != THREAD_KILLED) {
1179 RUBY_VM_SET_TERMINATE_INTERRUPT(main_th->ec);
1180 rb_threadptr_interrupt(main_th);
1181 }
1182 else {
1183 RUBY_DEBUG_LOG("killed (%p)", (void *)main_th);
1184 }
1185 }
1186}
1187
1188void rb_thread_terminate_all(rb_thread_t *th); // thread.c
1189
1190static void
1191ractor_terminal_interrupt_all(rb_vm_t *vm)
1192{
1193 if (vm->ractor.cnt > 1) {
1194 // send terminate notification to all ractors
1195 rb_ractor_t *r = 0;
1196 ccan_list_for_each(&vm->ractor.set, r, vmlr_node) {
1197 if (r != vm->ractor.main_ractor) {
1198 RUBY_DEBUG_LOG("r:%"PRI_SERIALT_PREFIX"u", rb_ractor_id(r));
1199 rb_ractor_terminate_interrupt_main_thread(r);
1200 }
1201 }
1202 }
1203}
1204
1205void rb_add_running_thread(rb_thread_t *th);
1206void rb_del_running_thread(rb_thread_t *th);
1207
1208void
1209rb_ractor_terminate_all(void)
1210{
1211 rb_vm_t *vm = GET_VM();
1212 rb_ractor_t *cr = vm->ractor.main_ractor;
1213
1214 RUBY_DEBUG_LOG("ractor.cnt:%d", (int)vm->ractor.cnt);
1215
1216 VM_ASSERT(cr == GET_RACTOR()); // only main-ractor's main-thread should kick it.
1217
1218 RB_VM_LOCK();
1219 {
1220 ractor_terminal_interrupt_all(vm); // kill all ractors
1221 }
1222 RB_VM_UNLOCK();
1223 rb_thread_terminate_all(GET_THREAD()); // kill other threads in main-ractor and wait
1224
1225 RB_VM_LOCK();
1226 {
1227 while (vm->ractor.cnt > 1) {
1228 RUBY_DEBUG_LOG("terminate_waiting:%d", vm->ractor.sync.terminate_waiting);
1229 vm->ractor.sync.terminate_waiting = true;
1230
1231 // wait for 1sec
1232 rb_vm_ractor_blocking_cnt_inc(vm, cr, __FILE__, __LINE__);
1233 rb_del_running_thread(rb_ec_thread_ptr(cr->threads.running_ec));
1234 rb_ractor_sched_wait_terminate(vm, &vm->ractor.sync.terminate_cond, 1000 /* ms */);
1235 while (vm->ractor.sched.barrier_is_waiting) {
1236 // A barrier is waiting. Threads relinquish the VM lock before joining the barrier and
1237 // since we just acquired the VM lock back, we're blocking other threads from joining it.
1238 // We loop until the barrier is over. We can't join this barrier because our thread isn't added to
1239 // running_threads until the call below to `rb_add_running_thread`.
1240 RB_VM_UNLOCK();
1241 unsigned int lev;
1242 RB_VM_LOCK_ENTER_LEV_NB(&lev);
1243 }
1244 rb_add_running_thread(rb_ec_thread_ptr(cr->threads.running_ec));
1245 rb_vm_ractor_blocking_cnt_dec(vm, cr, __FILE__, __LINE__);
1246
1247 ractor_terminal_interrupt_all(vm);
1248 }
1249 }
1250 RB_VM_UNLOCK();
1251
1252 /* Every other Ractor is dead. main inherits all uninherited objspaces, so the
1253 * remaining at-exit work (finalizers, IO flush, free-at-exit) sees every object. */
1254 rb_gc_objspace_absorb_all_zombies();
1255}
1256
1258rb_vm_main_ractor_ec(rb_vm_t *vm)
1259{
1260 /* This code needs to carefully work around two bugs:
1261 * - Bug #20016: When M:N threading is enabled, running_ec is NULL if no thread is
1262 * actually currently running (as opposed to without M:N threading, when
1263 * running_ec will still point to the _last_ thread which ran)
1264 * - Bug #20197: If the main thread is sleeping, setting its postponed job
1265 * interrupt flag is pointless; it won't look at the flag until it stops sleeping
1266 * for some reason. It would be better to set the flag on the running ec, which
1267 * will presumably look at it soon.
1268 *
1269 * Solution: use running_ec if it's set, otherwise fall back to the main thread ec.
1270 * This is still susceptible to some rare race conditions (what if the last thread
1271 * to run just entered a long-running sleep?), but seems like the best balance of
1272 * robustness and complexity.
1273 */
1274 rb_execution_context_t *running_ec = vm->ractor.main_ractor->threads.running_ec;
1275 if (running_ec) { return running_ec; }
1276 return vm->ractor.main_thread->ec;
1277}
1278
1279static VALUE
1280ractor_moved_missing(int argc, VALUE *argv, VALUE self)
1281{
1282 rb_raise(rb_eRactorMovedError, "can not send any methods to a moved object");
1283}
1284
1285/*
1286 * Document-class: Ractor::Error
1287 *
1288 * The parent class of Ractor-related error classes.
1289 */
1290
1291/*
1292 * Document-class: Ractor::ClosedError
1293 *
1294 * Raised when an attempt is made to send a message to a closed port,
1295 * or to retrieve a message from a closed and empty port.
1296 * Ports may be closed explicitly with Ractor::Port#close
1297 * and are closed implicitly when a Ractor terminates.
1298 *
1299 * port = Ractor::Port.new
1300 * port.close
1301 * port << "test" # Ractor::ClosedError
1302 * port.receive # Ractor::ClosedError
1303 *
1304 * ClosedError is a descendant of StopIteration, so the closing of a port will break
1305 * out of loops without propagating the error.
1306 */
1307
1308/*
1309 * Document-class: Ractor::IsolationError
1310 *
1311 * Raised on attempt to make a Ractor-unshareable object
1312 * Ractor-shareable.
1313 */
1314
1315/*
1316 * Document-class: Ractor::RemoteError
1317 *
1318 * Raised on Ractor#join or Ractor#value if there was an uncaught exception in the Ractor.
1319 * Its +cause+ will contain the original exception, and +ractor+ is the original ractor
1320 * it was raised in.
1321 *
1322 * r = Ractor.new { raise "Something weird happened" }
1323 *
1324 * begin
1325 * r.value
1326 * rescue => e
1327 * p e # => #<Ractor::RemoteError: thrown by remote Ractor.>
1328 * p e.ractor == r # => true
1329 * p e.cause # => #<RuntimeError: Something weird happened>
1330 * end
1331 *
1332 */
1333
1334/*
1335 * Document-class: Ractor::MovedError
1336 *
1337 * Raised on an attempt to access an object which was moved in Ractor#send or Ractor::Port#send.
1338 *
1339 * r = Ractor.new { sleep }
1340 *
1341 * ary = [1, 2, 3]
1342 * r.send(ary, move: true)
1343 * ary.inspect
1344 * # Ractor::MovedError (can not send any methods to a moved object)
1345 *
1346 */
1347
1348/*
1349 * Document-class: Ractor::MovedObject
1350 *
1351 * A special object which replaces any value that was moved to another ractor in Ractor#send
1352 * or Ractor::Port#send. Any attempt to access the object results in Ractor::MovedError.
1353 *
1354 * r = Ractor.new { receive }
1355 *
1356 * ary = [1, 2, 3]
1357 * r.send(ary, move: true)
1358 * p Ractor::MovedObject === ary
1359 * # => true
1360 * ary.inspect
1361 * # Ractor::MovedError (can not send any methods to a moved object)
1362 */
1363
1364/*
1365 * Document-class: Ractor::UnsafeError
1366 *
1367 * Raised when Ractor-unsafe C-methods is invoked by a non-main Ractor.
1368 */
1369
1370// Main docs are in ractor.rb, but without this clause there are weird artifacts
1371// in their rendering.
1372/*
1373 * Document-class: Ractor
1374 *
1375 */
1376
1377void
1378Init_Ractor(void)
1379{
1380 rb_cRactor = rb_define_class("Ractor", rb_cObject);
1382
1383 rb_eRactorError = rb_define_class_under(rb_cRactor, "Error", rb_eRuntimeError);
1384 rb_eRactorIsolationError = rb_define_class_under(rb_cRactor, "IsolationError", rb_eRactorError);
1385 rb_eRactorRemoteError = rb_define_class_under(rb_cRactor, "RemoteError", rb_eRactorError);
1386 rb_eRactorMovedError = rb_define_class_under(rb_cRactor, "MovedError", rb_eRactorError);
1387 rb_eRactorClosedError = rb_define_class_under(rb_cRactor, "ClosedError", rb_eStopIteration);
1388 rb_eRactorUnsafeError = rb_define_class_under(rb_cRactor, "UnsafeError", rb_eRactorError);
1389
1390 rb_cRactorMovedObject = rb_define_class_under(rb_cRactor, "MovedObject", rb_cBasicObject);
1391 rb_undef_alloc_func(rb_cRactorMovedObject);
1392 rb_define_method(rb_cRactorMovedObject, "method_missing", ractor_moved_missing, -1);
1393
1394 // override methods defined in BasicObject
1395 rb_define_method(rb_cRactorMovedObject, "__send__", ractor_moved_missing, -1);
1396 rb_define_method(rb_cRactorMovedObject, "!", ractor_moved_missing, -1);
1397 rb_define_method(rb_cRactorMovedObject, "==", ractor_moved_missing, -1);
1398 rb_define_method(rb_cRactorMovedObject, "!=", ractor_moved_missing, -1);
1399 rb_define_method(rb_cRactorMovedObject, "__id__", ractor_moved_missing, -1);
1400 rb_define_method(rb_cRactorMovedObject, "equal?", ractor_moved_missing, -1);
1401 rb_define_method(rb_cRactorMovedObject, "instance_eval", ractor_moved_missing, -1);
1402 rb_define_method(rb_cRactorMovedObject, "instance_exec", ractor_moved_missing, -1);
1403
1404 id_marshal_dump = rb_intern_const("marshal_dump");
1405 id_marshal_load = rb_intern_const("marshal_load");
1406 id_dump = rb_intern_const("_dump");
1407 id_load = rb_intern_const("_load");
1408 id_dump_data = rb_intern_const("_dump_data");
1409 id_load_data = rb_intern_const("_load_data");
1410
1411 Init_RactorPort();
1412}
1413
1414void
1415rb_ractor_dump(void)
1416{
1417 rb_vm_t *vm = GET_VM();
1418 rb_ractor_t *r = 0;
1419
1420 ccan_list_for_each(&vm->ractor.set, r, vmlr_node) {
1421 if (r != vm->ractor.main_ractor) {
1422 fprintf(stderr, "r:%"PRI_SERIALT_PREFIX"u (%s)\n", r->pub.id, ractor_status_str(r->status_));
1423 }
1424 }
1425}
1426
1427VALUE
1429{
1430 if (rb_ractor_main_p()) {
1431 return rb_stdin;
1432 }
1433 else {
1434 rb_ractor_t *cr = GET_RACTOR();
1435 if (UNLIKELY(cr->r_stdin == 0)) {
1436 cr->r_stdin = rb_io_prep_stdin();
1437 }
1438 return cr->r_stdin;
1439 }
1440}
1441
1442VALUE
1443rb_ractor_stdout(void)
1444{
1445 if (rb_ractor_main_p()) {
1446 return rb_stdout;
1447 }
1448 else {
1449 rb_ractor_t *cr = GET_RACTOR();
1450 if (UNLIKELY(cr->r_stdout == 0)) {
1451 cr->r_stdout = rb_io_prep_stdout();
1452 }
1453 return cr->r_stdout;
1454 }
1455}
1456
1457VALUE
1458rb_ractor_stderr(void)
1459{
1460 if (rb_ractor_main_p()) {
1461 return rb_stderr;
1462 }
1463 else {
1464 rb_ractor_t *cr = GET_RACTOR();
1465 if (UNLIKELY(cr->r_stderr == 0)) {
1466 cr->r_stderr = rb_io_prep_stderr();
1467 }
1468 return cr->r_stderr;
1469 }
1470}
1471
1472void
1474{
1475 if (rb_ractor_main_p()) {
1476 rb_stdin = in;
1477 }
1478 else {
1479 rb_ractor_t *cr = GET_RACTOR();
1480 RB_OBJ_WRITE(cr->pub.self, &cr->r_stdin, in);
1481 }
1482}
1483
1484void
1486{
1487 if (rb_ractor_main_p()) {
1488 rb_stdout = out;
1489 }
1490 else {
1491 rb_ractor_t *cr = GET_RACTOR();
1492 RB_OBJ_WRITE(cr->pub.self, &cr->r_stdout, out);
1493 }
1494}
1495
1496void
1498{
1499 if (rb_ractor_main_p()) {
1500 rb_stderr = err;
1501 }
1502 else {
1503 rb_ractor_t *cr = GET_RACTOR();
1504 RB_OBJ_WRITE(cr->pub.self, &cr->r_stderr, err);
1505 }
1506}
1507
1508
1509st_table *
1510rb_ractor_targeted_hooks(rb_ractor_t *cr)
1511{
1512 return &cr->pub.targeted_hooks;
1513}
1514
1515static void
1516rb_obj_set_shareable_no_assert(VALUE obj)
1517{
1518 /* make_shareable_check_shareable refuses an IO, because the traversal cannot reach
1519 * the VALUE members inside its fptr. */
1520 VM_ASSERT(!RB_TYPE_P(obj, T_FILE));
1521
1523 rb_gc_obj_became_shareable(obj);
1524
1525 /* Ivars on a shareable object would be mutable shared state, so freeze them
1526 * (not obj itself). A T_IMEMO has no shape id to transition. */
1527 bool froze_ivars = false;
1528 if (!RB_OBJ_FROZEN_RAW(obj) && !RB_TYPE_P(obj, T_IMEMO) &&
1529 !RB_TYPE_P(obj, T_CLASS) && !RB_TYPE_P(obj, T_MODULE) && !RB_TYPE_P(obj, T_ICLASS)) {
1530
1531 RBASIC_SET_SHAPE_ID(obj, rb_shape_transition_frozen(RBASIC_SHAPE_ID(obj)));
1532 froze_ivars = true;
1533 }
1534
1535 /* A T_OBJECT can have a fields imemo too (too_complex and friends), and an imemo
1536 * born while its owner was unshareable stays unshareable
1537 * (imemo_fields_complex_from_obj), so align it here. */
1538 if (rb_obj_gen_fields_p(obj) || BUILTIN_TYPE(obj) == T_OBJECT) {
1539 /* obj is shareable already, so rb_obj_fields_no_ractor_check finds the right
1540 * table. Make the fields imemo itself shareable and record shrefs for the
1541 * hidden field values the traversal never reaches. */
1542 VALUE fields = rb_obj_fields_no_ractor_check(obj);
1543 if (imemo_type_p(fields, imemo_fields)) {
1544 // no recursive mark
1545 FL_SET_RAW(fields, FL_SHAREABLE);
1546 rb_gc_obj_became_shareable(fields);
1547 // the imemo carries its owner's shape id, frozen bit included
1548 if (froze_ivars) RBASIC_SET_SHAPE_ID(fields, RBASIC_SHAPE_ID(obj));
1549 // Field values the traversal never reaches (hidden internal ivars, say)
1550 // can stay unshareable, so record their shrefs to keep the shareable
1551 // fields imemo's edges correct.
1552 rb_imemo_fields_record_shrefs(fields);
1553 }
1554 }
1555}
1556
1557#ifndef STRICT_VERIFY_SHAREABLE
1558#define STRICT_VERIFY_SHAREABLE 0
1559#endif
1560
1561bool
1562rb_ractor_verify_shareable(VALUE obj)
1563{
1564#if STRICT_VERIFY_SHAREABLE
1565 rb_gc_verify_shareable(obj);
1566#endif
1567 return true;
1568}
1569
1570VALUE
1572{
1574
1575 rb_obj_set_shareable_no_assert(obj);
1576 RUBY_ASSERT(rb_ractor_verify_shareable(obj));
1577
1578 return obj;
1579}
1580
1582
1583// 2: stop search
1584// 1: skip child
1585// 0: continue
1586
1587enum obj_traverse_iterator_result {
1588 traverse_cont,
1589 traverse_skip,
1590 traverse_stop,
1591};
1592
1593typedef enum obj_traverse_iterator_result (*rb_obj_traverse_enter_func)(VALUE obj);
1594typedef enum obj_traverse_iterator_result (*rb_obj_traverse_leave_func)(VALUE obj);
1595typedef enum obj_traverse_iterator_result (*rb_obj_traverse_final_func)(VALUE obj);
1596
1597static enum obj_traverse_iterator_result null_leave(VALUE obj);
1598
1600 rb_obj_traverse_enter_func enter_func;
1601 rb_obj_traverse_leave_func leave_func;
1602
1603 st_table *rec;
1604 VALUE rec_hash;
1605};
1606
1607
1609 bool stop;
1610 struct obj_traverse_data *data;
1611};
1612
1613static int obj_traverse_i(VALUE obj, struct obj_traverse_data *data);
1614
1615static int
1616obj_hash_traverse_i(VALUE key, VALUE val, VALUE ptr)
1617{
1619
1620 if (obj_traverse_i(key, d->data)) {
1621 d->stop = true;
1622 return ST_STOP;
1623 }
1624
1625 if (obj_traverse_i(val, d->data)) {
1626 d->stop = true;
1627 return ST_STOP;
1628 }
1629
1630 return ST_CONTINUE;
1631}
1632
1633static void
1634obj_traverse_reachable_i(VALUE obj, void *ptr)
1635{
1637
1638 if (obj_traverse_i(obj, d->data)) {
1639 d->stop = true;
1640 }
1641}
1642
1643// Traverse obj's children via its GC mark function. Returns 1 to stop.
1644static int
1645obj_traverse_reachable(VALUE obj, struct obj_traverse_data *data)
1646{
1647 struct obj_traverse_callback_data d = {
1648 .stop = false,
1649 .data = data,
1650 };
1651 RB_VM_LOCKING_NO_BARRIER() {
1652 rb_objspace_reachable_objects_from(obj, obj_traverse_reachable_i, &d);
1653 }
1654 return d.stop;
1655}
1656
1657static struct st_table *
1658obj_traverse_rec(struct obj_traverse_data *data)
1659{
1660 if (UNLIKELY(!data->rec)) {
1661 data->rec_hash = rb_ident_hash_new();
1662 rb_obj_hide(data->rec_hash);
1663 data->rec = RHASH_ST_TABLE(data->rec_hash);
1664 }
1665 return data->rec;
1666}
1667
1668static int
1669obj_traverse_ivar_foreach_i(ID key, VALUE val, st_data_t ptr)
1670{
1672
1673 if (obj_traverse_i(val, d->data)) {
1674 d->stop = true;
1675 return ST_STOP;
1676 }
1677
1678 return ST_CONTINUE;
1679}
1680
1681static int
1682obj_traverse_i(VALUE obj, struct obj_traverse_data *data)
1683{
1684 if (RB_SPECIAL_CONST_P(obj)) return 0;
1685
1686 switch (data->enter_func(obj)) {
1687 case traverse_cont: break;
1688 case traverse_skip: return 0; // skip children
1689 case traverse_stop: return 1; // stop search
1690 }
1691
1692 if (UNLIKELY(st_insert(obj_traverse_rec(data), obj, 1))) {
1693 // already traversed
1694 return 0;
1695 }
1696 RB_OBJ_WRITTEN(data->rec_hash, Qundef, obj);
1697
1698 if (rb_obj_shape_has_ivars(obj)) {
1699 struct obj_traverse_callback_data d = {
1700 .stop = false,
1701 .data = data,
1702 };
1703 rb_ivar_foreach(obj, obj_traverse_ivar_foreach_i, (st_data_t)&d);
1704 if (d.stop) return 1;
1705 }
1706
1707 switch (BUILTIN_TYPE(obj)) {
1708 // no child node
1709 case T_STRING:
1710 case T_FLOAT:
1711 case T_BIGNUM:
1712 case T_REGEXP:
1713 case T_SYMBOL:
1714 break;
1715
1716 case T_OBJECT:
1717 /* Instance variables already traversed. */
1718 break;
1719
1720 case T_ARRAY:
1721 {
1722 rb_ary_cancel_sharing(obj);
1723
1724 for (int i = 0; i < RARRAY_LENINT(obj); i++) {
1725 VALUE e = RARRAY_AREF(obj, i);
1726 if (obj_traverse_i(e, data)) return 1;
1727 }
1728 }
1729 break;
1730
1731 case T_HASH:
1732 {
1733 if (obj_traverse_i(RHASH_IFNONE(obj), data)) return 1;
1734
1735 struct obj_traverse_callback_data d = {
1736 .stop = false,
1737 .data = data,
1738 };
1739 rb_hash_foreach(obj, obj_hash_traverse_i, (VALUE)&d);
1740 if (d.stop) return 1;
1741 }
1742 break;
1743
1744 case T_STRUCT:
1745 {
1746 long len = RSTRUCT_LEN_RAW(obj);
1747 const VALUE *ptr = RSTRUCT_CONST_PTR(obj);
1748
1749 for (long i=0; i<len; i++) {
1750 if (obj_traverse_i(ptr[i], data)) return 1;
1751 }
1752 }
1753 break;
1754
1755 case T_MATCH:
1756 if (obj_traverse_i(RMATCH(obj)->str, data)) return 1;
1757 break;
1758
1759 case T_RATIONAL:
1760 if (obj_traverse_i(RRATIONAL(obj)->num, data)) return 1;
1761 if (obj_traverse_i(RRATIONAL(obj)->den, data)) return 1;
1762 break;
1763 case T_COMPLEX:
1764 if (obj_traverse_i(RCOMPLEX(obj)->real, data)) return 1;
1765 if (obj_traverse_i(RCOMPLEX(obj)->imag, data)) return 1;
1766 break;
1767
1768 case T_DATA:
1769 {
1770 void *const ptr = RTYPEDDATA_GET_DATA(obj);
1771 const rb_data_type_t *type = RTYPEDDATA_TYPE(obj);
1772
1773 if (!ptr || !type->function.dmark) {
1774 // no references (the class and ivars are handled elsewhere)
1775 }
1776 else if (type->flags & RUBY_TYPED_DECL_MARKING) {
1777 const size_t *offsets = (const size_t *)(uintptr_t)type->function.dmark;
1778 for (; *offsets != RUBY_REF_END; offsets++) {
1779 VALUE ref = *(VALUE *)((char *)ptr + *offsets);
1780 if (obj_traverse_i(ref, data)) return 1;
1781 }
1782 }
1783 else {
1784 if (obj_traverse_reachable(obj, data)) return 1;
1785 }
1786 }
1787 break;
1788
1789 case T_IMEMO:
1790 // TODO: Not sure this can actually happen; traverse rather than crash.
1791 if (obj_traverse_reachable(obj, data)) return 1;
1792 break;
1793
1794 // unreachable
1795 case T_CLASS:
1796 case T_MODULE:
1797 case T_ICLASS:
1798 default:
1799 rp(obj);
1800 rb_bug("unreachable");
1801 }
1802
1803 if (data->leave_func(obj) == traverse_stop) {
1804 return 1;
1805 }
1806 else {
1807 return 0;
1808 }
1809}
1810
1812 rb_obj_traverse_final_func final_func;
1813 int stopped;
1814};
1815
1816static int
1817obj_traverse_final_i(st_data_t key, st_data_t val, st_data_t arg)
1818{
1819 struct rb_obj_traverse_final_data *data = (void *)arg;
1820 if (data->final_func(key)) {
1821 data->stopped = 1;
1822 return ST_STOP;
1823 }
1824 return ST_CONTINUE;
1825}
1826
1827// 0: traverse all
1828// 1: stopped
1829static int
1830rb_obj_traverse(VALUE obj,
1831 rb_obj_traverse_enter_func enter_func,
1832 rb_obj_traverse_leave_func leave_func,
1833 rb_obj_traverse_final_func final_func)
1834{
1835 struct obj_traverse_data data = {
1836 .enter_func = enter_func,
1837 .leave_func = leave_func,
1838 .rec = NULL,
1839 };
1840
1841 if (obj_traverse_i(obj, &data)) return 1;
1842 if (final_func && data.rec) {
1843 struct rb_obj_traverse_final_data f = {final_func, 0};
1844 st_foreach(data.rec, obj_traverse_final_i, (st_data_t)&f);
1845 return f.stopped;
1846 }
1847 return 0;
1848}
1849
1850static int
1851allow_frozen_shareable_p(VALUE obj)
1852{
1853 if (RB_TYPE_P(obj, T_FILE)) {
1854 return false;
1855 }
1856 else if (!RB_TYPE_P(obj, T_DATA)) {
1857 return true;
1858 }
1859 else {
1860 const rb_data_type_t *type = RTYPEDDATA_TYPE(obj);
1861 if (type->flags & RUBY_TYPED_FROZEN_SHAREABLE) {
1862 return true;
1863 }
1864 }
1865
1866 return false;
1867}
1868
1869static void
1870make_shareable_freeze(VALUE obj)
1871{
1872 VALUE klass = RBASIC_CLASS(obj);
1873 if (klass == rb_cString && BASIC_OP_UNREDEFINED_P(BOP_FREEZE, STRING_REDEFINED_OP_FLAG)) {
1874 rb_str_freeze(obj);
1875 }
1876 else if (klass == rb_cArray && BASIC_OP_UNREDEFINED_P(BOP_FREEZE, ARRAY_REDEFINED_OP_FLAG)) {
1877 rb_ary_freeze(obj);
1878 }
1879 else if (klass == rb_cHash && BASIC_OP_UNREDEFINED_P(BOP_FREEZE, HASH_REDEFINED_OP_FLAG)) {
1880 rb_hash_freeze(obj);
1881 }
1882 else {
1883 rb_funcall(obj, idFreeze, 0);
1884 }
1885}
1886
1887static enum obj_traverse_iterator_result
1888make_shareable_check_shareable_freeze(VALUE obj, enum obj_traverse_iterator_result result)
1889{
1890 if (!RB_OBJ_FROZEN_RAW(obj)) {
1891 make_shareable_freeze(obj);
1892
1893 if (UNLIKELY(!RB_OBJ_FROZEN_RAW(obj))) {
1894 rb_raise(rb_eRactorError, "#freeze does not freeze object correctly");
1895 }
1896
1897 if (RB_OBJ_SHAREABLE_P(obj)) {
1898 return traverse_skip;
1899 }
1900 }
1901
1902 return result;
1903}
1904
1905static int obj_refer_only_shareables_p(VALUE obj);
1906
1907static enum obj_traverse_iterator_result
1908make_shareable_check_shareable(VALUE obj)
1909{
1910 VM_ASSERT(!SPECIAL_CONST_P(obj));
1911
1912 if (rb_ractor_shareable_p(obj)) {
1913 return traverse_skip;
1914 }
1915 else if (!allow_frozen_shareable_p(obj)) {
1916 if (!RB_TYPE_P(obj, T_DATA)) {
1917 rb_raise(rb_eRactorError,
1918 "can not make shareable object for %+"PRIsVALUE, obj);
1919 }
1920 else if (RTYPEDDATA_TYPE(obj)->flags & RUBY_TYPED_FROZEN_SHAREABLE_NO_REC) {
1921 if (obj_refer_only_shareables_p(obj)) {
1922 make_shareable_check_shareable_freeze(obj, traverse_skip);
1924 return traverse_skip;
1925 }
1926 else {
1927 rb_raise(rb_eRactorError,
1928 "can not make shareable object for %+"PRIsVALUE" because it refers unshareable objects", obj);
1929 }
1930 }
1931 else if (rb_obj_is_proc(obj)) {
1932 rb_proc_ractor_make_shareable(obj, Qundef);
1933 return traverse_cont;
1934 }
1935 else {
1936 rb_raise(rb_eRactorError, "can not make shareable object for %+"PRIsVALUE, obj);
1937 }
1938 }
1939
1940 switch (TYPE(obj)) {
1941 case T_IMEMO:
1942 return traverse_skip;
1943 case T_OBJECT:
1944 {
1945 // If a T_OBJECT is shared and has no free capacity, we can't safely store the object_id inline,
1946 // as it would require to move the object content into an external buffer.
1947 // This is only a problem for T_OBJECT, given other types have external fields and can do RCU.
1948 // To avoid this issue, we proactively create the object_id.
1949 shape_id_t shape_id = RBASIC_SHAPE_ID(obj);
1950 attr_index_t capacity = RSHAPE_CAPACITY(shape_id);
1951 attr_index_t free_capacity = capacity - RSHAPE_LEN(shape_id);
1952 if (!rb_shape_has_object_id(shape_id) && capacity && !free_capacity) {
1953 rb_obj_id(obj);
1954 }
1955 }
1956 break;
1957 default:
1958 break;
1959 }
1960
1961 return make_shareable_check_shareable_freeze(obj, traverse_cont);
1962}
1963
1964static enum obj_traverse_iterator_result
1965mark_shareable(VALUE obj)
1966{
1967 if (RB_BUILTIN_TYPE(obj) == T_STRING) {
1968 rb_str_make_independent(obj);
1969 }
1970
1971 rb_obj_set_shareable_no_assert(obj);
1972 return traverse_cont;
1973}
1974
1975VALUE
1977{
1978 rb_obj_traverse(obj,
1979 make_shareable_check_shareable,
1980 null_leave, mark_shareable);
1981 return obj;
1982}
1983
1984static VALUE ractor_copy(VALUE obj); // defined below
1985
1986VALUE
1988{
1989 VALUE copy = ractor_copy(obj);
1990 return rb_ractor_make_shareable(copy);
1991}
1992
1993VALUE
1994rb_ractor_ensure_shareable(VALUE obj, VALUE name)
1995{
1996 if (!rb_ractor_shareable_p(obj)) {
1997 VALUE message = rb_sprintf("cannot assign unshareable object to %"PRIsVALUE,
1998 name);
1999 rb_exc_raise(rb_exc_new_str(rb_eRactorIsolationError, message));
2000 }
2001 return obj;
2002}
2003
2004void
2005rb_ractor_ensure_main_ractor(const char *msg)
2006{
2007 if (!rb_ractor_main_p()) {
2008 rb_raise(rb_eRactorIsolationError, "%s", msg);
2009 }
2010}
2011
2012static enum obj_traverse_iterator_result
2013shareable_p_enter(VALUE obj)
2014{
2015 if (RB_OBJ_SHAREABLE_P(obj)) {
2016 return traverse_skip;
2017 }
2018 else if (RB_TYPE_P(obj, T_CLASS) ||
2019 RB_TYPE_P(obj, T_MODULE) ||
2020 RB_TYPE_P(obj, T_ICLASS)) {
2021 // TODO: remove it
2022 mark_shareable(obj);
2023 return traverse_skip;
2024 }
2025 else if (RB_OBJ_FROZEN_RAW(obj) &&
2026 allow_frozen_shareable_p(obj)) {
2027 return traverse_cont;
2028 }
2029 else if (RB_OBJ_FROZEN_RAW(obj) &&
2030 RB_TYPE_P(obj, T_DATA) &&
2031 (RTYPEDDATA_TYPE(obj)->flags & RUBY_TYPED_FROZEN_SHAREABLE_NO_REC)) {
2032 // Similar to RUBY_TYPED_FROZEN_SHAREABLE, but the object is only
2033 // shareable if all reachable objects are already shareable (they
2034 // are not made shareable recursively).
2035 if (obj_refer_only_shareables_p(obj)) {
2036 mark_shareable(obj);
2037 return traverse_skip;
2038 }
2039 }
2040
2041 return traverse_stop; // fail
2042}
2043
2044bool
2045rb_ractor_shareable_p_continue(VALUE obj)
2046{
2047 if (rb_obj_traverse(obj,
2048 shareable_p_enter, null_leave,
2049 mark_shareable)) {
2050 return false;
2051 }
2052 else {
2053 return true;
2054 }
2055}
2056
2057static enum obj_traverse_iterator_result
2058null_leave(VALUE obj)
2059{
2060 return traverse_cont;
2061}
2062
2063
2065
2066// 2: stop search
2067// 1: skip child
2068// 0: continue
2069
2071static int obj_traverse_replace_i(VALUE obj, struct obj_traverse_replace_data *data);
2072typedef enum obj_traverse_iterator_result (*rb_obj_traverse_replace_enter_func)(VALUE obj, struct obj_traverse_replace_data *data);
2073typedef enum obj_traverse_iterator_result (*rb_obj_traverse_replace_leave_func)(VALUE obj, struct obj_traverse_replace_data *data);
2074
2076 rb_obj_traverse_replace_enter_func enter_func;
2077 rb_obj_traverse_replace_leave_func leave_func;
2078
2079 /* old -> new map, a plain st_table: an OLD key may live in another Ractor's
2080 * objspace and must not become a GC edge here (marking a freed foreign key is a
2081 * UAF). Keys compare by address; replacements stay alive via rec_keepalive. */
2082 st_table *rec;
2083 VALUE rec_keepalive;
2084
2085 VALUE replacement;
2086 bool move;
2087};
2088
2090 bool stop;
2091 VALUE src;
2092 struct obj_traverse_replace_data *data;
2093};
2094
2095static int
2096obj_hash_traverse_replace_foreach_i(st_data_t key, st_data_t value, st_data_t argp, int error)
2097{
2098 return ST_REPLACE;
2099}
2100
2101static int
2102obj_hash_traverse_replace_i(st_data_t *key, st_data_t *val, st_data_t ptr, int exists)
2103{
2105 struct obj_traverse_replace_data *data = d->data;
2106
2107 if (obj_traverse_replace_i(*key, data)) {
2108 d->stop = true;
2109 return ST_STOP;
2110 }
2111 else if (*key != data->replacement) {
2112 VALUE v = *key = data->replacement;
2113 RB_OBJ_WRITTEN(d->src, Qundef, v);
2114 }
2115
2116 if (obj_traverse_replace_i(*val, data)) {
2117 d->stop = true;
2118 return ST_STOP;
2119 }
2120 else if (*val != data->replacement) {
2121 VALUE v = *val = data->replacement;
2122 RB_OBJ_WRITTEN(d->src, Qundef, v);
2123 }
2124
2125 return ST_CONTINUE;
2126}
2127
2128static int
2129obj_iv_hash_traverse_replace_foreach_i(st_data_t _key, st_data_t _val, st_data_t _data, int _x)
2130{
2131 return ST_REPLACE;
2132}
2133
2134static int
2135obj_iv_hash_traverse_replace_i(st_data_t * _key, st_data_t * val, st_data_t ptr, int exists)
2136{
2138 struct obj_traverse_replace_data *data = d->data;
2139
2140 if (obj_traverse_replace_i(*(VALUE *)val, data)) {
2141 d->stop = true;
2142 return ST_STOP;
2143 }
2144 else if (*(VALUE *)val != data->replacement) {
2145 VALUE v = *(VALUE *)val = data->replacement;
2146 RB_OBJ_WRITTEN(d->src, Qundef, v);
2147 }
2148
2149 return ST_CONTINUE;
2150}
2151
2152static struct st_table *
2153obj_traverse_replace_rec(struct obj_traverse_replace_data *data)
2154{
2155 if (UNLIKELY(!data->rec)) {
2156 data->rec = st_init_numtable();
2157 data->rec_keepalive = rb_ary_hidden_new(0);
2158 }
2159 return data->rec;
2160}
2161
2162static void
2163obj_refer_only_shareables_p_i(VALUE obj, void *ptr)
2164{
2165 int *pcnt = (int *)ptr;
2166
2167 if (!rb_ractor_shareable_p(obj)) {
2168 ++*pcnt;
2169 }
2170}
2171
2172static int
2173obj_refer_only_shareables_p(VALUE obj)
2174{
2175 int cnt = 0;
2176 RB_VM_LOCKING_NO_BARRIER() {
2177 rb_objspace_reachable_objects_from(obj, obj_refer_only_shareables_p_i, &cnt);
2178 }
2179 return cnt == 0;
2180}
2181
2182static int
2183obj_traverse_replace_i(VALUE obj, struct obj_traverse_replace_data *data)
2184{
2185 st_data_t replacement;
2186
2187 if (RB_SPECIAL_CONST_P(obj)) {
2188 data->replacement = obj;
2189 return 0;
2190 }
2191
2192 /* Dedup before enter_func, so a revisited shared/cyclic node reuses its recorded
2193 * replacement; otherwise the copy path would build a wasteful temporary holding a
2194 * containment-breaking cross-objspace edge. */
2195 if (UNLIKELY(st_lookup(obj_traverse_replace_rec(data), (st_data_t)obj, &replacement))) {
2196 data->replacement = (VALUE)replacement;
2197 return 0;
2198 }
2199
2200 switch (data->enter_func(obj, data)) {
2201 case traverse_cont: break;
2202 case traverse_skip: return 0; // skip children
2203 case traverse_stop: return 1; // stop search
2204 }
2205
2206 replacement = (st_data_t)data->replacement;
2207 st_insert(obj_traverse_replace_rec(data), (st_data_t)obj, replacement);
2208 if (!RB_SPECIAL_CONST_P((VALUE)replacement)) {
2209 rb_ary_push(data->rec_keepalive, (VALUE)replacement);
2210 }
2211
2212 if (!data->move) {
2213 obj = replacement;
2214 }
2215
2216#define CHECK_AND_REPLACE(parent_obj, v) do { \
2217 VALUE _val = (v); \
2218 if (obj_traverse_replace_i(_val, data)) { return 1; } \
2219 else if (data->replacement != _val) { RB_OBJ_WRITE(parent_obj, &v, data->replacement); } \
2220} while (0)
2221
2222 if (UNLIKELY(rb_obj_gen_fields_p(obj))) {
2223 VALUE fields_obj = rb_obj_fields_no_ractor_check(obj);
2224
2225 if (UNLIKELY(rb_obj_shape_complex_p(obj))) {
2227 .stop = false,
2228 .data = data,
2229 .src = fields_obj,
2230 };
2231 rb_st_foreach_with_replace(
2232 rb_imemo_fields_complex_tbl(fields_obj),
2233 obj_iv_hash_traverse_replace_foreach_i,
2234 obj_iv_hash_traverse_replace_i,
2235 (st_data_t)&d
2236 );
2237 if (d.stop) return 1;
2238 }
2239 else {
2240 uint32_t fields_count = RSHAPE_LEN(RBASIC_SHAPE_ID(obj));
2241 VALUE *fields = rb_imemo_fields_ptr(fields_obj);
2242 for (uint32_t i = 0; i < fields_count; i++) {
2243 CHECK_AND_REPLACE(fields_obj, fields[i]);
2244 }
2245 }
2246 }
2247
2248 switch (BUILTIN_TYPE(obj)) {
2249 // no child node
2250 case T_FLOAT:
2251 case T_BIGNUM:
2252 case T_REGEXP:
2253 case T_FILE:
2254 case T_SYMBOL:
2255 break;
2256 case T_STRING:
2257 rb_str_make_independent(obj);
2258 break;
2259
2260 case T_OBJECT:
2261 {
2262 VALUE fields_obj = ROBJECT_FIELDS_OBJ(obj);
2263 shape_id_t shape_id = RBASIC_SHAPE_ID(fields_obj);
2264 if (rb_shape_complex_p(shape_id)) {
2266 .stop = false,
2267 .data = data,
2268 .src = obj,
2269 };
2270 rb_st_foreach_with_replace(
2271 rb_imemo_fields_complex_tbl(fields_obj),
2272 obj_iv_hash_traverse_replace_foreach_i,
2273 obj_iv_hash_traverse_replace_i,
2274 (st_data_t)&d
2275 );
2276 if (d.stop) return 1;
2277 }
2278 else {
2279 attr_index_t len = RSHAPE_LEN(shape_id);
2280 VALUE *ptr = rb_imemo_fields_ptr(fields_obj);
2281
2282 for (attr_index_t i = 0; i < len; i++) {
2283 CHECK_AND_REPLACE(obj, ptr[i]);
2284 }
2285 }
2286 }
2287 break;
2288
2289 case T_ARRAY:
2290 {
2291 rb_ary_cancel_sharing(obj);
2292
2293 for (int i = 0; i < RARRAY_LENINT(obj); i++) {
2294 VALUE e = RARRAY_AREF(obj, i);
2295
2296 if (obj_traverse_replace_i(e, data)) {
2297 return 1;
2298 }
2299 else if (e != data->replacement) {
2300 RARRAY_ASET(obj, i, data->replacement);
2301 }
2302 }
2303 RB_GC_GUARD(obj);
2304 }
2305 break;
2306 case T_HASH:
2307 {
2309 .stop = false,
2310 .data = data,
2311 .src = obj,
2312 };
2313 rb_hash_stlike_foreach_with_replace(obj,
2314 obj_hash_traverse_replace_foreach_i,
2315 obj_hash_traverse_replace_i,
2316 (VALUE)&d);
2317 if (d.stop) return 1;
2318 // TODO: rehash here?
2319
2320 VALUE ifnone = RHASH_IFNONE(obj);
2321 if (obj_traverse_replace_i(ifnone, data)) {
2322 return 1;
2323 }
2324 else if (ifnone != data->replacement) {
2325 RHASH_SET_IFNONE(obj, data->replacement);
2326 }
2327 }
2328 break;
2329
2330 case T_STRUCT:
2331 {
2332 long len = RSTRUCT_LEN_RAW(obj);
2333 const VALUE *ptr = RSTRUCT_CONST_PTR(obj);
2334
2335 for (long i=0; i<len; i++) {
2336 CHECK_AND_REPLACE(obj, ptr[i]);
2337 }
2338 }
2339 break;
2340
2341 case T_MATCH:
2342 CHECK_AND_REPLACE(obj, RMATCH(obj)->str);
2343 break;
2344
2345 case T_RATIONAL:
2346 CHECK_AND_REPLACE(obj, RRATIONAL(obj)->num);
2347 CHECK_AND_REPLACE(obj, RRATIONAL(obj)->den);
2348 break;
2349 case T_COMPLEX:
2350 CHECK_AND_REPLACE(obj, RCOMPLEX(obj)->real);
2351 CHECK_AND_REPLACE(obj, RCOMPLEX(obj)->imag);
2352 break;
2353
2354 case T_DATA:
2355 if (!data->move && obj_refer_only_shareables_p(obj)) {
2356 break;
2357 }
2358 else {
2359 rb_raise(rb_eRactorError, "can not %s %"PRIsVALUE" object.",
2360 data->move ? "move" : "copy", rb_class_of(obj));
2361 }
2362
2363 case T_IMEMO:
2364 // not supported yet
2365 return 1;
2366
2367 // unreachable
2368 case T_CLASS:
2369 case T_MODULE:
2370 case T_ICLASS:
2371 default:
2372 rp(obj);
2373 rb_bug("unreachable");
2374 }
2375
2376 data->replacement = (VALUE)replacement;
2377
2378 if (data->leave_func(obj, data) == traverse_stop) {
2379 return 1;
2380 }
2381 else {
2382 return 0;
2383 }
2384}
2385
2386// 0: traverse all
2387// 1: stopped
2388static VALUE
2389rb_obj_traverse_replace(VALUE obj,
2390 rb_obj_traverse_replace_enter_func enter_func,
2391 rb_obj_traverse_replace_leave_func leave_func,
2392 bool move)
2393{
2394 struct obj_traverse_replace_data data = {
2395 .enter_func = enter_func,
2396 .leave_func = leave_func,
2397 .rec = NULL,
2398 .rec_keepalive = Qfalse,
2399 .replacement = Qundef,
2400 .move = move,
2401 };
2402
2403 int stopped = obj_traverse_replace_i(obj, &data);
2404
2405 /* The enter and leave functions report failure with traverse_stop rather than by
2406 * raising, so this is the only place the table is freed. */
2407 if (data.rec) st_free_table(data.rec);
2408 RB_GC_GUARD(data.rec_keepalive);
2409
2410 if (stopped) {
2411 return Qundef;
2412 }
2413 else {
2414 return data.replacement;
2415 }
2416}
2417
2418/* Courier: serializes a Ractor message payload -- copied or moved -- into an xmalloc'd
2419 * structure that belongs to no objspace, so no sender GC can mark, sweep, compact or
2420 * race with it. A node array with id references handles sharing and cycles, and the
2421 * receiver rebuilds it in its own objspace in two passes. Copy and move differ only in
2422 * whether the source is read or taken apart: see courier_build.copy. */
2423
2424enum courier_node_kind {
2425 COURIER_KIND_REF, /* an immediate or a shareable object: carried by value */
2426 COURIER_KIND_BACKTRACE, /* an exception's backtrace: frames copied into an off-heap blob */
2427 COURIER_KIND_STRING,
2428 COURIER_KIND_ARRAY,
2429 COURIER_KIND_HASH,
2430 COURIER_KIND_OBJECT,
2431 COURIER_KIND_STRUCT,
2432 COURIER_KIND_MATCH,
2433 COURIER_KIND_IO,
2434 COURIER_KIND_REGEXP, /* recompiled from its source and options (copy only) */
2435 COURIER_KIND_HOOKED, /* rebuilt from its dump hook's payload by klass._load, marshal_load or _load_data */
2436};
2437
2438/* Marshal's protocols, but nothing is serialized: the hook's return value travels as an
2439 * ordinary child node, so sharing, cycles and shareable references all survive. */
2440enum courier_hook {
2441 COURIER_HOOK_NONE,
2442 COURIER_HOOK_MARSHAL_DUMP, /* marshal_dump -> alloc + marshal_load */
2443 COURIER_HOOK_DUMP, /* _dump -> klass._load */
2444 COURIER_HOOK_COMPAT, /* rb_marshal_define_compat dumper -> alloc + loader (Set, Process::Status) */
2445 COURIER_HOOK_DUMP_DATA, /* _dump_data -> alloc + _load_data */
2446};
2447
2448/* Which one obj's class implements, in Marshal's order of preference. */
2449static enum courier_hook
2450courier_hook_of(VALUE obj)
2451{
2452 if (rb_obj_respond_to(obj, id_marshal_dump, TRUE)) return COURIER_HOOK_MARSHAL_DUMP;
2453 if (rb_obj_respond_to(obj, id_dump, TRUE)) return COURIER_HOOK_DUMP;
2454 if (rb_marshal_compat_lookup(CLASS_OF(obj), NULL, NULL)) return COURIER_HOOK_COMPAT;
2455 if (BUILTIN_TYPE(obj) == T_DATA && rb_obj_respond_to(obj, id_dump_data, TRUE)) return COURIER_HOOK_DUMP_DATA;
2456 return COURIER_HOOK_NONE;
2457}
2458
2460 enum courier_node_kind kind;
2461 bool frozen;
2462 /* The instance and generic ivars every non-REF node can have (a String or Array
2463 * can hold generic ivars too) */
2464 uint32_t niv;
2465 ID *iv_ids; /* owned by the courier */
2466 uint32_t *iv_vals; /* owned by the courier; node ids */
2467 union {
2468 VALUE ref;
2469 struct { char *ptr; long len, capa; int encidx; VALUE klass; } str; /* the courier owns ptr */
2470 struct { long len; uint32_t *elems; VALUE klass; } ary; /* the courier owns elems */
2471 struct { long size; uint32_t *kv; uint32_t ifnone_id; bool compare_by_id; bool proc_default; VALUE klass; } hash; /* owns kv (2*size) */
2472 struct { VALUE klass; } obj;
2473 struct { long len; uint32_t *elems; VALUE klass; } strct; /* owns elems */
2474 struct { uint32_t regexp_id, str_id; int num_regs; void *regs; VALUE klass; } match; /* owns regs */
2475 struct { void *blob; int size; } bt; /* the courier owns blob */
2476 struct { VALUE src; int options; VALUE klass; } re; /* src is an fstring: shareable */
2477 struct { VALUE klass; uint32_t payload_id; enum courier_hook hook; } hooked;
2478 struct {
2479 struct rb_io *fptr; /* carried by pointer (it owns the fd) */
2480 VALUE klass;
2481 /* The sender-side VALUE members of fptr travel as ordinary child nodes:
2482 * capture detaches them from fptr (see the T_FILE case) and rebuild writes
2483 * them back into the receiving shell with RB_OBJ_WRITE. */
2484 uint32_t pathv_id, ecopts_id, wc_pre_ecopts_id, wc_asciicompat_id, timeout_id;
2485 } io;
2486 } u;
2487};
2488
2489/* A child slot holds a node id, or -- with this bit set -- an index into c->refs.
2490 * The courier is in-process, so a shareable payload can travel as the VALUE itself
2491 * instead of costing a whole courier_node; the basket holding the courier marks c->refs. */
2492#define COURIER_ID_REF_BIT 0x80000000u
2493
2495 struct courier_node *nodes;
2496 uint32_t *order; /* node ids in capture's post-order: children before parents */
2497 uint32_t count;
2498 uint32_t capa;
2499 VALUE *refs; /* shareable payloads, embedded by value */
2500 uint32_t refs_count;
2501 uint32_t refs_capa;
2502 uint32_t root;
2503 /* src VALUE -> (node id + 1), only while building. Marked so that a key cannot
2504 * die (a dump hook's payload has no other owner) or move (compaction). */
2505 st_table *seen;
2506};
2507
2509 struct rb_ractor_courier *c;
2510 /* Copy mode: read the sources instead of taking them apart. No husk, no buffer
2511 * hand-over, no freeing of the source's internals. */
2512 bool copy;
2513 uint32_t ordered; /* nodes appended to c->order so far */
2514};
2515
2516static uint32_t courier_capture(struct courier_build *b, VALUE obj);
2517
2518/* Off the hot path: the preflight sizes both arrays, so this only runs if its count
2519 * came out short. Swap a fresh array in rather than realloc -- the courier is a GC
2520 * root while it is being built, and a realloc leaves the old pointer live over a
2521 * window where it may already have been freed. */
2522NOINLINE(static void courier_grow_nodes(struct rb_ractor_courier *c));
2523NOINLINE(static void courier_grow_refs(struct rb_ractor_courier *c));
2524
2525static void
2526courier_grow_nodes(struct rb_ractor_courier *c)
2527{
2528 uint32_t capa = c->capa ? c->capa * 2 : 8;
2529 struct courier_node *nodes = ALLOC_N(struct courier_node, capa);
2530 if (c->count > 0) MEMCPY(nodes, c->nodes, struct courier_node, c->count);
2531 struct courier_node *old_nodes = c->nodes;
2532 c->nodes = nodes;
2533 c->capa = capa;
2534 ruby_xfree(old_nodes);
2535 REALLOC_N(c->order, uint32_t, capa);
2536}
2537
2538static void
2539courier_grow_refs(struct rb_ractor_courier *c)
2540{
2541 uint32_t capa = c->refs_capa ? c->refs_capa * 2 : 8;
2542 VALUE *refs = ALLOC_N(VALUE, capa);
2543 if (c->refs_count > 0) MEMCPY(refs, c->refs, VALUE, c->refs_count);
2544 VALUE *old_refs = c->refs;
2545 c->refs = refs;
2546 c->refs_capa = capa;
2547 ruby_xfree(old_refs);
2548}
2549
2550static uint32_t
2551courier_alloc_node(struct rb_ractor_courier *c)
2552{
2553 if (RB_UNLIKELY(c->count == c->capa)) courier_grow_nodes(c);
2554 /* Fill the slot with a harmless REF/Qnil and bump the count only after, the way
2555 * courier_alloc_ref does: the courier is a GC root while it is being built, and
2556 * the mark walks nodes[0, count). A captured node overwrites this later. */
2557 struct courier_node *n = &c->nodes[c->count];
2558 n->kind = COURIER_KIND_REF;
2559 n->frozen = false;
2560 n->niv = 0;
2561 n->iv_ids = NULL;
2562 n->iv_vals = NULL;
2563 n->u.ref = Qnil;
2564 return c->count++;
2565}
2566
2567/* Size the arrays from the preflight's count, so capture never grows them. A count
2568 * that turns out short is not a problem: the growth path below still works. */
2569static void
2570courier_reserve(struct rb_ractor_courier *c, uint32_t nodes, uint32_t refs)
2571{
2572 if (nodes > 0) {
2573 c->nodes = ALLOC_N(struct courier_node, nodes);
2574 c->order = ALLOC_N(uint32_t, nodes);
2575 c->capa = nodes;
2576 }
2577 if (refs > 0) {
2578 c->refs = ALLOC_N(VALUE, refs);
2579 c->refs_capa = refs;
2580 }
2581}
2582
2583/* Embed a shareable payload by value and return its tagged child id. No dedup: a REF
2584 * is the same word however often it appears, and an array of immediates would otherwise
2585 * pay a lookup and an insert per element. */
2586static uint32_t
2587courier_alloc_ref(struct rb_ractor_courier *c, VALUE v)
2588{
2589 /* The count is bumped only after the slot holds a real VALUE: the courier is a GC
2590 * root while it is being built and must never be walkable half-written. */
2591 if (RB_UNLIKELY(c->refs_count == c->refs_capa)) courier_grow_refs(c);
2592 c->refs[c->refs_count] = v;
2593 return COURIER_ID_REF_BIT | c->refs_count++;
2594}
2595
2596/* Resolve a child slot to the object it names. */
2597static VALUE
2598courier_child(const struct rb_ractor_courier *c, VALUE shells, uint32_t id)
2599{
2600 if (id & COURIER_ID_REF_BIT) return c->refs[id & ~COURIER_ID_REF_BIT];
2601 return RARRAY_AREF(shells, id);
2602}
2603
2604/* Turn a moved source into a valid RactorMovedObject without passing through flags==0,
2605 * so a concurrent foreign marker always sees either the original object or the shell. */
2606static void
2607move_neutralize_source(VALUE obj)
2608{
2609 /* The shell stays in the original slot: keep the capacity bits, give it a frozen
2610 * field-less ROBJECT shape (read before the flags are overwritten). The old body is
2611 * then never read as ivars and compaction's slot-size check still holds. */
2612 shape_id_t shape_id = (RBASIC_SHAPE_ID(obj) & SHAPE_ID_CAPACITY_MASK) |
2613 ROOT_SHAPE_ID | SHAPE_ID_LAYOUT_ROBJECT | SHAPE_ID_FL_FROZEN;
2614
2615 /* A non-T_OBJECT host (a String with ivars, say) must drop its generic_fields
2616 * entry: obj stops being a host below and its fields_obj is collected, so a stale
2617 * entry would let the global GC walk a freed value. */
2619
2620 /* A copy-on-write sharer reads its payload straight out of an embedded root's slot
2621 * (String#dup of a frozen string, Array#[] of a frozen array), and it outlives the
2622 * move, so that body has to survive as it is. */
2623 bool wipe_body = true;
2624 switch (BUILTIN_TYPE(obj)) {
2625 case T_STRING:
2626 if (!STR_EMBED_P(obj) && !rb_str_reembeddable_p(obj)) {
2627 /* A heap (non-embedded), shared root string keeps its buffer because
2628 * other strings reference this shared root. It needs to keep T_STRING
2629 * because otherwise the GC will not free the buffer when this object
2630 * dies which will leak memory. */
2631 RBASIC_SET_CLASS_RAW(obj, rb_cRactorMovedObject);
2632 RBASIC(obj)->flags |= FL_FREEZE;
2633 RBASIC_SET_FULL_SHAPE_ID(obj, (shape_id & ~SHAPE_ID_LAYOUT_MASK) | SHAPE_ID_LAYOUT_OTHER);
2634 RSTRING(obj)->len = 0;
2635 return;
2636 }
2637 wipe_body = !rb_str_embedded_shared_root_p(obj);
2638 break;
2639 case T_ARRAY:
2640 if (!ARY_EMBED_P(obj) && !ARY_SHARED_P(obj) && (ARY_SHARED_ROOT_P(obj) || OBJ_FROZEN(obj))) {
2641 /* A heap (non-embedded), shared root array keeps its buffer because
2642 * other arrays reference this shared root. It needs to keep T_ARRAY
2643 * because otherwise the GC will not free the buffer when this object
2644 * dies which will leak memory. */
2645 RBASIC_SET_CLASS_RAW(obj, rb_cRactorMovedObject);
2646 RBASIC(obj)->flags |= FL_FREEZE;
2647 RBASIC_SET_FULL_SHAPE_ID(obj, (shape_id & ~SHAPE_ID_LAYOUT_MASK) | SHAPE_ID_LAYOUT_OTHER);
2648 if (!ARY_SHARED_ROOT_P(obj)) {
2649 /* Present as empty to stale readers. Not for a shared root: its
2650 * len doubles as the buffer capacity that ARY_HEAP_SIZE frees by. */
2651 RARRAY(obj)->as.heap.len = 0;
2652 }
2653 return;
2654 }
2655 wipe_body = !rb_ary_embedded_shared_root_p(obj);
2656 break;
2657 default:
2658 break;
2659 }
2660
2661 /* Keep FL_FINALIZE: the finalizer table entry stays keyed on this slot, and a
2662 * shell without the flag makes the two disagree (rb_gc_impl_shutdown_call_finalizer_i
2663 * asserts on it). The finalizer runs when the shell dies, in the Ractor that
2664 * defined it; the rebuilt object gets fresh flags and does not inherit it. */
2665 VALUE flags = T_OBJECT | FL_FREEZE | (RBASIC(obj)->flags & (FL_PROMOTED | FL_FINALIZE));
2666 /* Read the slot size before the header is rewritten. */
2667 size_t slot_size = rb_gc_obj_slot_size(obj);
2668 RBASIC_SET_CLASS_RAW(obj, rb_cRactorMovedObject);
2669 RBASIC(obj)->flags = flags;
2670 RBASIC_SET_FULL_SHAPE_ID(obj, shape_id);
2671
2672 /* Wipe the old body. The shell has no fields, so nothing reads it as ivars, but
2673 * C code holding the object from before the move still reads it with its old type
2674 * (a running Array iteration, the RMatch capa of a $~ entry): a zeroed body makes
2675 * those reads see an empty object instead of stale internals. */
2676 if (wipe_body) {
2677 MEMZERO((char *)obj + sizeof(struct RBasic), char, slot_size - sizeof(struct RBasic));
2678 }
2679}
2680
2682 struct courier_build *b;
2683 uint32_t *kv;
2684 long i;
2685};
2686
2687static int
2688courier_capture_hash_i(st_data_t key, st_data_t val, st_data_t arg)
2689{
2690 struct courier_hash_ctx *hc = (struct courier_hash_ctx *)arg;
2691 uint32_t kid = courier_capture(hc->b, (VALUE)key);
2692 uint32_t vid = courier_capture(hc->b, (VALUE)val);
2693 hc->kv[hc->i++] = kid;
2694 hc->kv[hc->i++] = vid;
2695 return ST_CONTINUE;
2696}
2697
2699 struct courier_build *b;
2700 ID *ids;
2701 uint32_t *vals;
2702 long n;
2703 long capa;
2704};
2705
2706static int
2707courier_capture_ivar_i(ID name, VALUE val, st_data_t arg)
2708{
2709 struct courier_obj_ctx *oc = (struct courier_obj_ctx *)arg;
2710 if (oc->n == oc->capa) {
2711 oc->capa = oc->capa ? oc->capa * 2 : 4;
2712 REALLOC_N(oc->ids, ID, oc->capa);
2713 REALLOC_N(oc->vals, uint32_t, oc->capa);
2714 }
2715 uint32_t vid = courier_capture(oc->b, val);
2716 oc->ids[oc->n] = name;
2717 oc->vals[oc->n] = vid;
2718 oc->n++;
2719 return ST_CONTINUE;
2720}
2721
2722/* Capture obj's instance and generic ivars as node ids, recursing into the values.
2723 * Handles both a T_OBJECT's inline ivars and the generic ivars of a String, Array and
2724 * so on. */
2725static void
2726courier_capture_ivars(struct courier_build *b, VALUE obj, uint32_t id)
2727{
2728 struct courier_obj_ctx oc = { b, NULL, NULL, 0, 0 };
2729 rb_ivar_foreach_buffered(obj, courier_capture_ivar_i, (st_data_t)&oc);
2730 b->c->nodes[id].niv = (uint32_t)oc.n;
2731 b->c->nodes[id].iv_ids = oc.ids;
2732 b->c->nodes[id].iv_vals = oc.vals;
2733}
2734
2735/* Run obj's dump hook and capture what it returns as an ordinary child node. That
2736 * includes _dump's String: Marshal writes its ivars next to its bytes (Time keeps the
2737 * sub-microsecond part and the zone there), and a String node carries them the same
2738 * way. */
2739static void
2740courier_capture_hooked(struct courier_build *b, VALUE obj, uint32_t id, enum courier_hook hook)
2741{
2742 VALUE klass = rb_obj_class(obj);
2743 VALUE payload;
2744
2745 switch (hook) {
2746 case COURIER_HOOK_DUMP: {
2747 /* _dump takes the depth limit Marshal would have applied; a copy has none. */
2748 VALUE limit = INT2FIX(-1);
2749 payload = rb_funcallv(obj, id_dump, 1, &limit);
2750 if (!RB_TYPE_P(payload, T_STRING)) {
2751 rb_raise(rb_eTypeError, "_dump() must return string");
2752 }
2753 break;
2754 }
2755 case COURIER_HOOK_MARSHAL_DUMP:
2756 payload = rb_funcallv(obj, id_marshal_dump, 0, 0);
2757 break;
2758 case COURIER_HOOK_DUMP_DATA:
2759 payload = rb_funcallv(obj, id_dump_data, 0, 0);
2760 break;
2761 case COURIER_HOOK_COMPAT: {
2762 VALUE (*dumper)(VALUE);
2763 rb_marshal_compat_lookup(klass, &dumper, NULL);
2764 payload = dumper(obj);
2765 break;
2766 }
2767 default:
2768 rb_bug("courier_capture_hooked: no dump protocol");
2769 }
2770
2771 uint32_t payload_id = courier_capture(b, payload);
2772
2773 b->c->nodes[id].kind = COURIER_KIND_HOOKED;
2774 b->c->nodes[id].u.hooked.klass = klass;
2775 b->c->nodes[id].u.hooked.hook = hook;
2776 b->c->nodes[id].u.hooked.payload_id = payload_id;
2777}
2778
2779/* A move carries the singleton class with its object; a copy drops it, like #dup. */
2780static inline VALUE
2781courier_klass(struct courier_build *b, VALUE obj)
2782{
2783 return b->copy ? rb_obj_class(obj) : RBASIC_CLASS(obj);
2784}
2785
2786/* Capture obj into the courier, recurse into its children, return its node id. The id
2787 * is registered before recursing (a cycle back resolves to the same node); node fields
2788 * are written after (recursion can realloc c->nodes); a move neutralizes the source
2789 * exactly once after the switch. */
2790static uint32_t
2791courier_capture(struct courier_build *b, VALUE obj)
2792{
2793 /* An immediate is never in seen (only captured objects are inserted), so it can
2794 * skip the lookup entirely: that is the whole cost of an array of numbers. */
2795 if (RB_SPECIAL_CONST_P(obj)) {
2796 return courier_alloc_ref(b->c, obj);
2797 }
2798
2799 /* Seen first, and only then shareable: move husks each source as it goes, and a
2800 * husk is a frozen field-less object, which rb_ractor_shareable_p answers true for.
2801 * Testing shareable first would embed the husk instead of resolving the second
2802 * occurrence to the node the first one built. */
2803 st_data_t existing;
2804 if (st_lookup(b->c->seen, (st_data_t)obj, &existing)) {
2805 return (uint32_t)existing - 1;
2806 }
2807
2808 if (rb_ractor_shareable_p(obj)) {
2809 return courier_alloc_ref(b->c, obj);
2810 }
2811
2812 uint32_t id = courier_alloc_node(b->c);
2813 st_insert(b->c->seen, (st_data_t)obj, (st_data_t)(uintptr_t)(id + 1));
2814
2815 /* Reject an unmovable object before anything is mutated. */
2816 if (BUILTIN_TYPE(obj) == T_FILE && RFILE(obj)->fptr == NULL) {
2817 rb_raise(rb_eRactorError, "can not move an uninitialized IO");
2818 }
2819
2820 bool frozen = OBJ_FROZEN(obj);
2821 b->c->nodes[id].frozen = frozen;
2822 courier_capture_ivars(b, obj, id); /* shared: instance and generic ivars */
2823
2824 switch (BUILTIN_TYPE(obj)) {
2825 case T_STRING: {
2826 /* Give the source its own buffer (drop sharing, copy a static STR_NOFREE one).
2827 * Safe even when frozen: it changes ownership, not content. Afterwards a string
2828 * is embedded, owns a private heap buffer, or is a shared ROOT (a no-op). */
2829 if (!b->copy) rb_str_make_independent(obj);
2830 long len = RSTRING_LEN(obj);
2831 int encidx = ENCODING_GET(obj);
2832 /* The receiver adopts this buffer as a String body, which is freed by size:
2833 * capa has to describe the allocation exactly (capa + terminator bytes). */
2834 const int termlen = rb_enc_mbminlen(rb_enc_from_index(encidx));
2835 char *ptr;
2836 long capa;
2837 if (!b->copy && !STR_EMBED_P(obj) && rb_str_reembeddable_p(obj)) {
2838 /* Owns a private heap buffer: carry the pointer over (zero-copy) and leave
2839 * the source as a shell that does not free it. */
2840 ptr = RSTRING(obj)->as.heap.ptr;
2841 capa = RSTRING(obj)->as.heap.aux.capa;
2842 }
2843 else {
2844 /* Embedded or a shared root: copy the bytes into a courier-owned buffer.
2845 * Taking a root's buffer would dangle its copy-on-write children, so leave
2846 * it (the same reason T_ARRAY excludes ARY_SHARED_ROOT_P below). */
2847 ptr = ALLOC_N(char, len + termlen);
2848 if (len) memcpy(ptr, RSTRING_PTR(obj), len);
2849 memset(ptr + len, 0, termlen);
2850 capa = len;
2851 }
2852 b->c->nodes[id].kind = COURIER_KIND_STRING;
2853 b->c->nodes[id].u.str.klass = courier_klass(b, obj);
2854 b->c->nodes[id].u.str.ptr = ptr;
2855 b->c->nodes[id].u.str.len = len;
2856 b->c->nodes[id].u.str.capa = capa;
2857 b->c->nodes[id].u.str.encidx = encidx;
2858 break;
2859 }
2860
2861 case T_ARRAY: {
2862 long len = RARRAY_LEN(obj);
2863 uint32_t *elems = len ? ALLOC_N(uint32_t, len) : NULL;
2864 for (long i = 0; i < len; i++) {
2865 elems[i] = courier_capture(b, RARRAY_AREF(obj, i));
2866 }
2867 b->c->nodes[id].kind = COURIER_KIND_ARRAY;
2868 b->c->nodes[id].u.ary.klass = courier_klass(b, obj);
2869 b->c->nodes[id].u.ary.len = len;
2870 b->c->nodes[id].u.ary.elems = elems;
2871 /* Free the source's heap buffer now that the children were read, but only when it
2872 * is private: a sharer's belongs to its root, a root's to its sharers -- and a
2873 * frozen array is a root without carrying the flag. */
2874 if (!b->copy && !ARY_EMBED_P(obj) && !ARY_SHARED_P(obj) && !ARY_SHARED_ROOT_P(obj) && !OBJ_FROZEN(obj)) {
2875 ruby_xfree((void *)RARRAY_CONST_PTR(obj));
2876 }
2877 break;
2878 }
2879
2880 case T_HASH: {
2881 uint32_t ifnone_id = courier_capture(b, RHASH_IFNONE(obj));
2882 long size = RHASH_SIZE(obj);
2883 uint32_t *kv = size ? ALLOC_N(uint32_t, size * 2) : NULL;
2884 struct courier_hash_ctx hc = { b, kv, 0 };
2885 rb_hash_stlike_foreach(obj, courier_capture_hash_i, (st_data_t)&hc);
2886 b->c->nodes[id].kind = COURIER_KIND_HASH;
2887 b->c->nodes[id].u.hash.klass = courier_klass(b, obj);
2888 b->c->nodes[id].u.hash.size = size;
2889 b->c->nodes[id].u.hash.kv = kv;
2890 b->c->nodes[id].u.hash.ifnone_id = ifnone_id;
2891 b->c->nodes[id].u.hash.compare_by_id = RTEST(rb_hash_compare_by_id_p(obj));
2892 b->c->nodes[id].u.hash.proc_default = FL_TEST_RAW(obj, RHASH_PROC_DEFAULT) != 0;
2893 /* Free the source's st-table internals (an ar table lives in the slot) */
2894 if (!b->copy) rb_hash_free(obj);
2895 break;
2896 }
2897
2898 case T_OBJECT:
2899 b->c->nodes[id].kind = COURIER_KIND_OBJECT;
2900 b->c->nodes[id].u.obj.klass = courier_klass(b, obj);
2901 break;
2902
2903 case T_STRUCT: {
2904 long len = RSTRUCT_LEN(obj);
2905 uint32_t *elems = len ? ALLOC_N(uint32_t, len) : NULL;
2906 for (long i = 0; i < len; i++) {
2907 elems[i] = courier_capture(b, RSTRUCT_GET(obj, (int)i));
2908 }
2909 b->c->nodes[id].kind = COURIER_KIND_STRUCT;
2910 b->c->nodes[id].u.strct.len = len;
2911 b->c->nodes[id].u.strct.elems = elems;
2912 b->c->nodes[id].u.strct.klass = courier_klass(b, obj);
2913 /* Free the source's private heap buffer (an embedded struct has none) */
2914 if (!b->copy && RSTRUCT_EMBED_LEN(obj) == 0) {
2915 ruby_xfree((void *)RSTRUCT_CONST_PTR(obj));
2916 }
2917 break;
2918 }
2919
2920 case T_MATCH: {
2921 /* The regexp and the matched string travel as ordinary children; re.c dumps the
2922 * registers (freeing the source's onig and char_offset). */
2923 VALUE re, st;
2924 int nregs;
2925 void *regs = rb_match_blob_dump(obj, &re, &st, &nregs, !b->copy);
2926 uint32_t rid = courier_capture(b, re);
2927 uint32_t sid = courier_capture(b, st);
2928 b->c->nodes[id].kind = COURIER_KIND_MATCH;
2929 b->c->nodes[id].u.match.regexp_id = rid;
2930 b->c->nodes[id].u.match.str_id = sid;
2931 b->c->nodes[id].u.match.num_regs = nregs;
2932 b->c->nodes[id].u.match.regs = regs;
2933 b->c->nodes[id].u.match.klass = courier_klass(b, obj);
2934 break;
2935 }
2936
2937 case T_FILE:
2938 {
2939 VM_ASSERT(!b->copy); /* copy_courier_supported_p rejects it */
2940 /* Carry the whole fptr (fd included) by pointer; the source shell does not
2941 * close it. fptr's VALUE members lose their root once the source is T_MOVED,
2942 * so capture them as ordinary child nodes, detached; rebuild writes them back. */
2943 struct rb_io *fptr = RFILE(obj)->fptr;
2944 VM_ASSERT(!RTEST(fptr->tied_io_for_writing) && !RTEST(fptr->wakeup_mutex));
2945 uint32_t pathv_id = courier_capture(b, fptr->pathv);
2946 uint32_t ecopts_id = courier_capture(b, fptr->encs.ecopts);
2947 uint32_t wc_pre_id = courier_capture(b, fptr->writeconv_pre_ecopts);
2948 uint32_t wc_ac_id = courier_capture(b, fptr->writeconv_asciicompat);
2949 uint32_t timeout_id = courier_capture(b, fptr->timeout);
2950 fptr->self = Qnil; /* it points at the moved-from T_MOVED; attach rebuilds it */
2951 fptr->pathv = Qnil;
2952 fptr->encs.ecopts = Qnil;
2953 fptr->writeconv_pre_ecopts = Qnil;
2955 fptr->timeout = Qnil;
2956 fptr->write_lock = Qnil;
2957 fptr->wakeup_mutex = Qnil;
2958 fptr->tied_io_for_writing = 0; /* io.c tests it as a C boolean, so 0 rather than Qnil */
2959 b->c->nodes[id].kind = COURIER_KIND_IO;
2960 b->c->nodes[id].u.io.fptr = fptr;
2961 b->c->nodes[id].u.io.klass = courier_klass(b, obj);
2962 b->c->nodes[id].u.io.pathv_id = pathv_id;
2963 b->c->nodes[id].u.io.ecopts_id = ecopts_id;
2964 b->c->nodes[id].u.io.wc_pre_ecopts_id = wc_pre_id;
2965 b->c->nodes[id].u.io.wc_asciicompat_id = wc_ac_id;
2966 b->c->nodes[id].u.io.timeout_id = timeout_id;
2967 break;
2968 }
2969
2970 case T_REGEXP:
2971 /* Copy only: the receiver compiles the source again, as Marshal does. Move
2972 * would have to take the onig pattern apart. */
2973 if (b->copy) {
2974 /* The source is an fstring (reg_set_source), so it can be carried as is. */
2975 VALUE src = RREGEXP_SRC(obj);
2976 VM_ASSERT(rb_ractor_shareable_p(src));
2977 b->c->nodes[id].kind = COURIER_KIND_REGEXP;
2978 b->c->nodes[id].u.re.klass = courier_klass(b, obj);
2979 b->c->nodes[id].u.re.src = src;
2980 b->c->nodes[id].u.re.options = rb_reg_options(obj);
2981 break;
2982 }
2983 /* fall through */
2984 case T_DATA:
2985 /* Only an exception's backtrace, and only for a copy: move still refuses every
2986 * T_DATA (its source would have to be taken apart). */
2987 if (b->copy && rb_backtrace_p(obj)) {
2988 int size;
2989 void *blob = rb_backtrace_blob_dump(obj, &size);
2990 b->c->nodes[id].kind = COURIER_KIND_BACKTRACE;
2991 b->c->nodes[id].u.bt.blob = blob;
2992 b->c->nodes[id].u.bt.size = size;
2993 break;
2994 }
2995 /* fall through */
2996 default: {
2997 /* Copy has one more option: the object's own dump hook, which the preflight
2998 * already found. Move has not, since it would have to take the source apart. */
2999 enum courier_hook hook = b->copy ? courier_hook_of(obj) : COURIER_HOOK_NONE;
3000 if (hook == COURIER_HOOK_NONE) {
3001 rb_raise(rb_eRactorError, "can not %s a %"PRIsVALUE" object",
3002 b->copy ? "copy" : "move", rb_class_name(rb_obj_class(obj)));
3003 }
3004 courier_capture_hooked(b, obj, id, hook);
3005 break;
3006 }
3007 }
3008
3009 if (!b->copy) move_neutralize_source(obj);
3010 /* Every child has returned: the post-order materialize fills in. */
3011 b->c->order[b->ordered++] = id;
3012 return id;
3013}
3014
3015/* Like the copy walk, this also sizes the courier: see copy_support_ctx. */
3017 st_table *seen;
3018 uint32_t nodes, refs;
3019};
3020
3021static void move_preflight(VALUE obj, struct move_preflight_ctx *ctx);
3022
3023static int
3024move_preflight_ivar_i(ID name, VALUE val, st_data_t arg)
3025{
3026 move_preflight(val, (struct move_preflight_ctx *)arg);
3027 return ST_CONTINUE;
3028}
3029
3030static int
3031move_preflight_hash_i(st_data_t key, st_data_t val, st_data_t arg)
3032{
3033 move_preflight((VALUE)key, (struct move_preflight_ctx *)arg);
3034 move_preflight((VALUE)val, (struct move_preflight_ctx *)arg);
3035 return ST_CONTINUE;
3036}
3037
3038/* A read-only pre-walk of courier_capture's decision tree. Capture turns sources into
3039 * T_MOVED as it goes, so an unmovable object midway would leave the graph broken beyond
3040 * repair; every "can not move" error is raised here, before anything is mutated. */
3041static void
3042move_preflight(VALUE obj, struct move_preflight_ctx *ctx)
3043{
3044 st_table *const seen = ctx->seen;
3045
3046 if (RB_SPECIAL_CONST_P(obj) || rb_ractor_shareable_p(obj)) {
3047 ctx->refs++;
3048 return;
3049 }
3050 if (st_lookup(seen, (st_data_t)obj, NULL)) return; /* cycle */
3051 st_insert(seen, (st_data_t)obj, 0);
3052 ctx->nodes++;
3053
3054 /* The receiver takes over a materialized singleton class, so its contents have to
3055 * be movable too. */
3056 VALUE klass = RBASIC_CLASS(obj);
3057 if (RB_UNLIKELY(klass && FL_TEST_RAW(klass, FL_SINGLETON))) {
3058 rb_class_check_singleton_movable(klass);
3059 }
3060
3061 switch (BUILTIN_TYPE(obj)) {
3062 case T_STRING:
3063 case T_OBJECT:
3064 break; /* children are ivars only (below) */
3065 case T_MATCH: {
3066 struct RMatch *rm = RMATCH(obj);
3067 move_preflight(rm->regexp, ctx);
3068 move_preflight(rm->str, ctx);
3069 break;
3070 }
3071 case T_ARRAY:
3072 for (long i = 0; i < RARRAY_LEN(obj); i++) {
3073 move_preflight(RARRAY_AREF(obj, i), ctx);
3074 }
3075 break;
3076 case T_HASH:
3077 rb_hash_stlike_foreach(obj, move_preflight_hash_i, (st_data_t)ctx);
3078 move_preflight(RHASH_IFNONE(obj), ctx);
3079 break;
3080 case T_STRUCT:
3081 for (long i = 0; i < RSTRUCT_LEN(obj); i++) {
3082 move_preflight(RSTRUCT_GET(obj, (int)i), ctx);
3083 }
3084 break;
3085 case T_FILE: {
3086 struct rb_io *fptr = RFILE(obj)->fptr;
3087 if (fptr == NULL) {
3088 rb_raise(rb_eRactorError, "can not move an uninitialized IO");
3089 }
3090 if (RTEST(fptr->tied_io_for_writing)) {
3091 /* A popen("r+") pair: moving one side would dangle the tied writer on the
3092 * sender. */
3093 rb_raise(rb_eRactorError, "can not move an IO tied to a writer IO");
3094 }
3095 if (RTEST(fptr->wakeup_mutex)) {
3096 /* A close is in progress: a thread is blocked on this IO. */
3097 rb_raise(rb_eRactorError, "can not move an IO that is being closed");
3098 }
3099 move_preflight(fptr->pathv, ctx);
3100 move_preflight(fptr->encs.ecopts, ctx);
3101 move_preflight(fptr->writeconv_pre_ecopts, ctx);
3102 move_preflight(fptr->writeconv_asciicompat, ctx);
3103 move_preflight(fptr->timeout, ctx);
3104 break;
3105 }
3106 default:
3107 rb_raise(rb_eRactorError, "can not move a %"PRIsVALUE" object",
3109 }
3110
3111 rb_ivar_foreach(obj, move_preflight_ivar_i, (st_data_t)ctx);
3112}
3113
3114/* The walk also sizes the courier: one node per distinct unshareable object, one ref
3115 * per occurrence of a shareable one -- exactly what courier_capture allocates, so the
3116 * arrays never have to grow while the graph is being captured. */
3118 st_table *seen;
3119 uint32_t nodes, refs;
3120 bool ok;
3121};
3122
3123static bool copy_courier_supported_p(VALUE obj, struct copy_support_ctx *ctx);
3124
3125static int
3126copy_support_val_i(st_data_t val, st_data_t arg)
3127{
3128 struct copy_support_ctx *ctx = (struct copy_support_ctx *)arg;
3129 if (!copy_courier_supported_p((VALUE)val, ctx)) {
3130 ctx->ok = false;
3131 return ST_STOP;
3132 }
3133 return ST_CONTINUE;
3134}
3135
3136static int
3137copy_support_ivar_i(ID name, VALUE val, st_data_t arg)
3138{
3139 return copy_support_val_i((st_data_t)val, arg);
3140}
3141
3142static int
3143copy_support_hash_i(st_data_t key, st_data_t val, st_data_t arg)
3144{
3145 if (copy_support_val_i(key, arg) == ST_STOP) return ST_STOP;
3146 return copy_support_val_i(val, arg);
3147}
3148
3149/* Read-only walk: can the copy courier carry obj's whole graph? A no is a send error. */
3150static bool
3151copy_courier_supported_p(VALUE obj, struct copy_support_ctx *ctx)
3152{
3153 st_table *const seen = ctx->seen;
3154
3155 if (RB_SPECIAL_CONST_P(obj) || rb_ractor_shareable_p(obj)) {
3156 ctx->refs++;
3157 return true;
3158 }
3159 if (st_lookup(seen, (st_data_t)obj, NULL)) return true; /* cycle */
3160 st_insert(seen, (st_data_t)obj, 0);
3161 ctx->nodes++;
3162
3163 if (RBASIC_CLASS(obj) == 0) return false;
3164
3165 switch (BUILTIN_TYPE(obj)) {
3166 case T_STRING:
3167 case T_OBJECT:
3168 case T_REGEXP:
3169 break; /* children are ivars only (below) */
3170 case T_MATCH: {
3171 struct RMatch *rm = RMATCH(obj);
3172 if (!copy_courier_supported_p(rm->regexp, ctx)) return false;
3173 if (!copy_courier_supported_p(rm->str, ctx)) return false;
3174 break;
3175 }
3176 case T_DATA:
3177 /* An exception's backtrace is the one T_DATA the courier carries natively. */
3178 if (!rb_backtrace_p(obj) && courier_hook_of(obj) == COURIER_HOOK_NONE) return false;
3179 break;
3180 case T_ARRAY:
3181 for (long i = 0; i < RARRAY_LEN(obj); i++) {
3182 if (!copy_courier_supported_p(RARRAY_AREF(obj, i), ctx)) return false;
3183 }
3184 break;
3185 case T_HASH:
3186 rb_hash_stlike_foreach(obj, copy_support_hash_i, (st_data_t)ctx);
3187 if (!ctx->ok) return false;
3188 if (!copy_courier_supported_p(RHASH_IFNONE(obj), ctx)) return false;
3189 break;
3190 case T_STRUCT:
3191 for (long i = 0; i < RSTRUCT_LEN(obj); i++) {
3192 if (!copy_courier_supported_p(RSTRUCT_GET(obj, (int)i), ctx)) return false;
3193 }
3194 break;
3195 default:
3196 /* Anything else has to dump itself. What the hook returns is not walked here:
3197 * running it twice is not an option, so capture allocates its nodes through the
3198 * growth path instead of the reservation. */
3199 if (courier_hook_of(obj) == COURIER_HOOK_NONE) return false;
3200 break;
3201 }
3202
3203 rb_ivar_foreach(obj, copy_support_ivar_i, (st_data_t)ctx);
3204 return ctx->ok;
3205}
3206
3207/* Build a courier holding a copy of obj's graph, leaving the sources untouched.
3208 * Returns NULL when the graph has a type it cannot carry. */
3209struct rb_ractor_courier *
3210rb_ractor_courier_build_copy(VALUE obj, struct rb_ractor_courier **slot)
3211{
3212 struct copy_support_ctx scan = { st_init_numtable(), 0, 0, true };
3213 {
3214 bool ok = copy_courier_supported_p(obj, &scan);
3215 st_free_table(scan.seen);
3216 if (!ok) return NULL;
3217 }
3218
3219 struct rb_ractor_courier *c = ZALLOC(struct rb_ractor_courier);
3220 courier_reserve(c, scan.nodes, scan.refs);
3221 c->seen = st_init_numtable();
3222 struct courier_build b = { c, true };
3223
3224 /* Publish it into the caller's basket before capturing anything: from here the
3225 * shareable payloads it collects are rooted by the basket's holder. */
3226 *slot = c;
3227
3228 enum ruby_tag_type state;
3229 rb_execution_context_t *ec = GET_EC();
3230 EC_PUSH_TAG(ec);
3231 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
3232 c->root = courier_capture(&b, obj);
3233 }
3234 EC_POP_TAG();
3235 st_free_table(c->seen);
3236 c->seen = NULL;
3237 /* Published above, so the basket owns it even half-built: it frees it. */
3238 if (state != TAG_NONE) EC_JUMP_TAG(ec, state);
3239 return c;
3240}
3241
3242/* Build a courier from obj and turn every captured source into a RactorMovedObject
3243 * (move semantics). Returns the xmalloc'd courier. */
3244struct rb_ractor_courier *
3245rb_ractor_courier_build_move(VALUE obj, struct rb_ractor_courier **slot)
3246{
3247 /* Two phases, preflight then commit, so an unmovable object is raised from the
3248 * read-only walk while the graph is still intact. */
3249 struct move_preflight_ctx scan = { st_init_numtable(), 0, 0 };
3250 {
3251 enum ruby_tag_type state;
3252 rb_execution_context_t *ec = GET_EC();
3253 EC_PUSH_TAG(ec);
3254 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
3255 move_preflight(obj, &scan);
3256 }
3257 EC_POP_TAG();
3258 st_free_table(scan.seen);
3259 if (state != TAG_NONE) EC_JUMP_TAG(ec, state);
3260 }
3261
3262 struct rb_ractor_courier *c = ZALLOC(struct rb_ractor_courier);
3263 courier_reserve(c, scan.nodes, scan.refs);
3264 c->seen = st_init_numtable();
3265 struct courier_build b = { c, false };
3266
3267 /* Publish it into the caller's basket before the sources become T_MOVED: from here
3268 * the basket's holder roots what the courier carries, and partial nodes are
3269 * initialized mark-safe. */
3270 *slot = c;
3271
3272 enum ruby_tag_type state;
3273 rb_execution_context_t *ec = GET_EC();
3274 EC_PUSH_TAG(ec);
3275 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
3276 c->root = courier_capture(&b, obj);
3277 }
3278 EC_POP_TAG();
3279 st_free_table(c->seen);
3280 c->seen = NULL;
3281 if (state != TAG_NONE) {
3282 /* courier_capture raised (an unmovable type, an interrupt). The courier belongs
3283 * to the basket from the publish above, so leave it there and re-raise: the
3284 * basket frees it, once, on the way out. */
3285 EC_JUMP_TAG(ec, state);
3286 }
3287 return c;
3288}
3289
3290/* Shells are created with the base/real class, so re-attach the original subclass or
3291 * singleton class (classes are shareable; the reference is safe). A singleton's
3292 * attached object still points at the sender's source: re-attach it to the shell. */
3293static void
3294courier_apply_klass(VALUE shell, VALUE klass)
3295{
3296 if (klass != RBASIC_CLASS(shell)) {
3297 RBASIC_SET_CLASS(shell, klass);
3298 }
3299 if (RB_UNLIKELY(FL_TEST_RAW(klass, FL_SINGLETON))) {
3300 rb_singleton_class_attached(klass, shell);
3301 /* the singleton class follows its object, which is now this Ractor's */
3302 rb_class_take_ownership(klass);
3303 }
3304}
3305
3306/* Rebuild the courier's graph in the current Ractor's objspace and return its root.
3307 * Two passes (allocate shells, then fill) break reference cycles. */
3308VALUE
3309rb_ractor_courier_materialize(struct rb_ractor_courier *c)
3310{
3311 /* A hidden Array roots every shell, keeping them alive while the allocations that
3312 * build the rest of the graph (which can start this Ractor's GC) run. */
3313 VALUE shells = rb_ary_hidden_new(c->count);
3314
3315 for (uint32_t i = 0; i < c->count; i++) {
3316 struct courier_node *n = &c->nodes[i];
3317 VALUE shell;
3318 switch (n->kind) {
3319 case COURIER_KIND_REF:
3320 shell = n->u.ref;
3321 break;
3322 case COURIER_KIND_STRING:
3323 /* Hand the courier's buffer to the String instead of copying it again: the
3324 * bytes were already copied (or taken from the source) when the node was
3325 * built. */
3326 shell = rb_str_new_owned(n->u.str.ptr, n->u.str.len, n->u.str.capa, n->u.str.encidx);
3327 n->u.str.ptr = NULL; /* consumed: the new String owns it now */
3328 courier_apply_klass(shell, n->u.str.klass);
3329 break;
3330 case COURIER_KIND_ARRAY:
3331 shell = rb_ary_new_capa(n->u.ary.len);
3332 courier_apply_klass(shell, n->u.ary.klass);
3333 break;
3334 case COURIER_KIND_HASH:
3335 shell = n->u.hash.compare_by_id ? rb_ident_hash_new() : rb_hash_new();
3336 courier_apply_klass(shell, n->u.hash.klass);
3337 break;
3338 case COURIER_KIND_OBJECT:
3339 /* A singleton class cannot allocate, so make an instance of the real class
3340 * and re-attach it afterwards */
3341 shell = rb_obj_alloc(rb_class_real(n->u.obj.klass));
3342 courier_apply_klass(shell, n->u.obj.klass);
3343 break;
3344 case COURIER_KIND_STRUCT:
3345 shell = rb_obj_alloc(rb_class_real(n->u.strct.klass));
3346 courier_apply_klass(shell, n->u.strct.klass);
3347 break;
3348 case COURIER_KIND_MATCH:
3349 shell = rb_match_blob_alloc(rb_class_real(n->u.match.klass), n->u.match.num_regs);
3350 courier_apply_klass(shell, n->u.match.klass);
3351 break;
3352 case COURIER_KIND_BACKTRACE:
3353 shell = rb_backtrace_blob_load(n->u.bt.blob, n->u.bt.size);
3354 break;
3355 case COURIER_KIND_REGEXP:
3356 /* Allocated as its real class up front, as Marshal does: initializing a
3357 * plain Regexp freezes it, and the freeze pass below decides that here. */
3358 shell = rb_reg_init_str(rb_reg_s_alloc(rb_class_real(n->u.re.klass)), n->u.re.src, n->u.re.options);
3359 courier_apply_klass(shell, n->u.re.klass);
3360 break;
3361 case COURIER_KIND_HOOKED:
3362 if (n->u.hooked.hook == COURIER_HOOK_DUMP) {
3363 shell = Qnil; /* klass._load makes it below, once its String exists */
3364 break;
3365 }
3366 /* Allocated now and filled by its load hook below, which is what lets a
3367 * cycle back through the payload resolve to the object itself. */
3368 shell = rb_obj_alloc(rb_class_real(n->u.hooked.klass));
3369 courier_apply_klass(shell, n->u.hooked.klass);
3370 break;
3371 case COURIER_KIND_IO:
3372 shell = rb_obj_alloc(rb_class_real(n->u.io.klass));
3373 courier_apply_klass(shell, n->u.io.klass);
3374 RFILE(shell)->fptr = n->u.io.fptr;
3375 n->u.io.fptr->self = shell;
3376 n->u.io.fptr = NULL; /* consumed: the new IO owns it now */
3377 break;
3378 default:
3379 rb_bug("rb_ractor_courier_materialize: bad node kind");
3380 }
3381 rb_ary_push(shells, shell);
3382 }
3383
3384 /* Fill in capture's post-order, so each node is settled after everything below it,
3385 * shared children included: a Hash sees complete keys (a content-based #hash would
3386 * collide on every key while the graph is still empty), a load hook sees a complete
3387 * payload, and a parent sees the object klass._load returned. Only a cycle reaches
3388 * a node still being filled (a #hash or a payload cycling through itself is out of
3389 * scope). */
3390 for (uint32_t k = 0; k < c->count; k++) {
3391 uint32_t i = c->order[k];
3392 struct courier_node *n = &c->nodes[i];
3393 VALUE shell = RARRAY_AREF(shells, i);
3394 switch (n->kind) {
3395 case COURIER_KIND_ARRAY: {
3396 /* The length is known, so set it once and write the slots, rather than
3397 * pushing each element through the capacity check. */
3398 const long len = n->u.ary.len;
3399 if (len > 0) {
3400 rb_ary_resize(shell, len);
3401 for (long j = 0; j < len; j++) {
3402 RARRAY_ASET(shell, j, courier_child(c, shells, n->u.ary.elems[j]));
3403 }
3404 }
3405 break;
3406 }
3407 case COURIER_KIND_HASH:
3408 for (long j = 0; j < n->u.hash.size; j++) {
3409 rb_hash_aset(shell, courier_child(c, shells, n->u.hash.kv[2 * j]),
3410 courier_child(c, shells, n->u.hash.kv[2 * j + 1]));
3411 }
3412 /* Restore the default value and default proc (before freezing) */
3413 VALUE ifnone = courier_child(c, shells, n->u.hash.ifnone_id);
3414 if (n->u.hash.proc_default) {
3415 rb_hash_set_default_proc(shell, ifnone);
3416 }
3417 else if (ifnone != Qnil) {
3418 rb_hash_set_default(shell, ifnone);
3419 }
3420 break;
3421 case COURIER_KIND_HOOKED: {
3422 VALUE payload = courier_child(c, shells, n->u.hooked.payload_id);
3423 VALUE klass = n->u.hooked.klass;
3424 ID mid;
3425 switch (n->u.hooked.hook) {
3426 case COURIER_HOOK_DUMP:
3427 if (!rb_obj_respond_to(klass, id_load, TRUE)) {
3428 rb_raise(rb_eTypeError, "class %"PRIsVALUE" needs to have method '_load'", klass);
3429 }
3430 /* _load returns the object: it takes the place of the Qnil placeholder
3431 * so everything filled after this receives it, and the ivars restored
3432 * below land on it. */
3433 shell = rb_funcallv(klass, id_load, 1, &payload);
3434 RARRAY_ASET(shells, i, shell);
3435 break;
3436 case COURIER_HOOK_MARSHAL_DUMP:
3437 case COURIER_HOOK_DUMP_DATA:
3438 mid = n->u.hooked.hook == COURIER_HOOK_MARSHAL_DUMP ? id_marshal_load : id_load_data;
3439 if (!rb_obj_respond_to(shell, mid, TRUE)) {
3440 rb_raise(rb_eTypeError, "instance of %"PRIsVALUE" needs to have method '%"PRIsVALUE"'",
3441 klass, rb_id2str(mid));
3442 }
3443 rb_funcallv(shell, mid, 1, &payload);
3444 break;
3445 case COURIER_HOOK_COMPAT: {
3446 VALUE (*loader)(VALUE, VALUE);
3447 rb_marshal_compat_lookup(klass, NULL, &loader);
3448 loader(shell, payload);
3449 break;
3450 }
3451 default:
3452 rb_bug("rb_ractor_courier_materialize: no dump protocol");
3453 }
3454 break;
3455 }
3456 case COURIER_KIND_STRUCT:
3457 for (long j = 0; j < n->u.strct.len; j++) {
3458 RSTRUCT_SET(shell, (int)j, courier_child(c, shells, n->u.strct.elems[j]));
3459 }
3460 break;
3461 case COURIER_KIND_MATCH:
3462 rb_match_blob_load(shell, courier_child(c, shells, n->u.match.regexp_id),
3463 courier_child(c, shells, n->u.match.str_id),
3464 n->u.match.num_regs, n->u.match.regs);
3465 break;
3466 case COURIER_KIND_IO: {
3467 /* Write the rebuilt VALUE members back into fptr (capture detached them).
3468 * write_lock and wakeup_mutex stay nil; io.c recreates them lazily. */
3469 struct rb_io *fptr = RFILE(shell)->fptr;
3470 RB_OBJ_WRITE(shell, &fptr->pathv, courier_child(c, shells, n->u.io.pathv_id));
3471 RB_OBJ_WRITE(shell, &fptr->encs.ecopts, courier_child(c, shells, n->u.io.ecopts_id));
3472 RB_OBJ_WRITE(shell, &fptr->writeconv_pre_ecopts, courier_child(c, shells, n->u.io.wc_pre_ecopts_id));
3473 RB_OBJ_WRITE(shell, &fptr->writeconv_asciicompat, courier_child(c, shells, n->u.io.wc_asciicompat_id));
3474 RB_OBJ_WRITE(shell, &fptr->timeout, courier_child(c, shells, n->u.io.timeout_id));
3475 break;
3476 }
3477 default:
3478 break;
3479 }
3480 /* Restore instance and generic ivars (any non-REF node can have them) */
3481 for (uint32_t j = 0; j < n->niv; j++) {
3482 rb_ivar_set(shell, n->iv_ids[j], courier_child(c, shells, n->iv_vals[j]));
3483 }
3484 }
3485
3486 /* Freeze after filling, so frozen containers and strings can be built too. */
3487 for (uint32_t i = 0; i < c->count; i++) {
3488 VALUE shell = RARRAY_AREF(shells, i);
3489 if (c->nodes[i].frozen && !RB_SPECIAL_CONST_P(shell)) {
3490 rb_obj_freeze(shell);
3491 }
3492 }
3493
3494 VALUE root = (c->count || c->refs_count) ? courier_child(c, shells, c->root) : Qnil;
3495 RB_GC_GUARD(shells);
3496 return root;
3497}
3498
3499void
3500rb_ractor_courier_free(struct rb_ractor_courier *c)
3501{
3502 for (uint32_t i = 0; i < c->count; i++) {
3503 struct courier_node *n = &c->nodes[i];
3504 ruby_xfree(n->iv_ids);
3505 ruby_xfree(n->iv_vals);
3506 switch (n->kind) {
3507 case COURIER_KIND_STRING:
3508 ruby_xfree(n->u.str.ptr);
3509 break;
3510 case COURIER_KIND_ARRAY:
3511 ruby_xfree(n->u.ary.elems);
3512 break;
3513 case COURIER_KIND_HASH:
3514 ruby_xfree(n->u.hash.kv);
3515 break;
3516 case COURIER_KIND_STRUCT:
3517 ruby_xfree(n->u.strct.elems);
3518 break;
3519 case COURIER_KIND_MATCH:
3520 rb_match_blob_free(n->u.match.regs);
3521 break;
3522 case COURIER_KIND_BACKTRACE:
3523 ruby_xfree(n->u.bt.blob);
3524 break;
3525 case COURIER_KIND_IO:
3526 /* A delivered IO left fptr == NULL (the rebuilt IO owns it). An
3527 * undelivered one still owns the fd and its source is already a
3528 * RactorMovedObject nobody can close: close it here, not leak it. */
3529 if (n->u.io.fptr) {
3530 rb_io_fptr_finalize(n->u.io.fptr);
3531 n->u.io.fptr = NULL;
3532 }
3533 break;
3534 default:
3535 break;
3536 }
3537 }
3538 ruby_xfree(c->nodes);
3539 ruby_xfree(c->order);
3540 ruby_xfree(c->refs);
3541 ruby_xfree(c);
3542}
3543
3544/* Mark the only VALUEs a courier holds: shareable objects and immediates (REF) and the
3545 * classes of its objects. All of them are shareable, so marking cannot race, and the
3546 * global GC keeps them reachable through the courier. While it is being built it also
3547 * holds the sender's sources in seen; the basket is on the sender's own list then. */
3548void
3549rb_ractor_courier_mark(struct rb_ractor_courier *c)
3550{
3551 if (!c) return;
3552 if (c->seen) rb_mark_set(c->seen);
3553 for (uint32_t i = 0; i < c->refs_count; i++) {
3554 rb_gc_mark(c->refs[i]);
3555 }
3556 for (uint32_t i = 0; i < c->count; i++) {
3557 struct courier_node *n = &c->nodes[i];
3558 if (n->kind == COURIER_KIND_REF) {
3559 rb_gc_mark(n->u.ref);
3560 }
3561 else if (n->kind == COURIER_KIND_OBJECT) {
3562 rb_gc_mark(n->u.obj.klass);
3563 }
3564 else if (n->kind == COURIER_KIND_STRUCT) {
3565 rb_gc_mark(n->u.strct.klass);
3566 }
3567 else if (n->kind == COURIER_KIND_MATCH) {
3568 rb_gc_mark(n->u.match.klass);
3569 }
3570 else if (n->kind == COURIER_KIND_IO) {
3571 rb_gc_mark(n->u.io.klass);
3572 }
3573 else if (n->kind == COURIER_KIND_STRING) {
3574 rb_gc_mark(n->u.str.klass);
3575 }
3576 else if (n->kind == COURIER_KIND_BACKTRACE) {
3577 rb_backtrace_blob_mark(n->u.bt.blob, n->u.bt.size);
3578 }
3579 else if (n->kind == COURIER_KIND_ARRAY) {
3580 rb_gc_mark(n->u.ary.klass);
3581 }
3582 else if (n->kind == COURIER_KIND_HASH) {
3583 rb_gc_mark(n->u.hash.klass);
3584 }
3585 else if (n->kind == COURIER_KIND_REGEXP) {
3586 rb_gc_mark(n->u.re.src);
3587 rb_gc_mark(n->u.re.klass);
3588 }
3589 else if (n->kind == COURIER_KIND_HOOKED) {
3590 rb_gc_mark(n->u.hooked.klass);
3591 }
3592 }
3593}
3594
3595/* The message copy traversal never calls #clone or #initialize_clone. Core container
3596 * types get a native shallow copy here (the traversal then rewrites the children inside
3597 * the copy); any other unshareable type falls back to a full Marshal round trip. */
3598static VALUE
3599ractor_native_shallow_copy(VALUE obj)
3600{
3601 VALUE copy;
3602
3603 /* An object with a singleton class cannot be copied natively; fall back to Marshal
3604 * so it reports a proper error. */
3605 VALUE klass = RBASIC_CLASS(obj);
3606 if (klass == 0 || FL_TEST_RAW(klass, FL_SINGLETON)) {
3607 return Qundef;
3608 }
3609
3610 switch (BUILTIN_TYPE(obj)) {
3611 case T_OBJECT:
3612 copy = rb_obj_alloc(rb_obj_class(obj));
3613 rb_obj_copy_ivar(copy, obj);
3614 break;
3615 case T_STRING:
3616 copy = rb_enc_str_new(RSTRING_PTR(obj), RSTRING_LEN(obj), rb_enc_get(obj));
3617 break;
3618 case T_ARRAY:
3620 break;
3621 case T_HASH:
3622 copy = rb_hash_dup(obj);
3623 break;
3624 case T_STRUCT:
3625 copy = rb_obj_alloc(rb_obj_class(obj));
3626 rb_struct_init_copy(copy, obj);
3627 break;
3628 case T_MATCH:
3629 copy = rb_obj_alloc(rb_obj_class(obj));
3630 rb_match_init_copy(copy, obj);
3631 break;
3632 case T_DATA:
3633 /* Keep a copied exception from carrying a raw pointer to the sender's backtrace
3634 * across objspaces */
3635 if (rb_backtrace_p(obj)) {
3636 copy = rb_backtrace_dup(obj);
3637 break;
3638 }
3639 return Qundef;
3640 default:
3641 return Qundef;
3642 }
3643
3644 /* A non-T_OBJECT host keeps its ivars in the generic fields table: copy them.
3645 * T_HASH is excluded: rb_hash_dup already ran rb_copy_generic_ivar, and a second
3646 * call asserts in rb_shape_rebuild (the first gave the copy an ivar shape). */
3647 if (BUILTIN_TYPE(obj) != T_OBJECT && BUILTIN_TYPE(obj) != T_HASH &&
3648 UNLIKELY(rb_obj_gen_fields_p(obj))) {
3649 rb_copy_generic_ivar(copy, obj);
3650 }
3651
3652 /* The traversal rewrites the children inside the copy with raw stores, so the frozen
3653 * bit can be set now: by the time leave runs the original is out of sight. The shape
3654 * has to be transitioned along with the flag, because field writes are refused based
3655 * on the shape (see rb_check_ivar_modifiable). */
3656 if (OBJ_FROZEN(obj)) {
3658 RBASIC_SET_SHAPE_ID(copy, rb_obj_shape_transition_frozen(copy));
3659 }
3660 return copy;
3661}
3662
3663static enum obj_traverse_iterator_result
3664copy_enter(VALUE obj, struct obj_traverse_replace_data *data)
3665{
3666 if (rb_ractor_shareable_p(obj)) {
3667 data->replacement = obj;
3668 return traverse_skip;
3669 }
3670 else {
3671 VALUE copy = ractor_native_shallow_copy(obj);
3672 if (UNDEF_P(copy)) return traverse_stop; /* no native copy for this type */
3673 data->replacement = copy;
3674 return traverse_cont;
3675 }
3676}
3677
3678static enum obj_traverse_iterator_result
3679copy_leave(VALUE obj, struct obj_traverse_replace_data *data)
3680{
3681 return traverse_cont;
3682}
3683
3684/* Native deep copy of obj's graph. Returns Qundef when it contains a type the native
3685 * copier does not support, and the caller falls back to Marshal. */
3686static VALUE
3687ractor_copy_native_try(VALUE obj)
3688{
3689 return rb_obj_traverse_replace(obj, copy_enter, copy_leave, false);
3690}
3691
3692/* Deep copy within one objspace (Ractor.make_shareable(obj, copy: true)): native first,
3693 * then a whole-graph Marshal round trip. */
3694static VALUE
3695ractor_copy(VALUE obj)
3696{
3697 VALUE copy = ractor_copy_native_try(obj);
3698 if (UNDEF_P(copy)) {
3699 copy = rb_marshal_load(rb_rescue2(ractor_marshal_dump_body, obj,
3700 ractor_marshal_dump_rescue, obj,
3701 rb_eTypeError, (VALUE)0));
3702 }
3703 return copy;
3704}
3705
3706// Ractor local storage
3707
3709 const struct rb_ractor_local_storage_type *type;
3710 void *main_cache;
3711};
3712
3714 int cnt;
3715 int capa;
3717} freed_ractor_local_keys;
3718
3719/* Purge deleted ractor-local keys from the storage tables and run their free hooks. */
3720static void
3721ractor_local_keys_purge(st_table *local_storage)
3722{
3723 for (int i=0; i<freed_ractor_local_keys.cnt; i++) {
3724 rb_ractor_local_key_t key = freed_ractor_local_keys.keys[i];
3725 st_data_t val, k = (st_data_t)key;
3726 if (st_delete(local_storage, &k, &val) &&
3727 (key = (rb_ractor_local_key_t)k)->type->free) {
3728 (*key->type->free)((void *)val);
3729 }
3730 }
3731}
3732
3733
3734static int
3735ractor_local_storage_mark_i(st_data_t key, st_data_t val, st_data_t dmy)
3736{
3738 if (k->type->mark) (*k->type->mark)((void *)val);
3739 return ST_CONTINUE;
3740}
3741
3742static enum rb_id_table_iterator_result
3743idkey_local_storage_mark_i(VALUE val, void *dmy)
3744{
3745 rb_gc_mark(val);
3746 return ID_TABLE_CONTINUE;
3747}
3748
3749static void
3750ractor_local_storage_mark(rb_ractor_t *r)
3751{
3752 if (r->local_storage) {
3753 st_foreach(r->local_storage, ractor_local_storage_mark_i, 0);
3754
3755 /* A deleted key is purged from every Ractor's storage in one collection, which
3756 * then frees its struct. Only a collection that visits every Ractor with no
3757 * other marker running can do that: a global GC, or a single objspace. */
3758 if (rb_gc_single_objspace_p() || rb_gc_during_global_gc_p()) {
3759 ractor_local_keys_purge(r->local_storage);
3760 }
3761 }
3762
3763 if (r->idkey_local_storage) {
3764 rb_id_table_foreach_values(r->idkey_local_storage, idkey_local_storage_mark_i, NULL);
3765 }
3766
3767 rb_gc_mark(r->local_storage_store_lock);
3768}
3769
3770static int
3771ractor_local_storage_free_i(st_data_t key, st_data_t val, st_data_t dmy)
3772{
3774 if (k->type->free) (*k->type->free)((void *)val);
3775 return ST_CONTINUE;
3776}
3777
3778static void
3779ractor_local_storage_free(rb_ractor_t *r)
3780{
3781 if (r->local_storage) {
3782 st_foreach(r->local_storage, ractor_local_storage_free_i, 0);
3783 st_free_table(r->local_storage);
3784 }
3785
3786 if (r->idkey_local_storage) {
3787 rb_id_table_free(r->idkey_local_storage);
3788 }
3789}
3790
3791static void
3792rb_ractor_local_storage_value_mark(void *ptr)
3793{
3794 rb_gc_mark((VALUE)ptr);
3795}
3796
3797static const struct rb_ractor_local_storage_type ractor_local_storage_type_null = {
3798 NULL,
3799 NULL,
3800};
3801
3803 NULL,
3804 ruby_xfree,
3805};
3806
3807static const struct rb_ractor_local_storage_type ractor_local_storage_type_value = {
3808 rb_ractor_local_storage_value_mark,
3809 NULL,
3810};
3811
3814{
3816 key->type = type ? type : &ractor_local_storage_type_null;
3817 key->main_cache = (void *)Qundef;
3818 return key;
3819}
3820
3823{
3824 return rb_ractor_local_storage_ptr_newkey(&ractor_local_storage_type_value);
3825}
3826
3827void
3828rb_ractor_local_storage_delkey(rb_ractor_local_key_t key)
3829{
3830 RB_VM_LOCKING() {
3831 if (freed_ractor_local_keys.cnt == freed_ractor_local_keys.capa) {
3832 freed_ractor_local_keys.capa = freed_ractor_local_keys.capa ? freed_ractor_local_keys.capa * 2 : 4;
3833 SIZED_REALLOC_N(freed_ractor_local_keys.keys, rb_ractor_local_key_t, freed_ractor_local_keys.capa, freed_ractor_local_keys.cnt);
3834 }
3835 freed_ractor_local_keys.keys[freed_ractor_local_keys.cnt++] = key;
3836 }
3837}
3838
3839static bool
3840ractor_local_ref(rb_ractor_local_key_t key, void **pret)
3841{
3842 if (rb_ractor_main_p()) {
3843 if (!UNDEF_P((VALUE)key->main_cache)) {
3844 *pret = key->main_cache;
3845 return true;
3846 }
3847 else {
3848 return false;
3849 }
3850 }
3851 else {
3852 rb_ractor_t *cr = GET_RACTOR();
3853
3854 if (cr->local_storage && st_lookup(cr->local_storage, (st_data_t)key, (st_data_t *)pret)) {
3855 return true;
3856 }
3857 else {
3858 return false;
3859 }
3860 }
3861}
3862
3863static void
3864ractor_local_set(rb_ractor_local_key_t key, void *ptr)
3865{
3866 rb_ractor_t *cr = GET_RACTOR();
3867
3868 if (cr->local_storage == NULL) {
3869 cr->local_storage = st_init_numtable();
3870 }
3871
3872 st_insert(cr->local_storage, (st_data_t)key, (st_data_t)ptr);
3873
3874 if (rb_ractor_main_p()) {
3875 key->main_cache = ptr;
3876 }
3877}
3878
3879VALUE
3881{
3882 void *val;
3883 if (ractor_local_ref(key, &val)) {
3884 return (VALUE)val;
3885 }
3886 else {
3887 return Qnil;
3888 }
3889}
3890
3891bool
3893{
3894 if (ractor_local_ref(key, (void **)val)) {
3895 return true;
3896 }
3897 else {
3898 return false;
3899 }
3900}
3901
3902void
3904{
3905 ractor_local_set(key, (void *)val);
3906}
3907
3908void *
3910{
3911 void *ret;
3912 if (ractor_local_ref(key, &ret)) {
3913 return ret;
3914 }
3915 else {
3916 return NULL;
3917 }
3918}
3919
3920void
3922{
3923 ractor_local_set(key, ptr);
3924}
3925
3926#define DEFAULT_KEYS_CAPA 0x10
3927
3928void
3929rb_ractor_finish_marking(bool full_mark)
3930{
3931 /* A freed key's struct may only be released by a collection that purged every
3932 * Ractor's storage with no other marker running: a global GC, or a single objspace.
3933 * A local GC also reaches here (gc_marks_finish) and must do nothing. */
3934 if (!(rb_gc_single_objspace_p() || rb_gc_during_global_gc_p())) {
3935 return;
3936 }
3937
3938 /* The root scan's purge never reaches a zombie's storage (not in the set;
3939 * zombie_objspaces only marks the join slot): purge here, under the barrier, before
3940 * the struct is freed, or a later ractor_free reads a freed key. */
3941 rb_vm_t *vm = GET_VM();
3942 rb_ractor_t *r;
3943
3944 for (size_t zi = 0; zi < vm->gc.zombie_objspaces_count; zi++) {
3945 rb_ractor_t *owner = vm->gc.zombie_objspaces[zi].owner;
3946 if (owner == NULL || owner->local_storage == NULL) continue;
3947 ractor_local_keys_purge(owner->local_storage);
3948 }
3949
3950 for (int i=0; i<freed_ractor_local_keys.cnt; i++) {
3951 SIZED_FREE(freed_ractor_local_keys.keys[i]);
3952 }
3953 freed_ractor_local_keys.cnt = 0;
3954 if (freed_ractor_local_keys.capa > DEFAULT_KEYS_CAPA) {
3955 freed_ractor_local_keys.capa = DEFAULT_KEYS_CAPA;
3956 SIZED_REALLOC_N(freed_ractor_local_keys.keys, rb_ractor_local_key_t, DEFAULT_KEYS_CAPA, freed_ractor_local_keys.capa);
3957 }
3958
3959 /* Under a minor mark an unmarked port is not a dead one. */
3960 if (full_mark) {
3961 ccan_list_for_each(&vm->ractor.set, r, vmlr_node) {
3962 rb_ractor_reap_dead_ports(r);
3963 }
3964 if (vm->ractor.cnt == 0 && vm->ractor.main_ractor) {
3965 rb_ractor_reap_dead_ports(vm->ractor.main_ractor);
3966 }
3967 }
3968}
3969
3970static VALUE
3971ractor_local_value(rb_execution_context_t *ec, VALUE self, VALUE sym)
3972{
3973 rb_ractor_t *cr = rb_ec_ractor_ptr(ec);
3974 ID id = rb_check_id(&sym);
3975 struct rb_id_table *tbl = cr->idkey_local_storage;
3976 VALUE val;
3977
3978 if (id && tbl && rb_id_table_lookup(tbl, id, &val)) {
3979 return val;
3980 }
3981 else {
3982 return Qnil;
3983 }
3984}
3985
3986static VALUE
3987ractor_local_value_set(rb_execution_context_t *ec, VALUE self, VALUE sym, VALUE val)
3988{
3989 rb_ractor_t *cr = rb_ec_ractor_ptr(ec);
3990 ID id = SYM2ID(rb_to_symbol(sym));
3991 struct rb_id_table *tbl = cr->idkey_local_storage;
3992
3993 if (tbl == NULL) {
3994 tbl = cr->idkey_local_storage = rb_id_table_create(2);
3995 }
3996 rb_id_table_insert(tbl, id, val);
3997 return val;
3998}
3999
4002 struct rb_id_table *tbl;
4003 ID id;
4004 VALUE sym;
4005};
4006
4007static VALUE
4008ractor_local_value_store_i(VALUE ptr)
4009{
4010 VALUE val;
4012
4013 if (rb_id_table_lookup(data->tbl, data->id, &val)) {
4014 // after synchronization, we found already registered entry
4015 }
4016 else {
4017 val = rb_yield(Qnil);
4018 ractor_local_value_set(data->ec, Qnil, data->sym, val);
4019 }
4020 return val;
4021}
4022
4023static VALUE
4024ractor_local_value_store_if_absent(rb_execution_context_t *ec, VALUE self, VALUE sym)
4025{
4026 rb_ractor_t *cr = rb_ec_ractor_ptr(ec);
4027 struct ractor_local_storage_store_data data = {
4028 .ec = ec,
4029 .sym = sym,
4030 .id = SYM2ID(rb_to_symbol(sym)),
4031 .tbl = cr->idkey_local_storage,
4032 };
4033 VALUE val;
4034
4035 if (data.tbl == NULL) {
4036 data.tbl = cr->idkey_local_storage = rb_id_table_create(2);
4037 }
4038 else if (rb_id_table_lookup(data.tbl, data.id, &val)) {
4039 // already set
4040 return val;
4041 }
4042
4043 if (!cr->local_storage_store_lock) {
4044 cr->local_storage_store_lock = rb_mutex_new();
4045 }
4046
4047 return rb_mutex_synchronize(cr->local_storage_store_lock, ractor_local_value_store_i, (VALUE)&data);
4048}
4049
4050// shareable_proc
4051
4052static VALUE
4053ractor_shareable_proc(rb_execution_context_t *ec, VALUE replace_self, bool is_lambda)
4054{
4055 if (!rb_ractor_shareable_p(replace_self)) {
4056 rb_raise(rb_eRactorIsolationError, "self should be shareable: %" PRIsVALUE, replace_self);
4057 }
4058 else {
4059 VALUE proc = is_lambda ? rb_block_lambda() : rb_block_proc();
4060 return rb_proc_ractor_make_shareable(rb_proc_dup(proc), replace_self);
4061 }
4062}
4063
4064// Ractor#require
4065
4067 VALUE port;
4068 bool raised;
4069
4070 union {
4071 struct {
4072 VALUE feature;
4073 } require;
4074
4075 struct {
4076 VALUE module;
4077 ID name;
4078 } autoload;
4079 } as;
4080
4081 bool silent;
4082};
4083
4084RUBY_REFERENCES(cross_ractor_require_refs) = {
4085 RUBY_REF_EDGE(struct cross_ractor_require, port),
4086 RUBY_REF_EDGE(struct cross_ractor_require, as.require.feature),
4087 RUBY_REF_END
4088};
4089
4090static const rb_data_type_t cross_ractor_require_data_type = {
4091 "ractor/cross_ractor_require",
4092 {
4093 RUBY_REFS_LIST_PTR(cross_ractor_require_refs),
4095 NULL, // memsize
4096 NULL, // compact
4097 },
4098 0, 0, RUBY_TYPED_THREAD_SAFE_FREE | RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_DECL_MARKING | RUBY_TYPED_EMBEDDABLE
4099};
4100
4101static VALUE
4102require_body(VALUE crr_obj)
4103{
4104 struct cross_ractor_require *crr;
4105 TypedData_Get_Struct(crr_obj, struct cross_ractor_require, &cross_ractor_require_data_type, crr);
4106 VALUE feature = crr->as.require.feature;
4107
4108 ID require;
4109 CONST_ID(require, "require");
4110
4111 if (crr->silent) {
4112 int rb_require_internal_silent(VALUE fname);
4113 return INT2NUM(rb_require_internal_silent(feature));
4114 }
4115 else {
4116 return rb_funcallv(Qnil, require, 1, &feature);
4117 }
4118}
4119
4120static VALUE
4121require_rescue(VALUE crr_obj, VALUE errinfo)
4122{
4123 struct cross_ractor_require *crr;
4124 TypedData_Get_Struct(crr_obj, struct cross_ractor_require, &cross_ractor_require_data_type, crr);
4125 crr->raised = true;
4126 return errinfo;
4127}
4128
4129static VALUE
4130require_result_send_body(VALUE ary)
4131{
4132 VALUE port = RARRAY_AREF(ary, 0);
4133 VALUE results = RARRAY_AREF(ary, 1);
4134
4135 rb_execution_context_t *ec = GET_EC();
4136
4137 ractor_port_send(ec, port, results, Qfalse);
4138 return Qnil;
4139}
4140
4141static VALUE
4142require_result_send_resuce(VALUE port, VALUE errinfo)
4143{
4144 // TODO: need rescue?
4145 ractor_port_send(GET_EC(), port, errinfo, Qfalse);
4146 return Qnil;
4147}
4148
4149static VALUE
4150ractor_require_protect(VALUE crr_obj, VALUE (*func)(VALUE))
4151{
4152 struct cross_ractor_require *crr;
4153 TypedData_Get_Struct(crr_obj, struct cross_ractor_require, &cross_ractor_require_data_type, crr);
4154
4155 const bool silent = crr->silent;
4156
4157 VALUE debug, errinfo;
4158 if (silent) {
4159 debug = ruby_debug;
4160 errinfo = rb_errinfo();
4161 }
4162
4163 // get normal result or raised exception (with crr->raised == true)
4164 VALUE result = rb_rescue2(func, crr_obj, require_rescue, crr_obj, rb_eException, 0);
4165
4166 if (silent) {
4167 ruby_debug = debug;
4168 rb_set_errinfo(errinfo);
4169 }
4170
4171 rb_rescue2(require_result_send_body,
4172 // [port, [result, raised]]
4173 rb_ary_new_from_args(2, crr->port, rb_ary_new_from_args(2, result, crr->raised ? Qtrue : Qfalse)),
4174 require_result_send_resuce, rb_eException, crr->port);
4175
4176 RB_GC_GUARD(crr_obj);
4177 return Qnil;
4178}
4179
4180static VALUE
4181ractor_require_func(void *crr_obj)
4182{
4183 return ractor_require_protect((VALUE)crr_obj, require_body);
4184}
4185
4186VALUE
4187rb_ractor_require(VALUE feature, bool silent)
4188{
4189 // We're about to block on the main ractor, so if we're holding the global lock we'll deadlock.
4190 ASSERT_vm_unlocking();
4191
4192 struct cross_ractor_require *crr;
4193 VALUE crr_obj = TypedData_Make_Struct(0, struct cross_ractor_require, &cross_ractor_require_data_type, crr);
4194 RB_OBJ_SET_SHAREABLE(crr_obj); // TODO: internal data?
4195
4196 // Convert feature to proper file path and make it shareable as fstring
4197 RB_OBJ_WRITE(crr_obj, &crr->as.require.feature, rb_fstring(FilePathValue(feature)));
4198 RB_OBJ_WRITE(crr_obj, &crr->port, rb_ractor_make_shareable(ractor_port_new(GET_RACTOR())));
4199 crr->raised = false;
4200 crr->silent = silent;
4201
4202 rb_execution_context_t *ec = GET_EC();
4203 rb_ractor_t *main_r = GET_VM()->ractor.main_ractor;
4204 rb_ractor_interrupt_exec(main_r, ractor_require_func, (void *)crr_obj, rb_interrupt_exec_flag_value_data);
4205
4206 // wait for require done
4207 VALUE results = ractor_port_receive(ec, crr->port, Qnil);
4208 ractor_port_close(ec, crr->port);
4209
4210 VALUE exc = rb_ary_pop(results);
4211 VALUE result = rb_ary_pop(results);
4212 RB_GC_GUARD(crr_obj);
4213
4214 if (RTEST(exc)) {
4215 rb_exc_raise(result);
4216 }
4217 else {
4218 return result;
4219 }
4220}
4221
4222static VALUE
4223ractor_require(rb_execution_context_t *ec, VALUE self, VALUE feature)
4224{
4225 return rb_ractor_require(feature, false);
4226}
4227
4228static VALUE
4229autoload_load_body(VALUE crr_obj)
4230{
4231 struct cross_ractor_require *crr;
4232 TypedData_Get_Struct(crr_obj, struct cross_ractor_require, &cross_ractor_require_data_type, crr);
4233 return rb_autoload_load(crr->as.autoload.module, crr->as.autoload.name);
4234}
4235
4236static VALUE
4237ractor_autoload_load_func(void *crr_obj)
4238{
4239 return ractor_require_protect((VALUE)crr_obj, autoload_load_body);
4240}
4241
4242VALUE
4243rb_ractor_autoload_load(VALUE module, ID name)
4244{
4245 struct cross_ractor_require *crr;
4246 VALUE crr_obj = TypedData_Make_Struct(0, struct cross_ractor_require, &cross_ractor_require_data_type, crr);
4247 RB_OBJ_SET_SHAREABLE(crr_obj); // TODO: internal data?
4248
4249 RB_OBJ_WRITE(crr_obj, &crr->as.autoload.module, module);
4250 RB_OBJ_WRITE(crr_obj, &crr->as.autoload.name, name);
4251 RB_OBJ_WRITE(crr_obj, &crr->port, rb_ractor_make_shareable(ractor_port_new(GET_RACTOR())));
4252
4253 rb_execution_context_t *ec = GET_EC();
4254 rb_ractor_t *main_r = GET_VM()->ractor.main_ractor;
4255 rb_ractor_interrupt_exec(main_r, ractor_autoload_load_func, (void *)crr_obj, rb_interrupt_exec_flag_value_data);
4256
4257 // wait for require done
4258 VALUE results = ractor_port_receive(ec, crr->port, Qnil);
4259 ractor_port_close(ec, crr->port);
4260
4261 VALUE exc = rb_ary_pop(results);
4262 VALUE result = rb_ary_pop(results);
4263 RB_GC_GUARD(crr_obj);
4264
4265 if (RTEST(exc)) {
4266 rb_exc_raise(result);
4267 }
4268 else {
4269 return result;
4270 }
4271}
4272
4273VALUE
4274rb_builtin_shareable_proc(rb_execution_context_t *ec, VALUE self, VALUE arg_self)
4275{
4276 return ractor_shareable_proc(ec, arg_self, false);
4277}
4278
4279VALUE
4280rb_builtin_shareable_lambda(rb_execution_context_t *ec, VALUE self, VALUE arg_self)
4281{
4282 return ractor_shareable_proc(ec, arg_self, true);
4283}
4284
4285#include "ractor.rbinc"
#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_PTR_LOAD(var)
Identical to RUBY_ATOMIC_LOAD, except it expects its arguments are void*.
Definition atomic.h:338
#define rb_define_method(klass, mid, func, arity)
Defines klass#mid.
static VALUE RB_OBJ_FROZEN_RAW(VALUE obj)
This is an implementation detail of RB_OBJ_FROZEN().
Definition fl_type.h:699
static void RB_FL_SET_RAW(VALUE obj, VALUE flags)
This is an implementation detail of RB_FL_SET().
Definition fl_type.h:544
@ RUBY_FL_FREEZE
This flag has something to do with data immutability.
Definition fl_type.h:278
void rb_singleton_class_attached(VALUE klass, VALUE obj)
Attaches a singleton class to its corresponding object.
Definition class.c:1277
#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 FL_PROMOTED
Old name of RUBY_FL_PROMOTED.
Definition fl_type.h:60
#define REALLOC_N
Old name of RB_REALLOC_N.
Definition memory.h:403
#define ALLOC
Old name of RB_ALLOC.
Definition memory.h:400
#define T_STRING
Old name of RUBY_T_STRING.
Definition value_type.h:78
#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_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 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 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 ZALLOC
Old name of RB_ZALLOC.
Definition memory.h:402
#define FL_SHAREABLE
Old name of RUBY_FL_SHAREABLE.
Definition fl_type.h:62
#define CLASS_OF
Old name of rb_class_of.
Definition globals.h:205
#define ENCODING_GET(obj)
Old name of RB_ENCODING_GET.
Definition encoding.h:109
#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 T_RATIONAL
Old name of RUBY_T_RATIONAL.
Definition value_type.h:76
#define T_ICLASS
Old name of RUBY_T_ICLASS.
Definition value_type.h:66
#define T_HASH
Old name of RUBY_T_HASH.
Definition value_type.h:65
#define ALLOC_N
Old name of RB_ALLOC_N.
Definition memory.h:399
#define FL_TEST_RAW
Old name of RB_FL_TEST_RAW.
Definition fl_type.h:128
#define Qtrue
Old name of RUBY_Qtrue.
#define INT2NUM
Old name of RB_INT2NUM.
Definition int.h:43
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#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 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 FL_FREEZE
Old name of RUBY_FL_FREEZE.
Definition fl_type.h:65
#define CONST_ID
Old name of RUBY_CONST_ID.
Definition symbol.h:47
#define FL_SET_RAW
Old name of RB_FL_SET_RAW.
Definition fl_type.h:126
#define T_REGEXP
Old name of RUBY_T_REGEXP.
Definition value_type.h:77
#define ruby_debug
This variable controls whether the interpreter is in debug mode.
Definition error.h:487
void rb_exc_raise(VALUE mesg)
Raises an exception in the current thread.
Definition eval.c:678
VALUE rb_eTypeError
TypeError exception.
Definition error.c:1473
VALUE rb_eRuntimeError
RuntimeError exception.
Definition error.c:1471
VALUE rb_eStopIteration
StopIteration exception.
Definition enumerator.c:196
VALUE rb_exc_new_str(VALUE etype, VALUE str)
Identical to rb_exc_new_cstr(), except it takes a Ruby's string instead of C's.
Definition error.c:1524
VALUE rb_eException
Mother of all exceptions.
Definition error.c:1465
VALUE rb_cArray
Array class.
VALUE rb_cObject
Object class.
Definition object.c:60
VALUE rb_obj_alloc(VALUE klass)
Allocates an instance of the given class.
Definition object.c:2252
VALUE rb_obj_hide(VALUE obj)
Make the object invisible from Ruby code.
Definition object.c:94
VALUE rb_cRactor
Ractor class.
Definition ractor.c:38
VALUE rb_stdin
STDIN constant.
Definition io.c:207
VALUE rb_cHash
Hash class.
Definition hash.c:123
VALUE rb_stderr
STDERR constant.
Definition io.c:207
static VALUE rb_class_of(VALUE obj)
Object to class mapping function.
Definition globals.h:174
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_freeze(VALUE obj)
Same as RB_OBJ_FREEZE(), but returns the given object.
Definition object.c:1309
VALUE rb_stdout
STDOUT constant.
Definition io.c:207
VALUE rb_cString
String class.
Definition string.c:85
#define RB_OBJ_WRITTEN(old, oldv, young)
Identical to RB_OBJ_WRITE(), except it doesn't write any values, but only a WB declaration.
Definition gc.h:504
#define RB_OBJ_WRITE(old, slot, young)
Declaration of a "back" pointer.
Definition gc.h:492
Encoding relates APIs.
VALUE rb_funcall(VALUE recv, ID mid, int n,...)
Calls a method.
Definition vm_eval.c:1123
VALUE rb_funcallv(VALUE recv, ID mid, int argc, const VALUE *argv)
Identical to rb_funcall(), except it takes the method arguments as a C array.
Definition vm_eval.c:1081
VALUE rb_ary_new_from_values(long n, const VALUE *elts)
Identical to rb_ary_new_from_args(), except how objects are passed.
VALUE rb_ary_new(void)
Allocates a new, empty array.
VALUE rb_ary_new_capa(long capa)
Identical to rb_ary_new(), except it additionally specifies how many rooms of objects it should alloc...
VALUE rb_ary_resize(VALUE ary, long len)
Expands or shrinks the passed array to the passed length.
VALUE rb_ary_pop(VALUE ary)
Destructively deletes an element from the end of the passed array and returns what was deleted.
VALUE rb_ary_hidden_new(long capa)
Allocates a hidden (no class) empty array.
VALUE rb_ary_push(VALUE ary, VALUE elem)
Special case of rb_ary_cat() that it adds only one element.
VALUE rb_ary_freeze(VALUE obj)
Freeze an array, preventing further modifications.
VALUE rb_marshal_load(VALUE port)
Deserialises a previous output of rb_marshal_dump() into a network of objects.
Definition marshal.c:2730
VALUE rb_block_proc(void)
Constructs a Proc object from implicitly passed components.
Definition proc.c:1575
VALUE rb_block_lambda(void)
Identical to rb_proc_new(), except it returns a lambda.
Definition proc.c:1594
VALUE rb_obj_is_proc(VALUE recv)
Queries if the given object is a proc.
Definition proc.c:386
int rb_reg_options(VALUE re)
Queries the options of the passed regular expression.
Definition re.c:4476
VALUE rb_str_new_frozen(VALUE str)
Creates a frozen copy of the string, if necessary.
Definition string.c:1555
VALUE rb_str_freeze(VALUE str)
This is the implementation of String#freeze.
Definition string.c:3384
VALUE rb_mutex_new(void)
Creates a mutex.
VALUE rb_mutex_synchronize(VALUE mutex, VALUE(*func)(VALUE arg), VALUE arg)
Obtains the lock, runs the passed function, and releases the lock when it completes.
VALUE rb_ivar_set(VALUE obj, ID name, VALUE val)
Identical to rb_iv_set(), except it accepts the name as an ID instead of a C string.
Definition variable.c:2141
VALUE rb_autoload_load(VALUE space, ID name)
Kicks the autoload procedure as if it was "touched".
Definition variable.c:3335
VALUE rb_class_name(VALUE obj)
Queries the name of the given object's class.
Definition variable.c:518
void rb_free_generic_ivar(VALUE obj)
Frees the list of instance variables.
Definition variable.c:1444
void rb_undef_alloc_func(VALUE klass)
Deletes the allocator function of a class.
Definition vm_method.c:1843
int rb_obj_respond_to(VALUE obj, ID mid, int private_p)
Identical to rb_respond_to(), except it additionally takes the visibility parameter.
Definition vm_method.c:3667
static ID rb_intern_const(const char *str)
This is a "tiny optimisation" over rb_intern().
Definition symbol.h:285
ID rb_check_id(volatile VALUE *namep)
Detects if the given name is already interned or not.
Definition symbol.c:1289
VALUE rb_to_symbol(VALUE name)
Identical to rb_intern_str(), except it generates a dynamic symbol if necessary.
Definition string.c:14138
int capa
Designed capacity of the buffer.
Definition io.h:11
int rb_io_fptr_finalize(rb_io_t *fptr)
Destroys the given IO.
Definition io.c:5980
int len
Length of the buffer.
Definition io.h:8
const struct rb_ractor_local_storage_type rb_ractor_local_storage_type_free
A type of ractor-local storage that destructs itself using ruby_xfree.
Definition ractor.c:3802
VALUE rb_ractor_make_shareable_copy(VALUE obj)
Identical to rb_ractor_make_shareable(), except it returns a (deep) copy of the passed one instead of...
Definition ractor.c:1987
struct rb_ractor_local_key_struct * rb_ractor_local_key_t
(Opaque) struct that holds a ractor-local storage key.
Definition ractor.h:42
void * rb_ractor_local_storage_ptr(rb_ractor_local_key_t key)
Identical to rb_ractor_local_storage_value() except the return type.
Definition ractor.c:3909
void rb_ractor_local_storage_ptr_set(rb_ractor_local_key_t key, void *ptr)
Identical to rb_ractor_local_storage_value_set() except the parameter type.
Definition ractor.c:3921
rb_ractor_local_key_t rb_ractor_local_storage_ptr_newkey(const struct rb_ractor_local_storage_type *type)
Extended version of rb_ractor_local_storage_value_newkey().
Definition ractor.c:3813
#define RB_OBJ_SET_SHAREABLE(obj)
Wrapper of rb_obj_set_shareable().
Definition ractor.h:290
VALUE rb_ractor_stdin(void)
Queries the standard input of the current Ractor that is calling this function.
Definition ractor.c:1428
static bool rb_ractor_shareable_p(VALUE obj)
Queries if multiple Ractors can share the passed object or not.
Definition ractor.h:269
void rb_ractor_stderr_set(VALUE io)
Assigns an IO to the standard error of the Ractor that is calling this function.
Definition ractor.c:1497
void rb_ractor_local_storage_value_set(rb_ractor_local_key_t key, VALUE val)
Associates the passed value to the passed key.
Definition ractor.c:3903
bool rb_ractor_local_storage_value_lookup(rb_ractor_local_key_t key, VALUE *val)
Queries the key.
Definition ractor.c:3892
#define RB_OBJ_SHAREABLE_P(obj)
Queries if the passed object has previously classified as shareable or not.
Definition ractor.h:255
VALUE rb_ractor_make_shareable(VALUE obj)
Destructively transforms the passed object so that multiple Ractors can share it.
Definition ractor.c:1976
VALUE rb_obj_set_shareable(VALUE obj)
Marks the passed object as shareable, without any check.
Definition ractor.c:1571
rb_ractor_local_key_t rb_ractor_local_storage_value_newkey(void)
Issues a new key.
Definition ractor.c:3822
void rb_ractor_stdout_set(VALUE io)
Assigns an IO to the standard output of the Ractor that is calling this function.
Definition ractor.c:1485
void rb_ractor_stdin_set(VALUE io)
Assigns an IO to the standard input of the Ractor that is calling this function.
Definition ractor.c:1473
VALUE rb_ractor_local_storage_value(rb_ractor_local_key_t key)
Queries the key.
Definition ractor.c:3880
VALUE rb_yield(VALUE val)
Yields the block.
Definition vm_eval.c:1378
rb_block_call_func * rb_block_call_func_t
Shorthand type that represents an iterator-written-in-C function pointer.
Definition iterator.h:88
#define MEMCPY(p1, p2, type, n)
Handy macro to call memcpy.
Definition memory.h:372
#define MEMZERO(p, type, n)
Handy macro to erase a region of memory.
Definition memory.h:360
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
Definition memory.h:167
VALUE rb_proc_new(type *q, VALUE w)
Creates a rb_cProc instance.
VALUE type(ANYARGS)
ANYARGS-ed function type.
void rb_hash_foreach(VALUE q, int_type *w, VALUE e)
Iteration over the given hash.
void rb_ivar_foreach(VALUE q, int_type *w, VALUE e)
Iteration over each instance variable of the object.
VALUE rb_rescue2(type *q, VALUE w, type *e, VALUE r,...)
An equivalent of rescue clause.
void rb_copy_generic_ivar(VALUE clone, VALUE obj)
Copies the list of instance variables.
Definition variable.c:2335
#define RARRAY_LEN
Just another name of rb_array_len.
Definition rarray.h:50
#define RARRAY(obj)
Convenient casting macro.
Definition rarray.h:44
static int RARRAY_LENINT(VALUE ary)
Identical to rb_array_len(), except it differs for the return type.
Definition rarray.h:280
static void RARRAY_ASET(VALUE ary, long i, VALUE v)
Assigns an object in an array.
Definition rarray.h:385
#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 RUBY_DEFAULT_FREE
This is a value you can set to RData::dfree.
Definition rdata.h:56
#define RFILE(obj)
Convenient casting macro.
Definition rfile.h:50
#define RHASH_SET_IFNONE(h, ifnone)
Destructively updates the default value of the hash.
Definition rhash.h:92
#define RHASH_IFNONE(h)
Definition rhash.h:59
#define RHASH_SIZE(h)
Queries the size of the hash.
Definition rhash.h:69
#define RMATCH(obj)
Convenient casting macro.
Definition rmatch.h:37
static VALUE RREGEXP_SRC(VALUE rexp)
Convenient getter function.
Definition rregexp.h:102
#define RSTRING(obj)
Convenient casting macro.
Definition rstring.h:41
#define StringValueCStr(v)
Identical to StringValuePtr, except it additionally checks for the contents for viability as a C stri...
Definition rstring.h:89
static long RSTRUCT_LEN(VALUE st)
Returns the number of struct members.
Definition rstruct.h:82
static VALUE RSTRUCT_SET(VALUE st, int k, VALUE v)
Resembles Struct#[]=.
Definition rstruct.h:92
static VALUE RSTRUCT_GET(VALUE st, int k)
Resembles Struct#[].
Definition rstruct.h:102
#define RUBY_TYPED_FREE_IMMEDIATELY
Macros to see if each corresponding flag is defined.
Definition rtypeddata.h:122
#define TypedData_Get_Struct(obj, type, data_type, sval)
Obtains a C struct from inside of a wrapper Ruby object.
Definition rtypeddata.h:773
#define DATA_PTR(obj)
Convenient casting macro for backward compatibility.
Definition rtypeddata.h:439
static const rb_data_type_t * RTYPEDDATA_TYPE(VALUE obj)
Queries for the type of given object.
Definition rtypeddata.h:692
#define TypedData_Wrap_Struct(klass, data_type, sval)
Converts sval, a pointer to your struct, into a Ruby object.
Definition rtypeddata.h:557
#define TypedData_Make_Struct(klass, type, data_type, sval)
Identical to TypedData_Wrap_Struct, except it allocates a new data region internally instead of takin...
Definition rtypeddata.h:604
#define FilePathValue(v)
Ensures that the parameter object is a path.
Definition ruby.h:90
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.
Ruby object's base components.
Definition rbasic.h:69
Regular expression execution context.
Definition rmatch.h:79
VALUE regexp
The expression of this match.
Definition rmatch.h:92
VALUE str
The target string that the match was made against.
Definition rmatch.h:87
This is the struct that holds necessary info for a struct.
Definition rtypeddata.h:242
VALUE ecopts
Flags as Ruby hash.
Definition io.h:152
Ruby's IO, metadata and buffers.
Definition io.h:295
struct rb_io_encoding encs
Decomposed encoding flags.
Definition io.h:348
VALUE self
The IO's Ruby level counterpart.
Definition io.h:298
VALUE write_lock
This is a Ruby level mutex.
Definition io.h:400
VALUE timeout
The timeout associated with this IO when performing blocking operations.
Definition io.h:406
VALUE writeconv_pre_ecopts
Value of ::rb_io_t::rb_io_enc_t::ecopts stored right before initialising rb_io_t::writeconv.
Definition io.h:390
VALUE tied_io_for_writing
Duplex IO object, if set.
Definition io.h:345
VALUE writeconv_asciicompat
This is, when set, an instance of rb_cString which holds the "common" encoding.
Definition io.h:372
VALUE pathv
pathname for file
Definition io.h:322
Type that defines a ractor-local storage.
Definition ractor.h:21
void(* free)(void *ptr)
A function to destruct a ractor-local storage.
Definition ractor.h:37
void(* mark)(void *ptr)
A function to mark a ractor-local storage.
Definition ractor.h:29
Definition st.h:79
void rb_native_mutex_lock(rb_nativethread_lock_t *lock)
Just another name of rb_nativethread_lock_lock.
void rb_native_mutex_unlock(rb_nativethread_lock_t *lock)
Just another name of rb_nativethread_lock_unlock.
void rb_native_mutex_destroy(rb_nativethread_lock_t *lock)
Just another name of rb_nativethread_lock_destroy.
void rb_native_cond_signal(rb_nativethread_cond_t *cond)
Signals a condition variable.
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 enum ruby_value_type RB_BUILTIN_TYPE(VALUE obj)
Queries the type of the object.
Definition value_type.h:182
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