Ruby 4.0.10p0 (2026-11-19 revision a704b7cd95a42cc0cf5f307137bf3aac0285b915)
ractor.c
1// Ractor implementation
2
3#include "ruby/ruby.h"
4#include "ruby/thread.h"
5#include "ruby/ractor.h"
6#include "ruby/re.h"
8#include "vm_core.h"
9#include "vm_sync.h"
10#include "ractor_core.h"
11#include "internal/complex.h"
12#include "internal/error.h"
13#include "internal/gc.h"
14#include "internal/hash.h"
15#include "internal/object.h"
16#include "internal/ractor.h"
17#include "internal/rational.h"
18#include "internal/struct.h"
19#include "internal/thread.h"
20#include "variable.h"
21#include "yjit.h"
22#include "zjit.h"
23
25static VALUE rb_cRactorSelector;
26
27VALUE rb_eRactorUnsafeError;
28VALUE rb_eRactorIsolationError;
29static VALUE rb_eRactorError;
30static VALUE rb_eRactorRemoteError;
31static VALUE rb_eRactorMovedError;
32static VALUE rb_eRactorClosedError;
33static VALUE rb_cRactorMovedObject;
34
35static void vm_ractor_blocking_cnt_inc(rb_vm_t *vm, rb_ractor_t *r, const char *file, int line);
36
37
38#if RACTOR_CHECK_MODE > 0
39bool rb_ractor_ignore_belonging_flag = false;
40#endif
41
42// Ractor locking
43
44static void
45ASSERT_ractor_unlocking(rb_ractor_t *r)
46{
47#if RACTOR_CHECK_MODE > 0
48 const rb_execution_context_t *ec = rb_current_ec_noinline();
49 if (ec != NULL && r->sync.locked_by == rb_ractor_self(rb_ec_ractor_ptr(ec))) {
50 rb_bug("recursive ractor locking");
51 }
52#endif
53}
54
55static void
56ASSERT_ractor_locking(rb_ractor_t *r)
57{
58#if RACTOR_CHECK_MODE > 0
59 const rb_execution_context_t *ec = rb_current_ec_noinline();
60 if (ec != NULL && r->sync.locked_by != rb_ractor_self(rb_ec_ractor_ptr(ec))) {
61 rp(r->sync.locked_by);
62 rb_bug("ractor lock is not acquired.");
63 }
64#endif
65}
66
67static void
68ractor_lock(rb_ractor_t *r, const char *file, int line)
69{
70 RUBY_DEBUG_LOG2(file, line, "locking r:%u%s", r->pub.id, rb_current_ractor_raw(false) == r ? " (self)" : "");
71
72 ASSERT_ractor_unlocking(r);
73 rb_native_mutex_lock(&r->sync.lock);
74
75 const rb_execution_context_t *ec = rb_current_ec_noinline();
76 if (ec) {
77 rb_ractor_t *cr = rb_ec_ractor_ptr(ec);
78 VM_ASSERT(!cr->malloc_gc_disabled);
79 cr->malloc_gc_disabled = true;
80 }
81
82#if RACTOR_CHECK_MODE > 0
83 if (ec != NULL) {
84 rb_ractor_t *cr = rb_ec_ractor_ptr(ec);
85 r->sync.locked_by = rb_ractor_self(cr);
86 }
87#endif
88
89 RUBY_DEBUG_LOG2(file, line, "locked r:%u%s", r->pub.id, rb_current_ractor_raw(false) == r ? " (self)" : "");
90}
91
92static void
93ractor_lock_self(rb_ractor_t *cr, const char *file, int line)
94{
95 VM_ASSERT(cr == rb_ec_ractor_ptr(rb_current_ec_noinline()));
96#if RACTOR_CHECK_MODE > 0
97 VM_ASSERT(cr->sync.locked_by != cr->pub.self);
98#endif
99 ractor_lock(cr, file, line);
100}
101
102static void
103ractor_unlock(rb_ractor_t *r, const char *file, int line)
104{
105 ASSERT_ractor_locking(r);
106#if RACTOR_CHECK_MODE > 0
107 r->sync.locked_by = Qnil;
108#endif
109
110 const rb_execution_context_t *ec = rb_current_ec_noinline();
111 if (ec) {
112 rb_ractor_t *cr = rb_ec_ractor_ptr(ec);
113 VM_ASSERT(cr->malloc_gc_disabled);
114 cr->malloc_gc_disabled = false;
115 }
116
117 rb_native_mutex_unlock(&r->sync.lock);
118
119 RUBY_DEBUG_LOG2(file, line, "r:%u%s", r->pub.id, rb_current_ractor_raw(false) == r ? " (self)" : "");
120}
121
122static void
123ractor_unlock_self(rb_ractor_t *cr, const char *file, int line)
124{
125 VM_ASSERT(cr == rb_ec_ractor_ptr(rb_current_ec_noinline()));
126#if RACTOR_CHECK_MODE > 0
127 VM_ASSERT(cr->sync.locked_by == cr->pub.self);
128#endif
129 ractor_unlock(cr, file, line);
130}
131
132#define RACTOR_LOCK(r) ractor_lock(r, __FILE__, __LINE__)
133#define RACTOR_UNLOCK(r) ractor_unlock(r, __FILE__, __LINE__)
134#define RACTOR_LOCK_SELF(r) ractor_lock_self(r, __FILE__, __LINE__)
135#define RACTOR_UNLOCK_SELF(r) ractor_unlock_self(r, __FILE__, __LINE__)
136
137void
138rb_ractor_lock_self(rb_ractor_t *r)
139{
140 RACTOR_LOCK_SELF(r);
141}
142
143void
144rb_ractor_unlock_self(rb_ractor_t *r)
145{
146 RACTOR_UNLOCK_SELF(r);
147}
148
149// Ractor status
150
151static const char *
152ractor_status_str(enum ractor_status status)
153{
154 switch (status) {
155 case ractor_created: return "created";
156 case ractor_running: return "running";
157 case ractor_blocking: return "blocking";
158 case ractor_terminated: return "terminated";
159 }
160 rb_bug("unreachable");
161}
162
163static void
164ractor_status_set(rb_ractor_t *r, enum ractor_status status)
165{
166 RUBY_DEBUG_LOG("r:%u [%s]->[%s]", r->pub.id, ractor_status_str(r->status_), ractor_status_str(status));
167
168 // check 1
169 if (r->status_ != ractor_created) {
170 VM_ASSERT(r == GET_RACTOR()); // only self-modification is allowed.
171 ASSERT_vm_locking();
172 }
173
174 // check2: transition check. assume it will be vanished on non-debug build.
175 switch (r->status_) {
176 case ractor_created:
177 VM_ASSERT(status == ractor_blocking);
178 break;
179 case ractor_running:
180 VM_ASSERT(status == ractor_blocking||
181 status == ractor_terminated);
182 break;
183 case ractor_blocking:
184 VM_ASSERT(status == ractor_running);
185 break;
186 case ractor_terminated:
187 rb_bug("unreachable");
188 break;
189 }
190
191 r->status_ = status;
192}
193
194static bool
195ractor_status_p(rb_ractor_t *r, enum ractor_status status)
196{
197 return rb_ractor_status_p(r, status);
198}
199
200// Ractor data/mark/free
201
202static void ractor_local_storage_mark(rb_ractor_t *r);
203static void ractor_local_storage_free(rb_ractor_t *r);
204
205static void ractor_sync_mark(rb_ractor_t *r);
206static void ractor_sync_free(rb_ractor_t *r);
207static size_t ractor_sync_memsize(const rb_ractor_t *r);
208static void ractor_sync_init(rb_ractor_t *r);
209
210static int
211mark_targeted_hook_list(st_data_t key, st_data_t value, st_data_t _arg)
212{
213 rb_hook_list_t *hook_list = (rb_hook_list_t*)value;
214
215 if (hook_list->type == hook_list_type_targeted_iseq) {
216 rb_gc_mark((VALUE)key);
217 }
218 else {
219 rb_method_definition_t *def = (rb_method_definition_t*)key;
220 RUBY_ASSERT(hook_list->type == hook_list_type_targeted_def);
221 rb_gc_mark(def->body.bmethod.proc);
222 }
223 rb_hook_list_mark(hook_list);
224
225 return ST_CONTINUE;
226}
227
228static void
229ractor_mark(void *ptr)
230{
231 rb_ractor_t *r = (rb_ractor_t *)ptr;
232 bool checking_shareable = rb_gc_checking_shareable();
233
234 rb_gc_mark(r->loc);
235 rb_gc_mark(r->name);
236
237 if (!checking_shareable) {
238 // may unshareable objects
239 rb_gc_mark(r->r_stdin);
240 rb_gc_mark(r->r_stdout);
241 rb_gc_mark(r->r_stderr);
242 rb_gc_mark(r->verbose);
243 rb_gc_mark(r->debug);
244
245 // mark received messages
246 ractor_sync_mark(r);
247
248 rb_hook_list_mark(&r->pub.hooks);
249 if (r->pub.targeted_hooks) {
250 st_foreach(r->pub.targeted_hooks, mark_targeted_hook_list, 0);
251 }
252
253 if (r->threads.cnt > 0) {
254 rb_thread_t *th = 0;
255 ccan_list_for_each(&r->threads.set, th, lt_node) {
256 VM_ASSERT(th != NULL);
257 rb_gc_mark(th->self);
258 }
259 }
260
261 ractor_local_storage_mark(r);
262 }
263}
264
265static int
266free_targeted_hook_lists(st_data_t key, st_data_t val, st_data_t _arg)
267{
268 rb_hook_list_t *hook_list = (rb_hook_list_t*)val;
269 rb_hook_list_free(hook_list);
270 return ST_DELETE;
271}
272
273static void
274free_targeted_hooks(st_table *hooks_tbl)
275{
276 st_foreach(hooks_tbl, free_targeted_hook_lists, 0);
277}
278
279static void
280ractor_free(void *ptr)
281{
282 rb_ractor_t *r = (rb_ractor_t *)ptr;
283 RUBY_DEBUG_LOG("free r:%d", rb_ractor_id(r));
284 free_targeted_hooks(r->pub.targeted_hooks);
285 rb_native_mutex_destroy(&r->sync.lock);
286#ifdef RUBY_THREAD_WIN32_H
287 rb_native_cond_destroy(&r->sync.wakeup_cond);
288#endif
289 ractor_local_storage_free(r);
290 rb_hook_list_free(&r->pub.hooks);
291 st_free_table(r->pub.targeted_hooks);
292
293 if (r->newobj_cache) {
294 RUBY_ASSERT(r == ruby_single_main_ractor);
295
296 rb_gc_ractor_cache_free(r->newobj_cache);
297 r->newobj_cache = NULL;
298 }
299
300 ractor_sync_free(r);
301 ruby_xfree(r);
302}
303
304static size_t
305ractor_memsize(const void *ptr)
306{
307 rb_ractor_t *r = (rb_ractor_t *)ptr;
308
309 // TODO: more correct?
310 return sizeof(rb_ractor_t) + ractor_sync_memsize(r);
311}
312
313static const rb_data_type_t ractor_data_type = {
314 "ractor",
315 {
316 ractor_mark,
317 ractor_free,
318 ractor_memsize,
319 NULL, // update
320 },
321 0, 0, RUBY_TYPED_FREE_IMMEDIATELY /* | RUBY_TYPED_WB_PROTECTED */
322};
323
324bool
325rb_ractor_p(VALUE gv)
326{
327 if (rb_typeddata_is_kind_of(gv, &ractor_data_type)) {
328 return true;
329 }
330 else {
331 return false;
332 }
333}
334
335static inline rb_ractor_t *
336RACTOR_PTR(VALUE self)
337{
338 VM_ASSERT(rb_ractor_p(self));
339 rb_ractor_t *r = DATA_PTR(self);
340 return r;
341}
342
343static rb_atomic_t ractor_last_id;
344
345#if RACTOR_CHECK_MODE > 0
346uint32_t
347rb_ractor_current_id(void)
348{
349 if (GET_THREAD()->ractor == NULL) {
350 return 1; // main ractor
351 }
352 else {
353 return rb_ractor_id(GET_RACTOR());
354 }
355}
356#endif
357
358#include "ractor_sync.c"
359
360// creation/termination
361
362static uint32_t
363ractor_next_id(void)
364{
365 uint32_t id;
366
367 id = (uint32_t)(RUBY_ATOMIC_FETCH_ADD(ractor_last_id, 1) + 1);
368
369 return id;
370}
371
372static void
373vm_insert_ractor0(rb_vm_t *vm, rb_ractor_t *r, bool single_ractor_mode)
374{
375 RUBY_DEBUG_LOG("r:%u ractor.cnt:%u++", r->pub.id, vm->ractor.cnt);
376 VM_ASSERT(single_ractor_mode || RB_VM_LOCKED_P());
377
378 ccan_list_add_tail(&vm->ractor.set, &r->vmlr_node);
379 vm->ractor.cnt++;
380
381 if (r->newobj_cache) {
382 VM_ASSERT(r == ruby_single_main_ractor);
383 }
384 else {
385 r->newobj_cache = rb_gc_ractor_cache_alloc(r);
386 }
387}
388
389static void
390cancel_single_ractor_mode(void)
391{
392 // enable multi-ractor mode
393 RUBY_DEBUG_LOG("enable multi-ractor mode");
394
395 ruby_single_main_ractor = NULL;
396 rb_funcall(rb_cRactor, rb_intern("_activated"), 0);
397}
398
399static void
400vm_insert_ractor(rb_vm_t *vm, rb_ractor_t *r)
401{
402 VM_ASSERT(ractor_status_p(r, ractor_created));
403
404 if (rb_multi_ractor_p()) {
405 RB_VM_LOCK();
406 {
407 vm_insert_ractor0(vm, r, false);
408 vm_ractor_blocking_cnt_inc(vm, r, __FILE__, __LINE__);
409 }
410 RB_VM_UNLOCK();
411 }
412 else {
413 if (vm->ractor.cnt == 0) {
414 // main ractor
415 vm_insert_ractor0(vm, r, true);
416 ractor_status_set(r, ractor_blocking);
417 ractor_status_set(r, ractor_running);
418 }
419 else {
420 cancel_single_ractor_mode();
421 vm_insert_ractor0(vm, r, true);
422 vm_ractor_blocking_cnt_inc(vm, r, __FILE__, __LINE__);
423 }
424 }
425}
426
427static void
428vm_remove_ractor(rb_vm_t *vm, rb_ractor_t *cr)
429{
430 VM_ASSERT(ractor_status_p(cr, ractor_running));
431 VM_ASSERT(vm->ractor.cnt > 1);
432 VM_ASSERT(cr->threads.cnt == 1);
433
434 RB_VM_LOCK();
435 {
436 RUBY_DEBUG_LOG("ractor.cnt:%u-- terminate_waiting:%d",
437 vm->ractor.cnt, vm->ractor.sync.terminate_waiting);
438
439 VM_ASSERT(vm->ractor.cnt > 0);
440 ccan_list_del(&cr->vmlr_node);
441
442 if (vm->ractor.cnt <= 2 && vm->ractor.sync.terminate_waiting) {
443 rb_native_cond_signal(&vm->ractor.sync.terminate_cond);
444 }
445 vm->ractor.cnt--;
446
447 rb_gc_ractor_cache_free(cr->newobj_cache);
448 cr->newobj_cache = NULL;
449
450 ractor_status_set(cr, ractor_terminated);
451 }
452 RB_VM_UNLOCK();
453}
454
455static VALUE
456ractor_alloc(VALUE klass)
457{
458 rb_ractor_t *r;
459 VALUE rv = TypedData_Make_Struct(klass, rb_ractor_t, &ractor_data_type, r);
461 r->pub.self = rv;
462 r->next_ec_serial = 1;
463 VM_ASSERT(ractor_status_p(r, ractor_created));
464 return rv;
465}
466
467rb_ractor_t *
468rb_ractor_main_alloc(void)
469{
470 rb_ractor_t *r = ruby_mimcalloc(1, sizeof(rb_ractor_t));
471 if (r == NULL) {
472 fprintf(stderr, "[FATAL] failed to allocate memory for main ractor\n");
473 exit(EXIT_FAILURE);
474 }
475 r->pub.id = ++ractor_last_id;
476 r->loc = Qnil;
477 r->name = Qnil;
478 r->pub.self = Qnil;
479 r->newobj_cache = rb_gc_ractor_cache_alloc(r);
480 r->next_ec_serial = 1;
481 ruby_single_main_ractor = r;
482
483 return r;
484}
485
486#if defined(HAVE_WORKING_FORK)
487// Set up the main Ractor for the VM after fork.
488// Puts us in "single Ractor mode"
489void
490rb_ractor_atfork(rb_vm_t *vm, rb_thread_t *th)
491{
492 // initialize as a main ractor
493 vm->ractor.cnt = 0;
494 vm->ractor.blocking_cnt = 0;
495 ruby_single_main_ractor = th->ractor;
496 th->ractor->status_ = ractor_created;
497
498 ractor_sync_atfork(th->ractor);
499 rb_ractor_living_threads_init(th->ractor);
500 rb_ractor_living_threads_insert(th->ractor, th);
501
502 VM_ASSERT(vm->ractor.blocking_cnt == 0);
503 VM_ASSERT(vm->ractor.cnt == 1);
504}
505
506void
507rb_ractor_terminate_atfork(rb_vm_t *vm, rb_ractor_t *r)
508{
509 rb_gc_ractor_cache_free(r->newobj_cache);
510 r->newobj_cache = NULL;
511 r->status_ = ractor_terminated;
512 ractor_sync_terminate_atfork(vm, r);
513}
514#endif
515
516void rb_thread_sched_init(struct rb_thread_sched *, bool atfork);
517
518void
519rb_ractor_living_threads_init(rb_ractor_t *r)
520{
521 ccan_list_head_init(&r->threads.set);
522 r->threads.cnt = 0;
523 r->threads.blocking_cnt = 0;
524}
525
526static void
527ractor_init(rb_ractor_t *r, VALUE name, VALUE loc)
528{
529 ractor_sync_init(r);
530 r->pub.targeted_hooks = st_init_numtable();
531 r->pub.hooks.type = hook_list_type_ractor_local;
532
533 // thread management
534 rb_thread_sched_init(&r->threads.sched, false);
535 rb_ractor_living_threads_init(r);
536
537 // naming
538 if (!NIL_P(name)) {
539 rb_encoding *enc;
540 StringValueCStr(name);
541 enc = rb_enc_get(name);
542 if (!rb_enc_asciicompat(enc)) {
543 rb_raise(rb_eArgError, "ASCII incompatible encoding (%s)",
544 rb_enc_name(enc));
545 }
546 name = RB_OBJ_SET_SHAREABLE(rb_str_new_frozen(name));
547 }
548
549 if (!SPECIAL_CONST_P(loc)) RB_OBJ_SET_SHAREABLE(loc);
550 r->loc = loc;
551 r->name = name;
552}
553
554void
555rb_ractor_main_setup(rb_vm_t *vm, rb_ractor_t *r, rb_thread_t *th)
556{
557 VALUE rv = r->pub.self = TypedData_Wrap_Struct(rb_cRactor, &ractor_data_type, r);
558 FL_SET_RAW(r->pub.self, RUBY_FL_SHAREABLE);
559 ractor_init(r, Qnil, Qnil);
560 r->threads.main = th;
561 rb_ractor_living_threads_insert(r, th);
562
563 RB_GC_GUARD(rv);
564}
565
566static VALUE
567ractor_create(rb_execution_context_t *ec, VALUE self, VALUE loc, VALUE name, VALUE args, VALUE block)
568{
569 VALUE rv = ractor_alloc(self);
570 rb_ractor_t *r = RACTOR_PTR(rv);
571 ractor_init(r, name, loc);
572
573 r->pub.id = ractor_next_id();
574 RUBY_DEBUG_LOG("r:%u", r->pub.id);
575
576 rb_ractor_t *cr = rb_ec_ractor_ptr(ec);
577 r->verbose = cr->verbose;
578 r->debug = cr->debug;
579
580 rb_yjit_before_ractor_spawn();
581 rb_zjit_before_ractor_spawn();
582 rb_thread_create_ractor(r, args, block);
583
584 RB_GC_GUARD(rv);
585 return rv;
586}
587
588#if 0
589static VALUE
590ractor_create_func(VALUE klass, VALUE loc, VALUE name, VALUE args, rb_block_call_func_t func)
591{
592 VALUE block = rb_proc_new(func, Qnil);
593 return ractor_create(rb_current_ec_noinline(), klass, loc, name, args, block);
594}
595#endif
596
597static void
598ractor_atexit(rb_execution_context_t *ec, rb_ractor_t *cr, VALUE result, bool exc)
599{
600 ractor_notify_exit(ec, cr, result, exc);
601}
602
603void
604rb_ractor_atexit(rb_execution_context_t *ec, VALUE result)
605{
606 rb_ractor_t *cr = rb_ec_ractor_ptr(ec);
607 ractor_atexit(ec, cr, result, false);
608}
609
610void
611rb_ractor_atexit_exception(rb_execution_context_t *ec)
612{
613 rb_ractor_t *cr = rb_ec_ractor_ptr(ec);
614 ractor_atexit(ec, cr, ec->errinfo, true);
615}
616
617void
618rb_ractor_teardown(rb_execution_context_t *ec)
619{
620 rb_ractor_t *cr = rb_ec_ractor_ptr(ec);
621
622 // sync with rb_ractor_terminate_interrupt_main_thread()
623 RB_VM_LOCKING() {
624 VM_ASSERT(cr->threads.main != NULL);
625 cr->threads.main = NULL;
626 }
627}
628
629void
630rb_ractor_receive_parameters(rb_execution_context_t *ec, rb_ractor_t *r, int len, VALUE *ptr)
631{
632 for (int i=0; i<len; i++) {
633 ptr[i] = ractor_receive(ec, ractor_default_port(r));
634 }
635}
636
637void
638rb_ractor_send_parameters(rb_execution_context_t *ec, rb_ractor_t *r, VALUE args)
639{
640 int len = RARRAY_LENINT(args);
641 for (int i=0; i<len; i++) {
642 ractor_send(ec, ractor_default_port(r), RARRAY_AREF(args, i), false);
643 }
644}
645
646bool
647rb_ractor_main_p_(void)
648{
649 VM_ASSERT(rb_multi_ractor_p());
650 rb_execution_context_t *ec = GET_EC();
651 return rb_ec_ractor_ptr(ec) == rb_ec_vm_ptr(ec)->ractor.main_ractor;
652}
653
654int
655rb_ractor_living_thread_num(const rb_ractor_t *r)
656{
657 return r->threads.cnt;
658}
659
660// only for current ractor
661VALUE
662rb_ractor_thread_list(void)
663{
664 rb_ractor_t *r = GET_RACTOR();
665 rb_thread_t *th = 0;
666 VALUE ary = rb_ary_new();
667
668 ccan_list_for_each(&r->threads.set, th, lt_node) {
669 switch (th->status) {
670 case THREAD_RUNNABLE:
671 case THREAD_STOPPED:
672 case THREAD_STOPPED_FOREVER:
673 rb_ary_push(ary, th->self);
674 default:
675 break;
676 }
677 }
678
679 return ary;
680}
681
682void
683rb_ractor_living_threads_insert(rb_ractor_t *r, rb_thread_t *th)
684{
685 VM_ASSERT(th != NULL);
686
687 RACTOR_LOCK(r);
688 {
689 RUBY_DEBUG_LOG("r(%d)->threads.cnt:%d++", r->pub.id, r->threads.cnt);
690 ccan_list_add_tail(&r->threads.set, &th->lt_node);
691 r->threads.cnt++;
692 }
693 RACTOR_UNLOCK(r);
694
695 // first thread for a ractor
696 if (r->threads.cnt == 1) {
697 VM_ASSERT(ractor_status_p(r, ractor_created));
698 vm_insert_ractor(th->vm, r);
699 }
700}
701
702static void
703vm_ractor_blocking_cnt_inc(rb_vm_t *vm, rb_ractor_t *r, const char *file, int line)
704{
705 ractor_status_set(r, ractor_blocking);
706
707 RUBY_DEBUG_LOG2(file, line, "vm->ractor.blocking_cnt:%d++", vm->ractor.blocking_cnt);
708 vm->ractor.blocking_cnt++;
709 VM_ASSERT(vm->ractor.blocking_cnt <= vm->ractor.cnt);
710}
711
712void
713rb_vm_ractor_blocking_cnt_inc(rb_vm_t *vm, rb_ractor_t *cr, const char *file, int line)
714{
715 ASSERT_vm_locking();
716 VM_ASSERT(GET_RACTOR() == cr);
717 vm_ractor_blocking_cnt_inc(vm, cr, file, line);
718}
719
720void
721rb_vm_ractor_blocking_cnt_dec(rb_vm_t *vm, rb_ractor_t *cr, const char *file, int line)
722{
723 ASSERT_vm_locking();
724 VM_ASSERT(GET_RACTOR() == cr);
725
726 RUBY_DEBUG_LOG2(file, line, "vm->ractor.blocking_cnt:%d--", vm->ractor.blocking_cnt);
727 VM_ASSERT(vm->ractor.blocking_cnt > 0);
728 vm->ractor.blocking_cnt--;
729
730 ractor_status_set(cr, ractor_running);
731}
732
733static void
734ractor_check_blocking(rb_ractor_t *cr, unsigned int remained_thread_cnt, const char *file, int line)
735{
736 VM_ASSERT(cr == GET_RACTOR());
737
738 RUBY_DEBUG_LOG2(file, line,
739 "cr->threads.cnt:%u cr->threads.blocking_cnt:%u vm->ractor.cnt:%u vm->ractor.blocking_cnt:%u",
740 cr->threads.cnt, cr->threads.blocking_cnt,
741 GET_VM()->ractor.cnt, GET_VM()->ractor.blocking_cnt);
742
743 VM_ASSERT(cr->threads.cnt >= cr->threads.blocking_cnt + 1);
744
745 if (remained_thread_cnt > 0 &&
746 // will be block
747 cr->threads.cnt == cr->threads.blocking_cnt + 1) {
748 // change ractor status: running -> blocking
749 rb_vm_t *vm = GET_VM();
750
751 RB_VM_LOCKING() {
752 rb_vm_ractor_blocking_cnt_inc(vm, cr, file, line);
753 }
754 }
755}
756
757void rb_threadptr_remove(rb_thread_t *th);
758
759void
760rb_ractor_living_threads_remove(rb_ractor_t *cr, rb_thread_t *th)
761{
762 VM_ASSERT(cr == GET_RACTOR());
763 RUBY_DEBUG_LOG("r->threads.cnt:%d--", cr->threads.cnt);
764 ractor_check_blocking(cr, cr->threads.cnt - 1, __FILE__, __LINE__);
765
766 rb_threadptr_remove(th);
767
768 if (cr->threads.cnt == 1) {
769 vm_remove_ractor(th->vm, cr);
770 }
771 else {
772 RACTOR_LOCK(cr);
773 {
774 ccan_list_del(&th->lt_node);
775 cr->threads.cnt--;
776 }
777 RACTOR_UNLOCK(cr);
778 }
779}
780
781void
782rb_ractor_blocking_threads_inc(rb_ractor_t *cr, const char *file, int line)
783{
784 RUBY_DEBUG_LOG2(file, line, "cr->threads.blocking_cnt:%d++", cr->threads.blocking_cnt);
785
786 VM_ASSERT(cr->threads.cnt > 0);
787 VM_ASSERT(cr == GET_RACTOR());
788
789 ractor_check_blocking(cr, cr->threads.cnt, __FILE__, __LINE__);
790 cr->threads.blocking_cnt++;
791}
792
793void
794rb_ractor_blocking_threads_dec(rb_ractor_t *cr, const char *file, int line)
795{
796 RUBY_DEBUG_LOG2(file, line,
797 "r->threads.blocking_cnt:%d--, r->threads.cnt:%u",
798 cr->threads.blocking_cnt, cr->threads.cnt);
799
800 VM_ASSERT(cr == GET_RACTOR());
801
802 if (cr->threads.cnt == cr->threads.blocking_cnt) {
803 rb_vm_t *vm = GET_VM();
804
805 RB_VM_LOCKING() {
806 rb_vm_ractor_blocking_cnt_dec(vm, cr, __FILE__, __LINE__);
807 }
808 }
809
810 cr->threads.blocking_cnt--;
811}
812
813void
814rb_ractor_vm_barrier_interrupt_running_thread(rb_ractor_t *r)
815{
816 VM_ASSERT(r != GET_RACTOR());
817 ASSERT_ractor_unlocking(r);
818 ASSERT_vm_locking();
819
820 RACTOR_LOCK(r);
821 {
822 if (ractor_status_p(r, ractor_running)) {
823 rb_execution_context_t *ec = r->threads.running_ec;
824 if (ec) {
825 RUBY_VM_SET_VM_BARRIER_INTERRUPT(ec);
826 }
827 }
828 }
829 RACTOR_UNLOCK(r);
830}
831
832void
833rb_ractor_terminate_interrupt_main_thread(rb_ractor_t *r)
834{
835 VM_ASSERT(r != GET_RACTOR());
836 ASSERT_ractor_unlocking(r);
837 ASSERT_vm_locking();
838
839 rb_thread_t *main_th = r->threads.main;
840 if (main_th) {
841 if (main_th->status != THREAD_KILLED) {
842 RUBY_VM_SET_TERMINATE_INTERRUPT(main_th->ec);
843 rb_threadptr_interrupt(main_th);
844 }
845 else {
846 RUBY_DEBUG_LOG("killed (%p)", (void *)main_th);
847 }
848 }
849}
850
851void rb_thread_terminate_all(rb_thread_t *th); // thread.c
852
853static void
854ractor_terminal_interrupt_all(rb_vm_t *vm)
855{
856 if (vm->ractor.cnt > 1) {
857 // send terminate notification to all ractors
858 rb_ractor_t *r = 0;
859 ccan_list_for_each(&vm->ractor.set, r, vmlr_node) {
860 if (r != vm->ractor.main_ractor) {
861 RUBY_DEBUG_LOG("r:%d", rb_ractor_id(r));
862 rb_ractor_terminate_interrupt_main_thread(r);
863 }
864 }
865 }
866}
867
868void rb_add_running_thread(rb_thread_t *th);
869void rb_del_running_thread(rb_thread_t *th);
870
871void
872rb_ractor_terminate_all(void)
873{
874 rb_vm_t *vm = GET_VM();
875 rb_ractor_t *cr = vm->ractor.main_ractor;
876
877 RUBY_DEBUG_LOG("ractor.cnt:%d", (int)vm->ractor.cnt);
878
879 VM_ASSERT(cr == GET_RACTOR()); // only main-ractor's main-thread should kick it.
880
881 RB_VM_LOCK();
882 {
883 ractor_terminal_interrupt_all(vm); // kill all ractors
884 }
885 RB_VM_UNLOCK();
886 rb_thread_terminate_all(GET_THREAD()); // kill other threads in main-ractor and wait
887
888 RB_VM_LOCK();
889 {
890 while (vm->ractor.cnt > 1) {
891 RUBY_DEBUG_LOG("terminate_waiting:%d", vm->ractor.sync.terminate_waiting);
892 vm->ractor.sync.terminate_waiting = true;
893
894 // wait for 1sec
895 rb_vm_ractor_blocking_cnt_inc(vm, cr, __FILE__, __LINE__);
896 rb_del_running_thread(rb_ec_thread_ptr(cr->threads.running_ec));
897 rb_vm_cond_timedwait(vm, &vm->ractor.sync.terminate_cond, 1000 /* ms */);
898#ifdef RUBY_THREAD_PTHREAD_H
899 while (vm->ractor.sched.barrier_waiting) {
900 // A barrier is waiting. Threads relinquish the VM lock before joining the barrier and
901 // since we just acquired the VM lock back, we're blocking other threads from joining it.
902 // We loop until the barrier is over. We can't join this barrier because our thread isn't added to
903 // running_threads until the call below to `rb_add_running_thread`.
904 RB_VM_UNLOCK();
905 unsigned int lev;
906 RB_VM_LOCK_ENTER_LEV_NB(&lev);
907 }
908#endif
909 rb_add_running_thread(rb_ec_thread_ptr(cr->threads.running_ec));
910 rb_vm_ractor_blocking_cnt_dec(vm, cr, __FILE__, __LINE__);
911
912 ractor_terminal_interrupt_all(vm);
913 }
914 }
915 RB_VM_UNLOCK();
916}
917
918rb_execution_context_t *
919rb_vm_main_ractor_ec(rb_vm_t *vm)
920{
921 /* This code needs to carefully work around two bugs:
922 * - Bug #20016: When M:N threading is enabled, running_ec is NULL if no thread is
923 * actually currently running (as opposed to without M:N threading, when
924 * running_ec will still point to the _last_ thread which ran)
925 * - Bug #20197: If the main thread is sleeping, setting its postponed job
926 * interrupt flag is pointless; it won't look at the flag until it stops sleeping
927 * for some reason. It would be better to set the flag on the running ec, which
928 * will presumably look at it soon.
929 *
930 * Solution: use running_ec if it's set, otherwise fall back to the main thread ec.
931 * This is still susceptible to some rare race conditions (what if the last thread
932 * to run just entered a long-running sleep?), but seems like the best balance of
933 * robustness and complexity.
934 */
935 rb_execution_context_t *running_ec = vm->ractor.main_ractor->threads.running_ec;
936 if (running_ec) { return running_ec; }
937 return vm->ractor.main_thread->ec;
938}
939
940static VALUE
941ractor_moved_missing(int argc, VALUE *argv, VALUE self)
942{
943 rb_raise(rb_eRactorMovedError, "can not send any methods to a moved object");
944}
945
946/*
947 * Document-class: Ractor::Error
948 *
949 * The parent class of Ractor-related error classes.
950 */
951
952/*
953 * Document-class: Ractor::ClosedError
954 *
955 * Raised when an attempt is made to send a message to a closed port,
956 * or to retrieve a message from a closed and empty port.
957 * Ports may be closed explicitly with Ractor::Port#close
958 * and are closed implicitly when a Ractor terminates.
959 *
960 * port = Ractor::Port.new
961 * port.close
962 * port << "test" # Ractor::ClosedError
963 * port.receive # Ractor::ClosedError
964 *
965 * ClosedError is a descendant of StopIteration, so the closing of a port will break
966 * out of loops without propagating the error.
967 */
968
969/*
970 * Document-class: Ractor::IsolationError
971 *
972 * Raised on attempt to make a Ractor-unshareable object
973 * Ractor-shareable.
974 */
975
976/*
977 * Document-class: Ractor::RemoteError
978 *
979 * Raised on Ractor#join or Ractor#value if there was an uncaught exception in the Ractor.
980 * Its +cause+ will contain the original exception, and +ractor+ is the original ractor
981 * it was raised in.
982 *
983 * r = Ractor.new { raise "Something weird happened" }
984 *
985 * begin
986 * r.value
987 * rescue => e
988 * p e # => #<Ractor::RemoteError: thrown by remote Ractor.>
989 * p e.ractor == r # => true
990 * p e.cause # => #<RuntimeError: Something weird happened>
991 * end
992 *
993 */
994
995/*
996 * Document-class: Ractor::MovedError
997 *
998 * Raised on an attempt to access an object which was moved in Ractor#send or Ractor::Port#send.
999 *
1000 * r = Ractor.new { sleep }
1001 *
1002 * ary = [1, 2, 3]
1003 * r.send(ary, move: true)
1004 * ary.inspect
1005 * # Ractor::MovedError (can not send any methods to a moved object)
1006 *
1007 */
1008
1009/*
1010 * Document-class: Ractor::MovedObject
1011 *
1012 * A special object which replaces any value that was moved to another ractor in Ractor#send
1013 * or Ractor::Port#send. Any attempt to access the object results in Ractor::MovedError.
1014 *
1015 * r = Ractor.new { receive }
1016 *
1017 * ary = [1, 2, 3]
1018 * r.send(ary, move: true)
1019 * p Ractor::MovedObject === ary
1020 * # => true
1021 * ary.inspect
1022 * # Ractor::MovedError (can not send any methods to a moved object)
1023 */
1024
1025/*
1026 * Document-class: Ractor::UnsafeError
1027 *
1028 * Raised when Ractor-unsafe C-methods is invoked by a non-main Ractor.
1029 */
1030
1031// Main docs are in ractor.rb, but without this clause there are weird artifacts
1032// in their rendering.
1033/*
1034 * Document-class: Ractor
1035 *
1036 */
1037
1038void
1039Init_Ractor(void)
1040{
1041 rb_cRactor = rb_define_class("Ractor", rb_cObject);
1043
1044 rb_eRactorError = rb_define_class_under(rb_cRactor, "Error", rb_eRuntimeError);
1045 rb_eRactorIsolationError = rb_define_class_under(rb_cRactor, "IsolationError", rb_eRactorError);
1046 rb_eRactorRemoteError = rb_define_class_under(rb_cRactor, "RemoteError", rb_eRactorError);
1047 rb_eRactorMovedError = rb_define_class_under(rb_cRactor, "MovedError", rb_eRactorError);
1048 rb_eRactorClosedError = rb_define_class_under(rb_cRactor, "ClosedError", rb_eStopIteration);
1049 rb_eRactorUnsafeError = rb_define_class_under(rb_cRactor, "UnsafeError", rb_eRactorError);
1050
1051 rb_cRactorMovedObject = rb_define_class_under(rb_cRactor, "MovedObject", rb_cBasicObject);
1052 rb_undef_alloc_func(rb_cRactorMovedObject);
1053 rb_define_method(rb_cRactorMovedObject, "method_missing", ractor_moved_missing, -1);
1054
1055 // override methods defined in BasicObject
1056 rb_define_method(rb_cRactorMovedObject, "__send__", ractor_moved_missing, -1);
1057 rb_define_method(rb_cRactorMovedObject, "!", ractor_moved_missing, -1);
1058 rb_define_method(rb_cRactorMovedObject, "==", ractor_moved_missing, -1);
1059 rb_define_method(rb_cRactorMovedObject, "!=", ractor_moved_missing, -1);
1060 rb_define_method(rb_cRactorMovedObject, "__id__", ractor_moved_missing, -1);
1061 rb_define_method(rb_cRactorMovedObject, "equal?", ractor_moved_missing, -1);
1062 rb_define_method(rb_cRactorMovedObject, "instance_eval", ractor_moved_missing, -1);
1063 rb_define_method(rb_cRactorMovedObject, "instance_exec", ractor_moved_missing, -1);
1064
1065 Init_RactorPort();
1066}
1067
1068void
1069rb_ractor_dump(void)
1070{
1071 rb_vm_t *vm = GET_VM();
1072 rb_ractor_t *r = 0;
1073
1074 ccan_list_for_each(&vm->ractor.set, r, vmlr_node) {
1075 if (r != vm->ractor.main_ractor) {
1076 fprintf(stderr, "r:%u (%s)\n", r->pub.id, ractor_status_str(r->status_));
1077 }
1078 }
1079}
1080
1081VALUE
1083{
1084 if (rb_ractor_main_p()) {
1085 return rb_stdin;
1086 }
1087 else {
1088 rb_ractor_t *cr = GET_RACTOR();
1089 return cr->r_stdin;
1090 }
1091}
1092
1093VALUE
1094rb_ractor_stdout(void)
1095{
1096 if (rb_ractor_main_p()) {
1097 return rb_stdout;
1098 }
1099 else {
1100 rb_ractor_t *cr = GET_RACTOR();
1101 return cr->r_stdout;
1102 }
1103}
1104
1105VALUE
1106rb_ractor_stderr(void)
1107{
1108 if (rb_ractor_main_p()) {
1109 return rb_stderr;
1110 }
1111 else {
1112 rb_ractor_t *cr = GET_RACTOR();
1113 return cr->r_stderr;
1114 }
1115}
1116
1117void
1119{
1120 if (rb_ractor_main_p()) {
1121 rb_stdin = in;
1122 }
1123 else {
1124 rb_ractor_t *cr = GET_RACTOR();
1125 RB_OBJ_WRITE(cr->pub.self, &cr->r_stdin, in);
1126 }
1127}
1128
1129void
1131{
1132 if (rb_ractor_main_p()) {
1133 rb_stdout = out;
1134 }
1135 else {
1136 rb_ractor_t *cr = GET_RACTOR();
1137 RB_OBJ_WRITE(cr->pub.self, &cr->r_stdout, out);
1138 }
1139}
1140
1141void
1143{
1144 if (rb_ractor_main_p()) {
1145 rb_stderr = err;
1146 }
1147 else {
1148 rb_ractor_t *cr = GET_RACTOR();
1149 RB_OBJ_WRITE(cr->pub.self, &cr->r_stderr, err);
1150 }
1151}
1152
1153rb_hook_list_t *
1154rb_ractor_hooks(rb_ractor_t *cr)
1155{
1156 return &cr->pub.hooks;
1157}
1158
1159st_table *
1160rb_ractor_targeted_hooks(rb_ractor_t *cr)
1161{
1162 return cr->pub.targeted_hooks;
1163}
1164
1165static void
1166rb_obj_set_shareable_no_assert(VALUE obj)
1167{
1169
1170 if (rb_obj_gen_fields_p(obj)) {
1171 VALUE fields = rb_obj_fields_no_ractor_check(obj);
1172 if (imemo_type_p(fields, imemo_fields)) {
1173 // no recursive mark
1174 FL_SET_RAW(fields, FL_SHAREABLE);
1175 }
1176 }
1177}
1178
1179#ifndef STRICT_VERIFY_SHAREABLE
1180#define STRICT_VERIFY_SHAREABLE 0
1181#endif
1182
1183bool
1184rb_ractor_verify_shareable(VALUE obj)
1185{
1186#if STRICT_VERIFY_SHAREABLE
1187 rb_gc_verify_shareable(obj);
1188#endif
1189 return true;
1190}
1191
1192VALUE
1193rb_obj_set_shareable(VALUE obj)
1194{
1195 RUBY_ASSERT(!RB_SPECIAL_CONST_P(obj));
1196
1197 rb_obj_set_shareable_no_assert(obj);
1198 RUBY_ASSERT(rb_ractor_verify_shareable(obj));
1199
1200 return obj;
1201}
1202
1204
1205// 2: stop search
1206// 1: skip child
1207// 0: continue
1208
1209enum obj_traverse_iterator_result {
1210 traverse_cont,
1211 traverse_skip,
1212 traverse_stop,
1213};
1214
1215typedef enum obj_traverse_iterator_result (*rb_obj_traverse_enter_func)(VALUE obj);
1216typedef enum obj_traverse_iterator_result (*rb_obj_traverse_leave_func)(VALUE obj);
1217typedef enum obj_traverse_iterator_result (*rb_obj_traverse_final_func)(VALUE obj);
1218
1219static enum obj_traverse_iterator_result null_leave(VALUE obj);
1220
1222 rb_obj_traverse_enter_func enter_func;
1223 rb_obj_traverse_leave_func leave_func;
1224
1225 st_table *rec;
1226 VALUE rec_hash;
1227};
1228
1229
1231 bool stop;
1232 struct obj_traverse_data *data;
1233};
1234
1235static int obj_traverse_i(VALUE obj, struct obj_traverse_data *data);
1236
1237static int
1238obj_hash_traverse_i(VALUE key, VALUE val, VALUE ptr)
1239{
1241
1242 if (obj_traverse_i(key, d->data)) {
1243 d->stop = true;
1244 return ST_STOP;
1245 }
1246
1247 if (obj_traverse_i(val, d->data)) {
1248 d->stop = true;
1249 return ST_STOP;
1250 }
1251
1252 return ST_CONTINUE;
1253}
1254
1255static void
1256obj_traverse_reachable_i(VALUE obj, void *ptr)
1257{
1259
1260 if (obj_traverse_i(obj, d->data)) {
1261 d->stop = true;
1262 }
1263}
1264
1265static struct st_table *
1266obj_traverse_rec(struct obj_traverse_data *data)
1267{
1268 if (UNLIKELY(!data->rec)) {
1269 data->rec_hash = rb_ident_hash_new();
1270 data->rec = RHASH_ST_TABLE(data->rec_hash);
1271 }
1272 return data->rec;
1273}
1274
1275static int
1276obj_traverse_ivar_foreach_i(ID key, VALUE val, st_data_t ptr)
1277{
1279
1280 if (obj_traverse_i(val, d->data)) {
1281 d->stop = true;
1282 return ST_STOP;
1283 }
1284
1285 return ST_CONTINUE;
1286}
1287
1288static int
1289obj_traverse_i(VALUE obj, struct obj_traverse_data *data)
1290{
1291 if (RB_SPECIAL_CONST_P(obj)) return 0;
1292
1293 switch (data->enter_func(obj)) {
1294 case traverse_cont: break;
1295 case traverse_skip: return 0; // skip children
1296 case traverse_stop: return 1; // stop search
1297 }
1298
1299 if (UNLIKELY(st_insert(obj_traverse_rec(data), obj, 1))) {
1300 // already traversed
1301 return 0;
1302 }
1303 RB_OBJ_WRITTEN(data->rec_hash, Qundef, obj);
1304
1305 struct obj_traverse_callback_data d = {
1306 .stop = false,
1307 .data = data,
1308 };
1309 rb_ivar_foreach(obj, obj_traverse_ivar_foreach_i, (st_data_t)&d);
1310 if (d.stop) return 1;
1311
1312 switch (BUILTIN_TYPE(obj)) {
1313 // no child node
1314 case T_STRING:
1315 case T_FLOAT:
1316 case T_BIGNUM:
1317 case T_REGEXP:
1318 case T_FILE:
1319 case T_SYMBOL:
1320 break;
1321
1322 case T_OBJECT:
1323 /* Instance variables already traversed. */
1324 break;
1325
1326 case T_ARRAY:
1327 {
1328 rb_ary_cancel_sharing(obj);
1329
1330 for (int i = 0; i < RARRAY_LENINT(obj); i++) {
1331 VALUE e = rb_ary_entry(obj, i);
1332 if (obj_traverse_i(e, data)) return 1;
1333 }
1334 }
1335 break;
1336
1337 case T_HASH:
1338 {
1339 if (obj_traverse_i(RHASH_IFNONE(obj), data)) return 1;
1340
1341 struct obj_traverse_callback_data d = {
1342 .stop = false,
1343 .data = data,
1344 };
1345 rb_hash_foreach(obj, obj_hash_traverse_i, (VALUE)&d);
1346 if (d.stop) return 1;
1347 }
1348 break;
1349
1350 case T_STRUCT:
1351 {
1352 long len = RSTRUCT_LEN(obj);
1353 const VALUE *ptr = RSTRUCT_CONST_PTR(obj);
1354
1355 for (long i=0; i<len; i++) {
1356 if (obj_traverse_i(ptr[i], data)) return 1;
1357 }
1358 }
1359 break;
1360
1361 case T_MATCH:
1362 if (obj_traverse_i(RMATCH(obj)->str, data)) return 1;
1363 break;
1364
1365 case T_RATIONAL:
1366 if (obj_traverse_i(RRATIONAL(obj)->num, data)) return 1;
1367 if (obj_traverse_i(RRATIONAL(obj)->den, data)) return 1;
1368 break;
1369 case T_COMPLEX:
1370 if (obj_traverse_i(RCOMPLEX(obj)->real, data)) return 1;
1371 if (obj_traverse_i(RCOMPLEX(obj)->imag, data)) return 1;
1372 break;
1373
1374 case T_DATA:
1375 case T_IMEMO:
1376 {
1377 struct obj_traverse_callback_data d = {
1378 .stop = false,
1379 .data = data,
1380 };
1381 RB_VM_LOCKING_NO_BARRIER() {
1382 rb_objspace_reachable_objects_from(obj, obj_traverse_reachable_i, &d);
1383 }
1384 if (d.stop) return 1;
1385 }
1386 break;
1387
1388 // unreachable
1389 case T_CLASS:
1390 case T_MODULE:
1391 case T_ICLASS:
1392 default:
1393 rp(obj);
1394 rb_bug("unreachable");
1395 }
1396
1397 if (data->leave_func(obj) == traverse_stop) {
1398 return 1;
1399 }
1400 else {
1401 return 0;
1402 }
1403}
1404
1406 rb_obj_traverse_final_func final_func;
1407 int stopped;
1408};
1409
1410static int
1411obj_traverse_final_i(st_data_t key, st_data_t val, st_data_t arg)
1412{
1413 struct rb_obj_traverse_final_data *data = (void *)arg;
1414 if (data->final_func(key)) {
1415 data->stopped = 1;
1416 return ST_STOP;
1417 }
1418 return ST_CONTINUE;
1419}
1420
1421// 0: traverse all
1422// 1: stopped
1423static int
1424rb_obj_traverse(VALUE obj,
1425 rb_obj_traverse_enter_func enter_func,
1426 rb_obj_traverse_leave_func leave_func,
1427 rb_obj_traverse_final_func final_func)
1428{
1429 struct obj_traverse_data data = {
1430 .enter_func = enter_func,
1431 .leave_func = leave_func,
1432 .rec = NULL,
1433 };
1434
1435 if (obj_traverse_i(obj, &data)) return 1;
1436 if (final_func && data.rec) {
1437 struct rb_obj_traverse_final_data f = {final_func, 0};
1438 st_foreach(data.rec, obj_traverse_final_i, (st_data_t)&f);
1439 return f.stopped;
1440 }
1441 return 0;
1442}
1443
1444static int
1445allow_frozen_shareable_p(VALUE obj)
1446{
1447 if (!RB_TYPE_P(obj, T_DATA)) {
1448 return true;
1449 }
1450 else if (RTYPEDDATA_P(obj)) {
1451 const rb_data_type_t *type = RTYPEDDATA_TYPE(obj);
1452 if (type->flags & RUBY_TYPED_FROZEN_SHAREABLE) {
1453 return true;
1454 }
1455 }
1456
1457 return false;
1458}
1459
1460static enum obj_traverse_iterator_result
1461make_shareable_check_shareable_freeze(VALUE obj, enum obj_traverse_iterator_result result)
1462{
1463 if (!RB_OBJ_FROZEN_RAW(obj)) {
1464 rb_funcall(obj, idFreeze, 0);
1465
1466 if (UNLIKELY(!RB_OBJ_FROZEN_RAW(obj))) {
1467 rb_raise(rb_eRactorError, "#freeze does not freeze object correctly");
1468 }
1469
1470 if (RB_OBJ_SHAREABLE_P(obj)) {
1471 return traverse_skip;
1472 }
1473 }
1474
1475 return result;
1476}
1477
1478static int obj_refer_only_shareables_p(VALUE obj);
1479
1480static enum obj_traverse_iterator_result
1481make_shareable_check_shareable(VALUE obj)
1482{
1483 VM_ASSERT(!SPECIAL_CONST_P(obj));
1484
1485 if (rb_ractor_shareable_p(obj)) {
1486 return traverse_skip;
1487 }
1488 else if (!allow_frozen_shareable_p(obj)) {
1489 if (!RB_TYPE_P(obj, T_DATA)) {
1490 rb_raise(rb_eRactorError,
1491 "can not make shareable object for %+"PRIsVALUE, obj);
1492 }
1493 else if (RTYPEDDATA_TYPE(obj)->flags & RUBY_TYPED_FROZEN_SHAREABLE_NO_REC) {
1494 if (obj_refer_only_shareables_p(obj)) {
1495 make_shareable_check_shareable_freeze(obj, traverse_skip);
1496 RB_OBJ_SET_SHAREABLE(obj);
1497 return traverse_skip;
1498 }
1499 else {
1500 rb_raise(rb_eRactorError,
1501 "can not make shareable object for %+"PRIsVALUE" because it refers unshareable objects", obj);
1502 }
1503 }
1504 else if (rb_obj_is_proc(obj)) {
1505 rb_proc_ractor_make_shareable(obj, Qundef);
1506 return traverse_cont;
1507 }
1508 else {
1509 rb_raise(rb_eRactorError, "can not make shareable object for %+"PRIsVALUE, obj);
1510 }
1511 }
1512
1513 switch (TYPE(obj)) {
1514 case T_IMEMO:
1515 return traverse_skip;
1516 case T_OBJECT:
1517 {
1518 // If a T_OBJECT is shared and has no free capacity, we can't safely store the object_id inline,
1519 // as it would require to move the object content into an external buffer.
1520 // This is only a problem for T_OBJECT, given other types have external fields and can do RCU.
1521 // To avoid this issue, we proactively create the object_id.
1522 shape_id_t shape_id = RBASIC_SHAPE_ID(obj);
1523 attr_index_t capacity = RSHAPE_CAPACITY(shape_id);
1524 attr_index_t free_capacity = capacity - RSHAPE_LEN(shape_id);
1525 if (!rb_shape_has_object_id(shape_id) && capacity && !free_capacity) {
1526 rb_obj_id(obj);
1527 }
1528 }
1529 break;
1530 default:
1531 break;
1532 }
1533
1534 return make_shareable_check_shareable_freeze(obj, traverse_cont);
1535}
1536
1537static enum obj_traverse_iterator_result
1538mark_shareable(VALUE obj)
1539{
1540 if (RB_TYPE_P(obj, T_STRING)) {
1541 rb_str_make_independent(obj);
1542 }
1543
1544 rb_obj_set_shareable_no_assert(obj);
1545 return traverse_cont;
1546}
1547
1548VALUE
1550{
1551 rb_obj_traverse(obj,
1552 make_shareable_check_shareable,
1553 null_leave, mark_shareable);
1554 return obj;
1555}
1556
1557VALUE
1559{
1560 VALUE copy = ractor_copy(obj);
1561 return rb_ractor_make_shareable(copy);
1562}
1563
1564VALUE
1565rb_ractor_ensure_shareable(VALUE obj, VALUE name)
1566{
1567 if (!rb_ractor_shareable_p(obj)) {
1568 VALUE message = rb_sprintf("cannot assign unshareable object to %"PRIsVALUE,
1569 name);
1570 rb_exc_raise(rb_exc_new_str(rb_eRactorIsolationError, message));
1571 }
1572 return obj;
1573}
1574
1575void
1576rb_ractor_ensure_main_ractor(const char *msg)
1577{
1578 if (!rb_ractor_main_p()) {
1579 rb_raise(rb_eRactorIsolationError, "%s", msg);
1580 }
1581}
1582
1583static enum obj_traverse_iterator_result
1584shareable_p_enter(VALUE obj)
1585{
1586 if (RB_OBJ_SHAREABLE_P(obj)) {
1587 return traverse_skip;
1588 }
1589 else if (RB_TYPE_P(obj, T_CLASS) ||
1590 RB_TYPE_P(obj, T_MODULE) ||
1591 RB_TYPE_P(obj, T_ICLASS)) {
1592 // TODO: remove it
1593 mark_shareable(obj);
1594 return traverse_skip;
1595 }
1596 else if (RB_OBJ_FROZEN_RAW(obj) &&
1597 allow_frozen_shareable_p(obj)) {
1598 return traverse_cont;
1599 }
1600
1601 return traverse_stop; // fail
1602}
1603
1604bool
1605rb_ractor_shareable_p_continue(VALUE obj)
1606{
1607 if (rb_obj_traverse(obj,
1608 shareable_p_enter, null_leave,
1609 mark_shareable)) {
1610 return false;
1611 }
1612 else {
1613 return true;
1614 }
1615}
1616
1617#if RACTOR_CHECK_MODE > 0
1618void
1619rb_ractor_setup_belonging(VALUE obj)
1620{
1621 rb_ractor_setup_belonging_to(obj, rb_ractor_current_id());
1622}
1623
1624static enum obj_traverse_iterator_result
1625reset_belonging_enter(VALUE obj)
1626{
1627 if (rb_ractor_shareable_p(obj)) {
1628 return traverse_skip;
1629 }
1630 else {
1631 rb_ractor_setup_belonging(obj);
1632 return traverse_cont;
1633 }
1634}
1635#endif
1636
1637static enum obj_traverse_iterator_result
1638null_leave(VALUE obj)
1639{
1640 return traverse_cont;
1641}
1642
1643static VALUE
1644ractor_reset_belonging(VALUE obj)
1645{
1646#if RACTOR_CHECK_MODE > 0
1647 rb_obj_traverse(obj, reset_belonging_enter, null_leave, NULL);
1648#endif
1649 return obj;
1650}
1651
1652
1654
1655// 2: stop search
1656// 1: skip child
1657// 0: continue
1658
1660static int obj_traverse_replace_i(VALUE obj, struct obj_traverse_replace_data *data);
1661typedef enum obj_traverse_iterator_result (*rb_obj_traverse_replace_enter_func)(VALUE obj, struct obj_traverse_replace_data *data);
1662typedef enum obj_traverse_iterator_result (*rb_obj_traverse_replace_leave_func)(VALUE obj, struct obj_traverse_replace_data *data);
1663
1665 rb_obj_traverse_replace_enter_func enter_func;
1666 rb_obj_traverse_replace_leave_func leave_func;
1667
1668 st_table *rec;
1669 VALUE rec_hash;
1670
1671 VALUE replacement;
1672 bool move;
1673};
1674
1676 bool stop;
1677 VALUE src;
1678 struct obj_traverse_replace_data *data;
1679};
1680
1681static int
1682obj_hash_traverse_replace_foreach_i(st_data_t key, st_data_t value, st_data_t argp, int error)
1683{
1684 return ST_REPLACE;
1685}
1686
1687static int
1688obj_hash_traverse_replace_i(st_data_t *key, st_data_t *val, st_data_t ptr, int exists)
1689{
1691 struct obj_traverse_replace_data *data = d->data;
1692
1693 if (obj_traverse_replace_i(*key, data)) {
1694 d->stop = true;
1695 return ST_STOP;
1696 }
1697 else if (*key != data->replacement) {
1698 VALUE v = *key = data->replacement;
1699 RB_OBJ_WRITTEN(d->src, Qundef, v);
1700 }
1701
1702 if (obj_traverse_replace_i(*val, data)) {
1703 d->stop = true;
1704 return ST_STOP;
1705 }
1706 else if (*val != data->replacement) {
1707 VALUE v = *val = data->replacement;
1708 RB_OBJ_WRITTEN(d->src, Qundef, v);
1709 }
1710
1711 return ST_CONTINUE;
1712}
1713
1714static int
1715obj_iv_hash_traverse_replace_foreach_i(st_data_t _key, st_data_t _val, st_data_t _data, int _x)
1716{
1717 return ST_REPLACE;
1718}
1719
1720static int
1721obj_iv_hash_traverse_replace_i(st_data_t * _key, st_data_t * val, st_data_t ptr, int exists)
1722{
1724 struct obj_traverse_replace_data *data = d->data;
1725
1726 if (obj_traverse_replace_i(*(VALUE *)val, data)) {
1727 d->stop = true;
1728 return ST_STOP;
1729 }
1730 else if (*(VALUE *)val != data->replacement) {
1731 VALUE v = *(VALUE *)val = data->replacement;
1732 RB_OBJ_WRITTEN(d->src, Qundef, v);
1733 }
1734
1735 return ST_CONTINUE;
1736}
1737
1738static struct st_table *
1739obj_traverse_replace_rec(struct obj_traverse_replace_data *data)
1740{
1741 if (UNLIKELY(!data->rec)) {
1742 data->rec_hash = rb_ident_hash_new();
1743 data->rec = RHASH_ST_TABLE(data->rec_hash);
1744 }
1745 return data->rec;
1746}
1747
1748static void
1749obj_refer_only_shareables_p_i(VALUE obj, void *ptr)
1750{
1751 int *pcnt = (int *)ptr;
1752
1753 if (!rb_ractor_shareable_p(obj)) {
1754 ++*pcnt;
1755 }
1756}
1757
1758static int
1759obj_refer_only_shareables_p(VALUE obj)
1760{
1761 int cnt = 0;
1762 RB_VM_LOCKING_NO_BARRIER() {
1763 rb_objspace_reachable_objects_from(obj, obj_refer_only_shareables_p_i, &cnt);
1764 }
1765 return cnt == 0;
1766}
1767
1768static int
1769obj_traverse_replace_i(VALUE obj, struct obj_traverse_replace_data *data)
1770{
1771 st_data_t replacement;
1772
1773 if (RB_SPECIAL_CONST_P(obj)) {
1774 data->replacement = obj;
1775 return 0;
1776 }
1777
1778 switch (data->enter_func(obj, data)) {
1779 case traverse_cont: break;
1780 case traverse_skip: return 0; // skip children
1781 case traverse_stop: return 1; // stop search
1782 }
1783
1784 replacement = (st_data_t)data->replacement;
1785
1786 if (UNLIKELY(st_lookup(obj_traverse_replace_rec(data), (st_data_t)obj, &replacement))) {
1787 data->replacement = (VALUE)replacement;
1788 return 0;
1789 }
1790 else {
1791 st_insert(obj_traverse_replace_rec(data), (st_data_t)obj, replacement);
1792 RB_OBJ_WRITTEN(data->rec_hash, Qundef, obj);
1793 RB_OBJ_WRITTEN(data->rec_hash, Qundef, replacement);
1794 }
1795
1796 if (!data->move) {
1797 obj = replacement;
1798 }
1799
1800#define CHECK_AND_REPLACE(parent_obj, v) do { \
1801 VALUE _val = (v); \
1802 if (obj_traverse_replace_i(_val, data)) { return 1; } \
1803 else if (data->replacement != _val) { RB_OBJ_WRITE(parent_obj, &v, data->replacement); } \
1804} while (0)
1805
1806 if (UNLIKELY(rb_obj_gen_fields_p(obj))) {
1807 VALUE fields_obj = rb_obj_fields_no_ractor_check(obj);
1808
1809 if (UNLIKELY(rb_shape_obj_too_complex_p(obj))) {
1811 .stop = false,
1812 .data = data,
1813 .src = fields_obj,
1814 };
1815 rb_st_foreach_with_replace(
1816 rb_imemo_fields_complex_tbl(fields_obj),
1817 obj_iv_hash_traverse_replace_foreach_i,
1818 obj_iv_hash_traverse_replace_i,
1819 (st_data_t)&d
1820 );
1821 if (d.stop) return 1;
1822 }
1823 else {
1824 uint32_t fields_count = RSHAPE_LEN(RBASIC_SHAPE_ID(obj));
1825 VALUE *fields = rb_imemo_fields_ptr(fields_obj);
1826 for (uint32_t i = 0; i < fields_count; i++) {
1827 CHECK_AND_REPLACE(fields_obj, fields[i]);
1828 }
1829 }
1830 }
1831
1832 switch (BUILTIN_TYPE(obj)) {
1833 // no child node
1834 case T_FLOAT:
1835 case T_BIGNUM:
1836 case T_REGEXP:
1837 case T_FILE:
1838 case T_SYMBOL:
1839 break;
1840 case T_STRING:
1841 rb_str_make_independent(obj);
1842 break;
1843
1844 case T_OBJECT:
1845 {
1846 if (rb_shape_obj_too_complex_p(obj)) {
1848 .stop = false,
1849 .data = data,
1850 .src = obj,
1851 };
1852 rb_st_foreach_with_replace(
1853 ROBJECT_FIELDS_HASH(obj),
1854 obj_iv_hash_traverse_replace_foreach_i,
1855 obj_iv_hash_traverse_replace_i,
1856 (st_data_t)&d
1857 );
1858 if (d.stop) return 1;
1859 }
1860 else {
1861 uint32_t len = ROBJECT_FIELDS_COUNT_NOT_COMPLEX(obj);
1862 VALUE *ptr = ROBJECT_FIELDS(obj);
1863
1864 for (uint32_t i = 0; i < len; i++) {
1865 CHECK_AND_REPLACE(obj, ptr[i]);
1866 }
1867 }
1868 }
1869 break;
1870
1871 case T_ARRAY:
1872 {
1873 rb_ary_cancel_sharing(obj);
1874
1875 for (int i = 0; i < RARRAY_LENINT(obj); i++) {
1876 VALUE e = rb_ary_entry(obj, i);
1877
1878 if (obj_traverse_replace_i(e, data)) {
1879 return 1;
1880 }
1881 else if (e != data->replacement) {
1882 RARRAY_ASET(obj, i, data->replacement);
1883 }
1884 }
1885 RB_GC_GUARD(obj);
1886 }
1887 break;
1888 case T_HASH:
1889 {
1891 .stop = false,
1892 .data = data,
1893 .src = obj,
1894 };
1895 rb_hash_stlike_foreach_with_replace(obj,
1896 obj_hash_traverse_replace_foreach_i,
1897 obj_hash_traverse_replace_i,
1898 (VALUE)&d);
1899 if (d.stop) return 1;
1900 // TODO: rehash here?
1901
1902 VALUE ifnone = RHASH_IFNONE(obj);
1903 if (obj_traverse_replace_i(ifnone, data)) {
1904 return 1;
1905 }
1906 else if (ifnone != data->replacement) {
1907 RHASH_SET_IFNONE(obj, data->replacement);
1908 }
1909 }
1910 break;
1911
1912 case T_STRUCT:
1913 {
1914 long len = RSTRUCT_LEN(obj);
1915 const VALUE *ptr = RSTRUCT_CONST_PTR(obj);
1916
1917 for (long i=0; i<len; i++) {
1918 CHECK_AND_REPLACE(obj, ptr[i]);
1919 }
1920 }
1921 break;
1922
1923 case T_MATCH:
1924 CHECK_AND_REPLACE(obj, RMATCH(obj)->str);
1925 break;
1926
1927 case T_RATIONAL:
1928 CHECK_AND_REPLACE(obj, RRATIONAL(obj)->num);
1929 CHECK_AND_REPLACE(obj, RRATIONAL(obj)->den);
1930 break;
1931 case T_COMPLEX:
1932 CHECK_AND_REPLACE(obj, RCOMPLEX(obj)->real);
1933 CHECK_AND_REPLACE(obj, RCOMPLEX(obj)->imag);
1934 break;
1935
1936 case T_DATA:
1937 if (!data->move && obj_refer_only_shareables_p(obj)) {
1938 break;
1939 }
1940 else {
1941 rb_raise(rb_eRactorError, "can not %s %"PRIsVALUE" object.",
1942 data->move ? "move" : "copy", rb_class_of(obj));
1943 }
1944
1945 case T_IMEMO:
1946 // not supported yet
1947 return 1;
1948
1949 // unreachable
1950 case T_CLASS:
1951 case T_MODULE:
1952 case T_ICLASS:
1953 default:
1954 rp(obj);
1955 rb_bug("unreachable");
1956 }
1957
1958 data->replacement = (VALUE)replacement;
1959
1960 if (data->leave_func(obj, data) == traverse_stop) {
1961 return 1;
1962 }
1963 else {
1964 return 0;
1965 }
1966}
1967
1968// 0: traverse all
1969// 1: stopped
1970static VALUE
1971rb_obj_traverse_replace(VALUE obj,
1972 rb_obj_traverse_replace_enter_func enter_func,
1973 rb_obj_traverse_replace_leave_func leave_func,
1974 bool move)
1975{
1976 struct obj_traverse_replace_data data = {
1977 .enter_func = enter_func,
1978 .leave_func = leave_func,
1979 .rec = NULL,
1980 .replacement = Qundef,
1981 .move = move,
1982 };
1983
1984 if (obj_traverse_replace_i(obj, &data)) {
1985 return Qundef;
1986 }
1987 else {
1988 return data.replacement;
1989 }
1990}
1991
1992static const bool wb_protected_types[RUBY_T_MASK] = {
2003};
2004
2005static enum obj_traverse_iterator_result
2006move_enter(VALUE obj, struct obj_traverse_replace_data *data)
2007{
2008 if (rb_ractor_shareable_p(obj)) {
2009 data->replacement = obj;
2010 return traverse_skip;
2011 }
2012 else {
2013 VALUE type = RB_BUILTIN_TYPE(obj);
2014 size_t slot_size = rb_gc_obj_slot_size(obj);
2015 type |= wb_protected_types[type] ? FL_WB_PROTECTED : 0;
2016 NEWOBJ_OF(moved, struct RBasic, 0, type, slot_size, 0);
2017 MEMZERO(&moved[1], char, slot_size - sizeof(*moved));
2018 data->replacement = (VALUE)moved;
2019 return traverse_cont;
2020 }
2021}
2022
2023static enum obj_traverse_iterator_result
2024move_leave(VALUE obj, struct obj_traverse_replace_data *data)
2025{
2026 // Copy flags
2027 VALUE ignored_flags = RUBY_FL_PROMOTED;
2028 RBASIC(data->replacement)->flags = (RBASIC(obj)->flags & ~ignored_flags) | (RBASIC(data->replacement)->flags & ignored_flags);
2029 // Copy contents without the flags
2030 memcpy(
2031 (char *)data->replacement + sizeof(VALUE),
2032 (char *)obj + sizeof(VALUE),
2033 rb_gc_obj_slot_size(obj) - sizeof(VALUE)
2034 );
2035
2036 // We've copied obj's references to the replacement
2037 rb_gc_writebarrier_remember(data->replacement);
2038
2039 void rb_replace_generic_ivar(VALUE clone, VALUE obj); // variable.c
2040 if (UNLIKELY(rb_obj_gen_fields_p(obj))) {
2041 rb_replace_generic_ivar(data->replacement, obj);
2042 }
2043
2044 rb_gc_obj_id_moved(data->replacement);
2045
2046 VALUE flags = T_OBJECT | FL_FREEZE | (RBASIC(obj)->flags & FL_PROMOTED);
2047
2048 // Avoid mutations using bind_call, etc.
2049 MEMZERO((char *)obj, char, sizeof(struct RBasic));
2050 RBASIC(obj)->flags = flags;
2051 RBASIC_SET_CLASS_RAW(obj, rb_cRactorMovedObject);
2052 return traverse_cont;
2053}
2054
2055static VALUE
2056ractor_move(VALUE obj)
2057{
2058 VALUE val = rb_obj_traverse_replace(obj, move_enter, move_leave, true);
2059 if (!UNDEF_P(val)) {
2060 return val;
2061 }
2062 else {
2063 rb_raise(rb_eRactorError, "can not move the object");
2064 }
2065}
2066
2067static enum obj_traverse_iterator_result
2068copy_enter(VALUE obj, struct obj_traverse_replace_data *data)
2069{
2070 if (rb_ractor_shareable_p(obj)) {
2071 data->replacement = obj;
2072 return traverse_skip;
2073 }
2074 else {
2075 data->replacement = rb_obj_clone(obj);
2076 return traverse_cont;
2077 }
2078}
2079
2080static enum obj_traverse_iterator_result
2081copy_leave(VALUE obj, struct obj_traverse_replace_data *data)
2082{
2083 return traverse_cont;
2084}
2085
2086static VALUE
2087ractor_copy(VALUE obj)
2088{
2089 VALUE val = rb_obj_traverse_replace(obj, copy_enter, copy_leave, false);
2090 if (!UNDEF_P(val)) {
2091 return val;
2092 }
2093 else {
2094 rb_raise(rb_eRactorError, "can not copy the object");
2095 }
2096}
2097
2098// Ractor local storage
2099
2101 const struct rb_ractor_local_storage_type *type;
2102 void *main_cache;
2103};
2104
2106 int cnt;
2107 int capa;
2109} freed_ractor_local_keys;
2110
2111static int
2112ractor_local_storage_mark_i(st_data_t key, st_data_t val, st_data_t dmy)
2113{
2115 if (k->type->mark) (*k->type->mark)((void *)val);
2116 return ST_CONTINUE;
2117}
2118
2119static enum rb_id_table_iterator_result
2120idkey_local_storage_mark_i(VALUE val, void *dmy)
2121{
2122 rb_gc_mark(val);
2123 return ID_TABLE_CONTINUE;
2124}
2125
2126static void
2127ractor_local_storage_mark(rb_ractor_t *r)
2128{
2129 if (r->local_storage) {
2130 st_foreach(r->local_storage, ractor_local_storage_mark_i, 0);
2131
2132 for (int i=0; i<freed_ractor_local_keys.cnt; i++) {
2133 rb_ractor_local_key_t key = freed_ractor_local_keys.keys[i];
2134 st_data_t val, k = (st_data_t)key;
2135 if (st_delete(r->local_storage, &k, &val) &&
2136 (key = (rb_ractor_local_key_t)k)->type->free) {
2137 (*key->type->free)((void *)val);
2138 }
2139 }
2140 }
2141
2142 if (r->idkey_local_storage) {
2143 rb_id_table_foreach_values(r->idkey_local_storage, idkey_local_storage_mark_i, NULL);
2144 }
2145
2146 rb_gc_mark(r->local_storage_store_lock);
2147}
2148
2149static int
2150ractor_local_storage_free_i(st_data_t key, st_data_t val, st_data_t dmy)
2151{
2153 if (k->type->free) (*k->type->free)((void *)val);
2154 return ST_CONTINUE;
2155}
2156
2157static void
2158ractor_local_storage_free(rb_ractor_t *r)
2159{
2160 if (r->local_storage) {
2161 st_foreach(r->local_storage, ractor_local_storage_free_i, 0);
2162 st_free_table(r->local_storage);
2163 }
2164
2165 if (r->idkey_local_storage) {
2166 rb_id_table_free(r->idkey_local_storage);
2167 }
2168}
2169
2170static void
2171rb_ractor_local_storage_value_mark(void *ptr)
2172{
2173 rb_gc_mark((VALUE)ptr);
2174}
2175
2176static const struct rb_ractor_local_storage_type ractor_local_storage_type_null = {
2177 NULL,
2178 NULL,
2179};
2180
2182 NULL,
2183 ruby_xfree,
2184};
2185
2186static const struct rb_ractor_local_storage_type ractor_local_storage_type_value = {
2187 rb_ractor_local_storage_value_mark,
2188 NULL,
2189};
2190
2193{
2195 key->type = type ? type : &ractor_local_storage_type_null;
2196 key->main_cache = (void *)Qundef;
2197 return key;
2198}
2199
2202{
2203 return rb_ractor_local_storage_ptr_newkey(&ractor_local_storage_type_value);
2204}
2205
2206void
2207rb_ractor_local_storage_delkey(rb_ractor_local_key_t key)
2208{
2209 RB_VM_LOCKING() {
2210 if (freed_ractor_local_keys.cnt == freed_ractor_local_keys.capa) {
2211 freed_ractor_local_keys.capa = freed_ractor_local_keys.capa ? freed_ractor_local_keys.capa * 2 : 4;
2212 REALLOC_N(freed_ractor_local_keys.keys, rb_ractor_local_key_t, freed_ractor_local_keys.capa);
2213 }
2214 freed_ractor_local_keys.keys[freed_ractor_local_keys.cnt++] = key;
2215 }
2216}
2217
2218static bool
2219ractor_local_ref(rb_ractor_local_key_t key, void **pret)
2220{
2221 if (rb_ractor_main_p()) {
2222 if (!UNDEF_P((VALUE)key->main_cache)) {
2223 *pret = key->main_cache;
2224 return true;
2225 }
2226 else {
2227 return false;
2228 }
2229 }
2230 else {
2231 rb_ractor_t *cr = GET_RACTOR();
2232
2233 if (cr->local_storage && st_lookup(cr->local_storage, (st_data_t)key, (st_data_t *)pret)) {
2234 return true;
2235 }
2236 else {
2237 return false;
2238 }
2239 }
2240}
2241
2242static void
2243ractor_local_set(rb_ractor_local_key_t key, void *ptr)
2244{
2245 rb_ractor_t *cr = GET_RACTOR();
2246
2247 if (cr->local_storage == NULL) {
2248 cr->local_storage = st_init_numtable();
2249 }
2250
2251 st_insert(cr->local_storage, (st_data_t)key, (st_data_t)ptr);
2252
2253 if (rb_ractor_main_p()) {
2254 key->main_cache = ptr;
2255 }
2256}
2257
2258VALUE
2260{
2261 void *val;
2262 if (ractor_local_ref(key, &val)) {
2263 return (VALUE)val;
2264 }
2265 else {
2266 return Qnil;
2267 }
2268}
2269
2270bool
2272{
2273 if (ractor_local_ref(key, (void **)val)) {
2274 return true;
2275 }
2276 else {
2277 return false;
2278 }
2279}
2280
2281void
2283{
2284 ractor_local_set(key, (void *)val);
2285}
2286
2287void *
2289{
2290 void *ret;
2291 if (ractor_local_ref(key, &ret)) {
2292 return ret;
2293 }
2294 else {
2295 return NULL;
2296 }
2297}
2298
2299void
2301{
2302 ractor_local_set(key, ptr);
2303}
2304
2305#define DEFAULT_KEYS_CAPA 0x10
2306
2307void
2308rb_ractor_finish_marking(void)
2309{
2310 for (int i=0; i<freed_ractor_local_keys.cnt; i++) {
2311 ruby_xfree(freed_ractor_local_keys.keys[i]);
2312 }
2313 freed_ractor_local_keys.cnt = 0;
2314 if (freed_ractor_local_keys.capa > DEFAULT_KEYS_CAPA) {
2315 freed_ractor_local_keys.capa = DEFAULT_KEYS_CAPA;
2316 REALLOC_N(freed_ractor_local_keys.keys, rb_ractor_local_key_t, DEFAULT_KEYS_CAPA);
2317 }
2318}
2319
2320static VALUE
2321ractor_local_value(rb_execution_context_t *ec, VALUE self, VALUE sym)
2322{
2323 rb_ractor_t *cr = rb_ec_ractor_ptr(ec);
2324 ID id = rb_check_id(&sym);
2325 struct rb_id_table *tbl = cr->idkey_local_storage;
2326 VALUE val;
2327
2328 if (id && tbl && rb_id_table_lookup(tbl, id, &val)) {
2329 return val;
2330 }
2331 else {
2332 return Qnil;
2333 }
2334}
2335
2336static VALUE
2337ractor_local_value_set(rb_execution_context_t *ec, VALUE self, VALUE sym, VALUE val)
2338{
2339 rb_ractor_t *cr = rb_ec_ractor_ptr(ec);
2340 ID id = SYM2ID(rb_to_symbol(sym));
2341 struct rb_id_table *tbl = cr->idkey_local_storage;
2342
2343 if (tbl == NULL) {
2344 tbl = cr->idkey_local_storage = rb_id_table_create(2);
2345 }
2346 rb_id_table_insert(tbl, id, val);
2347 return val;
2348}
2349
2351 rb_execution_context_t *ec;
2352 struct rb_id_table *tbl;
2353 ID id;
2354 VALUE sym;
2355};
2356
2357static VALUE
2358ractor_local_value_store_i(VALUE ptr)
2359{
2360 VALUE val;
2362
2363 if (rb_id_table_lookup(data->tbl, data->id, &val)) {
2364 // after synchronization, we found already registered entry
2365 }
2366 else {
2367 val = rb_yield(Qnil);
2368 ractor_local_value_set(data->ec, Qnil, data->sym, val);
2369 }
2370 return val;
2371}
2372
2373static VALUE
2374ractor_local_value_store_if_absent(rb_execution_context_t *ec, VALUE self, VALUE sym)
2375{
2376 rb_ractor_t *cr = rb_ec_ractor_ptr(ec);
2377 struct ractor_local_storage_store_data data = {
2378 .ec = ec,
2379 .sym = sym,
2380 .id = SYM2ID(rb_to_symbol(sym)),
2381 .tbl = cr->idkey_local_storage,
2382 };
2383 VALUE val;
2384
2385 if (data.tbl == NULL) {
2386 data.tbl = cr->idkey_local_storage = rb_id_table_create(2);
2387 }
2388 else if (rb_id_table_lookup(data.tbl, data.id, &val)) {
2389 // already set
2390 return val;
2391 }
2392
2393 if (!cr->local_storage_store_lock) {
2394 cr->local_storage_store_lock = rb_mutex_new();
2395 }
2396
2397 return rb_mutex_synchronize(cr->local_storage_store_lock, ractor_local_value_store_i, (VALUE)&data);
2398}
2399
2400// shareable_proc
2401
2402static VALUE
2403ractor_shareable_proc(rb_execution_context_t *ec, VALUE replace_self, bool is_lambda)
2404{
2405 if (!rb_ractor_shareable_p(replace_self)) {
2406 rb_raise(rb_eRactorIsolationError, "self should be shareable: %" PRIsVALUE, replace_self);
2407 }
2408 else {
2409 VALUE proc = is_lambda ? rb_block_lambda() : rb_block_proc();
2410 return rb_proc_ractor_make_shareable(rb_proc_dup(proc), replace_self);
2411 }
2412}
2413
2414// Ractor#require
2415
2417 VALUE port;
2418 bool raised;
2419
2420 union {
2421 struct {
2422 VALUE feature;
2423 } require;
2424
2425 struct {
2426 VALUE module;
2427 ID name;
2428 } autoload;
2429 } as;
2430
2431 bool silent;
2432};
2433
2434RUBY_REFERENCES(cross_ractor_require_refs) = {
2435 RUBY_REF_EDGE(struct cross_ractor_require, port),
2436 RUBY_REF_EDGE(struct cross_ractor_require, as.require.feature),
2437 RUBY_REF_END
2438};
2439
2440static const rb_data_type_t cross_ractor_require_data_type = {
2441 "ractor/cross_ractor_require",
2442 {
2443 RUBY_REFS_LIST_PTR(cross_ractor_require_refs),
2445 NULL, // memsize
2446 NULL, // compact
2447 },
2448 0, 0, RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_DECL_MARKING | RUBY_TYPED_EMBEDDABLE
2449};
2450
2451static VALUE
2452require_body(VALUE crr_obj)
2453{
2454 struct cross_ractor_require *crr;
2455 TypedData_Get_Struct(crr_obj, struct cross_ractor_require, &cross_ractor_require_data_type, crr);
2456 VALUE feature = crr->as.require.feature;
2457
2458 ID require;
2459 CONST_ID(require, "require");
2460
2461 if (crr->silent) {
2462 int rb_require_internal_silent(VALUE fname);
2463 return INT2NUM(rb_require_internal_silent(feature));
2464 }
2465 else {
2466 return rb_funcallv(Qnil, require, 1, &feature);
2467 }
2468}
2469
2470static VALUE
2471require_rescue(VALUE crr_obj, VALUE errinfo)
2472{
2473 struct cross_ractor_require *crr;
2474 TypedData_Get_Struct(crr_obj, struct cross_ractor_require, &cross_ractor_require_data_type, crr);
2475 crr->raised = true;
2476 return errinfo;
2477}
2478
2479static VALUE
2480require_result_send_body(VALUE ary)
2481{
2482 VALUE port = RARRAY_AREF(ary, 0);
2483 VALUE results = RARRAY_AREF(ary, 1);
2484
2485 rb_execution_context_t *ec = GET_EC();
2486
2487 ractor_port_send(ec, port, results, Qfalse);
2488 return Qnil;
2489}
2490
2491static VALUE
2492require_result_send_resuce(VALUE port, VALUE errinfo)
2493{
2494 // TODO: need rescue?
2495 ractor_port_send(GET_EC(), port, errinfo, Qfalse);
2496 return Qnil;
2497}
2498
2499static VALUE
2500ractor_require_protect(VALUE crr_obj, VALUE (*func)(VALUE))
2501{
2502 struct cross_ractor_require *crr;
2503 TypedData_Get_Struct(crr_obj, struct cross_ractor_require, &cross_ractor_require_data_type, crr);
2504
2505 const bool silent = crr->silent;
2506
2507 VALUE debug, errinfo;
2508 if (silent) {
2509 debug = ruby_debug;
2510 errinfo = rb_errinfo();
2511 }
2512
2513 // get normal result or raised exception (with crr->raised == true)
2514 VALUE result = rb_rescue2(func, crr_obj, require_rescue, crr_obj, rb_eException, 0);
2515
2516 if (silent) {
2517 ruby_debug = debug;
2518 rb_set_errinfo(errinfo);
2519 }
2520
2521 rb_rescue2(require_result_send_body,
2522 // [port, [result, raised]]
2523 rb_ary_new_from_args(2, crr->port, rb_ary_new_from_args(2, result, crr->raised ? Qtrue : Qfalse)),
2524 require_result_send_resuce, rb_eException, crr->port);
2525
2526 RB_GC_GUARD(crr_obj);
2527 return Qnil;
2528}
2529
2530static VALUE
2531ractor_require_func(void *crr_obj)
2532{
2533 return ractor_require_protect((VALUE)crr_obj, require_body);
2534}
2535
2536VALUE
2537rb_ractor_require(VALUE feature, bool silent)
2538{
2539 // We're about to block on the main ractor, so if we're holding the global lock we'll deadlock.
2540 ASSERT_vm_unlocking();
2541
2542 struct cross_ractor_require *crr;
2543 VALUE crr_obj = TypedData_Make_Struct(0, struct cross_ractor_require, &cross_ractor_require_data_type, crr);
2544 RB_OBJ_SET_SHAREABLE(crr_obj); // TODO: internal data?
2545
2546 // Convert feature to proper file path and make it shareable as fstring
2547 RB_OBJ_WRITE(crr_obj, &crr->as.require.feature, rb_fstring(FilePathValue(feature)));
2548 RB_OBJ_WRITE(crr_obj, &crr->port, rb_ractor_make_shareable(ractor_port_new(GET_RACTOR())));
2549 crr->raised = false;
2550 crr->silent = silent;
2551
2552 rb_execution_context_t *ec = GET_EC();
2553 rb_ractor_t *main_r = GET_VM()->ractor.main_ractor;
2554 rb_ractor_interrupt_exec(main_r, ractor_require_func, (void *)crr_obj, rb_interrupt_exec_flag_value_data);
2555
2556 // wait for require done
2557 VALUE results = ractor_port_receive(ec, crr->port);
2558 ractor_port_close(ec, crr->port);
2559
2560 VALUE exc = rb_ary_pop(results);
2561 VALUE result = rb_ary_pop(results);
2562 RB_GC_GUARD(crr_obj);
2563
2564 if (RTEST(exc)) {
2565 rb_exc_raise(result);
2566 }
2567 else {
2568 return result;
2569 }
2570}
2571
2572static VALUE
2573ractor_require(rb_execution_context_t *ec, VALUE self, VALUE feature)
2574{
2575 return rb_ractor_require(feature, false);
2576}
2577
2578static VALUE
2579autoload_load_body(VALUE crr_obj)
2580{
2581 struct cross_ractor_require *crr;
2582 TypedData_Get_Struct(crr_obj, struct cross_ractor_require, &cross_ractor_require_data_type, crr);
2583 return rb_autoload_load(crr->as.autoload.module, crr->as.autoload.name);
2584}
2585
2586static VALUE
2587ractor_autoload_load_func(void *crr_obj)
2588{
2589 return ractor_require_protect((VALUE)crr_obj, autoload_load_body);
2590}
2591
2592VALUE
2593rb_ractor_autoload_load(VALUE module, ID name)
2594{
2595 struct cross_ractor_require *crr;
2596 VALUE crr_obj = TypedData_Make_Struct(0, struct cross_ractor_require, &cross_ractor_require_data_type, crr);
2597 RB_OBJ_SET_SHAREABLE(crr_obj); // TODO: internal data?
2598
2599 RB_OBJ_WRITE(crr_obj, &crr->as.autoload.module, module);
2600 RB_OBJ_WRITE(crr_obj, &crr->as.autoload.name, name);
2601 RB_OBJ_WRITE(crr_obj, &crr->port, rb_ractor_make_shareable(ractor_port_new(GET_RACTOR())));
2602
2603 rb_execution_context_t *ec = GET_EC();
2604 rb_ractor_t *main_r = GET_VM()->ractor.main_ractor;
2605 rb_ractor_interrupt_exec(main_r, ractor_autoload_load_func, (void *)crr_obj, rb_interrupt_exec_flag_value_data);
2606
2607 // wait for require done
2608 VALUE results = ractor_port_receive(ec, crr->port);
2609 ractor_port_close(ec, crr->port);
2610
2611 VALUE exc = rb_ary_pop(results);
2612 VALUE result = rb_ary_pop(results);
2613 RB_GC_GUARD(crr_obj);
2614
2615 if (RTEST(exc)) {
2616 rb_exc_raise(result);
2617 }
2618 else {
2619 return result;
2620 }
2621}
2622
2623#include "ractor.rbinc"
#define RUBY_ASSERT(...)
Asserts that the given expression is truthy if and only if RUBY_DEBUG is truthy.
Definition assert.h:219
std::atomic< unsigned > rb_atomic_t
Type that is eligible for atomic operations.
Definition atomic.h:69
#define RUBY_ATOMIC_FETCH_ADD(var, val)
Atomically replaces the value pointed by var with the result of addition of val to the old value of v...
Definition atomic.h:118
#define rb_define_method(klass, mid, func, arity)
Defines klass#mid.
@ RUBY_FL_PROMOTED
Ruby objects are "generational".
Definition fl_type.h:217
@ RUBY_FL_SHAREABLE
This flag has something to do with Ractor.
Definition fl_type.h:280
VALUE rb_define_class(const char *name, VALUE super)
Defines a top-level class.
Definition class.c:1488
VALUE rb_define_class_under(VALUE outer, const char *name, VALUE super)
Defines a class under the namespace of outer.
Definition class.c:1519
#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 T_FILE
Old name of RUBY_T_FILE.
Definition value_type.h:62
#define FL_PROMOTED
Old name of RUBY_FL_PROMOTED.
Definition fl_type.h:60
#define REALLOC_N
Old name of RB_REALLOC_N.
Definition memory.h:403
#define ALLOC
Old name of RB_ALLOC.
Definition memory.h:400
#define T_STRING
Old name of RUBY_T_STRING.
Definition value_type.h:78
#define Qundef
Old name of RUBY_Qundef.
#define 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 FL_SHAREABLE
Old name of RUBY_FL_SHAREABLE.
Definition fl_type.h:63
#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 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 FL_WB_PROTECTED
Old name of RUBY_FL_WB_PROTECTED.
Definition fl_type.h:59
#define T_SYMBOL
Old name of RUBY_T_SYMBOL.
Definition value_type.h:80
#define T_MATCH
Old name of RUBY_T_MATCH.
Definition value_type.h:69
#define T_CLASS
Old name of RUBY_T_CLASS.
Definition value_type.h:58
#define BUILTIN_TYPE
Old name of RB_BUILTIN_TYPE.
Definition value_type.h:85
#define FL_FREEZE
Old name of RUBY_FL_FREEZE.
Definition fl_type.h:66
#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:129
#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:486
VALUE rb_rescue2(VALUE(*b_proc)(VALUE), VALUE data1, VALUE(*r_proc)(VALUE, VALUE), VALUE data2,...)
An equivalent of rescue clause.
Definition eval.c:1056
void rb_exc_raise(VALUE mesg)
Raises an exception in the current thread.
Definition eval.c:664
int rb_typeddata_is_kind_of(VALUE obj, const rb_data_type_t *data_type)
Checks if the given object is of given kind.
Definition error.c:1381
VALUE rb_eRuntimeError
RuntimeError exception.
Definition error.c:1429
VALUE rb_eStopIteration
StopIteration exception.
Definition enumerator.c:181
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:1482
VALUE rb_eException
Mother of all exceptions.
Definition error.c:1423
VALUE rb_cRactor
Ractor class.
Definition ractor.c:24
VALUE rb_stdin
STDIN constant.
Definition io.c:206
VALUE rb_stderr
STDERR constant.
Definition io.c:206
VALUE rb_cBasicObject
BasicObject class.
Definition object.c:59
VALUE rb_obj_clone(VALUE obj)
Produces a shallow copy of the given object.
Definition object.c:527
VALUE rb_stdout
STDOUT constant.
Definition io.c:206
#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:615
#define RB_OBJ_WRITE(old, slot, young)
Declaration of a "back" pointer.
Definition gc.h:603
VALUE rb_funcall(VALUE recv, ID mid, int n,...)
Calls a method.
Definition vm_eval.c:1119
#define RGENGC_WB_PROTECTED_STRUCT
This is a compile-time flag to enable/disable write barrier for struct RStruct.
Definition gc.h:468
#define RGENGC_WB_PROTECTED_STRING
This is a compile-time flag to enable/disable write barrier for struct RString.
Definition gc.h:479
#define RGENGC_WB_PROTECTED_HASH
This is a compile-time flag to enable/disable write barrier for struct RHash.
Definition gc.h:457
#define RGENGC_WB_PROTECTED_MATCH
This is a compile-time flag to enable/disable write barrier for struct RMatch.
Definition gc.h:512
#define RGENGC_WB_PROTECTED_ARRAY
This is a compile-time flag to enable/disable write barrier for struct RArray.
Definition gc.h:446
#define RGENGC_WB_PROTECTED_COMPLEX
This is a compile-time flag to enable/disable write barrier for struct RComplex.
Definition gc.h:545
#define RGENGC_WB_PROTECTED_FLOAT
This is a compile-time flag to enable/disable write barrier for struct RFloat.
Definition gc.h:534
#define RGENGC_WB_PROTECTED_RATIONAL
This is a compile-time flag to enable/disable write barrier for struct RRational.
Definition gc.h:556
#define RGENGC_WB_PROTECTED_REGEXP
This is a compile-time flag to enable/disable write barrier for struct RRegexp.
Definition gc.h:501
#define RGENGC_WB_PROTECTED_OBJECT
This is a compile-time flag to enable/disable write barrier for struct RObject.
Definition gc.h:490
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_push(VALUE ary, VALUE elem)
Special case of rb_ary_cat() that it adds only one element.
VALUE rb_ary_entry(VALUE ary, long off)
Queries an element of an array.
VALUE rb_block_proc(void)
Constructs a Proc object from implicitly passed components.
Definition proc.c:994
VALUE rb_block_lambda(void)
Identical to rb_proc_new(), except it returns a lambda.
Definition proc.c:1013
VALUE rb_obj_is_proc(VALUE recv)
Queries if the given object is a proc.
Definition proc.c:126
VALUE rb_str_new_frozen(VALUE str)
Creates a frozen copy of the string, if necessary.
Definition string.c:1535
VALUE rb_mutex_new(void)
Creates a mutex.
VALUE rb_mutex_synchronize(VALUE mutex, VALUE(*func)(VALUE arg), VALUE arg)
Obtains the lock, runs the passed function, and releases the lock when it completes.
VALUE rb_autoload_load(VALUE space, ID name)
Kicks the autoload procedure as if it was "touched".
Definition variable.c:3335
void rb_undef_alloc_func(VALUE klass)
Deletes the allocator function of a class.
Definition vm_method.c:1719
ID rb_check_id(volatile VALUE *namep)
Detects if the given name is already interned or not.
Definition symbol.c:1134
VALUE rb_to_symbol(VALUE name)
Identical to rb_intern_str(), except it generates a dynamic symbol if necessary.
Definition string.c:12779
char * ptr
Pointer to the underlying memory region, of at least capa bytes.
Definition io.h:2
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:2181
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:1558
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:2288
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:2300
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:2192
VALUE rb_ractor_stdin(void)
Queries the standard input of the current Ractor that is calling this function.
Definition ractor.c:1082
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:1142
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:2282
bool rb_ractor_local_storage_value_lookup(rb_ractor_local_key_t key, VALUE *val)
Queries the key.
Definition ractor.c:2271
#define RB_OBJ_SHAREABLE_P(obj)
Queries if the passed object has previously classified as shareable or not.
Definition ractor.h:235
VALUE rb_ractor_make_shareable(VALUE obj)
Destructively transforms the passed object so that multiple Ractors can share it.
Definition ractor.c:1549
rb_ractor_local_key_t rb_ractor_local_storage_value_newkey(void)
Issues a new key.
Definition ractor.c:2201
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:1130
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:1118
VALUE rb_ractor_local_storage_value(rb_ractor_local_key_t key)
Queries the key.
Definition ractor.c:2259
VALUE rb_yield(VALUE val)
Yields the block.
Definition vm_eval.c:1374
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 MEMZERO(p, type, n)
Handy macro to erase a region of memory.
Definition memory.h:360
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
Definition memory.h:167
VALUE rb_proc_new(type *q, VALUE w)
Creates a rb_cProc instance.
VALUE type(ANYARGS)
ANYARGS-ed function type.
void rb_ivar_foreach(VALUE q, int_type *w, VALUE e)
Iteration over each instance variable of the object.
#define RARRAY_AREF(a, i)
Definition rarray.h:403
#define RBASIC(obj)
Convenient casting macro.
Definition rbasic.h:40
#define DATA_PTR(obj)
Convenient getter macro.
Definition rdata.h:67
#define RUBY_DEFAULT_FREE
This is a value you can set to RData::dfree.
Definition rdata.h:78
#define RHASH_SET_IFNONE(h, ifnone)
Destructively updates the default value of the hash.
Definition rhash.h:92
#define RHASH_IFNONE(h)
Definition rhash.h:59
#define RMATCH(obj)
Convenient casting macro.
Definition rmatch.h:37
#define StringValueCStr(v)
Identical to StringValuePtr, except it additionally checks for the contents for viability as a C stri...
Definition rstring.h:89
#define TypedData_Get_Struct(obj, type, data_type, sval)
Obtains a C struct from inside of a wrapper Ruby object.
Definition rtypeddata.h:649
#define TypedData_Wrap_Struct(klass, data_type, sval)
Converts sval, a pointer to your struct, into a Ruby object.
Definition rtypeddata.h:461
struct rb_data_type_struct rb_data_type_t
This is the struct that holds necessary info for a struct.
Definition rtypeddata.h:205
#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:508
#define FilePathValue(v)
Ensures that the parameter object is a path.
Definition ruby.h:90
#define RTEST
This is an old name of RB_TEST.
Ruby object's base components.
Definition rbasic.h:69
Type that defines a ractor-local storage.
Definition ractor.h:21
void(*) free(void *ptr)
A function to destruct a ractor-local storage.
Definition ractor.h:37
void(*) mark(void *ptr)
A function to mark a ractor-local storage.
Definition ractor.h:29
Definition st.h:79
void rb_native_mutex_lock(rb_nativethread_lock_t *lock)
Just another name of rb_nativethread_lock_lock.
void rb_native_mutex_unlock(rb_nativethread_lock_t *lock)
Just another name of rb_nativethread_lock_unlock.
void rb_native_mutex_destroy(rb_nativethread_lock_t *lock)
Just another name of rb_nativethread_lock_destroy.
void rb_native_cond_destroy(rb_nativethread_cond_t *cond)
Destroys the passed condition variable.
void rb_native_cond_signal(rb_nativethread_cond_t *cond)
Signals a condition variable.
uintptr_t ID
Type that represents a Ruby identifier such as a variable name.
Definition value.h:52
uintptr_t VALUE
Type that represents a Ruby object.
Definition value.h:40
@ RUBY_T_MASK
Bitmask of ruby_value_type.
Definition value_type.h:145