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