Ruby 4.1.0dev (2026-12-06 revision 6b501f5444cf675f4a654bda46c812e2c1df9fb8)
thread.c (6b501f5444cf675f4a654bda46c812e2c1df9fb8)
1/**********************************************************************
2
3 thread.c -
4
5 $Author$
6
7 Copyright (C) 2004-2007 Koichi Sasada
8
9**********************************************************************/
10
11/*
12 YARV Thread Design
13
14 model 1: Userlevel Thread
15 Same as traditional ruby thread.
16
17 model 2: Native Thread with Global VM lock
18 Using pthread (or Windows thread) and Ruby threads run concurrent.
19
20 model 3: Native Thread with fine grain lock
21 Using pthread and Ruby threads run concurrent or parallel.
22
23 model 4: M:N User:Native threads with Global VM lock
24 Combination of model 1 and 2
25
26 model 5: M:N User:Native thread with fine grain lock
27 Combination of model 1 and 3
28
29------------------------------------------------------------------------
30
31 model 2:
32 A thread has mutex (GVL: Global VM Lock or Giant VM Lock) can run.
33 When thread scheduling, running thread release GVL. If running thread
34 try blocking operation, this thread must release GVL and another
35 thread can continue this flow. After blocking operation, thread
36 must check interrupt (RUBY_VM_CHECK_INTS).
37
38 Every VM can run parallel.
39
40 Ruby threads are scheduled by OS thread scheduler.
41
42------------------------------------------------------------------------
43
44 model 3:
45 Every threads run concurrent or parallel and to access shared object
46 exclusive access control is needed. For example, to access String
47 object or Array object, fine grain lock must be locked every time.
48 */
49
50
51/*
52 * FD_SET, FD_CLR and FD_ISSET have a small sanity check when using glibc
53 * 2.15 or later and set _FORTIFY_SOURCE > 0.
54 * However, the implementation is wrong. Even though Linux's select(2)
55 * supports large fd size (>FD_SETSIZE), it wrongly assumes fd is always
56 * less than FD_SETSIZE (i.e. 1024). And then when enabling HAVE_RB_FD_INIT,
57 * it doesn't work correctly and makes program abort. Therefore we need to
58 * disable FORTIFY_SOURCE until glibc fixes it.
59 */
60#undef _FORTIFY_SOURCE
61#undef __USE_FORTIFY_LEVEL
62#define __USE_FORTIFY_LEVEL 0
63
64/* for model 2 */
65
66#include "ruby/internal/config.h"
67
68#ifdef __linux__
69// Normally, gcc(1) translates calls to alloca() with inlined code. This is not done when either the -ansi, -std=c89, -std=c99, or the -std=c11 option is given and the header <alloca.h> is not included.
70# include <alloca.h>
71#endif
72
73#define TH_SCHED(th) (&(th)->ractor->threads.sched)
74
75#include "eval_intern.h"
76#include "hrtime.h"
77#include "internal.h"
78#include "internal/class.h"
79#include "internal/cont.h"
80#include "internal/jit.h"
81#include "internal/coverage.h"
82#include "internal/error.h"
83#include "internal/eval.h"
84#include "internal/gc.h"
85#include "internal/hash.h"
86#include "internal/io.h"
87#include "internal/object.h"
88#include "internal/proc.h"
90#include "internal/scheduler.h"
91#include "internal/signal.h"
92#include "internal/thread.h"
93#include "internal/time.h"
94#include "internal/warnings.h"
95#include "iseq.h"
96#include "ruby/debug.h"
97#include "ruby/io.h"
98#include "ruby/thread.h"
99#include "ruby/thread_native.h"
100#include "timev.h"
101#include "vm_core.h"
102#include "ractor_core.h"
103#include "vm_debug.h"
104#include "vm_sync.h"
105#include "zjit.h"
106
107#include "ccan/list/list.h"
108
109#ifndef USE_NATIVE_THREAD_PRIORITY
110#define USE_NATIVE_THREAD_PRIORITY 0
111#define RUBY_THREAD_PRIORITY_MAX 3
112#define RUBY_THREAD_PRIORITY_MIN -3
113#endif
114
115static VALUE rb_cThreadShield;
116static VALUE cThGroup;
117
118static VALUE sym_immediate;
119static VALUE sym_on_blocking;
120static VALUE sym_never;
121
122static uint32_t thread_default_quantum_ms = 100;
123
124#define THREAD_LOCAL_STORAGE_INITIALISED FL_USER13
125#define THREAD_LOCAL_STORAGE_INITIALISED_P(th) RB_FL_TEST_RAW((th), THREAD_LOCAL_STORAGE_INITIALISED)
126
127static inline VALUE
128rb_thread_local_storage(VALUE thread)
129{
130 if (LIKELY(!THREAD_LOCAL_STORAGE_INITIALISED_P(thread))) {
131 rb_ivar_set(thread, idLocals, rb_hash_new());
132 RB_FL_SET_RAW(thread, THREAD_LOCAL_STORAGE_INITIALISED);
133 }
134 return rb_ivar_get(thread, idLocals);
135}
136
137enum SLEEP_FLAGS {
138 SLEEP_DEADLOCKABLE = 0x01,
139 SLEEP_SPURIOUS_CHECK = 0x02,
140 SLEEP_ALLOW_SPURIOUS = 0x04,
141 SLEEP_NO_CHECKINTS = 0x08,
142};
143
144static void sleep_forever(rb_thread_t *th, unsigned int fl);
145static int sleep_hrtime(rb_thread_t *, rb_hrtime_t, unsigned int fl);
146
147static void rb_thread_sleep_deadly_allow_spurious_wakeup(VALUE blocker, VALUE timeout, rb_hrtime_t end);
148static int rb_threadptr_dead(rb_thread_t *th);
149static void rb_check_deadlock(rb_ractor_t *r);
150static int rb_threadptr_pending_interrupt_empty_p(const rb_thread_t *th);
151static const char *thread_status_name(rb_thread_t *th, int detail);
152static int hrtime_update_expire(rb_hrtime_t *, const rb_hrtime_t);
153NORETURN(static void async_bug_fd(const char *mesg, int errno_arg, int fd));
154MAYBE_UNUSED(static int consume_communication_pipe(int fd));
155
156static rb_atomic_t system_working = 1;
157static rb_internal_thread_specific_key_t specific_key_count;
158
159/********************************************************************************/
160
161#define THREAD_SYSTEM_DEPENDENT_IMPLEMENTATION
162
164 enum rb_thread_status prev_status;
165};
166
167static int unblock_function_set(rb_thread_t *th, rb_unblock_function_t *func, void *arg, int flags);
168static void unblock_function_clear(rb_thread_t *th);
169
170static inline int blocking_region_begin(rb_thread_t *th, struct rb_blocking_region_buffer *region,
171 rb_unblock_function_t *ubf, void *arg, int flags);
172static inline void blocking_region_end(rb_thread_t *th, struct rb_blocking_region_buffer *region);
173
174#define THREAD_BLOCKING_BEGIN(th) do { \
175 struct rb_thread_sched * const sched = TH_SCHED(th); \
176 RB_VM_SAVE_MACHINE_CONTEXT(th); \
177 thread_sched_to_waiting((sched), (th), true);
178
179#define THREAD_BLOCKING_END(th) \
180 thread_sched_to_running((sched), (th)); \
181 rb_ractor_thread_switch(th->ractor, th, false); \
182} while(0)
183
184#ifdef __GNUC__
185#ifdef HAVE_BUILTIN___BUILTIN_CHOOSE_EXPR_CONSTANT_P
186#define only_if_constant(expr, notconst) __builtin_choose_expr(__builtin_constant_p(expr), (expr), (notconst))
187#else
188#define only_if_constant(expr, notconst) (__builtin_constant_p(expr) ? (expr) : (notconst))
189#endif
190#else
191#define only_if_constant(expr, notconst) notconst
192#endif
193#define RB_NOGVL_FAIL_FLAGS (RB_NOGVL_INTR_FAIL | RB_NOGVL_PENDING_INTR_FAIL)
194#define BLOCKING_REGION(th, exec, ubf, ubfarg, flags) do { \
195 struct rb_blocking_region_buffer __region; \
196 if (blocking_region_begin(th, &__region, (ubf), (ubfarg), flags) || \
197 /* always return true unless one of the fail flags is set */ \
198 !only_if_constant((flags) & RB_NOGVL_FAIL_FLAGS, TRUE)) { \
199 /* Important that this is inlined into the macro, and not part of \
200 * blocking_region_begin - see bug #20493 */ \
201 RB_VM_SAVE_MACHINE_CONTEXT(th); \
202 thread_sched_to_waiting(TH_SCHED(th), th, false); \
203 exec; \
204 blocking_region_end(th, &__region); \
205 }; \
206} while(0)
207
208/*
209 * returns true if this thread was spuriously interrupted, false otherwise
210 * (e.g. hit by Thread#run or ran a Ruby-level Signal.trap handler)
211 */
212#define RUBY_VM_CHECK_INTS_BLOCKING(ec) vm_check_ints_blocking(ec)
213static inline int
214vm_check_ints_blocking(rb_execution_context_t *ec)
215{
216#ifdef RUBY_ASSERT_CRITICAL_SECTION
217 VM_ASSERT(ec->assert_critical_section_entered == 0);
218#endif
219
220 rb_thread_t *th = rb_ec_thread_ptr(ec);
221
222 if (LIKELY(rb_threadptr_pending_interrupt_empty_p(th))) {
223 if (LIKELY(!RUBY_VM_INTERRUPTED_ANY(ec))) return FALSE;
224 }
225 else {
226 th->pending_interrupt_queue_checked = 0;
227 RUBY_VM_SET_INTERRUPT(ec);
228 }
229
230 int result = rb_threadptr_execute_interrupts(th, 1);
231
232 // When a signal is received, we yield to the scheduler as soon as possible:
233 if (result || RUBY_VM_INTERRUPTED(ec)) {
235 if (scheduler != Qnil) {
236 rb_fiber_scheduler_yield(scheduler);
237 }
238 }
239
240 return result;
241}
242
243int
244rb_vm_check_ints_blocking(rb_execution_context_t *ec)
245{
246 return vm_check_ints_blocking(ec);
247}
248
249/*
250 * poll() is supported by many OSes, but so far Linux is the only
251 * one we know of that supports using poll() in all places select()
252 * would work.
253 */
254#if defined(HAVE_POLL)
255# if defined(__linux__)
256# define USE_POLL
257# endif
258# if defined(__FreeBSD_version) && __FreeBSD_version >= 1100000
259# define USE_POLL
260 /* FreeBSD does not set POLLOUT when POLLHUP happens */
261# define POLLERR_SET (POLLHUP | POLLERR)
262# endif
263#endif
264
265static void
266timeout_prepare(rb_hrtime_t **to, rb_hrtime_t *rel, rb_hrtime_t *end,
267 const struct timeval *timeout)
268{
269 if (timeout) {
270 *rel = rb_timeval2hrtime(timeout);
271 *end = rb_hrtime_add(rb_hrtime_now(), *rel);
272 *to = rel;
273 }
274 else {
275 *to = 0;
276 }
277}
278
279MAYBE_UNUSED(NOINLINE(static int thread_start_func_2(rb_thread_t *th, VALUE *stack_start)));
280MAYBE_UNUSED(static bool th_has_dedicated_nt(const rb_thread_t *th));
281MAYBE_UNUSED(static int waitfd_to_waiting_flag(int wfd_event));
282
283#ifdef RB_THREAD_SCHED_NONE
284// The no-thread model is not a set of primitives under the common scheduler:
285// it replaces the scheduler with stubs, so it stands alone.
286# include THREAD_IMPL_SRC
287#else
288// The scheduler pulls in the platform implementation (THREAD_IMPL_SRC) itself:
289// the platform primitives come first, the scheduler is built on top of them.
290# include "thread_sched.c"
291#endif
292
293/*
294 * TODO: somebody with win32 knowledge should be able to get rid of
295 * timer-thread by busy-waiting on signals.
296 */
297#ifndef BUSY_WAIT_SIGNALS
298# define BUSY_WAIT_SIGNALS (0)
299#endif
300
301#ifndef USE_EVENTFD
302# define USE_EVENTFD (0)
303#endif
304
305#include "thread_sync.c"
306
307void
308rb_nativethread_lock_initialize(rb_nativethread_lock_t *lock)
309{
311}
312
313void
314rb_nativethread_lock_destroy(rb_nativethread_lock_t *lock)
315{
317}
318
319void
320rb_nativethread_lock_lock(rb_nativethread_lock_t *lock)
321{
323}
324
325void
326rb_nativethread_lock_unlock(rb_nativethread_lock_t *lock)
327{
329}
330
331static int
332unblock_function_set(rb_thread_t *th, rb_unblock_function_t *func, void *arg, int flags)
333{
334 do {
335 if (flags & RB_NOGVL_INTR_FAIL) {
336 if (RUBY_VM_INTERRUPTED_ANY(th->ec)) {
337 return FALSE;
338 }
339 }
340 else {
341 RUBY_VM_CHECK_INTS(th->ec);
342 }
343 if (flags & RB_NOGVL_PENDING_INTR_FAIL) {
344 if (!rb_threadptr_pending_interrupt_empty_p(th)) {
345 return FALSE;
346 }
347 }
348
349 rb_native_mutex_lock(&th->interrupt_lock);
350 } while (!th->ec->raised_flag && RUBY_VM_INTERRUPTED_ANY(th->ec) &&
351 (rb_native_mutex_unlock(&th->interrupt_lock), TRUE));
352
353 VM_ASSERT(th->unblock.func == NULL);
354
355 th->unblock.func = func;
356 th->unblock.arg = arg;
357 rb_native_mutex_unlock(&th->interrupt_lock);
358
359 return TRUE;
360}
361
362static void
363unblock_function_clear(rb_thread_t *th)
364{
365 rb_native_mutex_lock(&th->interrupt_lock);
366 th->unblock.func = 0;
367 rb_native_mutex_unlock(&th->interrupt_lock);
368}
369
370static void
371threadptr_set_interrupt_locked(rb_thread_t *th, bool trap)
372{
373 // th->interrupt_lock should be acquired here
374
375 RUBY_DEBUG_LOG("th:%u trap:%d", rb_th_serial(th), trap);
376
377 if (trap) {
378 RUBY_VM_SET_TRAP_INTERRUPT(th->ec);
379 }
380 else {
381 RUBY_VM_SET_INTERRUPT(th->ec);
382 }
383
384 if (th->unblock.func != NULL) {
385 (th->unblock.func)(th->unblock.arg);
386 }
387 else {
388 /* none */
389 }
390}
391
392static void
393threadptr_set_interrupt(rb_thread_t *th, int trap)
394{
395 rb_native_mutex_lock(&th->interrupt_lock);
396 {
397 threadptr_set_interrupt_locked(th, trap);
398 }
399 rb_native_mutex_unlock(&th->interrupt_lock);
400}
401
402/* Set interrupt flag on another thread or current thread, and call its UBF if it has one set */
403void
404rb_threadptr_interrupt(rb_thread_t *th)
405{
406 RUBY_DEBUG_LOG("th:%u", rb_th_serial(th));
407 threadptr_set_interrupt(th, false);
408}
409
410static void
411threadptr_trap_interrupt(rb_thread_t *th)
412{
413 threadptr_set_interrupt(th, true);
414}
415
416static void
417terminate_all(rb_ractor_t *r, const rb_thread_t *main_thread)
418{
419 rb_thread_t *th = 0;
420
421 ccan_list_for_each(&r->threads.set, th, lt_node) {
422 if (th != main_thread) {
423 RUBY_DEBUG_LOG("terminate start th:%u status:%s", rb_th_serial(th), thread_status_name(th, TRUE));
424
425 rb_threadptr_pending_interrupt_enque(th, RUBY_FATAL_THREAD_TERMINATED);
426 rb_threadptr_interrupt(th);
427
428 RUBY_DEBUG_LOG("terminate done th:%u status:%s", rb_th_serial(th), thread_status_name(th, TRUE));
429 }
430 else {
431 RUBY_DEBUG_LOG("main thread th:%u", rb_th_serial(th));
432 }
433 }
434}
435
436static void
437rb_threadptr_join_list_wakeup(rb_thread_t *thread)
438{
439 while (thread->join_list) {
440 struct rb_waiting_list *join_list = thread->join_list;
441
442 // Consume the entry from the join list:
443 thread->join_list = join_list->next;
444
445 rb_thread_t *target_thread = join_list->thread;
446
447 if (target_thread->scheduler != Qnil && join_list->fiber) {
448 rb_fiber_scheduler_unblock(target_thread->scheduler, target_thread->self, rb_fiberptr_self(join_list->fiber));
449 }
450 else {
451 rb_threadptr_interrupt(target_thread);
452
453 switch (target_thread->status) {
454 case THREAD_STOPPED:
455 case THREAD_STOPPED_FOREVER:
456 target_thread->status = THREAD_RUNNABLE;
457 break;
458 default:
459 break;
460 }
461 }
462 }
463}
464
465void
466rb_threadptr_unlock_all_locking_mutexes(rb_thread_t *th)
467{
468 while (th->keeping_mutexes) {
469 rb_mutex_t *mutex = th->keeping_mutexes;
470
471 // rb_mutex_unlock_th unlinks the mutex from th->keeping_mutexes and
472 // clears its next_mutex so a later owner doesn't inherit our list.
473 // rb_warn("mutex #<%p> was not unlocked by thread #<%p>", (void *)mutex, (void*)th);
474 VM_ASSERT(mutex->ec_serial);
475 const char *error_message = rb_mutex_unlock_th(mutex, th, 0);
476 if (error_message) rb_bug("invalid keeping_mutexes: %s", error_message);
477 }
478}
479
480void
481rb_thread_terminate_all(rb_thread_t *th)
482{
483 rb_ractor_t *cr = th->ractor;
484 rb_execution_context_t * volatile ec = th->ec;
485 volatile int sleeping = 0;
486
487 if (cr->threads.main != th) {
488 rb_bug("rb_thread_terminate_all: called by child thread (%p, %p)",
489 (void *)cr->threads.main, (void *)th);
490 }
491
492 /* unlock all locking mutexes */
493 rb_threadptr_unlock_all_locking_mutexes(th);
494
495 // tells the last sub-thread to wake this one out of the sleep below. Nothing
496 // clears it: no thread of this Ractor can run again once this returns.
497 cr->threads.terminating = true;
498
499 EC_PUSH_TAG(ec);
500 if (EC_EXEC_TAG() == TAG_NONE) {
501 retry:
502 RUBY_DEBUG_LOG("th:%u", rb_th_serial(th));
503
504 terminate_all(cr, th);
505
506 while (rb_ractor_living_thread_num(cr) > 1) {
507 rb_hrtime_t rel = RB_HRTIME_PER_SEC;
508 /*q
509 * Thread exiting routine in thread_start_func_2 notify
510 * me when the last sub-thread exit.
511 */
512 sleeping = 1;
513 native_sleep(th, &rel);
514 RUBY_VM_CHECK_INTS_BLOCKING(ec);
515 sleeping = 0;
516 }
517 }
518 else {
519 /*
520 * When caught an exception (e.g. Ctrl+C), let's broadcast
521 * kill request again to ensure killing all threads even
522 * if they are blocked on sleep, mutex, etc.
523 */
524 if (sleeping) {
525 sleeping = 0;
526 goto retry;
527 }
528 }
529 EC_POP_TAG();
530}
531
532void rb_threadptr_root_fiber_terminate(rb_thread_t *th);
533static void threadptr_interrupt_exec_cleanup(rb_thread_t *th);
534
535static void
536thread_cleanup_func_before_exec(void *th_ptr)
537{
538 rb_thread_t *th = th_ptr;
539 th->status = THREAD_KILLED;
540
541 // The thread stack doesn't exist in the forked process:
542 th->ec->machine.stack_start = th->ec->machine.stack_end = NULL;
543
544 threadptr_interrupt_exec_cleanup(th);
545 rb_threadptr_root_fiber_terminate(th);
546}
547
548static void
549thread_cleanup_func(void *th_ptr, int atfork)
550{
551 rb_thread_t *th = th_ptr;
552
553 th->locking_mutex = Qfalse;
554 thread_cleanup_func_before_exec(th_ptr);
555
556 if (atfork) {
557 native_thread_destroy_atfork(th->nt);
558 th->nt = NULL;
559 // The copied interrupt_lock may have been held at the moment of
560 // fork (interrupters run concurrently); reinitialize it so that
561 // thread_free's destroy is well-defined in the child.
562 rb_native_mutex_initialize(&th->interrupt_lock);
563 return;
564 }
565
566 // interrupt_lock is destroyed in thread_free: while th is in its
567 // Ractor's living set, anyone (terminate_all on the Ractor's main
568 // thread, Thread#kill/#raise) may lock it -- and the living set keeps
569 // the Thread object marked, so it cannot reach thread_free while
570 // listed. Destroying it anywhere during teardown leaves a window where
571 // a concurrent interrupter locks a destroyed mutex (EINVAL).
572}
573
574void
575rb_thread_free_native_thread(void *th_ptr)
576{
577 rb_thread_t *th = th_ptr;
578
579 // A thread with a coroutine context does not own its native thread: that
580 // one is in the shared pool, listed there and with its altstack registered
581 // on whichever pthread is running this. See rb_threadptr_sched_free().
582 if (th->sched.context == NULL) {
583 native_thread_destroy_atfork(th->nt);
584 }
585 th->nt = NULL;
586}
587
588static VALUE rb_threadptr_raise(rb_thread_t *, int, VALUE *);
589static VALUE rb_thread_to_s(VALUE thread);
590
591void
592ruby_thread_init_stack(rb_thread_t *th, void *local_in_parent_frame)
593{
594 native_thread_init_stack(th, local_in_parent_frame);
595}
596
597const VALUE *
598rb_vm_proc_local_ep(VALUE proc)
599{
600 const VALUE *ep = vm_proc_ep(proc);
601
602 if (ep) {
603 return rb_vm_ep_local_ep(ep);
604 }
605 else {
606 return NULL;
607 }
608}
609
610// for ractor, defined in vm.c
611VALUE rb_vm_invoke_proc_with_self(rb_execution_context_t *ec, rb_proc_t *proc, VALUE self,
612 int argc, const VALUE *argv, int kw_splat, VALUE passed_block_handler,
613 const rb_cref_t *cref);
614
615static VALUE
616thread_do_start_proc(rb_thread_t *th)
617{
618 VALUE args = th->invoke_arg.proc.args;
619 const VALUE *args_ptr;
620 int args_len;
621 VALUE procval = th->invoke_arg.proc.proc;
622 rb_proc_t *proc;
623 GetProcPtr(procval, proc);
624 const rb_cref_t *cref = rb_proc_refinements_cref_for_call(procval);
625
626 th->ec->errinfo = Qnil;
627 th->ec->root_lep = rb_vm_proc_local_ep(procval);
628 th->ec->root_svar = Qfalse;
629
630 vm_check_ints_blocking(th->ec);
631
632 if (th->invoke_type == thread_invoke_type_ractor_proc) {
633 VALUE self = rb_ractor_self(th->ractor);
634 th->thgroup = th->ractor->thgroup_default = rb_obj_alloc(cThGroup);
635
636 VM_ASSERT(FIXNUM_P(args));
637 args_len = FIX2INT(args);
638 args_ptr = ALLOCA_N(VALUE, args_len);
639 rb_ractor_receive_parameters(th->ec, th->ractor, args_len, (VALUE *)args_ptr);
640 vm_check_ints_blocking(th->ec);
641
642 return rb_vm_invoke_proc_with_self(
643 th->ec, proc, self,
644 args_len, args_ptr,
645 th->invoke_arg.proc.kw_splat,
646 VM_BLOCK_HANDLER_NONE,
647 cref
648 );
649 }
650 else {
651 args_len = RARRAY_LENINT(args);
652 if (args_len < 8) {
653 /* free proc.args if the length is enough small */
654 args_ptr = ALLOCA_N(VALUE, args_len);
655 MEMCPY((VALUE *)args_ptr, RARRAY_CONST_PTR(args), VALUE, args_len);
656 th->invoke_arg.proc.args = Qnil;
657 }
658 else {
659 args_ptr = RARRAY_CONST_PTR(args);
660 }
661
662 vm_check_ints_blocking(th->ec);
663
664 return rb_vm_invoke_proc(
665 th->ec, proc,
666 args_len, args_ptr,
667 th->invoke_arg.proc.kw_splat,
668 VM_BLOCK_HANDLER_NONE,
669 cref
670 );
671 }
672}
673
674static VALUE
675thread_do_start(rb_thread_t *th)
676{
677 native_set_thread_name(th);
678 VALUE result = Qundef;
679
680 switch (th->invoke_type) {
681 case thread_invoke_type_proc:
682 result = thread_do_start_proc(th);
683 break;
684
685 case thread_invoke_type_ractor_proc:
686 result = thread_do_start_proc(th);
687 rb_ractor_atexit(th->ec, result);
688 break;
689
690 case thread_invoke_type_func:
691 result = (*th->invoke_arg.func.func)(th->invoke_arg.func.arg);
692 break;
693
694 case thread_invoke_type_none:
695 rb_bug("unreachable");
696 }
697
698 return result;
699}
700
701void rb_ec_clear_current_thread_trace_func(const rb_execution_context_t *ec);
702
703static int
704thread_start_func_2(rb_thread_t *th, VALUE *stack_start)
705{
706 RUBY_DEBUG_LOG("th:%u", rb_th_serial(th));
707 VM_ASSERT(th != th->vm->ractor.main_thread);
708
709 enum ruby_tag_type state;
710 VALUE errinfo = Qnil;
711 rb_thread_t *ractor_main_th = th->ractor->threads.main;
712
713 // setup ractor
714 if (rb_ractor_status_p(th->ractor, ractor_blocking)) {
715 RB_VM_LOCK();
716 {
717 rb_vm_ractor_blocking_cnt_dec(th->vm, th->ractor, __FILE__, __LINE__);
718
719 /* Left 0 at creation (building them then would put them in the parent's
720 * objspace), so build them here out of objects this Ractor owns. The mask
721 * stack starts empty: inheriting it would reference the parent's
722 * unshareable mask Hash. */
723 th->pending_interrupt_queue = rb_ary_hidden_new(0);
724 th->pending_interrupt_mask_stack = rb_ary_hidden_new(0);
725 }
726 RB_VM_UNLOCK();
727 }
728
729 // Ensure that we are not joinable.
730 VM_ASSERT(UNDEF_P(th->value));
731
732 volatile int fiber_scheduler_closed = 0, event_thread_end_hooked = 0;
733 VALUE result = Qundef;
734
735 EC_PUSH_TAG(th->ec);
736
737 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
738 EXEC_EVENT_HOOK(th->ec, RUBY_EVENT_THREAD_BEGIN, th->self, 0, 0, 0, Qundef);
739
740 result = thread_do_start(th);
741 }
742
743 if (!fiber_scheduler_closed) {
744 fiber_scheduler_closed = 1;
746 }
747
748 if (!event_thread_end_hooked) {
749 event_thread_end_hooked = 1;
750 EXEC_EVENT_HOOK(th->ec, RUBY_EVENT_THREAD_END, th->self, 0, 0, 0, Qundef);
751 }
752
753 if (state == TAG_NONE) {
754 // This must be set AFTER doing all user-level code. At this point, the thread is effectively finished and calls to `Thread#join` will succeed.
755 th->value = result;
756 }
757 else {
758 errinfo = th->ec->errinfo;
759
760 VALUE exc = rb_vm_make_jump_tag_but_local_jump(state, Qundef);
761 if (!NIL_P(exc)) errinfo = exc;
762
763 if (state == TAG_FATAL) {
764 if (th->invoke_type == thread_invoke_type_ractor_proc) {
765 rb_ractor_atexit(th->ec, Qnil);
766 }
767 /* fatal error within this thread, need to stop whole script */
768 }
769 else if (rb_obj_is_kind_of(errinfo, rb_eSystemExit)) {
770 if (th->invoke_type == thread_invoke_type_ractor_proc) {
771 rb_ractor_atexit_exception(th->ec);
772 }
773
774 /* exit on main_thread. */
775 }
776 else {
777 if (th->report_on_exception) {
778 VALUE mesg = rb_thread_to_s(th->self);
779 rb_str_cat_cstr(mesg, " terminated with exception (report_on_exception is true):\n");
780 rb_write_error_str(mesg);
781 rb_ec_error_print(th->ec, errinfo);
782 }
783
784 if (th->invoke_type == thread_invoke_type_ractor_proc) {
785 rb_ractor_atexit_exception(th->ec);
786 }
787
788 if (th->vm->thread_abort_on_exception ||
789 th->abort_on_exception || RTEST(ruby_debug)) {
790 /* exit on main_thread */
791 }
792 else {
793 errinfo = Qnil;
794 }
795 }
796 th->value = Qnil;
797 }
798
799 // The thread is effectively finished and can be joined.
800 VM_ASSERT(!UNDEF_P(th->value));
801
802 rb_threadptr_join_list_wakeup(th);
803 rb_threadptr_unlock_all_locking_mutexes(th);
804
805 if (th->invoke_type == thread_invoke_type_ractor_proc) {
806 rb_thread_terminate_all(th);
807 rb_ractor_teardown(th->ec);
808 }
809
810 th->status = THREAD_KILLED;
811 RUBY_DEBUG_LOG("killed th:%u", rb_th_serial(th));
812
813 if (th->vm->ractor.main_thread == th) {
814 ruby_stop(0);
815 }
816
817 if (RB_TYPE_P(errinfo, T_OBJECT)) {
818 /* treat with normal error object */
819 rb_threadptr_raise(ractor_main_th, 1, &errinfo);
820 }
821
822 EC_POP_TAG();
823
824 rb_ec_clear_current_thread_trace_func(th->ec);
825
826 /* locking_mutex must be Qfalse */
827 if (th->locking_mutex != Qfalse) {
828 rb_bug("thread_start_func_2: locking_mutex must not be set (%p:%"PRIxVALUE")",
829 (void *)th, th->locking_mutex);
830 }
831
832 if (th->ractor->threads.terminating &&
833 th->ractor->threads.cnt <= 2 /* main thread and this thread */) {
834 /* I'm last thread. wake up main thread from rb_thread_terminate_all */
835 rb_threadptr_interrupt(ractor_main_th);
836 }
837
838 rb_check_deadlock(th->ractor);
839
840 rb_fiber_close(th->ec->fiber_ptr);
841
842 thread_cleanup_func(th, FALSE);
843 VM_ASSERT(th->ec->vm_stack == NULL);
844
845 // A dying Ractor collects its own objspace here, before the scheduler handoff
846 // below, and captures the structs it must free at its last step.
847 struct rb_ractor_postmortem_frees pf = { NULL, NULL };
848 if (th->invoke_type == thread_invoke_type_ractor_proc) {
849 rb_ractor_postmortem(th, &pf);
850 }
851
852#if defined(USE_MN_THREADS) && USE_MN_THREADS
853 if (th_has_coroutine(th)) {
854 // wait out any pending wake while th and its Ractor are still alive
855 rb_thread_wake_fence(th);
856
857 // Run the coroutine thread's epilogue here, while th is still valid;
858 // co_start then only makes the final transfer (see
859 // coroutine_thread_terminated in thread_sched_mn.c).
860 coroutine_thread_terminated(th);
861 rb_ractor_postmortem_free(&pf);
862 return 0;
863 }
864#endif
865
866 if (th->invoke_type == thread_invoke_type_ractor_proc) {
867 // The postmortem epilogue below runs after this Ractor is unlinked and no
868 // longer counted, with the GVL already released, and it frees through
869 // VM-global state (the jit_cont list and its mutex, the fiber pool, the
870 // main objspace's malloc accounting). Nothing else holds the main Ractor
871 // back at that point, so count it like a coroutine epilogue: then
872 // ruby_vm_destruct waits for it (rb_thread_sched_wait_winding) instead of
873 // tearing that state down underneath. th is freed by the epilogue, so
874 // keep the VM pointer.
875 rb_vm_t *const vm = th->vm;
876 rb_thread_sched_winding_begin(vm);
877
878 // after rb_ractor_living_threads_remove()
879 // GC will happen anytime and this ractor can be collected (and destroy GVL).
880 // So gvl_release() should be before it.
881 thread_sched_to_dead(TH_SCHED(th), th);
882 rb_ractor_living_threads_remove(th->ractor, th);
883 rb_ractor_postmortem_free(&pf);
884
885 rb_thread_sched_winding_end(vm);
886 }
887 else {
888 rb_ractor_living_threads_remove(th->ractor, th);
889 thread_sched_to_dead(TH_SCHED(th), th);
890 }
891
892 return 0;
893}
896 enum thread_invoke_type type;
897
898 // for normal proc thread
899 VALUE args;
900 VALUE proc;
901
902 // for ractor
903 rb_ractor_t *g;
904
905 // for func
906 VALUE (*fn)(void *);
907};
908
909static void thread_specific_storage_alloc(rb_thread_t *th);
910
911static VALUE
912thread_create_core(VALUE thval, struct thread_create_params *params)
913{
914 rb_execution_context_t *ec = GET_EC();
915 rb_thread_t *th = rb_thread_ptr(thval), *current_th = rb_ec_thread_ptr(ec);
916 int err;
917
918 thread_specific_storage_alloc(th);
919
920 if (OBJ_FROZEN(current_th->thgroup)) {
921 rb_raise(rb_eThreadError,
922 "can't start a new thread (frozen ThreadGroup)");
923 }
924
925 /* A new Ractor must not inherit the creating thread's fiber storage: its
926 * entries may be objects owned by the creating Ractor. Only threads created
927 * within the same Ractor inherit it. */
928 if (params->type != thread_invoke_type_ractor_proc) {
929 rb_fiber_inherit_storage(ec, th->ec->fiber_ptr);
930 }
931
932 switch (params->type) {
933 case thread_invoke_type_proc:
934 th->invoke_type = thread_invoke_type_proc;
935 th->invoke_arg.proc.args = params->args;
936 th->invoke_arg.proc.proc = params->proc;
937 th->invoke_arg.proc.kw_splat = rb_keyword_given_p();
938 break;
939
940 case thread_invoke_type_ractor_proc:
941 th->invoke_type = thread_invoke_type_ractor_proc;
942 th->ractor = params->g;
943 th->ec->ractor_id = rb_ractor_id(th->ractor);
944 th->ec->serial = th->ractor->next_ec_serial++;
945 th->ractor->threads.main = th;
946 th->invoke_arg.proc.proc = params->proc; // already a shareable copy (see ractor_create)
947 th->invoke_arg.proc.args = INT2FIX(RARRAY_LENINT(params->args));
948 th->invoke_arg.proc.kw_splat = rb_keyword_given_p();
949 break;
950
951 case thread_invoke_type_func:
952 th->invoke_type = thread_invoke_type_func;
953 th->invoke_arg.func.func = params->fn;
954 th->invoke_arg.func.arg = (void *)params->args;
955 break;
956
957 default:
958 rb_bug("unreachable");
959 }
960
961 th->priority = current_th->priority;
962 th->thgroup = current_th->thgroup;
963
964 if (th->invoke_type == thread_invoke_type_ractor_proc) {
965 /* Left 0: the child's main thread builds this in its own objspace at start
966 * (thread_start_func_2). Built here it would sit rootless in the parent's
967 * objspace, freed by the parent's local GC before the child starts. */
968 th->pending_interrupt_queue = 0;
969 th->pending_interrupt_mask_stack = 0;
970 th->pending_interrupt_queue_checked = 0;
971 /* Same for the thread group: the parent's lives in the parent's objspace, and
972 * keeping it would point the child's Thread wrapper at a foreign unshareable
973 * object with no shref. Left 0 until thread_do_start_proc builds it. */
974 th->thgroup = 0;
975 }
976 else {
977 th->pending_interrupt_queue = rb_ary_hidden_new(0);
978 th->pending_interrupt_queue_checked = 0;
979 th->pending_interrupt_mask_stack = rb_ary_dup(current_th->pending_interrupt_mask_stack);
980 RBASIC_CLEAR_CLASS(th->pending_interrupt_mask_stack);
981 }
982
983 RUBY_DEBUG_LOG("r:%"PRI_SERIALT_PREFIX"u th:%u", rb_ractor_id(th->ractor), rb_th_serial(th));
984
985 rb_ractor_living_threads_insert(th->ractor, th);
986
987 if (th->invoke_type == thread_invoke_type_ractor_proc) {
988 /* Create the default port and send the arguments only after the child joined
989 * vm->ractor.set, so a global GC in between still marks the port in its root
990 * scan. If either raises (an uncopyable argument, NoMemoryError), undo the
991 * membership: left in place it would make terminate_all wait forever. */
992 enum ruby_tag_type state;
993 EC_PUSH_TAG(ec);
994 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
995 rb_ractor_setup_default_port(params->g);
996 rb_ractor_send_parameters(ec, params->g, params->args);
997 }
998 EC_POP_TAG();
999 if (state != TAG_NONE) {
1000 th->status = THREAD_KILLED;
1001 rb_ractor_cancel_creation(params->g, th);
1002 EC_JUMP_TAG(ec, state);
1003 }
1004 }
1005
1006 /* kick thread */
1007 err = native_thread_create(th);
1008 if (err) {
1009 th->status = THREAD_KILLED;
1010 if (th->invoke_type == thread_invoke_type_ractor_proc) {
1011 /* A child Ractor's main thread: the creator runs this, so the ordinary
1012 * removal (which assumes the current Ractor and would run the Ractor exit
1013 * protocol) does not apply. Undo the creation like the send-failure path. */
1014 rb_ractor_cancel_creation(th->ractor, th);
1015 }
1016 else {
1017 rb_ractor_living_threads_remove(th->ractor, th);
1018 }
1019 rb_raise(rb_eThreadError, "can't create Thread: %s", strerror(err));
1020 }
1021 return thval;
1022}
1023
1024#define threadptr_initialized(th) ((th)->invoke_type != thread_invoke_type_none)
1025
1026/*
1027 * call-seq:
1028 * Thread.new { ... } -> thread
1029 * Thread.new(*args, &proc) -> thread
1030 * Thread.new(*args) { |args| ... } -> thread
1031 *
1032 * Creates a new thread executing the given block.
1033 *
1034 * Any +args+ given to ::new will be passed to the block:
1035 *
1036 * arr = []
1037 * a, b, c = 1, 2, 3
1038 * Thread.new(a,b,c) { |d,e,f| arr << d << e << f }.join
1039 * arr #=> [1, 2, 3]
1040 *
1041 * A ThreadError exception is raised if ::new is called without a block.
1042 *
1043 * If you're going to subclass Thread, be sure to call super in your
1044 * +initialize+ method, otherwise a ThreadError will be raised.
1045 */
1046static VALUE
1047thread_s_new(int argc, VALUE *argv, VALUE klass)
1048{
1049 rb_thread_t *th;
1050 VALUE thread = rb_thread_alloc(klass);
1051
1052 if (GET_RACTOR()->threads.main->status == THREAD_KILLED) {
1053 rb_raise(rb_eThreadError, "can't alloc thread");
1054 }
1055
1056 rb_obj_call_init_kw(thread, argc, argv, RB_PASS_CALLED_KEYWORDS);
1057 th = rb_thread_ptr(thread);
1058 if (!threadptr_initialized(th)) {
1059 rb_raise(rb_eThreadError, "uninitialized thread - check '%"PRIsVALUE"#initialize'",
1060 klass);
1061 }
1062 return thread;
1063}
1064
1065/*
1066 * call-seq:
1067 * Thread.start([args]*) {|args| block } -> thread
1068 * Thread.fork([args]*) {|args| block } -> thread
1069 *
1070 * Basically the same as ::new. However, if class Thread is subclassed, then
1071 * calling +start+ in that subclass will not invoke the subclass's
1072 * +initialize+ method.
1073 */
1074
1075static VALUE
1076thread_start(VALUE klass, VALUE args)
1077{
1078 struct thread_create_params params = {
1079 .type = thread_invoke_type_proc,
1080 .args = args,
1081 .proc = rb_block_proc(),
1082 };
1083 return thread_create_core(rb_thread_alloc(klass), &params);
1084}
1085
1086static VALUE
1087threadptr_invoke_proc_location(rb_thread_t *th)
1088{
1089 if (th->invoke_type == thread_invoke_type_proc) {
1090 return rb_proc_location(th->invoke_arg.proc.proc);
1091 }
1092 else {
1093 return Qnil;
1094 }
1095}
1096
1097/* :nodoc: */
1098static VALUE
1099thread_initialize(VALUE thread, VALUE args)
1100{
1101 rb_thread_t *th = rb_thread_ptr(thread);
1102
1103 if (!rb_block_given_p()) {
1104 rb_raise(rb_eThreadError, "must be called with a block");
1105 }
1106 else if (th->invoke_type != thread_invoke_type_none) {
1107 VALUE loc = threadptr_invoke_proc_location(th);
1108 if (!NIL_P(loc)) {
1109 rb_raise(rb_eThreadError,
1110 "already initialized thread - %"PRIsVALUE":%"PRIsVALUE,
1111 RARRAY_AREF(loc, 0), RARRAY_AREF(loc, 1));
1112 }
1113 else {
1114 rb_raise(rb_eThreadError, "already initialized thread");
1115 }
1116 }
1117 else {
1118 struct thread_create_params params = {
1119 .type = thread_invoke_type_proc,
1120 .args = args,
1121 .proc = rb_block_proc(),
1122 };
1123 return thread_create_core(thread, &params);
1124 }
1125}
1126
1128rb_thread_create(VALUE (*fn)(void *), void *arg)
1129{
1130 struct thread_create_params params = {
1131 .type = thread_invoke_type_func,
1132 .fn = fn,
1133 .args = (VALUE)arg,
1134 };
1135 return thread_create_core(rb_thread_alloc(rb_cThread), &params);
1136}
1137
1138static VALUE
1139create_ractor_alloc_thread(rb_ractor_t *r, rb_ractor_t *cr, rb_execution_context_t *ec)
1140{
1141 /* Build the child's main Thread and root Fiber wrappers in the child's objspace,
1142 * so the thread is made of objects it owns. Hand that objspace down rather than
1143 * pointing cr->objspace at it: threads holding no GVL read that slot to charge
1144 * their frees, and one of them must never be sent to a heap a stillborn child is
1145 * about to free.
1146 *
1147 * The child's objspace is not in vm->ractor.set yet, so cover it through its
1148 * creator before the first allocation and keep the cover until vm_insert_ractor
1149 * clears it under the VM lock. One slot suffices: one Ractor creates children
1150 * serially. */
1151 void *const child_objspace = r->objspace;
1152 volatile VALUE thval = Qundef;
1153 const bool multi_objspace = rb_gc_multi_objspace_p();
1154 enum ruby_tag_type alloc_state = TAG_NONE;
1155 RB_VM_LOCKING() {
1156 if (multi_objspace) {
1157 RUBY_ASSERT(cr->creating_child_objspace == NULL);
1158 cr->creating_child_objspace = child_objspace;
1159 }
1160 /* Suppress the child's GC, not the creator's: a cycle here would collect a
1161 * half-built child. Single allocations; this costs only a little growth. */
1162 VALUE gc_was_disabled = rb_gc_objspace_disable_no_rest(child_objspace);
1163 /* The alloc can raise NoMemoryError; a longjmp here would skip the unlock of
1164 * RB_VM_LOCKING, so catch and rethrow outside. */
1165 EC_PUSH_TAG(ec);
1166 if ((alloc_state = EC_EXEC_TAG()) == TAG_NONE) {
1167 thval = rb_thread_alloc_in_objspace(rb_cThread, child_objspace);
1168 }
1169 EC_POP_TAG();
1170 if (gc_was_disabled == Qfalse) rb_gc_objspace_enable(child_objspace);
1171 if (alloc_state != TAG_NONE) {
1172 /* Drop the cover and park the objspace in this same section: between two of
1173 * them another Ractor's global GC would find a populated objspace that is
1174 * neither covered nor a zombie. */
1175 if (multi_objspace) cr->creating_child_objspace = NULL;
1176 if (r->objspace) {
1177 rb_gc_objspace_disown(r->objspace);
1178 r->objspace = NULL;
1179 }
1180 }
1181 }
1182 if (alloc_state != TAG_NONE) EC_JUMP_TAG(ec, alloc_state);
1183 return thval;
1184}
1185
1186VALUE
1187rb_thread_create_ractor(rb_ractor_t *r, VALUE args, VALUE proc)
1188{
1189 struct thread_create_params params = {
1190 .type = thread_invoke_type_ractor_proc,
1191 .g = r,
1192 .args = args,
1193 .proc = proc,
1194 };
1195
1196 rb_ractor_t *cr = GET_RACTOR();
1197 rb_execution_context_t *ec = GET_EC();
1198
1199 VALUE thval = create_ractor_alloc_thread(r, cr, ec);
1200
1201 /* Creation can still fail before vm_insert_ractor (NoMemoryError, say), and a
1202 * left-over cover would enumerate the dead child's objspace twice and dangle after
1203 * the merge: on failure hand the objspace to zombie_objspaces under the VM lock,
1204 * drop the cover, NULL r->objspace. */
1205 enum ruby_tag_type state;
1206 VALUE thret = Qundef;
1207 EC_PUSH_TAG(ec);
1208 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
1209 thret = thread_create_core(thval, &params);
1210 }
1211 EC_POP_TAG();
1212 if (state != TAG_NONE) {
1213 RB_VM_LOCKING() {
1214 if (cr->creating_child_objspace == r->objspace) {
1215 cr->creating_child_objspace = NULL;
1216 }
1217 if (r->objspace) {
1218 rb_gc_objspace_disown(r->objspace);
1219 r->objspace = NULL;
1220 }
1221 }
1222 EC_JUMP_TAG(ec, state);
1223 }
1224 return thret;
1225}
1226
1228struct join_arg {
1229 struct rb_waiting_list *waiter;
1230 rb_thread_t *target;
1231 VALUE timeout;
1232 rb_hrtime_t *limit;
1233};
1234
1235static VALUE
1236remove_from_join_list(VALUE arg)
1237{
1238 struct join_arg *p = (struct join_arg *)arg;
1239 rb_thread_t *target_thread = p->target;
1240
1241 if (target_thread->status != THREAD_KILLED) {
1242 struct rb_waiting_list **join_list = &target_thread->join_list;
1243
1244 while (*join_list) {
1245 if (*join_list == p->waiter) {
1246 *join_list = (*join_list)->next;
1247 break;
1248 }
1249
1250 join_list = &(*join_list)->next;
1251 }
1252 }
1253
1254 return Qnil;
1255}
1256
1257static int
1258thread_finished(rb_thread_t *th)
1259{
1260 return th->status == THREAD_KILLED || !UNDEF_P(th->value);
1261}
1262
1263static VALUE
1264thread_join_sleep(VALUE arg)
1265{
1266 struct join_arg *p = (struct join_arg *)arg;
1267 rb_thread_t *target_th = p->target, *th = p->waiter->thread;
1268 rb_hrtime_t end = 0, *limit = p->limit;
1269
1270 if (limit) {
1271 end = rb_hrtime_add(*limit, rb_hrtime_now());
1272 }
1273
1274 while (!thread_finished(target_th)) {
1276
1277 if (!limit) {
1278 if (scheduler != Qnil) {
1279 rb_fiber_scheduler_block(scheduler, target_th->self, Qnil);
1280 }
1281 else {
1282 sleep_forever(th, SLEEP_DEADLOCKABLE | SLEEP_ALLOW_SPURIOUS | SLEEP_NO_CHECKINTS);
1283 }
1284 }
1285 else {
1286 if (hrtime_update_expire(limit, end)) {
1287 RUBY_DEBUG_LOG("timeout target_th:%u", rb_th_serial(target_th));
1288 return Qfalse;
1289 }
1290
1291 if (scheduler != Qnil) {
1292 VALUE timeout = rb_float_new(hrtime2double(*limit));
1293 rb_fiber_scheduler_block(scheduler, target_th->self, timeout);
1294 }
1295 else {
1296 th->status = THREAD_STOPPED;
1297 native_sleep(th, limit);
1298 }
1299 }
1300 RUBY_VM_CHECK_INTS_BLOCKING(th->ec);
1301 th->status = THREAD_RUNNABLE;
1302
1303 RUBY_DEBUG_LOG("interrupted target_th:%u status:%s", rb_th_serial(target_th), thread_status_name(target_th, TRUE));
1304 }
1305
1306 return Qtrue;
1307}
1308
1309static VALUE
1310thread_join(rb_thread_t *target_th, VALUE timeout, rb_hrtime_t *limit)
1311{
1312 rb_execution_context_t *ec = GET_EC();
1313 rb_thread_t *th = ec->thread_ptr;
1314 rb_fiber_t *fiber = ec->fiber_ptr;
1315
1316 if (th == target_th) {
1317 rb_raise(rb_eThreadError, "Target thread must not be current thread");
1318 }
1319
1320 if (th->ractor->threads.main == target_th) {
1321 rb_raise(rb_eThreadError, "Target thread must not be main thread");
1322 }
1323
1324 RUBY_DEBUG_LOG("target_th:%u status:%s", rb_th_serial(target_th), thread_status_name(target_th, TRUE));
1325
1326 if (target_th->status != THREAD_KILLED) {
1327 struct rb_waiting_list waiter;
1328 waiter.next = target_th->join_list;
1329 waiter.thread = th;
1330 waiter.fiber = rb_fiberptr_blocking(fiber) ? NULL : fiber;
1331 target_th->join_list = &waiter;
1332
1333 struct join_arg arg;
1334 arg.waiter = &waiter;
1335 arg.target = target_th;
1336 arg.timeout = timeout;
1337 arg.limit = limit;
1338
1339 if (!rb_ensure(thread_join_sleep, (VALUE)&arg, remove_from_join_list, (VALUE)&arg)) {
1340 return Qnil;
1341 }
1342 }
1343
1344 RUBY_DEBUG_LOG("success target_th:%u status:%s", rb_th_serial(target_th), thread_status_name(target_th, TRUE));
1345
1346 if (target_th->ec->errinfo != Qnil) {
1347 VALUE err = target_th->ec->errinfo;
1348
1349 if (FIXNUM_P(err)) {
1350 switch (err) {
1351 case INT2FIX(TAG_FATAL):
1352 RUBY_DEBUG_LOG("terminated target_th:%u status:%s", rb_th_serial(target_th), thread_status_name(target_th, TRUE));
1353
1354 /* OK. killed. */
1355 break;
1356 default:
1357 if (err == RUBY_FATAL_FIBER_KILLED) { // not integer constant so can't be a case expression
1358 // root fiber killed in non-main thread
1359 break;
1360 }
1361 rb_bug("thread_join: Fixnum (%d) should not reach here.", FIX2INT(err));
1362 }
1363 }
1364 else if (THROW_DATA_P(target_th->ec->errinfo)) {
1365 rb_bug("thread_join: THROW_DATA should not reach here.");
1366 }
1367 else {
1368 /* normal exception */
1369 rb_exc_raise(err);
1370 }
1371 }
1372 return target_th->self;
1373}
1374
1375/*
1376 * call-seq:
1377 * thr.join -> thr
1378 * thr.join(limit) -> thr
1379 *
1380 * The calling thread will suspend execution and run this +thr+.
1381 *
1382 * Does not return until +thr+ exits or until the given +limit+ seconds have
1383 * passed.
1384 *
1385 * If the time limit expires, +nil+ will be returned, otherwise +thr+ is
1386 * returned.
1387 *
1388 * Any threads not joined will be killed when the main program exits.
1389 *
1390 * If +thr+ had previously raised an exception and the ::abort_on_exception or
1391 * $DEBUG flags are not set, (so the exception has not yet been processed), it
1392 * will be processed at this time.
1393 *
1394 * a = Thread.new { print "a"; sleep(10); print "b"; print "c" }
1395 * x = Thread.new { print "x"; Thread.pass; print "y"; print "z" }
1396 * x.join # Let thread x finish, thread a will be killed on exit.
1397 * #=> "axyz"
1398 *
1399 * The following example illustrates the +limit+ parameter.
1400 *
1401 * y = Thread.new { 4.times { sleep 0.1; puts 'tick... ' }}
1402 * puts "Waiting" until y.join(0.15)
1403 *
1404 * This will produce:
1405 *
1406 * tick...
1407 * Waiting
1408 * tick...
1409 * Waiting
1410 * tick...
1411 * tick...
1412 */
1413
1414static VALUE
1415thread_join_m(int argc, VALUE *argv, VALUE self)
1416{
1417 VALUE timeout = Qnil;
1418 rb_hrtime_t rel = 0, *limit = 0;
1419
1420 if (rb_check_arity(argc, 0, 1)) {
1421 timeout = argv[0];
1422 }
1423
1424 // Convert the timeout eagerly, so it's always converted and deterministic
1425 /*
1426 * This supports INFINITY and negative values, so we can't use
1427 * rb_time_interval right now...
1428 */
1429 if (NIL_P(timeout)) {
1430 /* unlimited */
1431 }
1432 else if (FIXNUM_P(timeout)) {
1433 rel = rb_sec2hrtime(NUM2TIMET(timeout));
1434 limit = &rel;
1435 }
1436 else {
1437 limit = double2hrtime(&rel, rb_num2dbl(timeout));
1438 }
1439
1440 return thread_join(rb_thread_ptr(self), timeout, limit);
1441}
1442
1443/*
1444 * call-seq:
1445 * thr.value -> obj
1446 *
1447 * Waits for +thr+ to complete, using #join, and returns its value or raises
1448 * the exception which terminated the thread.
1449 *
1450 * a = Thread.new { 2 + 2 }
1451 * a.value #=> 4
1452 *
1453 * b = Thread.new { raise 'something went wrong' }
1454 * b.value #=> RuntimeError: something went wrong
1455 */
1456
1457static VALUE
1458thread_value(VALUE self)
1459{
1460 rb_thread_t *th = rb_thread_ptr(self);
1461 thread_join(th, Qnil, 0);
1462 if (UNDEF_P(th->value)) {
1463 // If the thread is dead because we forked th->value is still Qundef.
1464 return Qnil;
1465 }
1466 return th->value;
1467}
1468
1469/*
1470 * Thread Scheduling
1471 */
1472
1473static void
1474getclockofday(struct timespec *ts)
1475{
1476#if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC)
1477 if (clock_gettime(CLOCK_MONOTONIC, ts) == 0)
1478 return;
1479#endif
1480 rb_timespec_now(ts);
1481}
1482
1483/*
1484 * Don't inline this, since library call is already time consuming
1485 * and we don't want "struct timespec" on stack too long for GC
1486 */
1487NOINLINE(rb_hrtime_t rb_hrtime_now(void));
1488rb_hrtime_t
1489rb_hrtime_now(void)
1490{
1491 struct timespec ts;
1492
1493 getclockofday(&ts);
1494 return rb_timespec2hrtime(&ts);
1495}
1496
1497/*
1498 * at least gcc 7.2 and 7.3 complains about "rb_hrtime_t end"
1499 * being uninitialized, maybe other versions, too.
1500 */
1501COMPILER_WARNING_PUSH
1502#if defined(__GNUC__) && __GNUC__ == 7 && __GNUC_MINOR__ <= 3
1503COMPILER_WARNING_IGNORED(-Wmaybe-uninitialized)
1504#endif
1505#ifndef PRIu64
1506#define PRIu64 PRI_64_PREFIX "u"
1507#endif
1508/*
1509 * @end is the absolute time when @ts is set to expire
1510 * Returns true if @end has past
1511 * Updates @ts and returns false otherwise
1512 */
1513static int
1514hrtime_update_expire(rb_hrtime_t *timeout, const rb_hrtime_t end)
1515{
1516 rb_hrtime_t now = rb_hrtime_now();
1517
1518 if (now > end) return 1;
1519
1520 RUBY_DEBUG_LOG("%"PRIu64" > %"PRIu64"", (uint64_t)end, (uint64_t)now);
1521
1522 *timeout = end - now;
1523 return 0;
1524}
1525COMPILER_WARNING_POP
1526
1527static int sleep_hrtime_until(rb_thread_t *th, rb_hrtime_t end, unsigned int fl);
1528
1529static int
1530sleep_hrtime(rb_thread_t *th, rb_hrtime_t rel, unsigned int fl)
1531{
1532 return sleep_hrtime_until(th, rb_hrtime_add(rb_hrtime_now(), rel), fl);
1533}
1534
1535static int
1536sleep_hrtime_until(rb_thread_t *th, rb_hrtime_t end, unsigned int fl)
1537{
1538 enum rb_thread_status prev_status = th->status;
1539 int woke;
1540 rb_hrtime_t rel = rb_hrtime_sub(end, rb_hrtime_now());
1541
1542 th->status = THREAD_STOPPED;
1543 RUBY_VM_CHECK_INTS_BLOCKING(th->ec);
1544 while (th->status == THREAD_STOPPED) {
1545 native_sleep(th, &rel);
1546 woke = vm_check_ints_blocking(th->ec);
1547 if (woke && !(fl & SLEEP_SPURIOUS_CHECK))
1548 break;
1549 if (hrtime_update_expire(&rel, end))
1550 break;
1551 woke = 1;
1552 }
1553 th->status = prev_status;
1554 return woke;
1555}
1556
1557static void
1558sleep_forever(rb_thread_t *th, unsigned int fl)
1559{
1560 enum rb_thread_status prev_status = th->status;
1561 enum rb_thread_status status;
1562 int woke;
1563
1564 status = fl & SLEEP_DEADLOCKABLE ? THREAD_STOPPED_FOREVER : THREAD_STOPPED;
1565 th->status = status;
1566
1567 if (!(fl & SLEEP_NO_CHECKINTS)) RUBY_VM_CHECK_INTS_BLOCKING(th->ec);
1568
1569 while (th->status == status) {
1570 if (fl & SLEEP_DEADLOCKABLE) {
1571 rb_ractor_sleeper_threads_inc(th->ractor);
1572 rb_check_deadlock(th->ractor);
1573 }
1574 {
1575 native_sleep(th, 0);
1576 }
1577 if (fl & SLEEP_DEADLOCKABLE) {
1578 rb_ractor_sleeper_threads_dec(th->ractor);
1579 }
1580 if (fl & SLEEP_ALLOW_SPURIOUS) {
1581 break;
1582 }
1583
1584 woke = vm_check_ints_blocking(th->ec);
1585
1586 if (woke && !(fl & SLEEP_SPURIOUS_CHECK)) {
1587 break;
1588 }
1589 }
1590 th->status = prev_status;
1591}
1592
1593void
1595{
1596 RUBY_DEBUG_LOG("forever");
1597 sleep_forever(GET_THREAD(), SLEEP_SPURIOUS_CHECK);
1598}
1599
1600void
1602{
1603 RUBY_DEBUG_LOG("deadly");
1604 sleep_forever(GET_THREAD(), SLEEP_DEADLOCKABLE|SLEEP_SPURIOUS_CHECK);
1605}
1606
1607static void
1608rb_thread_sleep_deadly_allow_spurious_wakeup(VALUE blocker, VALUE timeout, rb_hrtime_t end)
1609{
1610 rb_thread_t *th = GET_THREAD();
1612 if (scheduler != Qnil) {
1613 rb_fiber_scheduler_block(scheduler, blocker, timeout);
1614 }
1615 else {
1616 RUBY_DEBUG_LOG("...");
1617 if (end) {
1618 sleep_hrtime_until(th, end, SLEEP_SPURIOUS_CHECK);
1619 }
1620 else {
1621 sleep_forever(th, SLEEP_DEADLOCKABLE);
1622 }
1623 }
1624}
1625
1626void
1627rb_thread_wait_for(struct timeval time)
1628{
1629 rb_thread_t *th = GET_THREAD();
1630
1631 sleep_hrtime(th, rb_timeval2hrtime(&time), SLEEP_SPURIOUS_CHECK);
1632}
1633
1634void
1635rb_ec_check_ints(rb_execution_context_t *ec)
1636{
1637 RUBY_VM_CHECK_INTS_BLOCKING(ec);
1638}
1639
1640/*
1641 * CAUTION: This function causes thread switching.
1642 * rb_thread_check_ints() check ruby's interrupts.
1643 * some interrupt needs thread switching/invoke handlers,
1644 * and so on.
1645 */
1646
1647void
1649{
1650 rb_ec_check_ints(GET_EC());
1651}
1652
1653/*
1654 * Hidden API for tcl/tk wrapper.
1655 * There is no guarantee to perpetuate it.
1656 */
1657int
1658rb_thread_check_trap_pending(void)
1659{
1660 return rb_signal_buff_size() != 0;
1661}
1662
1663/* This function can be called in blocking region. */
1666{
1667 return (int)RUBY_VM_INTERRUPTED(rb_thread_ptr(thval)->ec);
1668}
1669
1670void
1671rb_thread_sleep(int sec)
1672{
1674}
1675
1676static void
1677rb_thread_schedule_limits(uint32_t limits_us)
1678{
1679 if (!rb_thread_alone()) {
1680 rb_thread_t *th = GET_THREAD();
1681 RUBY_DEBUG_LOG("us:%u", (unsigned int)limits_us);
1682
1683 if (th->running_time_us >= limits_us) {
1684 RUBY_DEBUG_LOG("switch %s", "start");
1685
1686 RB_VM_SAVE_MACHINE_CONTEXT(th);
1687 thread_sched_yield(TH_SCHED(th), th);
1688 rb_ractor_thread_switch(th->ractor, th, true);
1689
1690 RUBY_DEBUG_LOG("switch %s", "done");
1691 }
1692 }
1693}
1694
1695void
1697{
1698 rb_thread_schedule_limits(0);
1699 RUBY_VM_CHECK_INTS(GET_EC());
1700}
1701
1702/* blocking region */
1703
1704static inline int
1705blocking_region_begin(rb_thread_t *th, struct rb_blocking_region_buffer *region,
1706 rb_unblock_function_t *ubf, void *arg, int flags)
1707{
1708#ifdef RUBY_ASSERT_CRITICAL_SECTION
1709 VM_ASSERT(th->ec->assert_critical_section_entered == 0);
1710#endif
1711 VM_ASSERT(th == GET_THREAD());
1712
1713 region->prev_status = th->status;
1714 if (unblock_function_set(th, ubf, arg, flags)) {
1715 th->blocking_region_buffer = region;
1716 th->status = THREAD_STOPPED;
1717 rb_ractor_blocking_threads_inc(th->ractor, __FILE__, __LINE__);
1718
1719 RUBY_DEBUG_LOG("thread_id:%p", (void *)th->nt->thread_id);
1720 return TRUE;
1721 }
1722 else {
1723 return FALSE;
1724 }
1725}
1726
1727static inline void
1728blocking_region_end(rb_thread_t *th, struct rb_blocking_region_buffer *region)
1729{
1730 /* entry to ubf_list still permitted at this point, make it impossible: */
1731 unblock_function_clear(th);
1732 /* entry to ubf_list impossible at this point, so unregister is safe: */
1733 unregister_ubf_list(th);
1734
1735 thread_sched_to_running(TH_SCHED(th), th);
1736 rb_ractor_thread_switch(th->ractor, th, false);
1737
1738 th->blocking_region_buffer = 0;
1739 rb_ractor_blocking_threads_dec(th->ractor, __FILE__, __LINE__);
1740 if (th->status == THREAD_STOPPED) {
1741 th->status = region->prev_status;
1742 }
1743
1744 RUBY_DEBUG_LOG("end");
1745
1746#ifndef _WIN32
1747 // GET_THREAD() clears WSAGetLastError()
1748 VM_ASSERT(th == GET_THREAD());
1749#endif
1750}
1751
1752/*
1753 * Resolve sentinel unblock function values to their actual function pointers
1754 * and appropriate data2 values. This centralizes the logic for handling
1755 * RUBY_UBF_IO and RUBY_UBF_PROCESS sentinel values.
1756 *
1757 * @param unblock_function Pointer to unblock function pointer (modified in place)
1758 * @param data2 Pointer to data2 pointer (modified in place)
1759 * @param thread Thread context for resolving data2 when needed
1760 * @return true if sentinel values were resolved, false otherwise
1761 */
1762bool
1763rb_thread_resolve_unblock_function(rb_unblock_function_t **unblock_function, void **data2, struct rb_thread_struct *thread)
1764{
1765 rb_unblock_function_t *ubf = *unblock_function;
1766
1767 if ((ubf == RUBY_UBF_IO) || (ubf == RUBY_UBF_PROCESS)) {
1768 *unblock_function = ubf_select;
1769 *data2 = thread;
1770 return true;
1771 }
1772 return false;
1773}
1774
1775void *
1776rb_nogvl(void *(*func)(void *), void *data1,
1777 rb_unblock_function_t *ubf, void *data2,
1778 int flags)
1779{
1780 rb_execution_context_t *ec = GET_EC();
1781 rb_thread_t *th = rb_ec_thread_ptr(ec);
1782
1783 if (
1784 (flags & RB_NOGVL_PENDING_INTR_FAIL) &&
1785 !rb_threadptr_pending_interrupt_empty_p(th)
1786 ) {
1787 /* Match the in-region skip path, which leaves errno at saved_errno (0)
1788 * because the function was never called. */
1789 rb_errno_set(0);
1790 return 0;
1791 }
1792
1793 if (flags & RB_NOGVL_OFFLOAD_SAFE) {
1794 VALUE scheduler = rb_fiber_scheduler_current();
1795 if (scheduler != Qnil) {
1797
1798 VALUE result = rb_fiber_scheduler_blocking_operation_wait(scheduler, func, data1, ubf, data2, flags, &state);
1799
1800 if (!UNDEF_P(result)) {
1801 rb_errno_set(state.saved_errno);
1802 return state.result;
1803 }
1804 }
1805 }
1806
1807 void *val = 0;
1808 rb_vm_t *vm = rb_ec_vm_ptr(ec);
1809 bool is_main_thread = vm->ractor.main_thread == th;
1810 int saved_errno = 0;
1811
1812 bool sentinel_ubf = rb_thread_resolve_unblock_function(&ubf, &data2, th);
1813
1814 if (ubf && rb_ractor_living_thread_num(th->ractor) == 1 && is_main_thread) {
1815 // ubf_select, which the sentinel ubfs resolve to, takes ubf_list_lock
1816 // and the ractor scheduler lock: not async-signal-safe, whatever the
1817 // caller claims.
1818 if ((flags & RB_NOGVL_UBF_ASYNC_SAFE) && !sentinel_ubf) {
1819 vm->ubf_async_safe = 1;
1820 }
1821 }
1822
1823 rb_vm_t *volatile saved_vm = vm;
1824 BLOCKING_REGION(th, {
1825 val = func(data1);
1826 saved_errno = rb_errno();
1827 }, ubf, data2, flags);
1828 vm = saved_vm;
1829
1830 if (is_main_thread) vm->ubf_async_safe = 0;
1831
1832 if ((flags & RB_NOGVL_INTR_FAIL) == 0) {
1833 RUBY_VM_CHECK_INTS_BLOCKING(ec);
1834 }
1835
1836 rb_errno_set(saved_errno);
1837
1838 return val;
1839}
1840
1841/*
1842 * rb_thread_call_without_gvl - permit concurrent/parallel execution.
1843 * rb_thread_call_without_gvl2 - permit concurrent/parallel execution
1844 * without interrupt process.
1845 *
1846 * rb_thread_call_without_gvl() does:
1847 * (1) Check interrupts.
1848 * (2) release GVL.
1849 * Other Ruby threads may run in parallel.
1850 * (3) call func with data1
1851 * (4) acquire GVL.
1852 * Other Ruby threads can not run in parallel any more.
1853 * (5) Check interrupts.
1854 *
1855 * rb_thread_call_without_gvl2() does:
1856 * (1) Check interrupt and return if interrupted.
1857 * (2) release GVL.
1858 * (3) call func with data1 and a pointer to the flags.
1859 * (4) acquire GVL.
1860 *
1861 * If another thread interrupts this thread (Thread#kill, signal delivery,
1862 * VM-shutdown request, and so on), `ubf()' is called (`ubf()' means
1863 * "un-blocking function"). `ubf()' should interrupt `func()' execution by
1864 * toggling a cancellation flag, canceling the invocation of a call inside
1865 * `func()' or similar. Note that `ubf()' may not be called with the GVL.
1866 *
1867 * There are built-in ubfs and you can specify these ubfs:
1868 *
1869 * * RUBY_UBF_IO: ubf for IO operation
1870 * * RUBY_UBF_PROCESS: ubf for process operation
1871 *
1872 * However, we can not guarantee our built-in ubfs interrupt your `func()'
1873 * correctly. Be careful to use rb_thread_call_without_gvl(). If you don't
1874 * provide proper ubf(), your program will not stop for Control+C or other
1875 * shutdown events.
1876 *
1877 * "Check interrupts" on above list means checking asynchronous
1878 * interrupt events (such as Thread#kill, signal delivery, VM-shutdown
1879 * request, and so on) and calling corresponding procedures
1880 * (such as `trap' for signals, raise an exception for Thread#raise).
1881 * If `func()' finished and received interrupts, you may skip interrupt
1882 * checking. For example, assume the following func() it reads data from file.
1883 *
1884 * read_func(...) {
1885 * // (a) before read
1886 * read(buffer); // (b) reading
1887 * // (c) after read
1888 * }
1889 *
1890 * If an interrupt occurs at (a) or (b), then `ubf()' cancels this
1891 * `read_func()' and interrupts are checked. However, if an interrupt occurs
1892 * at (c), after *read* operation is completed, checking interrupts is harmful
1893 * because it causes irrevocable side-effect, the read data will vanish. To
1894 * avoid such problem, the `read_func()' should be used with
1895 * `rb_thread_call_without_gvl2()'.
1896 *
1897 * If `rb_thread_call_without_gvl2()' detects interrupt, it returns
1898 * immediately. This function does not show when the execution was interrupted.
1899 * For example, there are 4 possible timing (a), (b), (c) and before calling
1900 * read_func(). You need to record progress of a read_func() and check
1901 * the progress after `rb_thread_call_without_gvl2()'. You may need to call
1902 * `rb_thread_check_ints()' correctly or your program can not process proper
1903 * process such as `trap' and so on.
1904 *
1905 * NOTE: You can not execute most of Ruby C API and touch Ruby
1906 * objects in `func()' and `ubf()', including raising an
1907 * exception, because current thread doesn't acquire GVL
1908 * (it causes synchronization problems). If you need to
1909 * call ruby functions either use rb_thread_call_with_gvl()
1910 * or read source code of C APIs and confirm safety by
1911 * yourself.
1912 *
1913 * NOTE: In short, this API is difficult to use safely. I recommend you
1914 * use other ways if you have. We lack experiences to use this API.
1915 * Please report your problem related on it.
1916 *
1917 * NOTE: Releasing GVL and re-acquiring GVL may be expensive operations
1918 * for a short running `func()'. Be sure to benchmark and use this
1919 * mechanism when `func()' consumes enough time.
1920 *
1921 * Safe C API:
1922 * * rb_thread_interrupted() - check interrupt flag
1923 * * ruby_xmalloc(), ruby_xrealloc(), ruby_xfree() -
1924 * they will work without GVL, and may acquire GVL when GC is needed.
1925 */
1926void *
1927rb_thread_call_without_gvl2(void *(*func)(void *), void *data1,
1928 rb_unblock_function_t *ubf, void *data2)
1929{
1930 return rb_nogvl(func, data1, ubf, data2, RB_NOGVL_INTR_FAIL);
1931}
1932
1933void *
1934rb_thread_call_without_gvl(void *(*func)(void *data), void *data1,
1935 rb_unblock_function_t *ubf, void *data2)
1936{
1937 return rb_nogvl(func, data1, ubf, data2, 0);
1938}
1939
1940static int
1941waitfd_to_waiting_flag(int wfd_event)
1942{
1943 return wfd_event << 1;
1944}
1945
1946static struct ccan_list_head *
1947rb_io_blocking_operations(struct rb_io *io)
1948{
1949 rb_serial_t fork_generation = GET_VM()->fork_gen;
1950
1951 // On fork, all existing entries in this list (which are stack allocated) become invalid.
1952 // Therefore, we re-initialize the list which clears it.
1953 if (io->fork_generation != fork_generation) {
1954 ccan_list_head_init(&io->blocking_operations);
1955 io->fork_generation = fork_generation;
1956 }
1957
1958 return &io->blocking_operations;
1959}
1960
1961/*
1962 * Registers a blocking operation for an IO object. This is used to track all threads and fibers
1963 * that are currently blocked on this IO for reading, writing or other operations.
1964 *
1965 * When the IO is closed, all blocking operations will be notified via rb_fiber_scheduler_fiber_interrupt
1966 * for fibers with a scheduler, or via rb_threadptr_interrupt for threads without a scheduler.
1967 *
1968 * @parameter io The IO object on which the operation will block
1969 * @parameter blocking_operation The operation details including the execution context that will be blocked
1970 */
1971static void
1972rb_io_blocking_operation_enter(struct rb_io *io, struct rb_io_blocking_operation *blocking_operation)
1973{
1974 ccan_list_add(rb_io_blocking_operations(io), &blocking_operation->list);
1975}
1976
1977static void
1978rb_io_blocking_operation_pop(struct rb_io *io, struct rb_io_blocking_operation *blocking_operation)
1979{
1980 ccan_list_del(&blocking_operation->list);
1981}
1984 struct rb_io *io;
1985 struct rb_io_blocking_operation *blocking_operation;
1986};
1987
1988static VALUE
1989io_blocking_operation_exit(VALUE _arguments)
1990{
1991 struct io_blocking_operation_arguments *arguments = (void*)_arguments;
1992 struct rb_io_blocking_operation *blocking_operation = arguments->blocking_operation;
1993
1994 rb_io_blocking_operation_pop(arguments->io, blocking_operation);
1995
1996 rb_io_t *io = arguments->io;
1997 rb_thread_t *thread = io->closing_ec->thread_ptr;
1998 rb_fiber_t *fiber = io->closing_ec->fiber_ptr;
1999
2000 if (thread->scheduler != Qnil) {
2001 // This can cause spurious wakeups...
2002 rb_fiber_scheduler_unblock(thread->scheduler, io->self, rb_fiberptr_self(fiber));
2003 }
2004 else {
2005 rb_thread_wakeup(thread->self);
2006 }
2007
2008 return Qnil;
2009}
2010
2011/*
2012 * Called when a blocking operation completes or is interrupted. Removes the operation from
2013 * the IO's blocking_operations list and wakes up any waiting threads/fibers.
2014 *
2015 * If there's a wakeup_mutex (meaning an IO close is in progress), synchronizes the cleanup
2016 * through that mutex to ensure proper coordination with the closing thread.
2017 *
2018 * @parameter io The IO object the operation was performed on
2019 * @parameter blocking_operation The completed operation to clean up
2020 */
2021static void
2022rb_io_blocking_operation_exit(struct rb_io *io, struct rb_io_blocking_operation *blocking_operation)
2023{
2024 VALUE wakeup_mutex = io->wakeup_mutex;
2025
2026 // Indicate that the blocking operation is no longer active:
2027 blocking_operation->ec = NULL;
2028
2029 if (!NIL_P(blocking_operation->scheduler_interrupt_target)) {
2030 rb_fiber_scheduler_interrupt_target_invalidate(blocking_operation->scheduler_interrupt_target);
2031 }
2032
2033 if (RB_TEST(wakeup_mutex)) {
2034 struct io_blocking_operation_arguments arguments = {
2035 .io = io,
2036 .blocking_operation = blocking_operation
2037 };
2038
2039 rb_mutex_synchronize(wakeup_mutex, io_blocking_operation_exit, (VALUE)&arguments);
2040 }
2041 else {
2042 // If there's no wakeup_mutex, we can safely remove the operation directly:
2043 rb_io_blocking_operation_pop(io, blocking_operation);
2044 }
2045}
2046
2047static VALUE
2048rb_thread_io_blocking_operation_ensure(VALUE _argument)
2049{
2050 struct io_blocking_operation_arguments *arguments = (void*)_argument;
2051
2052 rb_io_blocking_operation_exit(arguments->io, arguments->blocking_operation);
2053
2054 return Qnil;
2055}
2058 VALUE (*function)(VALUE);
2059 VALUE argument;
2060 struct rb_io_blocking_operation *blocking_operation;
2061};
2062
2063static VALUE
2064rb_thread_io_blocking_operation_body(VALUE _arguments)
2065{
2066 struct thread_io_blocking_operation_arguments *arguments = (void *)_arguments;
2067 VALUE result = arguments->function(arguments->argument);
2068 VALUE target = arguments->blocking_operation->scheduler_interrupt_target;
2069
2070 if (!NIL_P(target)) {
2071 VALUE exception = rb_fiber_scheduler_interrupt_target_exception(target);
2072
2073 if (!NIL_P(exception)) {
2074 rb_exc_raise(exception);
2075 }
2076 }
2077
2078 return result;
2079}
2080
2081/*
2082 * Executes a function that performs a blocking IO operation, while properly tracking
2083 * the operation in the IO's blocking_operations list. This ensures proper cleanup
2084 * and interruption handling if the IO is closed while blocked.
2085 *
2086 * The operation is automatically removed from the blocking_operations list when the function
2087 * returns, whether normally or due to an exception.
2088 *
2089 * @parameter self The IO object
2090 * @parameter function The function to execute that will perform the blocking operation
2091 * @parameter argument The argument to pass to the function
2092 * @returns The result of the blocking operation function
2093 */
2094VALUE
2095rb_thread_io_blocking_operation(VALUE self, VALUE(*function)(VALUE), VALUE argument)
2096{
2097 struct rb_io *io;
2098 RB_IO_POINTER(self, io);
2099
2100 rb_execution_context_t *ec = GET_EC();
2101 struct rb_io_blocking_operation blocking_operation = {
2102 .ec = ec,
2103 .scheduler_interrupt_target = Qnil,
2104 };
2105 rb_io_blocking_operation_enter(io, &blocking_operation);
2106
2108 .io = io,
2109 .blocking_operation = &blocking_operation
2110 };
2111
2112 struct thread_io_blocking_operation_arguments arguments = {
2113 .function = function,
2114 .argument = argument,
2115 .blocking_operation = &blocking_operation,
2116 };
2117
2118 return rb_ensure(rb_thread_io_blocking_operation_body, (VALUE)&arguments, rb_thread_io_blocking_operation_ensure, (VALUE)&io_blocking_operation_arguments);
2119}
2120
2121static bool
2122thread_io_mn_schedulable(rb_thread_t *th, int events, const struct timeval *timeout)
2123{
2124#if defined(USE_MN_THREADS) && USE_MN_THREADS
2125 // RB_WAITFD_PRI has no thread_sched_waiting_* event: the scheduler would
2126 // register nothing and park the thread forever. POLLPRI works on the
2127 // blocking path.
2128 return !th_has_dedicated_nt(th) && (events || timeout) && th->blocking &&
2129 !(events & ~(RB_WAITFD_IN | RB_WAITFD_OUT));
2130#else
2131 return false;
2132#endif
2133}
2134
2135enum io_wait_result {
2136 io_wait_ready, // the MN scheduler waited and the fd is ready
2137 io_wait_timed_out, // the MN scheduler waited until the timeout expired
2138 io_wait_unhandled, // the MN scheduler did not wait; use the blocking path
2139 io_wait_interrupted, // the MN scheduler stopped for an interrupt; handle it and wait again
2140};
2141
2142// Wait for `fd` on the MN scheduler, if it can take this wait at all.
2143// `known_not_ready`: the caller just saw EAGAIN, so probing the fd would only
2144// repeat an answer we have. Callers with no preceding operation need the probe.
2145static enum io_wait_result
2146thread_io_wait_events(rb_thread_t *th, int fd, int events, const struct timeval *timeout,
2147 bool known_not_ready)
2148{
2149#if defined(USE_MN_THREADS) && USE_MN_THREADS
2150 if (thread_io_mn_schedulable(th, events, timeout)) {
2151 rb_hrtime_t rel, *prel;
2152
2153 if (timeout) {
2154 rel = rb_timeval2hrtime(timeout);
2155 prel = &rel;
2156 }
2157 else {
2158 prel = NULL;
2159 }
2160
2161 VM_ASSERT(prel || (events & (RB_WAITFD_IN | RB_WAITFD_OUT)));
2162
2163 enum thread_sched_waiting_flag flags = waitfd_to_waiting_flag(events);
2164 if (known_not_ready) flags |= thread_sched_waiting_io_force;
2165
2166 switch (thread_sched_wait_events(TH_SCHED(th), th, fd, flags, prel)) {
2167 case thread_sched_wait_event:
2168 return io_wait_ready;
2169 case thread_sched_wait_timeout:
2170 return io_wait_timed_out;
2171 case thread_sched_wait_unavailable:
2172 // Never waited: reporting "ready" here would fabricate readiness and
2173 // spin, so hand the wait back to the caller's blocking path.
2174 return io_wait_unhandled;
2175 case thread_sched_wait_interrupted:
2176 return io_wait_interrupted;
2177 }
2178 }
2179#endif // defined(USE_MN_THREADS) && USE_MN_THREADS
2180 return io_wait_unhandled;
2181}
2182
2183// assume read/write
2184static bool
2185blocking_call_retryable_p(int r, int eno)
2186{
2187 if (r != -1) return false;
2188
2189 switch (eno) {
2190 case EAGAIN:
2191#if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
2192 case EWOULDBLOCK:
2193#endif
2194 return true;
2195 default:
2196 return false;
2197 }
2198}
2199
2200bool
2201rb_thread_mn_schedulable(VALUE thval)
2202{
2203 rb_thread_t *th = rb_thread_ptr(thval);
2204 return th->mn_schedulable;
2205}
2206
2207VALUE
2208rb_thread_io_blocking_call(struct rb_io* io, rb_blocking_function_t *func, void *data1, int events)
2209{
2210 rb_execution_context_t * volatile ec = GET_EC();
2211 rb_thread_t * volatile th = rb_ec_thread_ptr(ec);
2212
2213 RUBY_DEBUG_LOG("th:%u fd:%d ev:%d", rb_th_serial(th), io->fd, events);
2214
2215 volatile VALUE val = Qundef; /* shouldn't be used */
2216 volatile int saved_errno = 0;
2217 enum ruby_tag_type state;
2218 volatile bool prev_mn_schedulable = th->mn_schedulable;
2219 th->mn_schedulable = thread_io_mn_schedulable(th, events, NULL);
2220
2221 int fd = io->fd;
2222
2223 struct rb_io_blocking_operation blocking_operation = {
2224 .ec = ec,
2225 .scheduler_interrupt_target = Qnil,
2226 };
2227 rb_io_blocking_operation_enter(io, &blocking_operation);
2228
2229 {
2230 EC_PUSH_TAG(ec);
2231 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
2232 volatile enum ruby_tag_type saved_state = state; /* for BLOCKING_REGION */
2233 retry:
2234 BLOCKING_REGION(th, {
2235 // `errno` is only valid when there is an actual error - but we can't
2236 // extract that from the return value of `func` alone, so we clear any
2237 // prior `errno` value here so that we can later check if it was set by
2238 // `func` or not (as opposed to some previously set value).
2239 errno = 0;
2240 val = func(data1);
2241 saved_errno = errno;
2242 }, ubf_select, th, FALSE);
2243
2244 RUBY_ASSERT(th == rb_ec_thread_ptr(ec));
2245 if (events && blocking_call_retryable_p((int)val, saved_errno)) {
2246 // `func` just returned EAGAIN, so the fd is known not to be ready.
2247 // Any M:N outcome but unhandled (ready, interrupted, woken early) retries `func`.
2248 if (thread_io_wait_events(th, fd, events, NULL, true) != io_wait_unhandled) {
2249 RUBY_VM_CHECK_INTS_BLOCKING(ec);
2250 goto retry;
2251 }
2252 else if (th->mn_schedulable) {
2253 // Retrying now would spin and returning would leak EAGAIN to
2254 // Ruby, so wait the ordinary blocking way, then retry.
2255 rb_thread_wait_for_single_fd(th, fd, events, NULL);
2256 RUBY_VM_CHECK_INTS_BLOCKING(ec);
2257 goto retry;
2258 }
2259 }
2260
2261 RUBY_VM_CHECK_INTS_BLOCKING(ec);
2262
2263 state = saved_state;
2264 }
2265 EC_POP_TAG();
2266
2267 th = rb_ec_thread_ptr(ec);
2268 th->mn_schedulable = prev_mn_schedulable;
2269 }
2270
2271 rb_io_blocking_operation_exit(io, &blocking_operation);
2272
2273 if (state) {
2274 EC_JUMP_TAG(ec, state);
2275 }
2276
2277 // If the error was a timeout, we raise a specific exception for that:
2278 if (saved_errno == ETIMEDOUT) {
2279 rb_raise(rb_eIOTimeoutError, "Blocking operation timed out!");
2280 }
2281
2282 errno = saved_errno;
2283
2284 return val;
2285}
2286
2287VALUE
2288rb_thread_io_blocking_region(struct rb_io *io, rb_blocking_function_t *func, void *data1)
2289{
2290 return rb_thread_io_blocking_call(io, func, data1, 0);
2291}
2292
2293/*
2294 * rb_thread_call_with_gvl - re-enter the Ruby world after GVL release.
2295 *
2296 * After releasing GVL using
2297 * rb_thread_call_without_gvl() you can not access Ruby values or invoke
2298 * methods. If you need to access Ruby you must use this function
2299 * rb_thread_call_with_gvl().
2300 *
2301 * This function rb_thread_call_with_gvl() does:
2302 * (1) acquire GVL.
2303 * (2) call passed function `func'.
2304 * (3) release GVL.
2305 * (4) return a value which is returned at (2).
2306 *
2307 * NOTE: You should not return Ruby object at (2) because such Object
2308 * will not be marked.
2309 *
2310 * NOTE: If an exception is raised in `func', this function DOES NOT
2311 * protect (catch) the exception. If you have any resources
2312 * which should free before throwing exception, you need use
2313 * rb_protect() in `func' and return a value which represents
2314 * exception was raised.
2315 *
2316 * NOTE: This function should not be called by a thread which was not
2317 * created as Ruby thread (created by Thread.new or so). In other
2318 * words, this function *DOES NOT* associate or convert a NON-Ruby
2319 * thread to a Ruby thread.
2320 *
2321 * NOTE: If this thread has already acquired the GVL, then the method call
2322 * is performed without acquiring or releasing the GVL (from Ruby 4.0).
2323 */
2324void *
2325rb_thread_call_with_gvl(void *(*func)(void *), void *data1)
2326{
2327 rb_thread_t *th = ruby_thread_from_native();
2328 struct rb_blocking_region_buffer *brb;
2329 struct rb_unblock_callback prev_unblock;
2330 void *r;
2331
2332 if (th == 0) {
2333 /* Error has occurred, but we can't use rb_bug()
2334 * because this thread is not Ruby's thread.
2335 * What should we do?
2336 */
2337 bp();
2338 fprintf(stderr, "[BUG] rb_thread_call_with_gvl() is called by non-ruby thread\n");
2339 exit(EXIT_FAILURE);
2340 }
2341
2342 brb = (struct rb_blocking_region_buffer *)th->blocking_region_buffer;
2343 prev_unblock = th->unblock;
2344
2345 if (brb == 0) {
2346 /* the GVL is already acquired, call method directly */
2347 return (*func)(data1);
2348 }
2349
2350 blocking_region_end(th, brb);
2351 /* enter to Ruby world: You can access Ruby values, methods and so on. */
2352 r = (*func)(data1);
2353 /* leave from Ruby world: You can not access Ruby values, etc. */
2354 int released = blocking_region_begin(th, brb, prev_unblock.func, prev_unblock.arg, FALSE);
2355 RUBY_ASSERT_ALWAYS(released);
2356 RB_VM_SAVE_MACHINE_CONTEXT(th);
2357 thread_sched_to_waiting(TH_SCHED(th), th, true);
2358 return r;
2359}
2360
2361/*
2362 * ruby_thread_has_gvl_p - check if current native thread has GVL.
2363 */
2364
2367{
2368 rb_thread_t *th = ruby_thread_from_native();
2369
2370 if (th && th->blocking_region_buffer == 0) {
2371 return 1;
2372 }
2373 else {
2374 return 0;
2375 }
2376}
2377
2378/*
2379 * call-seq:
2380 * Thread.pass -> nil
2381 *
2382 * Give the thread scheduler a hint to pass execution to another thread.
2383 * A running thread may or may not switch, it depends on OS and processor.
2384 */
2385
2386static VALUE
2387thread_s_pass(VALUE klass)
2388{
2390 return Qnil;
2391}
2392
2393/*****************************************************/
2394
2395/*
2396 * rb_threadptr_pending_interrupt_* - manage asynchronous error queue
2397 *
2398 * Async events such as an exception thrown by Thread#raise,
2399 * Thread#kill and thread termination (after main thread termination)
2400 * will be queued to th->pending_interrupt_queue.
2401 * - clear: clear the queue.
2402 * - enque: enqueue err object into queue.
2403 * - deque: dequeue err object from queue.
2404 * - active_p: return 1 if the queue should be checked.
2405 *
2406 * All rb_threadptr_pending_interrupt_* functions are called by
2407 * a GVL acquired thread, of course.
2408 * Note that all "rb_" prefix APIs need GVL to call.
2409 */
2410
2411void
2412rb_threadptr_pending_interrupt_clear(rb_thread_t *th)
2413{
2414 rb_ary_clear(th->pending_interrupt_queue);
2415}
2416
2417void
2418rb_threadptr_pending_interrupt_enque(rb_thread_t *th, VALUE v)
2419{
2420 rb_ary_push(th->pending_interrupt_queue, v);
2421 th->pending_interrupt_queue_checked = 0;
2422}
2423
2424static void
2425threadptr_check_pending_interrupt_queue(rb_thread_t *th)
2426{
2427 if (!th->pending_interrupt_queue) {
2428 rb_raise(rb_eThreadError, "uninitialized thread");
2429 }
2430}
2431
2432enum handle_interrupt_timing {
2433 INTERRUPT_NONE,
2434 INTERRUPT_IMMEDIATE,
2435 INTERRUPT_ON_BLOCKING,
2436 INTERRUPT_NEVER
2437};
2438
2439static enum handle_interrupt_timing
2440rb_threadptr_pending_interrupt_from_symbol(rb_thread_t *th, VALUE sym)
2441{
2442 if (sym == sym_immediate) {
2443 return INTERRUPT_IMMEDIATE;
2444 }
2445 else if (sym == sym_on_blocking) {
2446 return INTERRUPT_ON_BLOCKING;
2447 }
2448 else if (sym == sym_never) {
2449 return INTERRUPT_NEVER;
2450 }
2451 else {
2452 rb_raise(rb_eThreadError, "unknown mask signature");
2453 }
2454}
2455
2456static enum handle_interrupt_timing
2457rb_threadptr_pending_interrupt_check_mask(rb_thread_t *th, VALUE err)
2458{
2459 VALUE mask;
2460 rb_len_t mask_stack_len = RARRAY_LEN(th->pending_interrupt_mask_stack);
2461 const VALUE *mask_stack = RARRAY_CONST_PTR(th->pending_interrupt_mask_stack);
2462 VALUE mod;
2463 rb_len_t i;
2464
2465 for (i=0; i<mask_stack_len; i++) {
2466 mask = mask_stack[mask_stack_len-(i+1)];
2467
2468 if (SYMBOL_P(mask)) {
2469 /* do not match RUBY_FATAL_THREAD_KILLED etc */
2470 if (err != rb_cInteger) {
2471 return rb_threadptr_pending_interrupt_from_symbol(th, mask);
2472 }
2473 else {
2474 continue;
2475 }
2476 }
2477
2478 for (mod = err; mod; mod = RCLASS_SUPER(mod)) {
2479 VALUE klass = mod;
2480 VALUE sym;
2481
2482 if (BUILTIN_TYPE(mod) == T_ICLASS) {
2483 klass = RBASIC(mod)->klass;
2484 }
2485 else if (mod != RCLASS_ORIGIN(mod)) {
2486 continue;
2487 }
2488
2489 if ((sym = rb_hash_aref(mask, klass)) != Qnil) {
2490 return rb_threadptr_pending_interrupt_from_symbol(th, sym);
2491 }
2492 }
2493 /* try to next mask */
2494 }
2495 return INTERRUPT_NONE;
2496}
2497
2498static int
2499rb_threadptr_pending_interrupt_empty_p(const rb_thread_t *th)
2500{
2501 return RARRAY_LEN(th->pending_interrupt_queue) == 0;
2502}
2503
2504static int
2505rb_threadptr_pending_interrupt_include_p(rb_thread_t *th, VALUE err)
2506{
2507 int i;
2508 for (i=0; i<RARRAY_LEN(th->pending_interrupt_queue); i++) {
2509 VALUE e = RARRAY_AREF(th->pending_interrupt_queue, i);
2510 if (rb_obj_is_kind_of(e, err)) {
2511 return TRUE;
2512 }
2513 }
2514 return FALSE;
2515}
2516
2517static VALUE
2518rb_threadptr_pending_interrupt_deque(rb_thread_t *th, enum handle_interrupt_timing timing)
2519{
2520#if 1 /* 1 to enable Thread#handle_interrupt, 0 to ignore it */
2521 int i;
2522
2523 for (i=0; i<RARRAY_LEN(th->pending_interrupt_queue); i++) {
2524 VALUE err = RARRAY_AREF(th->pending_interrupt_queue, i);
2525
2526 enum handle_interrupt_timing mask_timing = rb_threadptr_pending_interrupt_check_mask(th, CLASS_OF(err));
2527
2528 switch (mask_timing) {
2529 case INTERRUPT_ON_BLOCKING:
2530 if (timing != INTERRUPT_ON_BLOCKING) {
2531 break;
2532 }
2533 /* fall through */
2534 case INTERRUPT_NONE: /* default: IMMEDIATE */
2535 case INTERRUPT_IMMEDIATE:
2536 rb_ary_delete_at(th->pending_interrupt_queue, i);
2537 return err;
2538 case INTERRUPT_NEVER:
2539 break;
2540 }
2541 }
2542
2543 th->pending_interrupt_queue_checked = 1;
2544 return Qundef;
2545#else
2546 VALUE err = rb_ary_shift(th->pending_interrupt_queue);
2547 if (rb_threadptr_pending_interrupt_empty_p(th)) {
2548 th->pending_interrupt_queue_checked = 1;
2549 }
2550 return err;
2551#endif
2552}
2553
2554static int
2555threadptr_pending_interrupt_active_p(rb_thread_t *th)
2556{
2557 /*
2558 * For optimization, we don't check async errinfo queue
2559 * if the queue and the thread interrupt mask were not changed
2560 * since last check.
2561 */
2562 if (th->pending_interrupt_queue_checked) {
2563 return 0;
2564 }
2565
2566 if (rb_threadptr_pending_interrupt_empty_p(th)) {
2567 return 0;
2568 }
2569
2570 return 1;
2571}
2572
2573static int
2574handle_interrupt_arg_check_i(VALUE key, VALUE val, VALUE args)
2575{
2576 VALUE *maskp = (VALUE *)args;
2577
2578 if (val != sym_immediate && val != sym_on_blocking && val != sym_never) {
2579 rb_raise(rb_eArgError, "unknown mask signature");
2580 }
2581
2582 if (key == rb_eException && (UNDEF_P(*maskp) || NIL_P(*maskp))) {
2583 *maskp = val;
2584 return ST_CONTINUE;
2585 }
2586
2587 if (RTEST(*maskp)) {
2588 if (!RB_TYPE_P(*maskp, T_HASH)) {
2589 VALUE prev = *maskp;
2590 *maskp = rb_ident_hash_new();
2591 if (SYMBOL_P(prev)) {
2592 rb_hash_aset(*maskp, rb_eException, prev);
2593 }
2594 }
2595 rb_hash_aset(*maskp, key, val);
2596 }
2597 else {
2598 *maskp = Qfalse;
2599 }
2600
2601 return ST_CONTINUE;
2602}
2603
2604/*
2605 * call-seq:
2606 * Thread.handle_interrupt(hash) { ... } -> result of the block
2607 *
2608 * Changes asynchronous interrupt timing.
2609 *
2610 * _interrupt_ means asynchronous event and corresponding procedure
2611 * by Thread#raise, Thread#kill, signal trap (not supported yet)
2612 * and main thread termination (if main thread terminates, then all
2613 * other thread will be killed).
2614 *
2615 * The given +hash+ has pairs like <code>ExceptionClass =>
2616 * :TimingSymbol</code>. Where the ExceptionClass is the interrupt handled by
2617 * the given block. The TimingSymbol can be one of the following symbols:
2618 *
2619 * [+:immediate+] Invoke interrupts immediately.
2620 * [+:on_blocking+] Invoke interrupts while _BlockingOperation_.
2621 * [+:never+] Never invoke all interrupts.
2622 *
2623 * _BlockingOperation_ means that the operation will block the calling thread,
2624 * such as read and write. On CRuby implementation, _BlockingOperation_ is any
2625 * operation executed without GVL.
2626 *
2627 * Masked asynchronous interrupts are delayed until they are enabled.
2628 * This method is similar to sigprocmask(3).
2629 *
2630 * === NOTE
2631 *
2632 * Asynchronous interrupts are difficult to use.
2633 *
2634 * If you need to communicate between threads, please consider to use another way such as Queue.
2635 *
2636 * Or use them with deep understanding about this method.
2637 *
2638 * === Usage
2639 *
2640 * In this example, we can guard from Thread#raise exceptions.
2641 *
2642 * Using the +:never+ TimingSymbol the RuntimeError exception will always be
2643 * ignored in the first block of the main thread. In the second
2644 * ::handle_interrupt block we can purposefully handle RuntimeError exceptions.
2645 *
2646 * th = Thread.new do
2647 * Thread.handle_interrupt(RuntimeError => :never) {
2648 * begin
2649 * # You can write resource allocation code safely.
2650 * Thread.handle_interrupt(RuntimeError => :immediate) {
2651 * # ...
2652 * }
2653 * ensure
2654 * # You can write resource deallocation code safely.
2655 * end
2656 * }
2657 * end
2658 * Thread.pass
2659 * # ...
2660 * th.raise "stop"
2661 *
2662 * While we are ignoring the RuntimeError exception, it's safe to write our
2663 * resource allocation code. Then, the ensure block is where we can safely
2664 * deallocate your resources.
2665 *
2666 * ==== Stack control settings
2667 *
2668 * It's possible to stack multiple levels of ::handle_interrupt blocks in order
2669 * to control more than one ExceptionClass and TimingSymbol at a time.
2670 *
2671 * Thread.handle_interrupt(FooError => :never) {
2672 * Thread.handle_interrupt(BarError => :never) {
2673 * # FooError and BarError are prohibited.
2674 * }
2675 * }
2676 *
2677 * ==== Inheritance with ExceptionClass
2678 *
2679 * All exceptions inherited from the ExceptionClass parameter will be considered.
2680 *
2681 * Thread.handle_interrupt(Exception => :never) {
2682 * # all exceptions inherited from Exception are prohibited.
2683 * }
2684 *
2685 * For handling all interrupts, use +Object+ and not +Exception+
2686 * as the ExceptionClass, as kill/terminate interrupts are not handled by +Exception+.
2687 */
2688static VALUE
2689rb_thread_s_handle_interrupt(VALUE self, VALUE mask_arg)
2690{
2691 VALUE mask = Qundef;
2692 rb_execution_context_t * volatile ec = GET_EC();
2693 rb_thread_t * volatile th = rb_ec_thread_ptr(ec);
2694 volatile VALUE r = Qnil;
2695 enum ruby_tag_type state;
2696
2697 if (!rb_block_given_p()) {
2698 rb_raise(rb_eArgError, "block is needed.");
2699 }
2700
2701 mask_arg = rb_to_hash_type(mask_arg);
2702
2703 if (OBJ_FROZEN(mask_arg) && rb_hash_compare_by_id_p(mask_arg)) {
2704 mask = Qnil;
2705 }
2706
2707 rb_hash_foreach(mask_arg, handle_interrupt_arg_check_i, (VALUE)&mask);
2708
2709 if (UNDEF_P(mask)) {
2710 return rb_yield(Qnil);
2711 }
2712
2713 if (!RTEST(mask)) {
2714 mask = mask_arg;
2715 }
2716 else if (RB_TYPE_P(mask, T_HASH)) {
2717 OBJ_FREEZE(mask);
2718 }
2719
2720 rb_ary_push(th->pending_interrupt_mask_stack, mask);
2721 if (!rb_threadptr_pending_interrupt_empty_p(th)) {
2722 th->pending_interrupt_queue_checked = 0;
2723 RUBY_VM_SET_INTERRUPT(th->ec);
2724 }
2725
2726 EC_PUSH_TAG(th->ec);
2727 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
2728 r = rb_yield(Qnil);
2729 }
2730 EC_POP_TAG();
2731
2732 rb_ary_pop(th->pending_interrupt_mask_stack);
2733 if (!rb_threadptr_pending_interrupt_empty_p(th)) {
2734 th->pending_interrupt_queue_checked = 0;
2735 RUBY_VM_SET_INTERRUPT(th->ec);
2736 }
2737
2738 RUBY_VM_CHECK_INTS(th->ec);
2739
2740 if (state) {
2741 EC_JUMP_TAG(th->ec, state);
2742 }
2743
2744 return r;
2745}
2746
2747/*
2748 * call-seq:
2749 * target_thread.pending_interrupt?(error = nil) -> true/false
2750 *
2751 * Returns whether or not the asynchronous queue is empty for the target thread.
2752 *
2753 * If +error+ is given, then check only for +error+ type deferred events.
2754 *
2755 * See ::pending_interrupt? for more information.
2756 */
2757static VALUE
2758rb_thread_pending_interrupt_p(int argc, VALUE *argv, VALUE target_thread)
2759{
2760 rb_thread_t *target_th = rb_thread_ptr(target_thread);
2761
2762 if (!target_th->pending_interrupt_queue) {
2763 return Qfalse;
2764 }
2765 if (rb_threadptr_pending_interrupt_empty_p(target_th)) {
2766 return Qfalse;
2767 }
2768 if (rb_check_arity(argc, 0, 1)) {
2769 VALUE err = argv[0];
2770 if (!rb_obj_is_kind_of(err, rb_cModule)) {
2771 rb_raise(rb_eTypeError, "class or module required for rescue clause");
2772 }
2773 return RBOOL(rb_threadptr_pending_interrupt_include_p(target_th, err));
2774 }
2775 else {
2776 return Qtrue;
2777 }
2778}
2779
2780/*
2781 * call-seq:
2782 * Thread.pending_interrupt?(error = nil) -> true/false
2783 *
2784 * Returns whether or not the asynchronous queue is empty.
2785 *
2786 * Since Thread::handle_interrupt can be used to defer asynchronous events,
2787 * this method can be used to determine if there are any deferred events.
2788 *
2789 * If you find this method returns true, then you may finish +:never+ blocks.
2790 *
2791 * For example, the following method processes deferred asynchronous events
2792 * immediately.
2793 *
2794 * def Thread.kick_interrupt_immediately
2795 * Thread.handle_interrupt(Object => :immediate) {
2796 * Thread.pass
2797 * }
2798 * end
2799 *
2800 * If +error+ is given, then check only for +error+ type deferred events.
2801 *
2802 * === Usage
2803 *
2804 * th = Thread.new{
2805 * Thread.handle_interrupt(RuntimeError => :on_blocking){
2806 * while true
2807 * ...
2808 * # reach safe point to invoke interrupt
2809 * if Thread.pending_interrupt?
2810 * Thread.handle_interrupt(Object => :immediate){}
2811 * end
2812 * ...
2813 * end
2814 * }
2815 * }
2816 * ...
2817 * th.raise # stop thread
2818 *
2819 * This example can also be written as the following, which you should use to
2820 * avoid asynchronous interrupts.
2821 *
2822 * flag = true
2823 * th = Thread.new{
2824 * Thread.handle_interrupt(RuntimeError => :on_blocking){
2825 * while true
2826 * ...
2827 * # reach safe point to invoke interrupt
2828 * break if flag == false
2829 * ...
2830 * end
2831 * }
2832 * }
2833 * ...
2834 * flag = false # stop thread
2835 */
2836
2837static VALUE
2838rb_thread_s_pending_interrupt_p(int argc, VALUE *argv, VALUE self)
2839{
2840 return rb_thread_pending_interrupt_p(argc, argv, GET_THREAD()->self);
2841}
2842
2843NORETURN(static void rb_threadptr_to_kill(rb_thread_t *th));
2844
2845static void
2846rb_threadptr_to_kill(rb_thread_t *th)
2847{
2848 VM_ASSERT(GET_THREAD() == th);
2849 rb_threadptr_pending_interrupt_clear(th);
2850 th->status = THREAD_RUNNABLE;
2851 th->to_kill = 1;
2852 th->ec->errinfo = INT2FIX(TAG_FATAL);
2853 EC_JUMP_TAG(th->ec, TAG_FATAL);
2854}
2855
2856static inline rb_atomic_t
2857threadptr_get_interrupts(rb_thread_t *th)
2858{
2859 rb_execution_context_t *ec = th->ec;
2860 rb_atomic_t interrupt;
2861 rb_atomic_t old;
2862
2863 old = ATOMIC_LOAD_RELAXED(ec->interrupt_flag);
2864 do {
2865 interrupt = old;
2866 old = ATOMIC_CAS(ec->interrupt_flag, interrupt, interrupt & ec->interrupt_mask);
2867 } while (old != interrupt);
2868 return interrupt & (rb_atomic_t)~ec->interrupt_mask;
2869}
2870
2871static void threadptr_interrupt_exec_exec(rb_thread_t *th);
2872
2873// Execute interrupts on currently running thread
2874// In certain situations, calling this function will raise an exception. Some examples are:
2875// * during VM shutdown (`rb_ractor_terminate_all`)
2876// * Call to Thread#exit for current thread (`rb_thread_kill`)
2877// * Call to Thread#raise for current thread
2878int
2879rb_threadptr_execute_interrupts(rb_thread_t *th, int blocking_timing)
2880{
2881 rb_atomic_t interrupt;
2882 int postponed_job_interrupt = 0;
2883 int ret = FALSE;
2884
2885 VM_ASSERT(GET_THREAD() == th);
2886
2887 if (th->ec->raised_flag) return ret;
2888
2889 /* Interrupts are checked at arbitrary points, including while a jump
2890 * (break/next/redo/return/raise/throw) is being propagated.
2891 * Save errinfo as the interrupt might run Ruby code that could clear it. */
2892 const VALUE saved_errinfo = th->ec->errinfo;
2893
2894 while ((interrupt = threadptr_get_interrupts(th)) != 0) {
2895 int sig;
2896 int timer_interrupt;
2897 int pending_interrupt;
2898 int trap_interrupt;
2899 int terminate_interrupt;
2900
2901 timer_interrupt = interrupt & TIMER_INTERRUPT_MASK;
2902 pending_interrupt = interrupt & PENDING_INTERRUPT_MASK;
2903 postponed_job_interrupt = interrupt & POSTPONED_JOB_INTERRUPT_MASK;
2904 trap_interrupt = interrupt & TRAP_INTERRUPT_MASK;
2905 terminate_interrupt = interrupt & TERMINATE_INTERRUPT_MASK; // request from other ractors
2906
2907 if (interrupt & VM_BARRIER_INTERRUPT_MASK) {
2908 RB_VM_LOCKING();
2909 }
2910
2911 if (postponed_job_interrupt) {
2912 rb_postponed_job_flush();
2913 }
2914
2915 if (trap_interrupt) {
2916 /* signal handling */
2917 if (th == th->vm->ractor.main_thread) {
2918 enum rb_thread_status prev_status = th->status;
2919
2920 th->status = THREAD_RUNNABLE;
2921 {
2922 while ((sig = rb_get_next_signal()) != 0) {
2923 ret |= rb_signal_exec(th, sig);
2924 }
2925 }
2926 th->status = prev_status;
2927 }
2928
2929 if (!ccan_list_empty(&th->interrupt_exec_tasks)) {
2930 enum rb_thread_status prev_status = th->status;
2931
2932 th->status = THREAD_RUNNABLE;
2933 {
2934 threadptr_interrupt_exec_exec(th);
2935 }
2936 th->status = prev_status;
2937 }
2938 }
2939
2940 /* exception from another thread */
2941 if (pending_interrupt && threadptr_pending_interrupt_active_p(th)) {
2942 VALUE err = rb_threadptr_pending_interrupt_deque(th, blocking_timing ? INTERRUPT_ON_BLOCKING : INTERRUPT_NONE);
2943 RUBY_DEBUG_LOG("err:%"PRIdVALUE, err);
2944 ret = TRUE;
2945
2946 if (UNDEF_P(err)) {
2947 /* no error */
2948 }
2949 else if (err == RUBY_FATAL_THREAD_KILLED /* Thread#kill received */ ||
2950 err == RUBY_FATAL_THREAD_TERMINATED /* Terminate thread */ ||
2951 err == INT2FIX(TAG_FATAL) /* Thread.exit etc. */ ) {
2952 terminate_interrupt = 1;
2953 }
2954 else {
2955 if (err == th->vm->special_exceptions[ruby_error_stream_closed]) {
2956 /* the only special exception to be queued across thread */
2957 err = ruby_vm_special_exception_copy(err);
2958 }
2959 /* set runnable if th was slept. */
2960 if (th->status == THREAD_STOPPED ||
2961 th->status == THREAD_STOPPED_FOREVER)
2962 th->status = THREAD_RUNNABLE;
2963 rb_exc_raise(err);
2964 }
2965 }
2966
2967 if (terminate_interrupt) {
2968 rb_threadptr_to_kill(th);
2969 }
2970
2971 if (timer_interrupt) {
2972 uint32_t limits_us = thread_default_quantum_ms * 1000;
2973
2974 if (th->priority > 0)
2975 limits_us <<= th->priority;
2976 else
2977 limits_us >>= -th->priority;
2978
2979 if (th->status == THREAD_RUNNABLE)
2980 th->running_time_us += 10 * 1000; // 10ms = 10_000us // TODO: use macro
2981
2982 VM_ASSERT(th->ec->cfp);
2983 EXEC_EVENT_HOOK(th->ec, RUBY_INTERNAL_EVENT_SWITCH, th->ec->cfp->self,
2984 0, 0, 0, Qundef);
2985
2986 rb_thread_schedule_limits(limits_us);
2987 }
2988 }
2989
2990 th->ec->errinfo = saved_errinfo;
2991
2992 return ret;
2993}
2994
2995void
2996rb_thread_execute_interrupts(VALUE thval)
2997{
2998 rb_threadptr_execute_interrupts(rb_thread_ptr(thval), 1);
2999}
3000
3001static void
3002rb_threadptr_ready(rb_thread_t *th)
3003{
3004 rb_threadptr_interrupt(th);
3005}
3006
3007static VALUE
3008rb_threadptr_raise(rb_thread_t *target_th, int argc, VALUE *argv)
3009{
3010 VALUE exc;
3011
3012 if (rb_threadptr_dead(target_th)) {
3013 return Qnil;
3014 }
3015
3016 if (argc == 0) {
3017 exc = rb_exc_new(rb_eRuntimeError, 0, 0);
3018 }
3019 else {
3020 exc = rb_make_exception(argc, argv);
3021 }
3022
3023 /* making an exception object can switch thread,
3024 so we need to check thread deadness again */
3025 if (rb_threadptr_dead(target_th)) {
3026 return Qnil;
3027 }
3028
3029 rb_ec_setup_exception(GET_EC(), exc, Qundef);
3030 rb_threadptr_pending_interrupt_enque(target_th, exc);
3031 rb_threadptr_interrupt(target_th);
3032
3033 return Qnil;
3034}
3035
3036void
3037rb_threadptr_signal_raise(rb_thread_t *th, int sig)
3038{
3039 VALUE argv[2];
3040
3041 argv[0] = rb_eSignal;
3042 argv[1] = INT2FIX(sig);
3043 rb_threadptr_raise(th->vm->ractor.main_thread, 2, argv);
3044}
3045
3046void
3047rb_threadptr_interrupt_raise(rb_thread_t *th)
3048{
3049 rb_thread_t *target_th = th->vm->ractor.main_thread;
3050
3051 if (rb_threadptr_dead(target_th)) {
3052 return;
3053 }
3054
3055 /* Preserve the traditional no-message Interrupt from default SIGINT. */
3056 VALUE exc = rb_exc_new(rb_eInterrupt, 0, 0);
3057
3058 /* making an exception object can switch thread,
3059 so we need to check thread deadness again */
3060 if (rb_threadptr_dead(target_th)) {
3061 return;
3062 }
3063
3064 rb_ec_setup_exception(GET_EC(), exc, Qundef);
3065 rb_threadptr_pending_interrupt_enque(target_th, exc);
3066 rb_threadptr_interrupt(target_th);
3067}
3068
3069void
3070rb_threadptr_signal_exit(rb_thread_t *th)
3071{
3072 VALUE argv[2];
3073
3074 argv[0] = rb_eSystemExit;
3075 argv[1] = rb_str_new2("exit");
3076
3077 // TODO: check signal raise deliverly
3078 rb_threadptr_raise(th->vm->ractor.main_thread, 2, argv);
3079}
3080
3081int
3082rb_ec_set_raised(rb_execution_context_t *ec)
3083{
3084 if (ec->raised_flag & RAISED_EXCEPTION) {
3085 return 1;
3086 }
3087 ec->raised_flag |= RAISED_EXCEPTION;
3088 return 0;
3089}
3090
3091int
3092rb_ec_reset_raised(rb_execution_context_t *ec)
3093{
3094 if (!(ec->raised_flag & RAISED_EXCEPTION)) {
3095 return 0;
3096 }
3097 ec->raised_flag &= ~RAISED_EXCEPTION;
3098 return 1;
3099}
3100
3101/*
3102 * Thread-safe IO closing mechanism.
3103 *
3104 * When an IO is closed while other threads or fibers are blocked on it, we need to:
3105 * 1. Track and notify all blocking operations through io->blocking_operations
3106 * 2. Ensure only one thread can close at a time using io->closing_ec
3107 * 3. Synchronize cleanup using wakeup_mutex
3108 *
3109 * The close process works as follows:
3110 * - First check if any thread is already closing (io->closing_ec)
3111 * - Set up wakeup_mutex for synchronization
3112 * - Iterate through all blocking operations in io->blocking_operations
3113 * - For each blocked fiber with a scheduler:
3114 * - Notify via rb_fiber_scheduler_fiber_interrupt
3115 * - For each blocked thread without a scheduler:
3116 * - Enqueue IOError via rb_threadptr_pending_interrupt_enque
3117 * - Wake via rb_threadptr_interrupt
3118 * - Wait on wakeup_mutex until all operations are cleaned up
3119 * - Only then clear closing state and allow actual close to proceed
3120 */
3121static VALUE
3122thread_io_close_notify_all(VALUE _io)
3123{
3124 struct rb_io *io = (struct rb_io *)_io;
3125
3126 size_t count = 0;
3127 rb_vm_t *vm = io->closing_ec->thread_ptr->vm;
3128 VALUE error = vm->special_exceptions[ruby_error_stream_closed];
3129
3130 struct rb_io_blocking_operation *blocking_operation;
3131 ccan_list_for_each(rb_io_blocking_operations(io), blocking_operation, list) {
3132 rb_execution_context_t *ec = blocking_operation->ec;
3133
3134 // If the operation is in progress, we need to interrupt it:
3135 if (ec) {
3136 rb_thread_t *thread = ec->thread_ptr;
3137
3138 if (thread->scheduler != Qnil) {
3139 VALUE target = blocking_operation->scheduler_interrupt_target;
3140
3141 if (NIL_P(target)) {
3142 VALUE fiber = rb_fiberptr_self(ec->fiber_ptr);
3143 target = rb_fiber_scheduler_interrupt_target_new(fiber, error);
3144 blocking_operation->scheduler_interrupt_target = target;
3145 }
3146
3147 rb_fiber_scheduler_fiber_interrupt(thread->scheduler, target, error);
3148 RB_GC_GUARD(target);
3149 }
3150 else {
3151 // If the thread is not the current thread, we need to enqueue an error:
3152 rb_threadptr_pending_interrupt_enque(thread, error);
3153 rb_threadptr_interrupt(thread);
3154 }
3155 }
3156
3157 count += 1;
3158 }
3159
3160 return (VALUE)count;
3161}
3162
3163size_t
3164rb_thread_io_close_interrupt(struct rb_io *io)
3165{
3166 // We guard this operation based on `io->closing_ec` -> only one thread will ever enter this function.
3167 if (io->closing_ec) {
3168 return 0;
3169 }
3170
3171 // If there are no blocking operations, we are done:
3172 if (ccan_list_empty(rb_io_blocking_operations(io))) {
3173 return 0;
3174 }
3175
3176 // Otherwise, we are now closing the IO:
3177 rb_execution_context_t *ec = GET_EC();
3178 io->closing_ec = ec;
3179
3180 // This is used to ensure the correct execution context is woken up after the blocking operation is interrupted:
3181 io->wakeup_mutex = rb_mutex_new();
3182 rb_mutex_allow_trap(io->wakeup_mutex, 1);
3183
3184 // We need to use a mutex here as entering the fiber scheduler may cause a context switch:
3185 VALUE result = rb_mutex_synchronize(io->wakeup_mutex, thread_io_close_notify_all, (VALUE)io);
3186
3187 return (size_t)result;
3188}
3189
3190void
3191rb_thread_io_close_wait(struct rb_io* io)
3192{
3193 VALUE wakeup_mutex = io->wakeup_mutex;
3194
3195 if (!RB_TEST(wakeup_mutex)) {
3196 // There was nobody else using this file when we closed it, so we never bothered to allocate a mutex:
3197 return;
3198 }
3199
3200 rb_mutex_lock(wakeup_mutex);
3201 while (!ccan_list_empty(rb_io_blocking_operations(io))) {
3202 rb_mutex_sleep(wakeup_mutex, Qnil);
3203 }
3204 rb_mutex_unlock(wakeup_mutex);
3205
3206 // We are done closing:
3207 io->wakeup_mutex = Qnil;
3208 io->closing_ec = NULL;
3209}
3210
3211void
3212rb_thread_fd_close(int fd)
3213{
3214 rb_warn("rb_thread_fd_close is deprecated (and is now a no-op).");
3215}
3216
3217/*
3218 * call-seq:
3219 * raise(exception, message = exception.to_s, backtrace = nil, cause: $!)
3220 * raise(message = nil, cause: $!)
3221 *
3222 * Raises an exception from the given thread. The caller does not have to be
3223 * +thr+. See Kernel#raise for more information on arguments.
3224 *
3225 * Thread.abort_on_exception = true
3226 * a = Thread.new { sleep(200) }
3227 * a.raise("Gotcha")
3228 *
3229 * This will produce:
3230 *
3231 * prog.rb:3: Gotcha (RuntimeError)
3232 * from prog.rb:2:in `initialize'
3233 * from prog.rb:2:in `new'
3234 * from prog.rb:2
3235 */
3236
3237static VALUE
3238thread_raise_m(int argc, VALUE *argv, VALUE self)
3239{
3240 rb_thread_t *target_th = rb_thread_ptr(self);
3241 const rb_thread_t *current_th = GET_THREAD();
3242
3243 threadptr_check_pending_interrupt_queue(target_th);
3244
3245 if (rb_threadptr_dead(target_th)) {
3246 return Qnil;
3247 }
3248
3249 VALUE exception = rb_exception_setup(argc, argv);
3250 rb_threadptr_pending_interrupt_enque(target_th, exception);
3251 rb_threadptr_interrupt(target_th);
3252
3253 /* To perform Thread.current.raise as Kernel.raise */
3254 if (current_th == target_th) {
3255 RUBY_VM_CHECK_INTS(target_th->ec);
3256 }
3257 return Qnil;
3258}
3259
3260
3261/*
3262 * call-seq:
3263 * thr.exit -> thr
3264 * thr.kill -> thr
3265 * thr.terminate -> thr
3266 *
3267 * Terminates +thr+ and schedules another thread to be run, returning
3268 * the terminated Thread. If this is the main thread, or the last
3269 * thread, exits the process. Note that the caller does not wait for
3270 * the thread to terminate if the receiver is different from the currently
3271 * running thread. The termination is asynchronous, and the thread can still
3272 * run a small amount of ruby code before exiting.
3273 */
3274
3276rb_thread_kill(VALUE thread)
3277{
3278 rb_thread_t *target_th = rb_thread_ptr(thread);
3279
3280 if (target_th->to_kill || target_th->status == THREAD_KILLED) {
3281 return thread;
3282 }
3283 if (target_th == target_th->vm->ractor.main_thread) {
3284 rb_exit(EXIT_SUCCESS);
3285 }
3286
3287 RUBY_DEBUG_LOG("target_th:%u", rb_th_serial(target_th));
3288
3289 if (target_th == GET_THREAD()) {
3290 /* kill myself immediately */
3291 rb_threadptr_to_kill(target_th);
3292 }
3293 else {
3294 threadptr_check_pending_interrupt_queue(target_th);
3295 rb_threadptr_pending_interrupt_enque(target_th, RUBY_FATAL_THREAD_KILLED);
3296 rb_threadptr_interrupt(target_th);
3297 }
3298
3299 return thread;
3300}
3301
3302int
3303rb_thread_to_be_killed(VALUE thread)
3304{
3305 rb_thread_t *target_th = rb_thread_ptr(thread);
3306
3307 if (target_th->to_kill || target_th->status == THREAD_KILLED) {
3308 return TRUE;
3309 }
3310 return FALSE;
3311}
3312
3313/*
3314 * call-seq:
3315 * Thread.kill(thread) -> thread
3316 *
3317 * Causes the given +thread+ to exit, see also Thread::exit.
3318 *
3319 * count = 0
3320 * a = Thread.new { loop { count += 1 } }
3321 * sleep(0.1) #=> 0
3322 * Thread.kill(a) #=> #<Thread:0x401b3d30 dead>
3323 * count #=> 93947
3324 * a.alive? #=> false
3325 */
3326
3327static VALUE
3328rb_thread_s_kill(VALUE obj, VALUE th)
3329{
3330 return rb_thread_kill(th);
3331}
3332
3333
3334/*
3335 * call-seq:
3336 * Thread.exit -> thread
3337 *
3338 * Terminates the currently running thread and schedules another thread to be
3339 * run.
3340 *
3341 * If this thread is already marked to be killed, ::exit returns the Thread.
3342 *
3343 * If this is the main thread, or the last thread, exit the process.
3344 */
3345
3346static VALUE
3347rb_thread_exit(VALUE _)
3348{
3349 rb_thread_t *th = GET_THREAD();
3350 return rb_thread_kill(th->self);
3351}
3352
3353
3354/*
3355 * call-seq:
3356 * thr.wakeup -> thr
3357 *
3358 * Marks a given thread as eligible for scheduling, however it may still
3359 * remain blocked on I/O.
3360 *
3361 * *Note:* This does not invoke the scheduler, see #run for more information.
3362 *
3363 * c = Thread.new { Thread.stop; puts "hey!" }
3364 * sleep 0.1 while c.status!='sleep'
3365 * c.wakeup
3366 * c.join
3367 * #=> "hey!"
3368 */
3369
3371rb_thread_wakeup(VALUE thread)
3372{
3373 if (!RTEST(rb_thread_wakeup_alive(thread))) {
3374 rb_raise(rb_eThreadError, "killed thread");
3375 }
3376 return thread;
3377}
3378
3381{
3382 rb_thread_t *target_th = rb_thread_ptr(thread);
3383 if (target_th->status == THREAD_KILLED) return Qnil;
3384
3385 rb_threadptr_ready(target_th);
3386
3387 if (target_th->status == THREAD_STOPPED ||
3388 target_th->status == THREAD_STOPPED_FOREVER) {
3389 target_th->status = THREAD_RUNNABLE;
3390 }
3391
3392 return thread;
3393}
3394
3395
3396/*
3397 * call-seq:
3398 * thr.run -> thr
3399 *
3400 * Wakes up +thr+, making it eligible for scheduling.
3401 *
3402 * a = Thread.new { puts "a"; Thread.stop; puts "c" }
3403 * sleep 0.1 while a.status!='sleep'
3404 * puts "Got here"
3405 * a.run
3406 * a.join
3407 *
3408 * This will produce:
3409 *
3410 * a
3411 * Got here
3412 * c
3413 *
3414 * See also the instance method #wakeup.
3415 */
3416
3418rb_thread_run(VALUE thread)
3419{
3420 rb_thread_wakeup(thread);
3422 return thread;
3423}
3424
3425
3427rb_thread_stop(void)
3428{
3429 if (rb_thread_alone()) {
3430 rb_raise(rb_eThreadError,
3431 "stopping only thread\n\tnote: use sleep to stop forever");
3432 }
3434 return Qnil;
3435}
3436
3437/*
3438 * call-seq:
3439 * Thread.stop -> nil
3440 *
3441 * Stops execution of the current thread, putting it into a ``sleep'' state,
3442 * and schedules execution of another thread.
3443 *
3444 * a = Thread.new { print "a"; Thread.stop; print "c" }
3445 * sleep 0.1 while a.status!='sleep'
3446 * print "b"
3447 * a.run
3448 * a.join
3449 * #=> "abc"
3450 */
3451
3452static VALUE
3453thread_stop(VALUE _)
3454{
3455 return rb_thread_stop();
3456}
3457
3458/********************************************************************/
3459
3460VALUE
3461rb_thread_list(void)
3462{
3463 // TODO
3464 return rb_ractor_thread_list();
3465}
3466
3467/*
3468 * call-seq:
3469 * Thread.list -> array
3470 *
3471 * Returns an array of Thread objects for all threads that are either runnable
3472 * or stopped.
3473 *
3474 * Thread.new { sleep(200) }
3475 * Thread.new { 1000000.times {|i| i*i } }
3476 * Thread.new { Thread.stop }
3477 * Thread.list.each {|t| p t}
3478 *
3479 * This will produce:
3480 *
3481 * #<Thread:0x401b3e84 sleep>
3482 * #<Thread:0x401b3f38 run>
3483 * #<Thread:0x401b3fb0 sleep>
3484 * #<Thread:0x401bdf4c run>
3485 */
3486
3487static VALUE
3488thread_list(VALUE _)
3489{
3490 return rb_thread_list();
3491}
3492
3495{
3496 return GET_THREAD()->self;
3497}
3498
3499/*
3500 * call-seq:
3501 * Thread.current -> thread
3502 *
3503 * Returns the currently executing thread.
3504 *
3505 * Thread.current #=> #<Thread:0x401bdf4c run>
3506 */
3507
3508static VALUE
3509thread_s_current(VALUE klass)
3510{
3511 return rb_thread_current();
3512}
3513
3515rb_thread_main(void)
3516{
3517 return GET_RACTOR()->threads.main->self;
3518}
3519
3520/*
3521 * call-seq:
3522 * Thread.main -> thread
3523 *
3524 * Returns the main thread.
3525 */
3526
3527static VALUE
3528rb_thread_s_main(VALUE klass)
3529{
3530 return rb_thread_main();
3531}
3532
3533
3534/*
3535 * call-seq:
3536 * Thread.abort_on_exception -> true or false
3537 *
3538 * Returns the status of the global ``abort on exception'' condition.
3539 *
3540 * The default is +false+.
3541 *
3542 * When set to +true+, if any thread is aborted by an exception, the
3543 * raised exception will be re-raised in the main thread.
3544 *
3545 * Can also be specified by the global $DEBUG flag or command line option
3546 * +-d+.
3547 *
3548 * See also ::abort_on_exception=.
3549 *
3550 * There is also an instance level method to set this for a specific thread,
3551 * see #abort_on_exception.
3552 */
3553
3554static VALUE
3555rb_thread_s_abort_exc(VALUE _)
3556{
3557 return RBOOL(GET_THREAD()->vm->thread_abort_on_exception);
3558}
3559
3560
3561/*
3562 * call-seq:
3563 * Thread.abort_on_exception= boolean -> true or false
3564 *
3565 * When set to +true+, if any thread is aborted by an exception, the
3566 * raised exception will be re-raised in the main thread.
3567 * Returns the new state.
3568 *
3569 * Thread.abort_on_exception = true
3570 * t1 = Thread.new do
3571 * puts "In new thread"
3572 * raise "Exception from thread"
3573 * end
3574 * sleep(1)
3575 * puts "not reached"
3576 *
3577 * This will produce:
3578 *
3579 * In new thread
3580 * prog.rb:4: Exception from thread (RuntimeError)
3581 * from prog.rb:2:in `initialize'
3582 * from prog.rb:2:in `new'
3583 * from prog.rb:2
3584 *
3585 * See also ::abort_on_exception.
3586 *
3587 * There is also an instance level method to set this for a specific thread,
3588 * see #abort_on_exception=.
3589 */
3590
3591static VALUE
3592rb_thread_s_abort_exc_set(VALUE self, VALUE val)
3593{
3594 GET_THREAD()->vm->thread_abort_on_exception = RTEST(val);
3595 return val;
3596}
3597
3598
3599/*
3600 * call-seq:
3601 * thr.abort_on_exception -> true or false
3602 *
3603 * Returns the status of the thread-local ``abort on exception'' condition for
3604 * this +thr+.
3605 *
3606 * The default is +false+.
3607 *
3608 * See also #abort_on_exception=.
3609 *
3610 * There is also a class level method to set this for all threads, see
3611 * ::abort_on_exception.
3612 */
3613
3614static VALUE
3615rb_thread_abort_exc(VALUE thread)
3616{
3617 return RBOOL(rb_thread_ptr(thread)->abort_on_exception);
3618}
3619
3620
3621/*
3622 * call-seq:
3623 * thr.abort_on_exception= boolean -> true or false
3624 *
3625 * When set to +true+, if this +thr+ is aborted by an exception, the
3626 * raised exception will be re-raised in the main thread.
3627 *
3628 * See also #abort_on_exception.
3629 *
3630 * There is also a class level method to set this for all threads, see
3631 * ::abort_on_exception=.
3632 */
3633
3634static VALUE
3635rb_thread_abort_exc_set(VALUE thread, VALUE val)
3636{
3637 rb_thread_ptr(thread)->abort_on_exception = RTEST(val);
3638 return val;
3639}
3640
3641
3642/*
3643 * call-seq:
3644 * Thread.report_on_exception -> true or false
3645 *
3646 * Returns the status of the global ``report on exception'' condition.
3647 *
3648 * The default is +true+ since Ruby 2.5.
3649 *
3650 * All threads created when this flag is true will report
3651 * a message on $stderr if an exception kills the thread.
3652 *
3653 * Thread.new { 1.times { raise } }
3654 *
3655 * will produce this output on $stderr:
3656 *
3657 * #<Thread:...> terminated with exception (report_on_exception is true):
3658 * Traceback (most recent call last):
3659 * 2: from -e:1:in `block in <main>'
3660 * 1: from -e:1:in `times'
3661 *
3662 * This is done to catch errors in threads early.
3663 * In some cases, you might not want this output.
3664 * There are multiple ways to avoid the extra output:
3665 *
3666 * * If the exception is not intended, the best is to fix the cause of
3667 * the exception so it does not happen anymore.
3668 * * If the exception is intended, it might be better to rescue it closer to
3669 * where it is raised rather then let it kill the Thread.
3670 * * If it is guaranteed the Thread will be joined with Thread#join or
3671 * Thread#value, then it is safe to disable this report with
3672 * <code>Thread.current.report_on_exception = false</code>
3673 * when starting the Thread.
3674 * However, this might handle the exception much later, or not at all
3675 * if the Thread is never joined due to the parent thread being blocked, etc.
3676 *
3677 * See also ::report_on_exception=.
3678 *
3679 * There is also an instance level method to set this for a specific thread,
3680 * see #report_on_exception=.
3681 *
3682 */
3683
3684static VALUE
3685rb_thread_s_report_exc(VALUE _)
3686{
3687 return RBOOL(GET_THREAD()->vm->thread_report_on_exception);
3688}
3689
3690
3691/*
3692 * call-seq:
3693 * Thread.report_on_exception= boolean -> true or false
3694 *
3695 * Returns the new state.
3696 * When set to +true+, all threads created afterwards will inherit the
3697 * condition and report a message on $stderr if an exception kills a thread:
3698 *
3699 * Thread.report_on_exception = true
3700 * t1 = Thread.new do
3701 * puts "In new thread"
3702 * raise "Exception from thread"
3703 * end
3704 * sleep(1)
3705 * puts "In the main thread"
3706 *
3707 * This will produce:
3708 *
3709 * In new thread
3710 * #<Thread:...prog.rb:2> terminated with exception (report_on_exception is true):
3711 * Traceback (most recent call last):
3712 * prog.rb:4:in `block in <main>': Exception from thread (RuntimeError)
3713 * In the main thread
3714 *
3715 * See also ::report_on_exception.
3716 *
3717 * There is also an instance level method to set this for a specific thread,
3718 * see #report_on_exception=.
3719 */
3720
3721static VALUE
3722rb_thread_s_report_exc_set(VALUE self, VALUE val)
3723{
3724 GET_THREAD()->vm->thread_report_on_exception = RTEST(val);
3725 return val;
3726}
3727
3728
3729/*
3730 * call-seq:
3731 * Thread.ignore_deadlock -> true or false
3732 *
3733 * Returns the status of the global ``ignore deadlock'' condition.
3734 * The default is +false+, so that deadlock conditions are not ignored.
3735 *
3736 * See also ::ignore_deadlock=.
3737 *
3738 */
3739
3740static VALUE
3741rb_thread_s_ignore_deadlock(VALUE _)
3742{
3743 return RBOOL(GET_THREAD()->vm->thread_ignore_deadlock);
3744}
3745
3746
3747/*
3748 * call-seq:
3749 * Thread.ignore_deadlock = boolean -> true or false
3750 *
3751 * Returns the new state.
3752 * When set to +true+, the VM will not check for deadlock conditions.
3753 * It is only useful to set this if your application can break a
3754 * deadlock condition via some other means, such as a signal.
3755 *
3756 * Thread.ignore_deadlock = true
3757 * queue = Thread::Queue.new
3758 *
3759 * trap(:SIGUSR1){queue.push "Received signal"}
3760 *
3761 * # raises fatal error unless ignoring deadlock
3762 * puts queue.pop
3763 *
3764 * See also ::ignore_deadlock.
3765 */
3766
3767static VALUE
3768rb_thread_s_ignore_deadlock_set(VALUE self, VALUE val)
3769{
3770 GET_THREAD()->vm->thread_ignore_deadlock = RTEST(val);
3771 return val;
3772}
3773
3774
3775/*
3776 * call-seq:
3777 * thr.report_on_exception -> true or false
3778 *
3779 * Returns the status of the thread-local ``report on exception'' condition for
3780 * this +thr+.
3781 *
3782 * The default value when creating a Thread is the value of
3783 * the global flag Thread.report_on_exception.
3784 *
3785 * See also #report_on_exception=.
3786 *
3787 * There is also a class level method to set this for all new threads, see
3788 * ::report_on_exception=.
3789 */
3790
3791static VALUE
3792rb_thread_report_exc(VALUE thread)
3793{
3794 return RBOOL(rb_thread_ptr(thread)->report_on_exception);
3795}
3796
3797
3798/*
3799 * call-seq:
3800 * thr.report_on_exception= boolean -> true or false
3801 *
3802 * When set to +true+, a message is printed on $stderr if an exception
3803 * kills this +thr+. See ::report_on_exception for details.
3804 *
3805 * See also #report_on_exception.
3806 *
3807 * There is also a class level method to set this for all new threads, see
3808 * ::report_on_exception=.
3809 */
3810
3811static VALUE
3812rb_thread_report_exc_set(VALUE thread, VALUE val)
3813{
3814 rb_thread_ptr(thread)->report_on_exception = RTEST(val);
3815 return val;
3816}
3817
3818
3819/*
3820 * call-seq:
3821 * thr.group -> thgrp or nil
3822 *
3823 * Returns the ThreadGroup which contains the given thread.
3824 *
3825 * Thread.main.group #=> #<ThreadGroup:0x4029d914>
3826 */
3827
3828VALUE
3829rb_thread_group(VALUE thread)
3830{
3831 return rb_thread_ptr(thread)->thgroup;
3832}
3833
3834static const char *
3835thread_status_name(rb_thread_t *th, int detail)
3836{
3837 switch (th->status) {
3838 case THREAD_RUNNABLE:
3839 return th->to_kill ? "aborting" : "run";
3840 case THREAD_STOPPED_FOREVER:
3841 if (detail) return "sleep_forever";
3842 case THREAD_STOPPED:
3843 return "sleep";
3844 case THREAD_KILLED:
3845 return "dead";
3846 default:
3847 return "unknown";
3848 }
3849}
3850
3851static int
3852rb_threadptr_dead(rb_thread_t *th)
3853{
3854 return th->status == THREAD_KILLED;
3855}
3856
3857
3858/*
3859 * call-seq:
3860 * thr.status -> string, false or nil
3861 *
3862 * Returns the status of +thr+.
3863 *
3864 * [<tt>"sleep"</tt>]
3865 * Returned if this thread is sleeping or waiting on I/O
3866 * [<tt>"run"</tt>]
3867 * When this thread is executing
3868 * [<tt>"aborting"</tt>]
3869 * If this thread is aborting
3870 * [+false+]
3871 * When this thread is terminated normally
3872 * [+nil+]
3873 * If terminated with an exception.
3874 *
3875 * a = Thread.new { raise("die now") }
3876 * b = Thread.new { Thread.stop }
3877 * c = Thread.new { Thread.exit }
3878 * d = Thread.new { sleep }
3879 * d.kill #=> #<Thread:0x401b3678 aborting>
3880 * a.status #=> nil
3881 * b.status #=> "sleep"
3882 * c.status #=> false
3883 * d.status #=> "aborting"
3884 * Thread.current.status #=> "run"
3885 *
3886 * See also the instance methods #alive? and #stop?
3887 */
3888
3889static VALUE
3890rb_thread_status(VALUE thread)
3891{
3892 rb_thread_t *target_th = rb_thread_ptr(thread);
3893
3894 if (rb_threadptr_dead(target_th)) {
3895 if (!NIL_P(target_th->ec->errinfo) &&
3896 !FIXNUM_P(target_th->ec->errinfo)) {
3897 return Qnil;
3898 }
3899 else {
3900 return Qfalse;
3901 }
3902 }
3903 else {
3904 return rb_str_new2(thread_status_name(target_th, FALSE));
3905 }
3906}
3907
3908
3909/*
3910 * call-seq:
3911 * thr.alive? -> true or false
3912 *
3913 * Returns +true+ if +thr+ is running or sleeping.
3914 *
3915 * thr = Thread.new { }
3916 * thr.join #=> #<Thread:0x401b3fb0 dead>
3917 * Thread.current.alive? #=> true
3918 * thr.alive? #=> false
3919 *
3920 * See also #stop? and #status.
3921 */
3922
3923static VALUE
3924rb_thread_alive_p(VALUE thread)
3925{
3926 return RBOOL(!thread_finished(rb_thread_ptr(thread)));
3927}
3928
3929/*
3930 * call-seq:
3931 * thr.stop? -> true or false
3932 *
3933 * Returns +true+ if +thr+ is dead or sleeping.
3934 *
3935 * a = Thread.new { Thread.stop }
3936 * b = Thread.current
3937 * a.stop? #=> true
3938 * b.stop? #=> false
3939 *
3940 * See also #alive? and #status.
3941 */
3942
3943static VALUE
3944rb_thread_stop_p(VALUE thread)
3945{
3946 rb_thread_t *th = rb_thread_ptr(thread);
3947
3948 if (rb_threadptr_dead(th)) {
3949 return Qtrue;
3950 }
3951 return RBOOL(th->status == THREAD_STOPPED || th->status == THREAD_STOPPED_FOREVER);
3952}
3953
3954/*
3955 * call-seq:
3956 * thr.name -> string
3957 *
3958 * show the name of the thread.
3959 */
3960
3961static VALUE
3962rb_thread_getname(VALUE thread)
3963{
3964 return rb_thread_ptr(thread)->name;
3965}
3966
3967/*
3968 * call-seq:
3969 * thr.name=(name) -> string
3970 *
3971 * set given name to the ruby thread.
3972 * On some platform, it may set the name to pthread and/or kernel.
3973 */
3974
3975static VALUE
3976rb_thread_setname(VALUE thread, VALUE name)
3977{
3978 rb_thread_t *target_th = rb_thread_ptr(thread);
3979
3980 if (!NIL_P(name)) {
3981 rb_encoding *enc;
3982 StringValueCStr(name);
3983 enc = rb_enc_get(name);
3984 if (!rb_enc_asciicompat(enc)) {
3985 rb_raise(rb_eArgError, "ASCII incompatible encoding (%s)",
3986 rb_enc_name(enc));
3987 }
3988 name = rb_str_new_frozen(name);
3989 }
3990 target_th->name = name;
3991 if (threadptr_initialized(target_th) && target_th->has_dedicated_nt &&
3992 target_th->status != THREAD_KILLED) {
3993 native_set_another_thread_name(ACCESS_ONCE(rb_nativethread_id_t, target_th->nt->thread_id), name);
3994 }
3995 return name;
3996}
3997
3998#if USE_NATIVE_THREAD_NATIVE_THREAD_ID
3999/*
4000 * call-seq:
4001 * thr.native_thread_id -> integer
4002 *
4003 * Return the native thread ID which is used by the Ruby thread.
4004 *
4005 * The ID depends on the OS. (not POSIX thread ID returned by pthread_self(3))
4006 * * On Linux it is TID returned by gettid(2).
4007 * * On macOS it is the system-wide unique integral ID of thread returned
4008 * by pthread_threadid_np(3).
4009 * * On FreeBSD it is the unique integral ID of the thread returned by
4010 * pthread_getthreadid_np(3).
4011 * * On Windows it is the thread identifier returned by GetThreadId().
4012 * * On other platforms, it raises NotImplementedError.
4013 *
4014 * NOTE:
4015 * If the thread is not associated yet or already deassociated with a native
4016 * thread, it returns _nil_.
4017 * If the Ruby implementation uses M:N thread model, the ID may change
4018 * depending on the timing.
4019 */
4020
4021static VALUE
4022rb_thread_native_thread_id(VALUE thread)
4023{
4024 rb_thread_t *target_th = rb_thread_ptr(thread);
4025 if (rb_threadptr_dead(target_th)) return Qnil;
4026 return native_thread_native_thread_id(target_th);
4027}
4028#else
4029# define rb_thread_native_thread_id rb_f_notimplement
4030#endif
4031
4032/*
4033 * call-seq:
4034 * thr.to_s -> string
4035 *
4036 * Dump the name, id, and status of _thr_ to a string.
4037 */
4038
4039static VALUE
4040rb_thread_to_s(VALUE thread)
4041{
4042 VALUE cname = rb_class_path(rb_obj_class(thread));
4043 rb_thread_t *target_th = rb_thread_ptr(thread);
4044 const char *status;
4045 VALUE str, loc;
4046
4047 status = thread_status_name(target_th, TRUE);
4048 str = rb_sprintf("#<%"PRIsVALUE":%p", cname, (void *)thread);
4049 if (!NIL_P(target_th->name)) {
4050 rb_str_catf(str, "@%"PRIsVALUE, target_th->name);
4051 }
4052 if ((loc = threadptr_invoke_proc_location(target_th)) != Qnil) {
4053 rb_str_catf(str, " %"PRIsVALUE":%"PRIsVALUE,
4054 RARRAY_AREF(loc, 0), RARRAY_AREF(loc, 1));
4055 }
4056 rb_str_catf(str, " %s>", status);
4057
4058 return str;
4059}
4060
4061/* variables for recursive traversals */
4062#define recursive_key id__recursive_key__
4063
4064static VALUE
4065threadptr_local_aref(rb_thread_t *th, ID id)
4066{
4067 if (id == recursive_key) {
4068 return th->ec->local_storage_recursive_hash;
4069 }
4070 else {
4071 VALUE val;
4072 struct rb_id_table *local_storage = th->ec->local_storage;
4073
4074 if (local_storage != NULL && rb_id_table_lookup(local_storage, id, &val)) {
4075 return val;
4076 }
4077 else {
4078 return Qnil;
4079 }
4080 }
4081}
4082
4084rb_thread_local_aref(VALUE thread, ID id)
4085{
4086 return threadptr_local_aref(rb_thread_ptr(thread), id);
4087}
4088
4089/*
4090 * call-seq:
4091 * thr[sym] -> obj or nil
4092 *
4093 * Attribute Reference---Returns the value of a fiber-local variable (current thread's root fiber
4094 * if not explicitly inside a Fiber), using either a symbol or a string name.
4095 * If the specified variable does not exist, returns +nil+.
4096 *
4097 * [
4098 * Thread.new { Thread.current["name"] = "A" },
4099 * Thread.new { Thread.current[:name] = "B" },
4100 * Thread.new { Thread.current["name"] = "C" }
4101 * ].each do |th|
4102 * th.join
4103 * puts "#{th.inspect}: #{th[:name]}"
4104 * end
4105 *
4106 * This will produce:
4107 *
4108 * #<Thread:0x00000002a54220 dead>: A
4109 * #<Thread:0x00000002a541a8 dead>: B
4110 * #<Thread:0x00000002a54130 dead>: C
4111 *
4112 * Thread#[] and Thread#[]= are not thread-local but fiber-local.
4113 * This confusion did not exist in Ruby 1.8 because
4114 * fibers are only available since Ruby 1.9.
4115 * Ruby 1.9 chooses that the methods behaves fiber-local to save
4116 * following idiom for dynamic scope.
4117 *
4118 * def meth(newvalue)
4119 * begin
4120 * oldvalue = Thread.current[:name]
4121 * Thread.current[:name] = newvalue
4122 * yield
4123 * ensure
4124 * Thread.current[:name] = oldvalue
4125 * end
4126 * end
4127 *
4128 * The idiom may not work as dynamic scope if the methods are thread-local
4129 * and a given block switches fiber.
4130 *
4131 * f = Fiber.new {
4132 * meth(1) {
4133 * Fiber.yield
4134 * }
4135 * }
4136 * meth(2) {
4137 * f.resume
4138 * }
4139 * f.resume
4140 * p Thread.current[:name]
4141 * #=> nil if fiber-local
4142 * #=> 2 if thread-local (The value 2 is leaked to outside of meth method.)
4143 *
4144 * For thread-local variables, please see #thread_variable_get and
4145 * #thread_variable_set.
4146 *
4147 */
4148
4149static VALUE
4150rb_thread_aref(VALUE thread, VALUE key)
4151{
4152 ID id = rb_check_id(&key);
4153 if (!id) return Qnil;
4154 return rb_thread_local_aref(thread, id);
4155}
4156
4157/*
4158 * call-seq:
4159 * thr.fetch(sym) -> obj
4160 * thr.fetch(sym) { } -> obj
4161 * thr.fetch(sym, default) -> obj
4162 *
4163 * Returns a fiber-local for the given key. If the key can't be
4164 * found, there are several options: With no other arguments, it will
4165 * raise a KeyError exception; if <i>default</i> is given, then that
4166 * will be returned; if the optional code block is specified, then
4167 * that will be run and its result returned. See Thread#[] and
4168 * Hash#fetch.
4169 */
4170static VALUE
4171rb_thread_fetch(int argc, VALUE *argv, VALUE self)
4172{
4173 VALUE key, val;
4174 ID id;
4175 rb_thread_t *target_th = rb_thread_ptr(self);
4176 int block_given;
4177
4178 rb_check_arity(argc, 1, 2);
4179 key = argv[0];
4180
4181 block_given = rb_block_given_p();
4182 if (block_given && argc == 2) {
4183 rb_warn("block supersedes default value argument");
4184 }
4185
4186 id = rb_check_id(&key);
4187
4188 if (id == recursive_key) {
4189 return target_th->ec->local_storage_recursive_hash;
4190 }
4191 else if (id && target_th->ec->local_storage &&
4192 rb_id_table_lookup(target_th->ec->local_storage, id, &val)) {
4193 return val;
4194 }
4195 else if (block_given) {
4196 return rb_yield(key);
4197 }
4198 else if (argc == 1) {
4199 rb_key_err_raise(rb_sprintf("key not found: %+"PRIsVALUE, key), self, key);
4200 }
4201 else {
4202 return argv[1];
4203 }
4204}
4205
4206static VALUE
4207threadptr_local_aset(rb_thread_t *th, ID id, VALUE val)
4208{
4209 if (id == recursive_key) {
4210 th->ec->local_storage_recursive_hash = val;
4211 return val;
4212 }
4213 else {
4214 struct rb_id_table *local_storage = th->ec->local_storage;
4215
4216 if (NIL_P(val)) {
4217 if (!local_storage) return Qnil;
4218 rb_id_table_delete(local_storage, id);
4219 return Qnil;
4220 }
4221 else {
4222 if (local_storage == NULL) {
4223 th->ec->local_storage = local_storage = rb_id_table_create(0);
4224 }
4225 rb_id_table_insert(local_storage, id, val);
4226 return val;
4227 }
4228 }
4229}
4230
4232rb_thread_local_aset(VALUE thread, ID id, VALUE val)
4233{
4234 if (OBJ_FROZEN(thread)) {
4235 rb_frozen_error_raise(thread, "can't modify frozen thread locals");
4236 }
4237
4238 return threadptr_local_aset(rb_thread_ptr(thread), id, val);
4239}
4240
4241/*
4242 * call-seq:
4243 * thr[sym] = obj -> obj
4244 *
4245 * Attribute Assignment---Sets or creates the value of a fiber-local variable,
4246 * using either a symbol or a string.
4247 * Assigning +nil+ deletes the variable.
4248 *
4249 * See also Thread#[].
4250 *
4251 * For thread-local variables, please see #thread_variable_set and
4252 * #thread_variable_get.
4253 */
4254
4255static VALUE
4256rb_thread_aset(VALUE self, VALUE id, VALUE val)
4257{
4258 return rb_thread_local_aset(self, rb_to_id(id), val);
4259}
4260
4261/*
4262 * call-seq:
4263 * thr.thread_variable_get(key) -> obj or nil
4264 *
4265 * Returns the value of a thread local variable that has been set. Note that
4266 * these are different than fiber local values. For fiber local values,
4267 * please see Thread#[] and Thread#[]=.
4268 *
4269 * Thread local values are carried along with threads, and do not respect
4270 * fibers. For example:
4271 *
4272 * Thread.new {
4273 * Thread.current.thread_variable_set("foo", "bar") # set a thread local
4274 * Thread.current["foo"] = "bar" # set a fiber local
4275 *
4276 * Fiber.new {
4277 * Fiber.yield [
4278 * Thread.current.thread_variable_get("foo"), # get the thread local
4279 * Thread.current["foo"], # get the fiber local
4280 * ]
4281 * }.resume
4282 * }.join.value # => ['bar', nil]
4283 *
4284 * The value "bar" is returned for the thread local, where nil is returned
4285 * for the fiber local. The fiber is executed in the same thread, so the
4286 * thread local values are available.
4287 */
4288
4289static VALUE
4290rb_thread_variable_get(VALUE thread, VALUE key)
4291{
4292 VALUE locals;
4293 VALUE symbol = rb_to_symbol(key);
4294
4295 if (LIKELY(!THREAD_LOCAL_STORAGE_INITIALISED_P(thread))) {
4296 return Qnil;
4297 }
4298 locals = rb_thread_local_storage(thread);
4299 return rb_hash_aref(locals, symbol);
4300}
4301
4302/*
4303 * call-seq:
4304 * thr.thread_variable_set(key, value)
4305 *
4306 * Sets a thread local with +key+ to +value+. Note that these are local to
4307 * threads, and not to fibers. Please see Thread#thread_variable_get and
4308 * Thread#[] for more information.
4309 * Assigning +nil+ deletes the variable.
4310 */
4311
4312static VALUE
4313rb_thread_variable_set(VALUE thread, VALUE key, VALUE val)
4314{
4315 VALUE locals;
4316 VALUE symbol;
4317
4318 if (OBJ_FROZEN(thread)) {
4319 rb_frozen_error_raise(thread, "can't modify frozen thread locals");
4320 }
4321
4322 symbol = rb_to_symbol(key);
4323
4324 if (NIL_P(val)) {
4325 if (LIKELY(!THREAD_LOCAL_STORAGE_INITIALISED_P(thread))) {
4326 return Qnil;
4327 }
4328
4329 locals = rb_thread_local_storage(thread);
4330 rb_hash_delete(locals, symbol);
4331 return Qnil;
4332 }
4333
4334 locals = rb_thread_local_storage(thread);
4335 return rb_hash_aset(locals, symbol, val);
4336}
4337
4338/*
4339 * call-seq:
4340 * thr.key?(sym) -> true or false
4341 *
4342 * Returns +true+ if the given string (or symbol) exists as a fiber-local
4343 * variable.
4344 *
4345 * me = Thread.current
4346 * me[:oliver] = "a"
4347 * me.key?(:oliver) #=> true
4348 * me.key?(:stanley) #=> false
4349 */
4350
4351static VALUE
4352rb_thread_key_p(VALUE self, VALUE key)
4353{
4354 VALUE val;
4355 ID id = rb_check_id(&key);
4356 struct rb_id_table *local_storage = rb_thread_ptr(self)->ec->local_storage;
4357
4358 if (!id || local_storage == NULL) {
4359 return Qfalse;
4360 }
4361 return RBOOL(rb_id_table_lookup(local_storage, id, &val));
4362}
4363
4364static enum rb_id_table_iterator_result
4365thread_keys_i(ID key, VALUE value, void *ary)
4366{
4367 rb_ary_push((VALUE)ary, ID2SYM(key));
4368 return ID_TABLE_CONTINUE;
4369}
4370
4372rb_thread_alone(void)
4373{
4374 // TODO
4375 return rb_ractor_living_thread_num(GET_RACTOR()) == 1;
4376}
4377
4378/*
4379 * call-seq:
4380 * thr.keys -> array
4381 *
4382 * Returns an array of the names of the fiber-local variables (as Symbols).
4383 *
4384 * thr = Thread.new do
4385 * Thread.current[:cat] = 'meow'
4386 * Thread.current["dog"] = 'woof'
4387 * end
4388 * thr.join #=> #<Thread:0x401b3f10 dead>
4389 * thr.keys #=> [:dog, :cat]
4390 */
4391
4392static VALUE
4393rb_thread_keys(VALUE self)
4394{
4395 struct rb_id_table *local_storage = rb_thread_ptr(self)->ec->local_storage;
4396 VALUE ary = rb_ary_new();
4397
4398 if (local_storage) {
4399 rb_id_table_foreach(local_storage, thread_keys_i, (void *)ary);
4400 }
4401 return ary;
4402}
4403
4404static int
4405keys_i(VALUE key, VALUE value, VALUE ary)
4406{
4407 rb_ary_push(ary, key);
4408 return ST_CONTINUE;
4409}
4410
4411/*
4412 * call-seq:
4413 * thr.thread_variables -> array
4414 *
4415 * Returns an array of the names of the thread-local variables (as Symbols).
4416 *
4417 * thr = Thread.new do
4418 * Thread.current.thread_variable_set(:cat, 'meow')
4419 * Thread.current.thread_variable_set("dog", 'woof')
4420 * end
4421 * thr.join #=> #<Thread:0x401b3f10 dead>
4422 * thr.thread_variables #=> [:dog, :cat]
4423 *
4424 * Note that these are not fiber local variables. Please see Thread#[] and
4425 * Thread#thread_variable_get for more details.
4426 */
4427
4428static VALUE
4429rb_thread_variables(VALUE thread)
4430{
4431 VALUE locals;
4432 VALUE ary;
4433
4434 ary = rb_ary_new();
4435 if (LIKELY(!THREAD_LOCAL_STORAGE_INITIALISED_P(thread))) {
4436 return ary;
4437 }
4438 locals = rb_thread_local_storage(thread);
4439 rb_hash_foreach(locals, keys_i, ary);
4440
4441 return ary;
4442}
4443
4444/*
4445 * call-seq:
4446 * thr.thread_variable?(key) -> true or false
4447 *
4448 * Returns +true+ if the given string (or symbol) exists as a thread-local
4449 * variable.
4450 *
4451 * me = Thread.current
4452 * me.thread_variable_set(:oliver, "a")
4453 * me.thread_variable?(:oliver) #=> true
4454 * me.thread_variable?(:stanley) #=> false
4455 *
4456 * Note that these are not fiber local variables. Please see Thread#[] and
4457 * Thread#thread_variable_get for more details.
4458 */
4459
4460static VALUE
4461rb_thread_variable_p(VALUE thread, VALUE key)
4462{
4463 VALUE locals;
4464 VALUE symbol = rb_to_symbol(key);
4465
4466 if (LIKELY(!THREAD_LOCAL_STORAGE_INITIALISED_P(thread))) {
4467 return Qfalse;
4468 }
4469 locals = rb_thread_local_storage(thread);
4470
4471 return RBOOL(rb_hash_lookup(locals, symbol) != Qnil);
4472}
4473
4474/*
4475 * call-seq:
4476 * thr.priority -> integer
4477 *
4478 * Returns the priority of <i>thr</i>. Default is inherited from the
4479 * current thread which creating the new thread, or zero for the
4480 * initial main thread; higher-priority thread will run more frequently
4481 * than lower-priority threads (but lower-priority threads can also run).
4482 *
4483 * This is just hint for Ruby thread scheduler. It may be ignored on some
4484 * platform.
4485 *
4486 * Thread.current.priority #=> 0
4487 */
4488
4489static VALUE
4490rb_thread_priority(VALUE thread)
4491{
4492 return INT2NUM(rb_thread_ptr(thread)->priority);
4493}
4494
4495
4496/*
4497 * call-seq:
4498 * thr.priority= integer -> thr
4499 *
4500 * Sets the priority of <i>thr</i> to <i>integer</i>. Higher-priority threads
4501 * will run more frequently than lower-priority threads (but lower-priority
4502 * threads can also run).
4503 *
4504 * This is just hint for Ruby thread scheduler. It may be ignored on some
4505 * platform.
4506 *
4507 * count1 = count2 = 0
4508 * a = Thread.new do
4509 * loop { count1 += 1 }
4510 * end
4511 * a.priority = -1
4512 *
4513 * b = Thread.new do
4514 * loop { count2 += 1 }
4515 * end
4516 * b.priority = -2
4517 * sleep 1 #=> 1
4518 * count1 #=> 622504
4519 * count2 #=> 5832
4520 */
4521
4522static VALUE
4523rb_thread_priority_set(VALUE thread, VALUE prio)
4524{
4525 rb_thread_t *target_th = rb_thread_ptr(thread);
4526 int priority;
4527
4528#if USE_NATIVE_THREAD_PRIORITY
4529 target_th->priority = NUM2INT(prio);
4530 native_thread_apply_priority(th);
4531#else
4532 priority = NUM2INT(prio);
4533 if (priority > RUBY_THREAD_PRIORITY_MAX) {
4534 priority = RUBY_THREAD_PRIORITY_MAX;
4535 }
4536 else if (priority < RUBY_THREAD_PRIORITY_MIN) {
4537 priority = RUBY_THREAD_PRIORITY_MIN;
4538 }
4539 target_th->priority = (int8_t)priority;
4540#endif
4541 return INT2NUM(target_th->priority);
4542}
4543
4544/* for IO */
4545
4546#if defined(NFDBITS) && defined(HAVE_RB_FD_INIT)
4547
4548/*
4549 * several Unix platforms support file descriptors bigger than FD_SETSIZE
4550 * in select(2) system call.
4551 *
4552 * - Linux 2.2.12 (?)
4553 * - NetBSD 1.2 (src/sys/kern/sys_generic.c:1.25)
4554 * select(2) documents how to allocate fd_set dynamically.
4555 * http://netbsd.gw.com/cgi-bin/man-cgi?select++NetBSD-4.0
4556 * - FreeBSD 2.2 (src/sys/kern/sys_generic.c:1.19)
4557 * - OpenBSD 2.0 (src/sys/kern/sys_generic.c:1.4)
4558 * select(2) documents how to allocate fd_set dynamically.
4559 * http://www.openbsd.org/cgi-bin/man.cgi?query=select&manpath=OpenBSD+4.4
4560 * - Solaris 8 has select_large_fdset
4561 * - Mac OS X 10.7 (Lion)
4562 * select(2) returns EINVAL if nfds is greater than FD_SET_SIZE and
4563 * _DARWIN_UNLIMITED_SELECT (or _DARWIN_C_SOURCE) isn't defined.
4564 * https://developer.apple.com/library/archive/releasenotes/Darwin/SymbolVariantsRelNotes/index.html
4565 *
4566 * When fd_set is not big enough to hold big file descriptors,
4567 * it should be allocated dynamically.
4568 * Note that this assumes fd_set is structured as bitmap.
4569 *
4570 * rb_fd_init allocates the memory.
4571 * rb_fd_term free the memory.
4572 * rb_fd_set may re-allocates bitmap.
4573 *
4574 * So rb_fd_set doesn't reject file descriptors bigger than FD_SETSIZE.
4575 */
4576
4577void
4579{
4580 fds->maxfd = 0;
4581 fds->fdset = ALLOC(fd_set);
4582 FD_ZERO(fds->fdset);
4583}
4584
4585static inline size_t
4586fdset_memsize(int maxfd)
4587{
4588 size_t o = howmany(maxfd, NFDBITS) * sizeof(fd_mask);
4589 if (o < sizeof(fd_set)) {
4590 return sizeof(fd_set);
4591 }
4592 return o;
4593}
4594
4595void
4596rb_fd_init_copy(rb_fdset_t *dst, rb_fdset_t *src)
4597{
4598 size_t size = fdset_memsize(rb_fd_max(src));
4599 dst->maxfd = src->maxfd;
4600 dst->fdset = xmalloc(size);
4601 memcpy(dst->fdset, src->fdset, size);
4602}
4603
4604void
4606{
4607 ruby_xfree_sized(fds->fdset, fdset_memsize(fds->maxfd));
4608 fds->maxfd = 0;
4609 fds->fdset = 0;
4610}
4611
4612void
4614{
4615 if (fds->fdset)
4616 MEMZERO(fds->fdset, fd_mask, howmany(fds->maxfd, NFDBITS));
4617}
4618
4619static void
4620rb_fd_resize(int n, rb_fdset_t *fds)
4621{
4622 size_t m = fdset_memsize(n + 1);
4623 size_t o = fdset_memsize(fds->maxfd);
4624
4625 if (m > o) {
4626 fds->fdset = ruby_xrealloc_sized(fds->fdset, m, o);
4627 memset((char *)fds->fdset + o, 0, m - o);
4628 }
4629 if (n >= fds->maxfd) fds->maxfd = n + 1;
4630}
4631
4632void
4633rb_fd_set(int n, rb_fdset_t *fds)
4634{
4635 rb_fd_resize(n, fds);
4636 FD_SET(n, fds->fdset);
4637}
4638
4639void
4640rb_fd_clr(int n, rb_fdset_t *fds)
4641{
4642 if (n >= fds->maxfd) return;
4643 FD_CLR(n, fds->fdset);
4644}
4645
4646int
4647rb_fd_isset(int n, const rb_fdset_t *fds)
4648{
4649 if (n >= fds->maxfd) return 0;
4650 return FD_ISSET(n, fds->fdset) != 0; /* "!= 0" avoids FreeBSD PR 91421 */
4651}
4652
4653void
4654rb_fd_copy(rb_fdset_t *dst, const fd_set *src, int max)
4655{
4656 size_t size = fdset_memsize(max);
4657 dst->fdset = ruby_xrealloc_sized(dst->fdset, size, fdset_memsize(dst->maxfd));
4658 dst->maxfd = max;
4659 memcpy(dst->fdset, src, size);
4660}
4661
4662void
4663rb_fd_dup(rb_fdset_t *dst, const rb_fdset_t *src)
4664{
4665 size_t size = fdset_memsize(rb_fd_max(src));
4666 dst->fdset = ruby_xrealloc_sized(dst->fdset, size, fdset_memsize(dst->maxfd));
4667 dst->maxfd = src->maxfd;
4668 memcpy(dst->fdset, src->fdset, size);
4669}
4670
4671int
4672rb_fd_select(int n, rb_fdset_t *readfds, rb_fdset_t *writefds, rb_fdset_t *exceptfds, struct timeval *timeout)
4673{
4674 fd_set *r = NULL, *w = NULL, *e = NULL;
4675 if (readfds) {
4676 rb_fd_resize(n - 1, readfds);
4677 r = rb_fd_ptr(readfds);
4678 }
4679 if (writefds) {
4680 rb_fd_resize(n - 1, writefds);
4681 w = rb_fd_ptr(writefds);
4682 }
4683 if (exceptfds) {
4684 rb_fd_resize(n - 1, exceptfds);
4685 e = rb_fd_ptr(exceptfds);
4686 }
4687 return select(n, r, w, e, timeout);
4688}
4689
4690#define rb_fd_no_init(fds) ((void)((fds)->fdset = 0), (void)((fds)->maxfd = 0))
4691
4692#undef FD_ZERO
4693#undef FD_SET
4694#undef FD_CLR
4695#undef FD_ISSET
4696
4697#define FD_ZERO(f) rb_fd_zero(f)
4698#define FD_SET(i, f) rb_fd_set((i), (f))
4699#define FD_CLR(i, f) rb_fd_clr((i), (f))
4700#define FD_ISSET(i, f) rb_fd_isset((i), (f))
4701
4702#elif defined(_WIN32)
4703
4704void
4706{
4707 set->capa = FD_SETSIZE;
4708 set->fdset = ALLOC(fd_set);
4709 FD_ZERO(set->fdset);
4710}
4711
4712void
4713rb_fd_init_copy(rb_fdset_t *dst, rb_fdset_t *src)
4714{
4715 rb_fd_init(dst);
4716 rb_fd_dup(dst, src);
4717}
4718
4719static inline size_t
4720fdset_memsize(int capa)
4721{
4722 return offsetof(fd_set, fd_array) + (capa * sizeof(SOCKET));
4723}
4724
4725void
4727{
4728 ruby_xfree_sized(set->fdset, fdset_memsize(set->capa));
4729 set->fdset = NULL;
4730 set->capa = 0;
4731}
4732
4733void
4734rb_fd_set(int fd, rb_fdset_t *set)
4735{
4736 unsigned int i;
4737 SOCKET s = rb_w32_get_osfhandle(fd);
4738
4739 for (i = 0; i < set->fdset->fd_count; i++) {
4740 if (set->fdset->fd_array[i] == s) {
4741 return;
4742 }
4743 }
4744 if (set->fdset->fd_count >= (unsigned)set->capa) {
4745 set->capa = (set->fdset->fd_count / FD_SETSIZE + 1) * FD_SETSIZE;
4746 set->fdset =
4747 rb_xrealloc_mul_add(
4748 set->fdset, set->capa, sizeof(SOCKET), offsetof(fd_set, fd_array));
4749 }
4750 set->fdset->fd_array[set->fdset->fd_count++] = s;
4751}
4752
4753#undef FD_ZERO
4754#undef FD_SET
4755#undef FD_CLR
4756#undef FD_ISSET
4757
4758#define FD_ZERO(f) rb_fd_zero(f)
4759#define FD_SET(i, f) rb_fd_set((i), (f))
4760#define FD_CLR(i, f) rb_fd_clr((i), (f))
4761#define FD_ISSET(i, f) rb_fd_isset((i), (f))
4762
4763#define rb_fd_no_init(fds) (void)((fds)->fdset = 0)
4764
4765#endif
4766
4767#ifndef rb_fd_no_init
4768#define rb_fd_no_init(fds) (void)(fds)
4769#endif
4770
4771static int
4772wait_retryable(volatile int *result, int errnum, rb_hrtime_t *rel, rb_hrtime_t end)
4773{
4774 int r = *result;
4775 if (r < 0) {
4776 switch (errnum) {
4777 case EINTR:
4778#ifdef ERESTART
4779 case ERESTART:
4780#endif
4781 *result = 0;
4782 if (rel && hrtime_update_expire(rel, end)) {
4783 *rel = 0;
4784 }
4785 return TRUE;
4786 }
4787 return FALSE;
4788 }
4789 else if (r == 0) {
4790 /* check for spurious wakeup */
4791 if (rel) {
4792 return !hrtime_update_expire(rel, end);
4793 }
4794 return TRUE;
4795 }
4796 return FALSE;
4797}
4799struct select_set {
4800 int max;
4801 rb_thread_t *th;
4802 rb_fdset_t *rset;
4803 rb_fdset_t *wset;
4804 rb_fdset_t *eset;
4805 rb_fdset_t orig_rset;
4806 rb_fdset_t orig_wset;
4807 rb_fdset_t orig_eset;
4808 struct timeval *timeout;
4809};
4810
4811static VALUE
4812select_set_free(VALUE p)
4813{
4814 struct select_set *set = (struct select_set *)p;
4815
4816 rb_fd_term(&set->orig_rset);
4817 rb_fd_term(&set->orig_wset);
4818 rb_fd_term(&set->orig_eset);
4819
4820 return Qfalse;
4821}
4822
4823static VALUE
4824do_select(VALUE p)
4825{
4826 struct select_set *set = (struct select_set *)p;
4827 volatile int result = 0;
4828 int lerrno;
4829 rb_hrtime_t *to, rel, end = 0;
4830
4831 timeout_prepare(&to, &rel, &end, set->timeout);
4832 volatile rb_hrtime_t endtime = end;
4833#define restore_fdset(dst, src) \
4834 ((dst) ? rb_fd_dup(dst, src) : (void)0)
4835#define do_select_update() \
4836 (restore_fdset(set->rset, &set->orig_rset), \
4837 restore_fdset(set->wset, &set->orig_wset), \
4838 restore_fdset(set->eset, &set->orig_eset), \
4839 TRUE)
4840
4841 do {
4842 // A skipped select is not a timeout; report EINTR so wait_retryable selects again.
4843 result = -1;
4844 lerrno = EINTR;
4845
4846 BLOCKING_REGION(set->th, {
4847 struct timeval tv;
4848
4849 if (!RUBY_VM_INTERRUPTED(set->th->ec)) {
4850 result = native_fd_select(set->max,
4851 set->rset, set->wset, set->eset,
4852 rb_hrtime2timeval(&tv, to), set->th);
4853 lerrno = result < 0 ? errno : 0;
4854 }
4855 }, ubf_select, set->th, TRUE);
4856
4857 RUBY_VM_CHECK_INTS_BLOCKING(set->th->ec); /* may raise */
4858 } while (wait_retryable(&result, lerrno, to, endtime) && do_select_update());
4859
4860 RUBY_VM_CHECK_INTS_BLOCKING(set->th->ec);
4861
4862 if (result < 0) {
4863 errno = lerrno;
4864 }
4865
4866 return (VALUE)result;
4867}
4868
4870rb_thread_fd_select(int max, rb_fdset_t * read, rb_fdset_t * write, rb_fdset_t * except,
4871 struct timeval *timeout)
4872{
4873 struct select_set set;
4874
4875 set.th = GET_THREAD();
4876 RUBY_VM_CHECK_INTS_BLOCKING(set.th->ec);
4877 set.max = max;
4878 set.rset = read;
4879 set.wset = write;
4880 set.eset = except;
4881 set.timeout = timeout;
4882
4883 if (!set.rset && !set.wset && !set.eset) {
4884 if (!timeout) {
4886 return 0;
4887 }
4888 rb_thread_wait_for(*timeout);
4889 return 0;
4890 }
4891
4892#define fd_init_copy(f) do { \
4893 if (set.f) { \
4894 rb_fd_resize(set.max - 1, set.f); \
4895 if (&set.orig_##f != set.f) { /* sigwait_fd */ \
4896 rb_fd_init_copy(&set.orig_##f, set.f); \
4897 } \
4898 } \
4899 else { \
4900 rb_fd_no_init(&set.orig_##f); \
4901 } \
4902 } while (0)
4903 fd_init_copy(rset);
4904 fd_init_copy(wset);
4905 fd_init_copy(eset);
4906#undef fd_init_copy
4907
4908 return (int)rb_ensure(do_select, (VALUE)&set, select_set_free, (VALUE)&set);
4909}
4910
4911#ifdef USE_POLL
4912
4913/* The same with linux kernel. TODO: make platform independent definition. */
4914#define POLLIN_SET (POLLRDNORM | POLLRDBAND | POLLIN | POLLHUP | POLLERR)
4915#define POLLOUT_SET (POLLWRBAND | POLLWRNORM | POLLOUT | POLLERR)
4916#define POLLEX_SET (POLLPRI)
4917
4918#ifndef POLLERR_SET /* defined for FreeBSD for now */
4919# define POLLERR_SET (0)
4920#endif
4921
4922static int
4923wait_for_single_fd_blocking_region(rb_thread_t *th, struct pollfd *fds, nfds_t nfds,
4924 rb_hrtime_t *const to, volatile int *lerrno)
4925{
4926 struct timespec ts;
4927 // A skipped ppoll is not a timeout; report EINTR so wait_retryable polls again.
4928 volatile int result = -1;
4929
4930 *lerrno = EINTR;
4931 BLOCKING_REGION(th, {
4932 if (!RUBY_VM_INTERRUPTED(th->ec)) {
4933 result = ppoll(fds, nfds, rb_hrtime2timespec(&ts, to), 0);
4934 *lerrno = result < 0 ? errno : 0;
4935 }
4936 }, ubf_select, th, TRUE);
4937 return result;
4938}
4939
4940/*
4941 * returns a mask of events
4942 */
4943static int
4944thread_io_wait(rb_thread_t *th, struct rb_io *io, int fd, int events, struct timeval *timeout)
4945{
4946 struct pollfd fds[1] = {{
4947 .fd = fd,
4948 .events = (short)events,
4949 .revents = 0,
4950 }};
4951 volatile int result = 0;
4952 nfds_t nfds;
4953 struct rb_io_blocking_operation blocking_operation;
4954 enum ruby_tag_type state = TAG_NONE;
4955 volatile int lerrno;
4956
4957 RUBY_ASSERT(th);
4958 rb_execution_context_t *ec = th->ec;
4959
4960 if (io) {
4961 blocking_operation.ec = ec;
4962 blocking_operation.scheduler_interrupt_target = Qnil;
4963COMPILER_WARNING_PUSH
4964#if RBIMPL_COMPILER_SINCE(GCC, 12, 0, 0)
4965COMPILER_WARNING_IGNORED(-Wdangling-pointer)
4966#endif
4967 // rb_io_blocking_operation_exit() below unlinks it on every path.
4968 rb_io_blocking_operation_enter(io, &blocking_operation);
4969COMPILER_WARNING_POP
4970 }
4971
4972 struct timeval tv_rest;
4973 struct timeval *volatile wait_timeout = timeout;
4974 const rb_hrtime_t deadline = timeout ? rb_hrtime_add(rb_hrtime_now(), rb_timeval2hrtime(timeout)) : 0;
4975
4976 // The interrupt checks below may raise; the tag lets the exit path unlink blocking_operation.
4977 EC_PUSH_TAG(ec);
4978 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
4979 enum io_wait_result mn_result;
4980
4981 while (1) {
4982 // A zero timeout is a plain probe; ppoll answers it without parking.
4983 bool mn_wait = wait_timeout == NULL || wait_timeout->tv_sec != 0 || wait_timeout->tv_usec != 0;
4984 mn_result = mn_wait ? thread_io_wait_events(th, fd, events, wait_timeout, false) : io_wait_unhandled;
4985 if (mn_result == io_wait_ready) break;
4986
4987 // Charge what the M:N wait spent against the deadline the caller asked for.
4988 rb_hrtime_t rest = 0;
4989 if (wait_timeout) {
4990 rb_hrtime_t now = rb_hrtime_now();
4991 rest = now < deadline ? deadline - now : 0;
4992 rb_hrtime2timeval(&tv_rest, &rest);
4993 wait_timeout = &tv_rest;
4994 }
4995 if (mn_result == io_wait_unhandled) break;
4996 if (mn_result == io_wait_timed_out && wait_timeout && rest == 0) break;
4997
4998 // Stopped without an event before the deadline (an interrupt, or a wakeup
4999 // for a masked one): handle it and wait again. At the deadline this probes once.
5000 RUBY_VM_CHECK_INTS_BLOCKING(ec);
5001 }
5002
5003 switch (mn_result) {
5004 case io_wait_ready:
5005 fds[0].revents = events;
5006 errno = 0;
5007 break;
5008 case io_wait_timed_out:
5009 // revents stays 0, so the result below becomes 0 as with ppoll's timeout.
5010 errno = 0;
5011 break;
5012 case io_wait_unhandled: {
5013 rb_hrtime_t *to, rel, end = 0;
5014 RUBY_VM_CHECK_INTS_BLOCKING(ec);
5015 timeout_prepare(&to, &rel, &end, wait_timeout);
5016 do {
5017 nfds = numberof(fds);
5018 result = wait_for_single_fd_blocking_region(th, fds, nfds, to, &lerrno);
5019
5020 RUBY_VM_CHECK_INTS_BLOCKING(ec);
5021 } while (wait_retryable(&result, lerrno, to, end));
5022
5023 RUBY_VM_CHECK_INTS_BLOCKING(ec);
5024 break;
5025 }
5026 case io_wait_interrupted:
5028 }
5029 }
5030 EC_POP_TAG();
5031
5032 if (io) {
5033 rb_io_blocking_operation_exit(io, &blocking_operation);
5034 }
5035
5036 if (state) {
5037 EC_JUMP_TAG(ec, state);
5038 }
5039
5040 if (result < 0) {
5041 errno = lerrno;
5042 return -1;
5043 }
5044
5045 if (fds[0].revents & POLLNVAL) {
5046 errno = EBADF;
5047 return -1;
5048 }
5049
5050 /*
5051 * POLLIN, POLLOUT have a different meanings from select(2)'s read/write bit.
5052 * Therefore we need to fix it up.
5053 */
5054 result = 0;
5055 if (fds[0].revents & POLLIN_SET)
5056 result |= RB_WAITFD_IN;
5057 if (fds[0].revents & POLLOUT_SET)
5058 result |= RB_WAITFD_OUT;
5059 if (fds[0].revents & POLLEX_SET)
5060 result |= RB_WAITFD_PRI;
5061
5062 /* all requested events are ready if there is an error */
5063 if (fds[0].revents & POLLERR_SET)
5064 result |= events;
5065
5066 return result;
5067}
5068#else /* ! USE_POLL - implement rb_io_poll_fd() using select() */
5069struct select_args {
5070 struct rb_io *io;
5071 struct rb_io_blocking_operation *blocking_operation;
5072
5073 union {
5074 int fd;
5075 int error;
5076 } as;
5077 rb_fdset_t *read;
5078 rb_fdset_t *write;
5079 rb_fdset_t *except;
5080 struct timeval *tv;
5081};
5082
5083static VALUE
5084select_single(VALUE ptr)
5085{
5086 struct select_args *args = (struct select_args *)ptr;
5087 int r;
5088
5089 r = rb_thread_fd_select(args->as.fd + 1,
5090 args->read, args->write, args->except, args->tv);
5091 if (r == -1)
5092 args->as.error = errno;
5093 if (r > 0) {
5094 r = 0;
5095 if (args->read && rb_fd_isset(args->as.fd, args->read))
5096 r |= RB_WAITFD_IN;
5097 if (args->write && rb_fd_isset(args->as.fd, args->write))
5098 r |= RB_WAITFD_OUT;
5099 if (args->except && rb_fd_isset(args->as.fd, args->except))
5100 r |= RB_WAITFD_PRI;
5101 }
5102 return (VALUE)r;
5103}
5104
5105static VALUE
5106select_single_cleanup(VALUE ptr)
5107{
5108 struct select_args *args = (struct select_args *)ptr;
5109
5110 if (args->blocking_operation) {
5111 rb_io_blocking_operation_exit(args->io, args->blocking_operation);
5112 }
5113
5114 if (args->read) rb_fd_term(args->read);
5115 if (args->write) rb_fd_term(args->write);
5116 if (args->except) rb_fd_term(args->except);
5117
5118 return (VALUE)-1;
5119}
5120
5121static rb_fdset_t *
5122init_set_fd(int fd, rb_fdset_t *fds)
5123{
5124 if (fd < 0) {
5125 return 0;
5126 }
5127 rb_fd_init(fds);
5128 rb_fd_set(fd, fds);
5129
5130 return fds;
5131}
5132
5133static int
5134thread_io_wait(rb_thread_t *th, struct rb_io *io, int fd, int events, struct timeval *timeout)
5135{
5136 rb_fdset_t rfds, wfds, efds;
5137 struct select_args args;
5138 VALUE ptr = (VALUE)&args;
5139
5140 struct rb_io_blocking_operation blocking_operation;
5141 if (io) {
5142 args.io = io;
5143 blocking_operation.ec = th->ec;
5144 blocking_operation.scheduler_interrupt_target = Qnil;
5145 rb_io_blocking_operation_enter(io, &blocking_operation);
5146 args.blocking_operation = &blocking_operation;
5147 }
5148 else {
5149 args.io = NULL;
5150 blocking_operation.ec = NULL;
5151 blocking_operation.scheduler_interrupt_target = Qnil;
5152 args.blocking_operation = NULL;
5153 }
5154
5155 args.as.fd = fd;
5156 args.read = (events & RB_WAITFD_IN) ? init_set_fd(fd, &rfds) : NULL;
5157 args.write = (events & RB_WAITFD_OUT) ? init_set_fd(fd, &wfds) : NULL;
5158 args.except = (events & RB_WAITFD_PRI) ? init_set_fd(fd, &efds) : NULL;
5159 args.tv = timeout;
5160
5161 int result = (int)rb_ensure(select_single, ptr, select_single_cleanup, ptr);
5162 if (result == -1)
5163 errno = args.as.error;
5164
5165 return result;
5166}
5167#endif /* ! USE_POLL */
5168
5169int
5170rb_thread_wait_for_single_fd(rb_thread_t *th, int fd, int events, struct timeval *timeout)
5171{
5172 return thread_io_wait(th, NULL, fd, events, timeout);
5173}
5174
5175int
5176rb_thread_io_wait(rb_thread_t *th, struct rb_io *io, int events, struct timeval * timeout)
5177{
5178 return thread_io_wait(th, io, io->fd, events, timeout);
5179}
5180
5181/*
5182 * for GC
5183 */
5184
5185#ifdef USE_CONSERVATIVE_STACK_END
5186void
5187rb_gc_set_stack_end(VALUE **stack_end_p)
5188{
5189 VALUE stack_end;
5190COMPILER_WARNING_PUSH
5191#if RBIMPL_COMPILER_SINCE(GCC, 12, 0, 0)
5192COMPILER_WARNING_IGNORED(-Wdangling-pointer);
5193#endif
5194 *stack_end_p = &stack_end;
5195COMPILER_WARNING_POP
5196}
5197#endif
5198
5199/*
5200 *
5201 */
5202
5203void
5204rb_threadptr_check_signal(rb_thread_t *mth)
5205{
5206 /* mth must be main_thread */
5207 if (rb_signal_buff_size() > 0) {
5208 /* wakeup main thread */
5209 threadptr_trap_interrupt(mth);
5210 }
5211}
5212
5213static void
5214async_bug_fd(const char *mesg, int errno_arg, int fd)
5215{
5216 char buff[64];
5217 size_t n = strlcpy(buff, mesg, sizeof(buff));
5218 if (n < sizeof(buff)-3) {
5219 ruby_snprintf(buff+n, sizeof(buff)-n, "(%d)", fd);
5220 }
5221 rb_async_bug_errno(buff, errno_arg);
5222}
5223
5224/* VM-dependent API is not available for this function */
5225static int
5226consume_communication_pipe(int fd)
5227{
5228#if USE_EVENTFD
5229 uint64_t buff[1];
5230#else
5231 /* buffer can be shared because no one refers to them. */
5232 static char buff[1024];
5233#endif
5234 ssize_t result;
5235 int ret = FALSE; /* for rb_sigwait_sleep */
5236
5237 while (1) {
5238 result = read(fd, buff, sizeof(buff));
5239#if USE_EVENTFD
5240 RUBY_DEBUG_LOG("resultf:%d buff:%lu", (int)result, (unsigned long)buff[0]);
5241#else
5242 RUBY_DEBUG_LOG("result:%d", (int)result);
5243#endif
5244 if (result > 0) {
5245 ret = TRUE;
5246 if (USE_EVENTFD || result < (ssize_t)sizeof(buff)) {
5247 return ret;
5248 }
5249 }
5250 else if (result == 0) {
5251 return ret;
5252 }
5253 else if (result < 0) {
5254 int e = errno;
5255 switch (e) {
5256 case EINTR:
5257 continue; /* retry */
5258 case EAGAIN:
5259#if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
5260 case EWOULDBLOCK:
5261#endif
5262 return ret;
5263 default:
5264 async_bug_fd("consume_communication_pipe: read", e, fd);
5265 }
5266 }
5267 }
5268}
5269
5270void
5271rb_thread_stop_timer_thread(void)
5272{
5273 if (TIMER_THREAD_CREATED_P() && native_stop_timer_thread()) {
5274 native_reset_timer_thread();
5275 }
5276}
5277
5278void
5279rb_thread_reset_timer_thread(void)
5280{
5281 native_reset_timer_thread();
5282}
5283
5284void
5285rb_thread_start_timer_thread(void)
5286{
5287 system_working = 1;
5288 rb_thread_create_timer_thread();
5289}
5290
5291static int
5292clear_coverage_i(st_data_t key, st_data_t val, st_data_t dummy)
5293{
5294 int i;
5295 VALUE coverage = (VALUE)val;
5296 VALUE lines = RARRAY_AREF(coverage, COVERAGE_INDEX_LINES);
5297 VALUE branches = RARRAY_AREF(coverage, COVERAGE_INDEX_BRANCHES);
5298
5299 if (lines) {
5300 if (GET_VM()->coverage_mode & COVERAGE_TARGET_ONESHOT_LINES) {
5301 rb_ary_clear(lines);
5302 }
5303 else {
5304 int i;
5305 for (i = 0; i < RARRAY_LEN(lines); i++) {
5306 if (RARRAY_AREF(lines, i) != Qnil)
5307 RARRAY_ASET(lines, i, INT2FIX(0));
5308 }
5309 }
5310 }
5311 if (branches) {
5312 VALUE counters = RARRAY_AREF(branches, 1);
5313 for (i = 0; i < RARRAY_LEN(counters); i++) {
5314 RARRAY_ASET(counters, i, INT2FIX(0));
5315 }
5316 }
5317
5318 return ST_CONTINUE;
5319}
5320
5321void
5322rb_clear_coverages(void)
5323{
5324 VALUE coverages = rb_get_coverages();
5325 if (RTEST(coverages)) {
5326 rb_hash_foreach(coverages, clear_coverage_i, 0);
5327 }
5328}
5329
5330#if defined(HAVE_WORKING_FORK)
5331
5332static void
5333rb_thread_atfork_internal(rb_thread_t *th, void (*atfork)(rb_thread_t *, const rb_thread_t *))
5334{
5335 rb_thread_t *i = 0;
5336 rb_vm_t *vm = th->vm;
5337 rb_ractor_t *r = th->ractor;
5338 vm->ractor.main_ractor = r;
5339 vm->ractor.main_thread = th;
5340 r->threads.main = th;
5341 r->status_ = ractor_created;
5342
5343 thread_sched_atfork(TH_SCHED(th));
5344 ubf_list_atfork();
5345 rb_signal_atfork();
5346
5347 // OK. Only this thread accesses:
5348 rb_ractor_t *r_next;
5349 ccan_list_for_each_safe(&vm->ractor.set, r, r_next, vmlr_node) {
5350 if (r != vm->ractor.main_ractor) {
5351 rb_ractor_terminate_atfork(vm, r);
5352 }
5353 ccan_list_for_each(&r->threads.set, i, lt_node) {
5354 atfork(i, th);
5355 }
5356 }
5357
5358 ccan_list_head_init(&vm->ractor.set);
5359
5360 rb_ractor_atfork(vm, th);
5361 rb_vm_postponed_job_atfork();
5362
5363 /* may be held by any thread in parent */
5364 rb_native_mutex_initialize(&th->interrupt_lock);
5365 rb_native_mutex_initialize(&vm->once_lock);
5366 rb_native_cond_initialize(&vm->once_cond);
5367 rb_jit_cont_init(); // cont.c's jit_cont_lock, likewise
5368 rb_gc_zombie_objspaces_atfork();
5369 rb_gc_atfork_global_locks();
5370 rb_generic_fields_lock_atfork();
5371 rb_fiber_pool_lock_atfork();
5372 ccan_list_head_init(&th->interrupt_exec_tasks);
5373
5374 vm->fork_gen++;
5375 rb_ractor_sleeper_threads_clear(th->ractor);
5376 rb_clear_coverages();
5377
5378 // restart timer thread (timer threads access to `vm->waitpid_lock` and so on.
5379 rb_thread_reset_timer_thread();
5380 rb_thread_start_timer_thread();
5381
5382 VM_ASSERT(vm->ractor.blocking_cnt == 0);
5383 VM_ASSERT(vm->ractor.cnt == 1);
5384}
5385
5386static void
5387terminate_atfork_i(rb_thread_t *th, const rb_thread_t *current_th)
5388{
5389 if (th != current_th) {
5390 // Clear the scheduler as it is no longer operational:
5391 th->scheduler = Qnil;
5392
5393 rb_native_mutex_initialize(&th->interrupt_lock);
5394 rb_mutex_abandon_keeping_mutexes(th);
5395 rb_mutex_abandon_locking_mutex(th);
5396 thread_cleanup_func(th, TRUE);
5397 }
5398}
5399
5400void rb_fiber_atfork(rb_thread_t *);
5401void
5402rb_thread_atfork(void)
5403{
5404 rb_thread_t *th = GET_THREAD();
5405 rb_threadptr_pending_interrupt_clear(th);
5406 rb_thread_atfork_internal(th, terminate_atfork_i);
5407 th->join_list = NULL;
5408 th->scheduler = Qnil;
5409 rb_fiber_atfork(th);
5410
5411 /* We don't want reproduce CVE-2003-0900. */
5413}
5414
5415static void
5416terminate_atfork_before_exec_i(rb_thread_t *th, const rb_thread_t *current_th)
5417{
5418 if (th != current_th) {
5419 thread_cleanup_func_before_exec(th);
5420 }
5421}
5422
5423void
5425{
5426 rb_thread_t *th = GET_THREAD();
5427 rb_thread_atfork_internal(th, terminate_atfork_before_exec_i);
5428}
5429#else
5430void
5431rb_thread_atfork(void)
5432{
5433}
5434
5435void
5437{
5438}
5439#endif
5441struct thgroup {
5442 int enclosed;
5443};
5444
5445static const rb_data_type_t thgroup_data_type = {
5446 "thgroup",
5447 {
5448 0,
5450 NULL, // No external memory to report
5451 },
5452 0, 0, RUBY_TYPED_THREAD_SAFE_FREE | RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_EMBEDDABLE
5453};
5454
5455/*
5456 * Document-class: ThreadGroup
5457 *
5458 * ThreadGroup provides a means of keeping track of a number of threads as a
5459 * group.
5460 *
5461 * A given Thread object can only belong to one ThreadGroup at a time; adding
5462 * a thread to a new group will remove it from any previous group.
5463 *
5464 * Newly created threads belong to the same group as the thread from which they
5465 * were created.
5466 */
5467
5468/*
5469 * Document-const: Default
5470 *
5471 * The default ThreadGroup created when Ruby starts; all Threads belong to it
5472 * by default.
5473 */
5474static VALUE
5475thgroup_s_alloc(VALUE klass)
5476{
5477 VALUE group;
5478 struct thgroup *data;
5479
5480 group = TypedData_Make_Struct(klass, struct thgroup, &thgroup_data_type, data);
5481 data->enclosed = 0;
5482
5483 return group;
5484}
5485
5486/*
5487 * call-seq:
5488 * thgrp.list -> array
5489 *
5490 * Returns an array of all existing Thread objects that belong to this group.
5491 *
5492 * ThreadGroup::Default.list #=> [#<Thread:0x401bdf4c run>]
5493 */
5494
5495static VALUE
5496thgroup_list(VALUE group)
5497{
5498 VALUE ary = rb_ary_new();
5499 rb_thread_t *th = 0;
5500 rb_ractor_t *r = GET_RACTOR();
5501
5502 ccan_list_for_each(&r->threads.set, th, lt_node) {
5503 if (th->thgroup == group) {
5504 rb_ary_push(ary, th->self);
5505 }
5506 }
5507 return ary;
5508}
5509
5510
5511/*
5512 * call-seq:
5513 * thgrp.enclose -> thgrp
5514 *
5515 * Prevents threads from being added to or removed from the receiving
5516 * ThreadGroup.
5517 *
5518 * New threads can still be started in an enclosed ThreadGroup.
5519 *
5520 * ThreadGroup::Default.enclose #=> #<ThreadGroup:0x4029d914>
5521 * thr = Thread.new { Thread.stop } #=> #<Thread:0x402a7210 sleep>
5522 * tg = ThreadGroup.new #=> #<ThreadGroup:0x402752d4>
5523 * tg.add thr
5524 * #=> ThreadError: can't move from the enclosed thread group
5525 */
5526
5527static VALUE
5528thgroup_enclose(VALUE group)
5529{
5530 struct thgroup *data;
5531
5532 TypedData_Get_Struct(group, struct thgroup, &thgroup_data_type, data);
5533 data->enclosed = 1;
5534
5535 return group;
5536}
5537
5538
5539/*
5540 * call-seq:
5541 * thgrp.enclosed? -> true or false
5542 *
5543 * Returns +true+ if the +thgrp+ is enclosed. See also ThreadGroup#enclose.
5544 */
5545
5546static VALUE
5547thgroup_enclosed_p(VALUE group)
5548{
5549 struct thgroup *data;
5550
5551 TypedData_Get_Struct(group, struct thgroup, &thgroup_data_type, data);
5552 return RBOOL(data->enclosed);
5553}
5554
5555
5556/*
5557 * call-seq:
5558 * thgrp.add(thread) -> thgrp
5559 *
5560 * Adds the given +thread+ to this group, removing it from any other
5561 * group to which it may have previously been a member.
5562 *
5563 * puts "Initial group is #{ThreadGroup::Default.list}"
5564 * tg = ThreadGroup.new
5565 * t1 = Thread.new { sleep }
5566 * t2 = Thread.new { sleep }
5567 * puts "t1 is #{t1}"
5568 * puts "t2 is #{t2}"
5569 * tg.add(t1)
5570 * puts "Initial group now #{ThreadGroup::Default.list}"
5571 * puts "tg group now #{tg.list}"
5572 *
5573 * This will produce:
5574 *
5575 * Initial group is #<Thread:0x401bdf4c>
5576 * t1 is #<Thread:0x401b3c90>
5577 * t2 is #<Thread:0x401b3c18>
5578 * Initial group now #<Thread:0x401b3c18>#<Thread:0x401bdf4c>
5579 * tg group now #<Thread:0x401b3c90>
5580 */
5581
5582static VALUE
5583thgroup_add(VALUE group, VALUE thread)
5584{
5585 rb_thread_t *target_th = rb_thread_ptr(thread);
5586 struct thgroup *data;
5587
5588 if (OBJ_FROZEN(group)) {
5589 rb_raise(rb_eThreadError, "can't move to the frozen thread group");
5590 }
5591 TypedData_Get_Struct(group, struct thgroup, &thgroup_data_type, data);
5592 if (data->enclosed) {
5593 rb_raise(rb_eThreadError, "can't move to the enclosed thread group");
5594 }
5595
5596 if (OBJ_FROZEN(target_th->thgroup)) {
5597 rb_raise(rb_eThreadError, "can't move from the frozen thread group");
5598 }
5599 TypedData_Get_Struct(target_th->thgroup, struct thgroup, &thgroup_data_type, data);
5600 if (data->enclosed) {
5601 rb_raise(rb_eThreadError,
5602 "can't move from the enclosed thread group");
5603 }
5604
5605 target_th->thgroup = group;
5606 return group;
5607}
5608
5609/*
5610 * Document-class: ThreadShield
5611 */
5612static void
5613thread_shield_mark(void *ptr)
5614{
5615 rb_gc_mark((VALUE)ptr);
5616}
5617
5618static const rb_data_type_t thread_shield_data_type = {
5619 "thread_shield",
5620 {thread_shield_mark, 0, 0,},
5621 0, 0, RUBY_TYPED_THREAD_SAFE_FREE
5622};
5623
5624static VALUE
5625thread_shield_alloc(VALUE klass)
5626{
5627 return TypedData_Wrap_Struct(klass, &thread_shield_data_type, (void *)mutex_alloc(0));
5628}
5629
5630#define GetThreadShieldPtr(obj) ((VALUE)rb_check_typeddata((obj), &thread_shield_data_type))
5631#define THREAD_SHIELD_WAITING_MASK (((FL_USER19-1)&~(FL_USER0-1))|FL_USER19)
5632#define THREAD_SHIELD_WAITING_SHIFT (FL_USHIFT)
5633#define THREAD_SHIELD_WAITING_MAX (THREAD_SHIELD_WAITING_MASK>>THREAD_SHIELD_WAITING_SHIFT)
5634STATIC_ASSERT(THREAD_SHIELD_WAITING_MAX, THREAD_SHIELD_WAITING_MAX <= UINT_MAX);
5635static inline unsigned int
5636rb_thread_shield_waiting(VALUE b)
5637{
5638 return ((RBASIC(b)->flags&THREAD_SHIELD_WAITING_MASK)>>THREAD_SHIELD_WAITING_SHIFT);
5639}
5640
5641static inline void
5642rb_thread_shield_waiting_inc(VALUE b)
5643{
5644 unsigned int w = rb_thread_shield_waiting(b);
5645 w++;
5646 if (w > THREAD_SHIELD_WAITING_MAX)
5647 rb_raise(rb_eRuntimeError, "waiting count overflow");
5648 RBASIC(b)->flags &= ~THREAD_SHIELD_WAITING_MASK;
5649 RBASIC(b)->flags |= ((VALUE)w << THREAD_SHIELD_WAITING_SHIFT);
5650}
5651
5652static inline void
5653rb_thread_shield_waiting_dec(VALUE b)
5654{
5655 unsigned int w = rb_thread_shield_waiting(b);
5656 if (!w) rb_raise(rb_eRuntimeError, "waiting count underflow");
5657 w--;
5658 RBASIC(b)->flags &= ~THREAD_SHIELD_WAITING_MASK;
5659 RBASIC(b)->flags |= ((VALUE)w << THREAD_SHIELD_WAITING_SHIFT);
5660}
5661
5662VALUE
5663rb_thread_shield_new(void)
5664{
5665 VALUE thread_shield = thread_shield_alloc(rb_cThreadShield);
5666 rb_mutex_lock((VALUE)DATA_PTR(thread_shield));
5667 return thread_shield;
5668}
5669
5670bool
5671rb_thread_shield_owned(VALUE self)
5672{
5673 VALUE mutex = GetThreadShieldPtr(self);
5674 if (!mutex) return false;
5675
5676 rb_mutex_t *m = mutex_ptr(mutex);
5677
5678 return m->ec_serial == rb_ec_serial(GET_EC());
5679}
5680
5681/*
5682 * Wait a thread shield.
5683 *
5684 * Returns
5685 * true: acquired the thread shield
5686 * false: the thread shield was destroyed and no other threads waiting
5687 * nil: the thread shield was destroyed but still in use
5688 */
5689VALUE
5690rb_thread_shield_wait(VALUE self)
5691{
5692 VALUE mutex = GetThreadShieldPtr(self);
5693 rb_mutex_t *m;
5694
5695 if (!mutex) return Qfalse;
5696 m = mutex_ptr(mutex);
5697 if (m->ec_serial == rb_ec_serial(GET_EC())) return Qnil;
5698 rb_thread_shield_waiting_inc(self);
5699 rb_mutex_lock(mutex);
5700 rb_thread_shield_waiting_dec(self);
5701 if (DATA_PTR(self)) return Qtrue;
5702 rb_mutex_unlock(mutex);
5703 return rb_thread_shield_waiting(self) > 0 ? Qnil : Qfalse;
5704}
5705
5706static VALUE
5707thread_shield_get_mutex(VALUE self)
5708{
5709 VALUE mutex = GetThreadShieldPtr(self);
5710 if (!mutex)
5711 rb_raise(rb_eThreadError, "destroyed thread shield - %p", (void *)self);
5712 return mutex;
5713}
5714
5715/*
5716 * Release a thread shield, and return true if it has waiting threads.
5717 */
5718VALUE
5719rb_thread_shield_release(VALUE self)
5720{
5721 VALUE mutex = thread_shield_get_mutex(self);
5722 rb_mutex_unlock(mutex);
5723 return RBOOL(rb_thread_shield_waiting(self) > 0);
5724}
5725
5726/*
5727 * Release and destroy a thread shield, and return true if it has waiting threads.
5728 */
5729VALUE
5730rb_thread_shield_destroy(VALUE self)
5731{
5732 VALUE mutex = thread_shield_get_mutex(self);
5733 DATA_PTR(self) = 0;
5734 rb_mutex_unlock(mutex);
5735 return RBOOL(rb_thread_shield_waiting(self) > 0);
5736}
5737
5738static VALUE
5739threadptr_recursive_hash(rb_thread_t *th)
5740{
5741 return th->ec->local_storage_recursive_hash;
5742}
5743
5744static void
5745threadptr_recursive_hash_set(rb_thread_t *th, VALUE hash)
5746{
5747 th->ec->local_storage_recursive_hash = hash;
5748}
5749
5751
5752/*
5753 * Returns the current "recursive list" used to detect recursion.
5754 * This list is a hash table, unique for the current thread and for
5755 * the current __callee__.
5756 */
5757
5758static VALUE
5759recursive_list_access(VALUE sym)
5760{
5761 rb_thread_t *th = GET_THREAD();
5762 VALUE hash = threadptr_recursive_hash(th);
5763 VALUE list;
5764 if (NIL_P(hash) || !RB_TYPE_P(hash, T_HASH)) {
5765 hash = rb_ident_hash_new();
5766 threadptr_recursive_hash_set(th, hash);
5767 list = Qnil;
5768 }
5769 else {
5770 list = rb_hash_aref(hash, sym);
5771 }
5772 if (NIL_P(list) || !RB_TYPE_P(list, T_HASH)) {
5773 list = rb_ident_hash_new();
5774 rb_hash_aset(hash, sym, list);
5775 }
5776 return list;
5777}
5778
5779/*
5780 * Returns true if and only if obj (or the pair <obj, paired_obj>) is already
5781 * in the recursion list.
5782 * Assumes the recursion list is valid.
5783 */
5784
5785static bool
5786recursive_check(VALUE list, VALUE obj, VALUE paired_obj_id)
5787{
5788#if SIZEOF_LONG == SIZEOF_VOIDP
5789 #define OBJ_ID_EQL(obj_id, other) ((obj_id) == (other))
5790#elif SIZEOF_LONG_LONG == SIZEOF_VOIDP
5791 #define OBJ_ID_EQL(obj_id, other) (RB_BIGNUM_TYPE_P((obj_id)) ? \
5792 rb_big_eql((obj_id), (other)) : ((obj_id) == (other)))
5793#endif
5794
5795 VALUE pair_list = rb_hash_lookup2(list, obj, Qundef);
5796 if (UNDEF_P(pair_list))
5797 return false;
5798 if (paired_obj_id) {
5799 if (!RB_TYPE_P(pair_list, T_HASH)) {
5800 if (!OBJ_ID_EQL(paired_obj_id, pair_list))
5801 return false;
5802 }
5803 else {
5804 if (NIL_P(rb_hash_lookup(pair_list, paired_obj_id)))
5805 return false;
5806 }
5807 }
5808 return true;
5809}
5810
5811/*
5812 * Pushes obj (or the pair <obj, paired_obj>) in the recursion list.
5813 * For a single obj, it sets list[obj] to Qtrue.
5814 * For a pair, it sets list[obj] to paired_obj_id if possible,
5815 * otherwise list[obj] becomes a hash like:
5816 * {paired_obj_id_1 => true, paired_obj_id_2 => true, ... }
5817 * Assumes the recursion list is valid.
5818 */
5819
5820static void
5821recursive_push(VALUE list, VALUE obj, VALUE paired_obj)
5822{
5823 VALUE pair_list;
5824
5825 if (!paired_obj) {
5826 rb_hash_aset(list, obj, Qtrue);
5827 }
5828 else if (UNDEF_P(pair_list = rb_hash_lookup2(list, obj, Qundef))) {
5829 rb_hash_aset(list, obj, paired_obj);
5830 }
5831 else {
5832 if (!RB_TYPE_P(pair_list, T_HASH)){
5833 VALUE other_paired_obj = pair_list;
5834 pair_list = rb_hash_new();
5835 rb_hash_aset(pair_list, other_paired_obj, Qtrue);
5836 rb_hash_aset(list, obj, pair_list);
5837 }
5838 rb_hash_aset(pair_list, paired_obj, Qtrue);
5839 }
5840}
5841
5842/*
5843 * Pops obj (or the pair <obj, paired_obj>) from the recursion list.
5844 * For a pair, if list[obj] is a hash, then paired_obj_id is
5845 * removed from the hash and no attempt is made to simplify
5846 * list[obj] from {only_one_paired_id => true} to only_one_paired_id
5847 * Assumes the recursion list is valid.
5848 */
5849
5850static int
5851recursive_pop(VALUE list, VALUE obj, VALUE paired_obj)
5852{
5853 if (paired_obj) {
5854 VALUE pair_list = rb_hash_lookup2(list, obj, Qundef);
5855 if (UNDEF_P(pair_list)) {
5856 return 0;
5857 }
5858 if (RB_TYPE_P(pair_list, T_HASH)) {
5859 rb_hash_delete_entry(pair_list, paired_obj);
5860 if (!RHASH_EMPTY_P(pair_list)) {
5861 return 1; /* keep hash until is empty */
5862 }
5863 }
5864 }
5865 rb_hash_delete_entry(list, obj);
5866 return 1;
5867}
5869struct exec_recursive_params {
5870 VALUE (*func) (VALUE, VALUE, int);
5871 VALUE list;
5872 VALUE obj;
5873 VALUE pairid;
5874 VALUE arg;
5875};
5876
5877static VALUE
5878exec_recursive_i(RB_BLOCK_CALL_FUNC_ARGLIST(tag, data))
5879{
5880 struct exec_recursive_params *p = (void *)data;
5881 return (*p->func)(p->obj, p->arg, FALSE);
5882}
5883
5884/*
5885 * Calls func(obj, arg, recursive), where recursive is non-zero if the
5886 * current method is called recursively on obj, or on the pair <obj, pairid>
5887 * If outer is 0, then the innermost func will be called with recursive set
5888 * to true, otherwise the outermost func will be called. In the latter case,
5889 * all inner func are short-circuited by throw.
5890 * Implementation details: the value thrown is the recursive list which is
5891 * proper to the current method and unlikely to be caught anywhere else.
5892 * list[recursive_key] is used as a flag for the outermost call.
5893 */
5894
5895static VALUE
5896exec_recursive(VALUE (*func) (VALUE, VALUE, int), VALUE obj, VALUE pairid, VALUE arg, int outer, ID mid)
5897{
5898 VALUE result = Qundef;
5899 const VALUE sym = mid ? ID2SYM(mid) : ID2SYM(idNULL);
5900 struct exec_recursive_params p;
5901 int outermost;
5902 p.list = recursive_list_access(sym);
5903 p.obj = obj;
5904 p.pairid = pairid;
5905 p.arg = arg;
5906 outermost = outer && !recursive_check(p.list, ID2SYM(recursive_key), 0);
5907
5908 if (recursive_check(p.list, p.obj, pairid)) {
5909 if (outer && !outermost) {
5910 rb_throw_obj(p.list, p.list);
5911 }
5912 return (*func)(obj, arg, TRUE);
5913 }
5914 else {
5915 enum ruby_tag_type state;
5916
5917 p.func = func;
5918
5919 if (outermost) {
5920 recursive_push(p.list, ID2SYM(recursive_key), 0);
5921 recursive_push(p.list, p.obj, p.pairid);
5922 result = rb_catch_protect(p.list, exec_recursive_i, (VALUE)&p, &state);
5923 if (!recursive_pop(p.list, p.obj, p.pairid)) goto invalid;
5924 if (!recursive_pop(p.list, ID2SYM(recursive_key), 0)) goto invalid;
5925 if (state != TAG_NONE) EC_JUMP_TAG(GET_EC(), state);
5926 if (result == p.list) {
5927 result = (*func)(obj, arg, TRUE);
5928 }
5929 }
5930 else {
5931 volatile VALUE ret = Qundef;
5932 recursive_push(p.list, p.obj, p.pairid);
5933 EC_PUSH_TAG(GET_EC());
5934 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
5935 ret = (*func)(obj, arg, FALSE);
5936 }
5937 EC_POP_TAG();
5938 if (!recursive_pop(p.list, p.obj, p.pairid)) {
5939 goto invalid;
5940 }
5941 if (state != TAG_NONE) EC_JUMP_TAG(GET_EC(), state);
5942 result = ret;
5943 }
5944 }
5945 *(volatile struct exec_recursive_params *)&p;
5946 return result;
5947
5948 invalid:
5949 rb_raise(rb_eTypeError, "invalid inspect_tbl pair_list "
5950 "for %+"PRIsVALUE" in %+"PRIsVALUE,
5951 sym, rb_thread_current());
5953}
5954
5955/*
5956 * Calls func(obj, arg, recursive), where recursive is non-zero if the
5957 * current method is called recursively on obj
5958 */
5959
5961rb_exec_recursive(VALUE (*func) (VALUE, VALUE, int), VALUE obj, VALUE arg)
5962{
5963 return exec_recursive(func, obj, 0, arg, 0, rb_frame_last_func());
5964}
5965
5966/*
5967 * Calls func(obj, arg, recursive), where recursive is non-zero if the
5968 * current method is called recursively on the ordered pair <obj, paired_obj>
5969 */
5970
5972rb_exec_recursive_paired(VALUE (*func) (VALUE, VALUE, int), VALUE obj, VALUE paired_obj, VALUE arg)
5973{
5974 return exec_recursive(func, obj, rb_memory_id(paired_obj), arg, 0, rb_frame_last_func());
5975}
5976
5977/*
5978 * If recursion is detected on the current method and obj, the outermost
5979 * func will be called with (obj, arg, true). All inner func will be
5980 * short-circuited using throw.
5981 */
5982
5984rb_exec_recursive_outer(VALUE (*func) (VALUE, VALUE, int), VALUE obj, VALUE arg)
5985{
5986 return exec_recursive(func, obj, 0, arg, 1, rb_frame_last_func());
5987}
5988
5989VALUE
5990rb_exec_recursive_outer_mid(VALUE (*func) (VALUE, VALUE, int), VALUE obj, VALUE arg, ID mid)
5991{
5992 return exec_recursive(func, obj, 0, arg, 1, mid);
5993}
5994
5995/*
5996 * If recursion is detected on the current method, obj and paired_obj,
5997 * the outermost func will be called with (obj, arg, true). All inner
5998 * func will be short-circuited using throw.
5999 */
6000
6002rb_exec_recursive_paired_outer(VALUE (*func) (VALUE, VALUE, int), VALUE obj, VALUE paired_obj, VALUE arg)
6003{
6004 return exec_recursive(func, obj, rb_memory_id(paired_obj), arg, 1, rb_frame_last_func());
6005}
6006
6007/*
6008 * call-seq:
6009 * thread.backtrace -> array or nil
6010 *
6011 * Returns the current backtrace of the target thread.
6012 *
6013 */
6014
6015static VALUE
6016rb_thread_backtrace_m(int argc, VALUE *argv, VALUE thval)
6017{
6018 return rb_vm_thread_backtrace(argc, argv, thval);
6019}
6020
6021/* call-seq:
6022 * thread.backtrace_locations(*args) -> array or nil
6023 *
6024 * Returns the execution stack for the target thread---an array containing
6025 * backtrace location objects.
6026 *
6027 * See Thread::Backtrace::Location for more information.
6028 *
6029 * This method behaves similarly to Kernel#caller_locations except it applies
6030 * to a specific thread.
6031 */
6032static VALUE
6033rb_thread_backtrace_locations_m(int argc, VALUE *argv, VALUE thval)
6034{
6035 return rb_vm_thread_backtrace_locations(argc, argv, thval);
6036}
6037
6038void
6039Init_Thread_Mutex(void)
6040{
6041 rb_thread_t *th = GET_THREAD();
6042
6043 rb_native_mutex_initialize(&th->vm->once_lock);
6044 rb_native_cond_initialize(&th->vm->once_cond);
6045 rb_native_mutex_initialize(&th->interrupt_lock);
6046}
6047
6048/*
6049 * Document-class: ThreadError
6050 *
6051 * Raised when an invalid operation is attempted on a thread.
6052 *
6053 * For example, when no other thread has been started:
6054 *
6055 * Thread.stop
6056 *
6057 * This will raises the following exception:
6058 *
6059 * ThreadError: stopping only thread
6060 * note: use sleep to stop forever
6061 */
6062
6063void
6064Init_Thread(void)
6065{
6066 rb_thread_t *th = GET_THREAD();
6067
6068 sym_never = ID2SYM(rb_intern_const("never"));
6069 sym_immediate = ID2SYM(rb_intern_const("immediate"));
6070 sym_on_blocking = ID2SYM(rb_intern_const("on_blocking"));
6071
6072 rb_define_singleton_method(rb_cThread, "new", thread_s_new, -1);
6073 rb_define_singleton_method(rb_cThread, "start", thread_start, -2);
6074 rb_define_singleton_method(rb_cThread, "fork", thread_start, -2);
6075 rb_define_singleton_method(rb_cThread, "main", rb_thread_s_main, 0);
6076 rb_define_singleton_method(rb_cThread, "current", thread_s_current, 0);
6077 rb_define_singleton_method(rb_cThread, "stop", thread_stop, 0);
6078 rb_define_singleton_method(rb_cThread, "kill", rb_thread_s_kill, 1);
6079 rb_define_singleton_method(rb_cThread, "exit", rb_thread_exit, 0);
6080 rb_define_singleton_method(rb_cThread, "pass", thread_s_pass, 0);
6081 rb_define_singleton_method(rb_cThread, "list", thread_list, 0);
6082 rb_define_singleton_method(rb_cThread, "abort_on_exception", rb_thread_s_abort_exc, 0);
6083 rb_define_singleton_method(rb_cThread, "abort_on_exception=", rb_thread_s_abort_exc_set, 1);
6084 rb_define_singleton_method(rb_cThread, "report_on_exception", rb_thread_s_report_exc, 0);
6085 rb_define_singleton_method(rb_cThread, "report_on_exception=", rb_thread_s_report_exc_set, 1);
6086 rb_define_singleton_method(rb_cThread, "ignore_deadlock", rb_thread_s_ignore_deadlock, 0);
6087 rb_define_singleton_method(rb_cThread, "ignore_deadlock=", rb_thread_s_ignore_deadlock_set, 1);
6088 rb_define_singleton_method(rb_cThread, "handle_interrupt", rb_thread_s_handle_interrupt, 1);
6089 rb_define_singleton_method(rb_cThread, "pending_interrupt?", rb_thread_s_pending_interrupt_p, -1);
6090 rb_define_method(rb_cThread, "pending_interrupt?", rb_thread_pending_interrupt_p, -1);
6091
6092 rb_define_method(rb_cThread, "initialize", thread_initialize, -2);
6093 rb_define_method(rb_cThread, "raise", thread_raise_m, -1);
6094 rb_define_method(rb_cThread, "join", thread_join_m, -1);
6095 rb_define_method(rb_cThread, "value", thread_value, 0);
6097 rb_define_method(rb_cThread, "terminate", rb_thread_kill, 0);
6101 rb_define_method(rb_cThread, "[]", rb_thread_aref, 1);
6102 rb_define_method(rb_cThread, "[]=", rb_thread_aset, 2);
6103 rb_define_method(rb_cThread, "fetch", rb_thread_fetch, -1);
6104 rb_define_method(rb_cThread, "key?", rb_thread_key_p, 1);
6105 rb_define_method(rb_cThread, "keys", rb_thread_keys, 0);
6106 rb_define_method(rb_cThread, "priority", rb_thread_priority, 0);
6107 rb_define_method(rb_cThread, "priority=", rb_thread_priority_set, 1);
6108 rb_define_method(rb_cThread, "status", rb_thread_status, 0);
6109 rb_define_method(rb_cThread, "thread_variable_get", rb_thread_variable_get, 1);
6110 rb_define_method(rb_cThread, "thread_variable_set", rb_thread_variable_set, 2);
6111 rb_define_method(rb_cThread, "thread_variables", rb_thread_variables, 0);
6112 rb_define_method(rb_cThread, "thread_variable?", rb_thread_variable_p, 1);
6113 rb_define_method(rb_cThread, "alive?", rb_thread_alive_p, 0);
6114 rb_define_method(rb_cThread, "stop?", rb_thread_stop_p, 0);
6115 rb_define_method(rb_cThread, "abort_on_exception", rb_thread_abort_exc, 0);
6116 rb_define_method(rb_cThread, "abort_on_exception=", rb_thread_abort_exc_set, 1);
6117 rb_define_method(rb_cThread, "report_on_exception", rb_thread_report_exc, 0);
6118 rb_define_method(rb_cThread, "report_on_exception=", rb_thread_report_exc_set, 1);
6119 rb_define_method(rb_cThread, "group", rb_thread_group, 0);
6120 rb_define_method(rb_cThread, "backtrace", rb_thread_backtrace_m, -1);
6121 rb_define_method(rb_cThread, "backtrace_locations", rb_thread_backtrace_locations_m, -1);
6122
6123 rb_define_method(rb_cThread, "name", rb_thread_getname, 0);
6124 rb_define_method(rb_cThread, "name=", rb_thread_setname, 1);
6125 rb_define_method(rb_cThread, "native_thread_id", rb_thread_native_thread_id, 0);
6126 rb_define_method(rb_cThread, "to_s", rb_thread_to_s, 0);
6127 rb_define_alias(rb_cThread, "inspect", "to_s");
6128
6129 rb_vm_register_special_exception(ruby_error_stream_closed, rb_eIOError,
6130 "stream closed in another thread");
6131
6132 cThGroup = rb_define_class("ThreadGroup", rb_cObject);
6133 rb_define_alloc_func(cThGroup, thgroup_s_alloc);
6134 rb_define_method(cThGroup, "list", thgroup_list, 0);
6135 rb_define_method(cThGroup, "enclose", thgroup_enclose, 0);
6136 rb_define_method(cThGroup, "enclosed?", thgroup_enclosed_p, 0);
6137 rb_define_method(cThGroup, "add", thgroup_add, 1);
6138
6139 const char * ptr = getenv("RUBY_THREAD_TIMESLICE");
6140
6141 if (ptr) {
6142 long quantum = strtol(ptr, NULL, 0);
6143 if (quantum > 0 && !(SIZEOF_LONG > 4 && quantum > UINT32_MAX)) {
6144 thread_default_quantum_ms = (uint32_t)quantum;
6145 }
6146 else if (0) {
6147 fprintf(stderr, "Ignored RUBY_THREAD_TIMESLICE=%s\n", ptr);
6148 }
6149 }
6150
6151 {
6152 th->thgroup = th->ractor->thgroup_default = rb_obj_alloc(cThGroup);
6153 rb_define_const(cThGroup, "Default", th->thgroup);
6154 }
6155
6156 rb_eThreadError = rb_define_class("ThreadError", rb_eStandardError);
6157
6158 /* init thread core */
6159 {
6160 /* main thread setting */
6161 {
6162 /* acquire global vm lock */
6163#ifdef HAVE_PTHREAD_NP_H
6164 VM_ASSERT(TH_SCHED(th)->running == th);
6165#endif
6166 // thread_sched_to_running() should not be called because
6167 // it assumes blocked by thread_sched_to_waiting().
6168 // thread_sched_to_running(sched, th);
6169
6170 th->pending_interrupt_queue = rb_ary_hidden_new(0);
6171 th->pending_interrupt_queue_checked = 0;
6172 th->pending_interrupt_mask_stack = rb_ary_hidden_new(0);
6173 }
6174 }
6175
6176 rb_thread_create_timer_thread();
6177
6178 Init_thread_sync();
6179
6180 // TODO: Suppress unused function warning for now
6181 // if (0) rb_thread_sched_destroy(NULL);
6182}
6183
6186{
6187 rb_thread_t *th = ruby_thread_from_native();
6188
6189 return th != 0;
6190}
6191
6192#ifdef NON_SCALAR_THREAD_ID
6193 #define thread_id_str(th) (NULL)
6194#else
6195 #define thread_id_str(th) ((void *)(uintptr_t)(th)->nt->thread_id)
6196#endif
6197
6198static void
6199debug_deadlock_check(rb_ractor_t *r, VALUE msg)
6200{
6201 rb_thread_t *th = 0;
6202 VALUE sep = rb_str_new_cstr("\n ");
6203
6204 rb_str_catf(msg, "\n%d threads, %d sleeps current:%p main thread:%p\n",
6205 rb_ractor_living_thread_num(r), rb_ractor_sleeper_thread_num(r),
6206 (void *)GET_THREAD(), (void *)r->threads.main);
6207
6208 ccan_list_for_each(&r->threads.set, th, lt_node) {
6209 rb_str_catf(msg, "* %+"PRIsVALUE"\n rb_thread_t:%p "
6210 "native:%p int:%u",
6211 th->self, (void *)th, th->nt ? thread_id_str(th) : "N/A", th->ec->interrupt_flag);
6212
6213 if (th->locking_mutex) {
6214 rb_mutex_t *mutex = mutex_ptr(th->locking_mutex);
6215 rb_str_catf(msg, " mutex:%llu cond:%"PRIuSIZE,
6216 (unsigned long long)mutex->ec_serial, rb_mutex_num_waiting(mutex));
6217 }
6218
6219 {
6220 struct rb_waiting_list *list = th->join_list;
6221 while (list) {
6222 rb_str_catf(msg, "\n depended by: tb_thread_id:%p", (void *)list->thread);
6223 list = list->next;
6224 }
6225 }
6226 rb_str_catf(msg, "\n ");
6227 rb_str_concat(msg, rb_ary_join(rb_ec_backtrace_str_ary(th->ec, RUBY_BACKTRACE_START, RUBY_ALL_BACKTRACE_LINES), sep));
6228 rb_str_catf(msg, "\n");
6229 }
6230}
6231
6232static void
6233rb_check_deadlock(rb_ractor_t *r)
6234{
6235 if (GET_THREAD()->vm->thread_ignore_deadlock) return;
6236
6237 if (r->threads.sched.readyq_cnt > 0) return;
6238
6239 int sleeper_num = rb_ractor_sleeper_thread_num(r);
6240 int ltnum = rb_ractor_living_thread_num(r);
6241
6242 if (ltnum > sleeper_num) return;
6243 if (ltnum < sleeper_num) rb_bug("sleeper must not be more than vm_living_thread_num(vm)");
6244
6245 int found = 0;
6246 rb_thread_t *th = NULL;
6247
6248 ccan_list_for_each(&r->threads.set, th, lt_node) {
6249 if (th->status != THREAD_STOPPED_FOREVER || RUBY_VM_INTERRUPTED(th->ec)) {
6250 found = 1;
6251 }
6252 else if (th->locking_mutex) {
6253 rb_mutex_t *mutex = mutex_ptr(th->locking_mutex);
6254 if (mutex->ec_serial == rb_ec_serial(th->ec) || (!mutex->ec_serial && !ccan_list_empty(&mutex->waitq))) {
6255 found = 1;
6256 }
6257 }
6258 if (found)
6259 break;
6260 }
6261
6262 if (!found) {
6263 VALUE argv[2];
6264 argv[0] = rb_eFatal;
6265 argv[1] = rb_str_new2("No live threads left. Deadlock?");
6266 debug_deadlock_check(r, argv[1]);
6267 rb_threadptr_raise(r->threads.main, 2, argv);
6268 }
6269}
6270
6271static void
6272update_line_coverage(VALUE data, const rb_trace_arg_t *trace_arg)
6273{
6274 const rb_control_frame_t *cfp = GET_EC()->cfp;
6275 VALUE coverage = rb_iseq_coverage(CFP_ISEQ(cfp));
6276 if (RB_TYPE_P(coverage, T_ARRAY) && !RBASIC_CLASS(coverage)) {
6277 VALUE lines = RARRAY_AREF(coverage, COVERAGE_INDEX_LINES);
6278 if (lines) {
6279 long line = rb_sourceline() - 1;
6280 VM_ASSERT(line >= 0);
6281 long count;
6282 VALUE num;
6283 void rb_iseq_clear_event_flags(const rb_iseq_t *iseq, size_t start, rb_iseq_events_t reset);
6284 if (GET_VM()->coverage_mode & COVERAGE_TARGET_ONESHOT_LINES) {
6285 rb_iseq_clear_event_flags(CFP_ISEQ(cfp), FIX2LONG(trace_arg->data), RUBY_EVENT_COVERAGE_LINE);
6286 rb_ary_push(lines, LONG2NUM(line + 1));
6287 return;
6288 }
6289 if (line >= RARRAY_LEN(lines)) { /* no longer tracked */
6290 return;
6291 }
6292 num = RARRAY_AREF(lines, line);
6293 if (!FIXNUM_P(num)) return;
6294 count = FIX2LONG(num) + 1;
6295 if (POSFIXABLE(count)) {
6296 RARRAY_ASET(lines, line, LONG2FIX(count));
6297 }
6298 }
6299 }
6300}
6301
6302static void
6303update_branch_coverage(VALUE data, const rb_trace_arg_t *trace_arg)
6304{
6305 const rb_control_frame_t *cfp = GET_EC()->cfp;
6306 VALUE coverage = rb_iseq_coverage(CFP_ISEQ(cfp));
6307 if (RB_TYPE_P(coverage, T_ARRAY) && !RBASIC_CLASS(coverage)) {
6308 VALUE branches = RARRAY_AREF(coverage, COVERAGE_INDEX_BRANCHES);
6309 if (branches) {
6310 long pc = CFP_PC(cfp) - ISEQ_BODY(CFP_ISEQ(cfp))->iseq_encoded - 1;
6311 long idx = FIX2INT(RARRAY_AREF(ISEQ_PC2BRANCHINDEX(CFP_ISEQ(cfp)), pc)), count;
6312 VALUE counters = RARRAY_AREF(branches, 1);
6313 VALUE num = RARRAY_AREF(counters, idx);
6314 count = FIX2LONG(num) + 1;
6315 if (POSFIXABLE(count)) {
6316 RARRAY_ASET(counters, idx, LONG2FIX(count));
6317 }
6318 }
6319 }
6320}
6321
6322const rb_method_entry_t *
6323rb_resolve_me_location(const rb_method_entry_t *me, VALUE resolved_location[5])
6324{
6325 VALUE path, beg_pos_lineno, beg_pos_column, end_pos_lineno, end_pos_column;
6326 const rb_method_definition_t *def;
6327
6328 if (!me->def) return NULL; // negative cme
6329
6330 retry:
6331 def = rb_method_entry_def_acquire(me);
6332 switch (def->type) {
6333 case VM_METHOD_TYPE_ISEQ: {
6334 const rb_iseq_t *iseq = def->body.iseq.iseqptr;
6335 rb_iseq_location_t *loc = &ISEQ_BODY(iseq)->location;
6336 path = rb_iseq_path(iseq);
6337 beg_pos_lineno = INT2NUM(loc->code_location.beg_pos.lineno);
6338 beg_pos_column = INT2NUM(loc->code_location.beg_pos.column);
6339 end_pos_lineno = INT2NUM(loc->code_location.end_pos.lineno);
6340 end_pos_column = INT2NUM(loc->code_location.end_pos.column);
6341 break;
6342 }
6343 case VM_METHOD_TYPE_BMETHOD: {
6344 const rb_iseq_t *iseq = rb_proc_get_iseq(def->body.bmethod.proc, 0);
6345 if (iseq) {
6346 rb_iseq_location_t *loc;
6347 rb_iseq_check(iseq);
6348 path = rb_iseq_path(iseq);
6349 loc = &ISEQ_BODY(iseq)->location;
6350 beg_pos_lineno = INT2NUM(loc->code_location.beg_pos.lineno);
6351 beg_pos_column = INT2NUM(loc->code_location.beg_pos.column);
6352 end_pos_lineno = INT2NUM(loc->code_location.end_pos.lineno);
6353 end_pos_column = INT2NUM(loc->code_location.end_pos.column);
6354 break;
6355 }
6356 return NULL;
6357 }
6358 case VM_METHOD_TYPE_ALIAS:
6359 me = rb_method_alias_original_me(def);
6360 goto retry;
6361 case VM_METHOD_TYPE_REFINED:
6362 me = def->body.refined.orig_me;
6363 if (!me) return NULL;
6364 goto retry;
6365 default:
6366 return NULL;
6367 }
6368
6369 /* found */
6370 if (RB_TYPE_P(path, T_ARRAY)) {
6371 path = rb_ary_entry(path, 1);
6372 if (!RB_TYPE_P(path, T_STRING)) return NULL; /* just for the case... */
6373 }
6374 if (resolved_location) {
6375 resolved_location[0] = path;
6376 resolved_location[1] = beg_pos_lineno;
6377 resolved_location[2] = beg_pos_column;
6378 resolved_location[3] = end_pos_lineno;
6379 resolved_location[4] = end_pos_column;
6380 }
6381 return me;
6382}
6384struct method_coverage_arg {
6385 rb_coverage_method_callback *callback;
6386 void *data;
6387};
6388
6389/* Fills *out for the method entry `me_v` and returns true, or returns false
6390 * if the method entry is not a subject of method coverage (aliases,
6391 * complemented entries, and methods without a source location). */
6392bool
6393rb_coverage_method_data_of(VALUE me_v, VALUE count, struct rb_coverage_method_data *out)
6394{
6395 const rb_method_entry_t *me = (const rb_method_entry_t *)me_v;
6396 VALUE location[5];
6397 const rb_method_entry_t *resolved_me = rb_resolve_me_location(me, location);
6398
6399 if (me != resolved_me || RB_TYPE_P(me->owner, T_ICLASS) ||
6400 FIX2LONG(location[1]) <= 0) return false;
6401
6402 out->owner = me->owner;
6403 out->method_id = ID2SYM(me->def->original_id);
6404 out->path = location[0];
6405 out->first_lineno = location[1];
6406 out->first_column = location[2];
6407 out->last_lineno = location[3];
6408 out->last_column = location[4];
6409 out->count = count;
6410 return true;
6411}
6412
6413static void
6414method_coverage_call(const rb_method_entry_t *me, VALUE count,
6415 struct method_coverage_arg *arg)
6416{
6417 struct rb_coverage_method_data method;
6418 if (rb_coverage_method_data_of((VALUE)me, count, &method)) {
6419 arg->callback(&method, arg->data);
6420 }
6421}
6422
6423static int
6424method_coverage_me_i(VALUE me, VALUE value, VALUE data)
6425{
6426 method_coverage_call((const rb_method_entry_t *)me, INT2FIX(0),
6427 (struct method_coverage_arg *)data);
6428 return ST_CONTINUE;
6429}
6430
6431static int
6432method_coverage_count_i(VALUE me, VALUE count, VALUE data)
6433{
6434 if (!FIXNUM_P(count)) count = INT2FIX(0);
6435 method_coverage_call((const rb_method_entry_t *)me, count,
6436 (struct method_coverage_arg *)data);
6437 return ST_CONTINUE;
6438}
6439
6440void
6441rb_coverage_each_method(rb_coverage_method_callback callback, void *data)
6442{
6443 struct method_coverage_arg arg = {callback, data};
6444 VALUE me_set = GET_VM()->me_set;
6445 VALUE cme2counter = GET_VM()->cme2counter;
6446
6447 if (RTEST(me_set)) {
6448 rb_hash_foreach(me_set, method_coverage_me_i, (VALUE)&arg);
6449 }
6450 if (RTEST(cme2counter)) {
6451 rb_hash_foreach(cme2counter, method_coverage_count_i, (VALUE)&arg);
6452 }
6453}
6454
6455static void
6456update_method_coverage(VALUE cme2counter, rb_trace_arg_t *trace_arg)
6457{
6458 const rb_control_frame_t *cfp = GET_EC()->cfp;
6459 const rb_callable_method_entry_t *cme = rb_vm_frame_method_entry(cfp);
6460 const rb_method_entry_t *me = (const rb_method_entry_t *)cme;
6461 VALUE rcount;
6462 long count;
6463
6464 me = rb_resolve_me_location(me, 0);
6465 if (!me) return;
6466
6467 rcount = rb_hash_aref(cme2counter, (VALUE) me);
6468 count = FIXNUM_P(rcount) ? FIX2LONG(rcount) + 1 : 1;
6469 if (POSFIXABLE(count)) {
6470 rb_hash_aset(cme2counter, (VALUE) me, LONG2FIX(count));
6471 }
6472}
6473
6474/* [Bug #22179] Record every method entry as it is defined (via method_added)
6475 * into me_set, so that method coverage no longer needs to reconstruct the set
6476 * of defined methods by walking the heap. This keeps shadowed/removed method
6477 * entries discoverable (me_set holds them as keys, so GC cannot reclaim them)
6478 * and makes the result independent of GC timing. Only entries that resolve to
6479 * themselves (i.e. methods defined by `def` or Module#define_method) are
6480 * recorded. */
6481void
6482rb_vm_coverage_record_me(const rb_method_entry_t *me)
6483{
6484 if (!RTEST(GET_VM()->coverages)) return;
6485 if (!(GET_VM()->coverage_mode & COVERAGE_TARGET_METHODS)) return;
6486
6487 VALUE me_set = GET_VM()->me_set;
6488 if (!RTEST(me_set)) return;
6489
6490 if (rb_resolve_me_location(me, 0) == me) {
6491 rb_hash_aset(me_set, (VALUE)me, Qtrue);
6492 }
6493}
6494
6495VALUE
6496rb_get_coverages(void)
6497{
6498 return GET_VM()->coverages;
6499}
6500
6501int
6502rb_get_coverage_mode(void)
6503{
6504 return GET_VM()->coverage_mode;
6505}
6506
6507void
6508rb_set_coverages(VALUE coverages, int mode, VALUE cme2counter, VALUE me_set)
6509{
6510 GET_VM()->coverages = coverages;
6511 GET_VM()->cme2counter = cme2counter;
6512 GET_VM()->me_set = me_set;
6513 GET_VM()->coverage_mode = mode;
6514}
6515
6516void
6517rb_resume_coverages(void)
6518{
6519 int mode = GET_VM()->coverage_mode;
6520 VALUE cme2counter = GET_VM()->cme2counter;
6521 rb_add_event_hook2((rb_event_hook_func_t) update_line_coverage, RUBY_EVENT_COVERAGE_LINE, Qnil, RUBY_EVENT_HOOK_FLAG_SAFE | RUBY_EVENT_HOOK_FLAG_RAW_ARG);
6522 if (mode & COVERAGE_TARGET_BRANCHES) {
6523 rb_add_event_hook2((rb_event_hook_func_t) update_branch_coverage, RUBY_EVENT_COVERAGE_BRANCH, Qnil, RUBY_EVENT_HOOK_FLAG_SAFE | RUBY_EVENT_HOOK_FLAG_RAW_ARG);
6524 }
6525 if (mode & COVERAGE_TARGET_METHODS) {
6526 rb_add_event_hook2((rb_event_hook_func_t) update_method_coverage, RUBY_EVENT_CALL, cme2counter, RUBY_EVENT_HOOK_FLAG_SAFE | RUBY_EVENT_HOOK_FLAG_RAW_ARG);
6527 }
6528}
6529
6530void
6531rb_suspend_coverages(void)
6532{
6533 rb_remove_event_hook((rb_event_hook_func_t) update_line_coverage);
6534 if (GET_VM()->coverage_mode & COVERAGE_TARGET_BRANCHES) {
6535 rb_remove_event_hook((rb_event_hook_func_t) update_branch_coverage);
6536 }
6537 if (GET_VM()->coverage_mode & COVERAGE_TARGET_METHODS) {
6538 rb_remove_event_hook((rb_event_hook_func_t) update_method_coverage);
6539 }
6540}
6541
6542/* Make coverage arrays empty so old covered files are no longer tracked. */
6543void
6544rb_reset_coverages(void)
6545{
6546 rb_clear_coverages();
6547 rb_iseq_remove_coverage_all();
6548 GET_VM()->coverages = Qfalse;
6549 GET_VM()->cme2counter = Qnil;
6550 GET_VM()->me_set = Qnil;
6551}
6552
6553VALUE
6554rb_default_coverage(int n)
6555{
6556 VALUE coverage = rb_ary_hidden_new_fill(3);
6557 VALUE lines = Qfalse, branches = Qfalse;
6558 int mode = GET_VM()->coverage_mode;
6559
6560 if (mode & COVERAGE_TARGET_LINES) {
6561 lines = n > 0 ? rb_ary_hidden_new_fill(n) : rb_ary_hidden_new(0);
6562 }
6563 RARRAY_ASET(coverage, COVERAGE_INDEX_LINES, lines);
6564
6565 if (mode & COVERAGE_TARGET_BRANCHES) {
6566 branches = rb_ary_hidden_new_fill(2);
6567 /* internal data structures for branch coverage:
6568 *
6569 * { branch base key (see decl_branch_base) =>
6570 * [base_type, base_first_lineno, base_first_column, base_last_lineno, base_last_column, {
6571 * branch target id =>
6572 * [target_type, target_first_lineno, target_first_column, target_last_lineno, target_last_column, target_counter_index],
6573 * ...
6574 * }],
6575 * ...
6576 * }
6577 *
6578 * Example:
6579 * { [source_hash, node_id, lineno] =>
6580 * [1, 0, 4, 3, {
6581 * 0 => [2, 8, 2, 9, 0],
6582 * 1 => [3, 8, 3, 9, 1],
6583 * ...
6584 * }],
6585 * ...
6586 * }
6587 */
6588 VALUE structure = rb_hash_new();
6589 rb_obj_hide(structure);
6590 RARRAY_ASET(branches, 0, structure);
6591 /* branch execution counters */
6592 RARRAY_ASET(branches, 1, rb_ary_hidden_new(0));
6593 }
6594 RARRAY_ASET(coverage, COVERAGE_INDEX_BRANCHES, branches);
6595
6596 return coverage;
6597}
6598
6599static VALUE
6600uninterruptible_exit(VALUE v)
6601{
6602 rb_thread_t *cur_th = GET_THREAD();
6603 rb_ary_pop(cur_th->pending_interrupt_mask_stack);
6604
6605 cur_th->pending_interrupt_queue_checked = 0;
6606 if (!rb_threadptr_pending_interrupt_empty_p(cur_th)) {
6607 RUBY_VM_SET_INTERRUPT(cur_th->ec);
6608 }
6609 return Qnil;
6610}
6611
6612VALUE
6613rb_uninterruptible(VALUE (*b_proc)(VALUE), VALUE data)
6614{
6615 VALUE interrupt_mask = rb_ident_hash_new();
6616 rb_thread_t *cur_th = GET_THREAD();
6617
6618 rb_hash_aset(interrupt_mask, rb_cObject, sym_never);
6619 OBJ_FREEZE(interrupt_mask);
6620 rb_ary_push(cur_th->pending_interrupt_mask_stack, interrupt_mask);
6621
6622 VALUE ret = rb_ensure(b_proc, data, uninterruptible_exit, Qnil);
6623
6624 RUBY_VM_CHECK_INTS(cur_th->ec);
6625 return ret;
6626}
6627
6628static void
6629thread_specific_storage_alloc(rb_thread_t *th)
6630{
6631 VM_ASSERT(th->specific_storage == NULL);
6632
6633 if (UNLIKELY(specific_key_count > 0)) {
6634 th->specific_storage = ZALLOC_N(void *, RB_INTERNAL_THREAD_SPECIFIC_KEY_MAX);
6635 }
6636}
6637
6638rb_internal_thread_specific_key_t
6640{
6641 rb_vm_t *vm = GET_VM();
6642
6643 if (specific_key_count == 0 && vm->ractor.cnt > 1) {
6644 rb_raise(rb_eThreadError, "The first rb_internal_thread_specific_key_create() is called with multiple ractors");
6645 }
6646 else if (specific_key_count >= RB_INTERNAL_THREAD_SPECIFIC_KEY_MAX) {
6647 rb_raise(rb_eThreadError, "rb_internal_thread_specific_key_create() is called more than %d times", RB_INTERNAL_THREAD_SPECIFIC_KEY_MAX);
6648 }
6649 else {
6650 rb_internal_thread_specific_key_t key = specific_key_count++;
6651
6652 if (key == 0) {
6653 // allocate
6654 rb_ractor_t *cr = GET_RACTOR();
6655 rb_thread_t *th;
6656
6657 ccan_list_for_each(&cr->threads.set, th, lt_node) {
6658 thread_specific_storage_alloc(th);
6659 }
6660 }
6661 return key;
6662 }
6663}
6664
6665// async and native thread safe.
6666void *
6667rb_internal_thread_specific_get(VALUE thread_val, rb_internal_thread_specific_key_t key)
6668{
6669 rb_thread_t *th = DATA_PTR(thread_val);
6670
6671 VM_ASSERT(rb_thread_ptr(thread_val) == th);
6672 VM_ASSERT(key < RB_INTERNAL_THREAD_SPECIFIC_KEY_MAX);
6673 VM_ASSERT(th->specific_storage);
6674
6675 return th->specific_storage[key];
6676}
6677
6678// async and native thread safe.
6679void
6680rb_internal_thread_specific_set(VALUE thread_val, rb_internal_thread_specific_key_t key, void *data)
6681{
6682 rb_thread_t *th = DATA_PTR(thread_val);
6683
6684 VM_ASSERT(rb_thread_ptr(thread_val) == th);
6685 VM_ASSERT(key < RB_INTERNAL_THREAD_SPECIFIC_KEY_MAX);
6686 VM_ASSERT(th->specific_storage);
6687
6688 th->specific_storage[key] = data;
6689}
6690
6691// interrupt_exec
6694 struct ccan_list_node node;
6695
6696 rb_interrupt_exec_func_t *func;
6697 void *data;
6698 enum rb_interrupt_exec_flag flags;
6699};
6700
6701void
6702rb_threadptr_interrupt_exec_task_mark(rb_thread_t *th)
6703{
6704 struct rb_interrupt_exec_task *task;
6705
6706 ccan_list_for_each(&th->interrupt_exec_tasks, task, node) {
6707 if (task->flags & rb_interrupt_exec_flag_value_data) {
6708 rb_gc_mark((VALUE)task->data);
6709 }
6710 }
6711}
6712
6713// native thread safe
6714// th should be available
6715void
6716rb_threadptr_interrupt_exec(rb_thread_t *th, rb_interrupt_exec_func_t *func, void *data, enum rb_interrupt_exec_flag flags)
6717{
6718 // should not use ALLOC
6720 *task = (struct rb_interrupt_exec_task) {
6721 .flags = flags,
6722 .func = func,
6723 .data = data,
6724 };
6725
6726 rb_native_mutex_lock(&th->interrupt_lock);
6727 {
6728 ccan_list_add_tail(&th->interrupt_exec_tasks, &task->node);
6729 threadptr_set_interrupt_locked(th, true);
6730 }
6731 rb_native_mutex_unlock(&th->interrupt_lock);
6732}
6733
6734static void
6735threadptr_interrupt_exec_exec(rb_thread_t *th)
6736{
6737 while (1) {
6738 struct rb_interrupt_exec_task *task;
6739
6740 rb_native_mutex_lock(&th->interrupt_lock);
6741 {
6742 task = ccan_list_pop(&th->interrupt_exec_tasks, struct rb_interrupt_exec_task, node);
6743 }
6744 rb_native_mutex_unlock(&th->interrupt_lock);
6745
6746 RUBY_DEBUG_LOG("task:%p", task);
6747
6748 if (task) {
6749 if (task->flags & rb_interrupt_exec_flag_new_thread) {
6750 rb_thread_create(task->func, task->data);
6751 }
6752 else {
6753 (*task->func)(task->data);
6754 }
6755 SIZED_FREE(task);
6756 }
6757 else {
6758 break;
6759 }
6760 }
6761}
6762
6763static void
6764threadptr_interrupt_exec_cleanup(rb_thread_t *th)
6765{
6766 rb_native_mutex_lock(&th->interrupt_lock);
6767 {
6768 struct rb_interrupt_exec_task *task;
6769
6770 while ((task = ccan_list_pop(&th->interrupt_exec_tasks, struct rb_interrupt_exec_task, node)) != NULL) {
6771 SIZED_FREE(task);
6772 }
6773 }
6774 rb_native_mutex_unlock(&th->interrupt_lock);
6775}
6776
6777// native thread safe
6778// func/data should be native thread safe
6779void
6780rb_ractor_interrupt_exec(struct rb_ractor_struct *target_r,
6781 rb_interrupt_exec_func_t *func, void *data, enum rb_interrupt_exec_flag flags)
6782{
6783 RUBY_DEBUG_LOG("flags:%d", (int)flags);
6784
6785 rb_thread_t *main_th = target_r->threads.main;
6786 rb_threadptr_interrupt_exec(main_th, func, data, flags | rb_interrupt_exec_flag_new_thread);
6787}
std::atomic< unsigned > rb_atomic_t
Type that is eligible for atomic operations.
Definition atomic.h:69
#define rb_define_method(klass, mid, func, arity)
Defines klass#mid.
#define rb_define_singleton_method(klass, mid, func, arity)
Defines klass.mid.
struct rb_trace_arg_struct rb_trace_arg_t
Type that represents a specific trace event.
Definition debug.h:465
#define RUBY_INTERNAL_EVENT_SWITCH
Thread switched.
Definition event.h:93
int rb_remove_event_hook(rb_event_hook_func_t func)
Removes the passed function from the list of event hooks.
Definition vm_trace.c:454
#define RUBY_EVENT_THREAD_BEGIN
Encountered a new thread.
Definition event.h:76
void(* rb_event_hook_func_t)(rb_event_flag_t evflag, VALUE data, VALUE self, ID mid, VALUE klass)
Type of event hooks.
Definition event.h:127
#define RUBY_EVENT_CALL
A method, written in Ruby, is called.
Definition event.h:41
#define RUBY_EVENT_THREAD_END
Encountered an end of a thread.
Definition event.h:77
static void RB_FL_SET_RAW(VALUE obj, VALUE flags)
This is an implementation detail of RB_FL_SET().
Definition fl_type.h:544
void rb_define_alias(VALUE klass, const char *name1, const char *name2)
Defines an alias of a method.
Definition class.c:3117
ID rb_frame_last_func(void)
Returns the ID of the last method in the call stack.
Definition eval.c:1276
int rb_keyword_given_p(void)
Determines if the current method is given a keyword argument.
Definition eval.c:1055
int rb_block_given_p(void)
Determines if the current method is given a block.
Definition eval.c:1042
#define rb_str_new2
Old name of rb_str_new_cstr.
Definition string.h:1700
#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 UNREACHABLE
Old name of RBIMPL_UNREACHABLE.
Definition assume.h:28
#define ID2SYM
Old name of RB_ID2SYM.
Definition symbol.h:44
#define OBJ_FREEZE
Old name of RB_OBJ_FREEZE.
Definition fl_type.h:131
#define UNREACHABLE_RETURN
Old name of RBIMPL_UNREACHABLE_RETURN.
Definition assume.h:29
#define CLASS_OF
Old name of rb_class_of.
Definition globals.h:205
#define xmalloc
Old name of ruby_xmalloc.
Definition xmalloc.h:53
#define LONG2FIX
Old name of RB_INT2FIX.
Definition long.h:49
#define FIX2INT
Old name of RB_FIX2INT.
Definition int.h:41
#define ZALLOC_N
Old name of RB_ZALLOC_N.
Definition memory.h:404
#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 LONG2NUM
Old name of RB_LONG2NUM.
Definition long.h:50
#define Qtrue
Old name of RUBY_Qtrue.
#define NUM2INT
Old name of RB_NUM2INT.
Definition int.h:44
#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 FIX2LONG
Old name of RB_FIX2LONG.
Definition long.h:46
#define T_ARRAY
Old name of RUBY_T_ARRAY.
Definition value_type.h:56
#define T_OBJECT
Old name of RUBY_T_OBJECT.
Definition value_type.h:75
#define NIL_P
Old name of RB_NIL_P.
#define POSFIXABLE
Old name of RB_POSFIXABLE.
Definition fixnum.h:29
#define BUILTIN_TYPE
Old name of RB_BUILTIN_TYPE.
Definition value_type.h:85
#define FIXNUM_P
Old name of RB_FIXNUM_P.
#define SYMBOL_P
Old name of RB_SYMBOL_P.
Definition value_type.h:88
void ruby_stop(int ex)
Calls ruby_cleanup() and exits the process.
Definition eval.c:308
#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_eSystemExit
SystemExit exception.
Definition error.c:1450
VALUE rb_eIOError
IOError exception.
Definition io.c:180
VALUE rb_eStandardError
StandardError exception.
Definition error.c:1454
VALUE rb_eTypeError
TypeError exception.
Definition error.c:1457
void rb_frozen_error_raise(VALUE frozen_obj, const char *fmt,...)
Raises an instance of rb_eFrozenError.
Definition error.c:4265
VALUE rb_eFatal
fatal exception.
Definition error.c:1453
VALUE rb_eInterrupt
Interrupt exception.
Definition error.c:1451
VALUE rb_eRuntimeError
RuntimeError exception.
Definition error.c:1455
void rb_warn(const char *fmt,...)
Identical to rb_warning(), except it reports unless $VERBOSE is nil.
Definition error.c:464
VALUE rb_eException
Mother of all exceptions.
Definition error.c:1449
VALUE rb_exc_new(VALUE etype, const char *ptr, rb_len_t len)
Creates an instance of the passed exception class.
Definition error.c:1495
VALUE rb_eThreadError
ThreadError exception.
Definition eval.c:1060
void rb_exit(int status)
Terminates the current execution context.
Definition process.c:4322
VALUE rb_eSignal
SignalException exception.
Definition error.c:1452
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_cInteger
Module class.
Definition numeric.c:202
VALUE rb_obj_hide(VALUE obj)
Make the object invisible from Ruby code.
Definition object.c:94
VALUE rb_obj_class(VALUE obj)
Queries the class of an object.
Definition object.c:230
VALUE rb_cThread
Thread class.
Definition vm.c:719
VALUE rb_cModule
Module class.
Definition object.c:61
double rb_num2dbl(VALUE num)
Converts an instance of rb_cNumeric into C's double.
Definition object.c:3845
VALUE rb_obj_is_kind_of(VALUE obj, VALUE klass)
Queries if the given object is an instance (of possibly descendants) of the given class.
Definition object.c:902
#define RUBY_ASSERT_ALWAYS(expr,...)
A variant of RUBY_ASSERT that does not interface with RUBY_DEBUG.
Definition assert.h:199
#define RUBY_ASSERT(...)
Asserts that the given expression is truthy if and only if RUBY_DEBUG is truthy.
Definition assert.h:219
Scheduler APIs.
VALUE rb_fiber_scheduler_blocking_operation_wait(VALUE scheduler, void *(*function)(void *), void *data, rb_unblock_function_t *unblock_function, void *data2, int flags, struct rb_fiber_scheduler_blocking_operation_state *state)
Defer the execution of the passed function to the scheduler.
Definition scheduler.c:1243
VALUE rb_fiber_scheduler_current(void)
Identical to rb_fiber_scheduler_get(), except it also returns RUBY_Qnil in case of a blocking fiber.
Definition scheduler.c:581
VALUE rb_fiber_scheduler_block(VALUE scheduler, VALUE blocker, VALUE timeout)
Non-blocking wait for the passed "blocker", which is for instance Thread.join or Mutex....
Definition scheduler.c:770
VALUE rb_fiber_scheduler_fiber_interrupt(VALUE scheduler, VALUE target, VALUE exception)
Interrupt a target by raising an exception.
Definition scheduler.c:1290
VALUE rb_fiber_scheduler_yield(VALUE scheduler)
Yield to the scheduler, to be resumed on the next scheduling cycle.
Definition scheduler.c:671
VALUE rb_fiber_scheduler_set(VALUE scheduler)
Destructively assigns the passed scheduler to that of the current thread that is calling this functio...
Definition scheduler.c:543
VALUE rb_fiber_scheduler_current_for_threadptr(struct rb_thread_struct *thread)
Identical to rb_fiber_scheduler_current_for_thread(), except it expects a threadptr instead of a thre...
Definition scheduler.c:594
VALUE rb_fiber_scheduler_unblock(VALUE scheduler, VALUE blocker, VALUE fiber)
Wakes up a fiber previously blocked using rb_fiber_scheduler_block().
Definition scheduler.c:789
VALUE rb_ary_shift(VALUE ary)
Destructively deletes an element from the beginning of the passed array and returns what was deleted.
VALUE rb_ary_entry(VALUE ary, rb_len_t off)
Queries an element of an array.
VALUE rb_ary_dup(VALUE ary)
Duplicates an array.
VALUE rb_ary_delete_at(VALUE ary, rb_len_t pos)
Destructively removes an element which resides at the specific index of the passed array.
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_clear(VALUE ary)
Destructively removes everything form an array.
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_join(VALUE ary, VALUE sep)
Recursively stringises the elements of the passed array, flattens that result, then joins the sequenc...
static int rb_check_arity(int argc, int min, int max)
Ensures that the passed integer is in the passed range.
Definition error.h:284
VALUE rb_hash_new(void)
Creates a new, empty hash object.
Definition hash.c:1670
VALUE rb_block_proc(void)
Constructs a Proc object from implicitly passed components.
Definition proc.c:1588
void rb_reset_random_seed(void)
Resets the RNG behind rb_genrand_int32()/rb_genrand_real().
Definition random.c:1757
VALUE rb_str_new_frozen(VALUE str)
Creates a frozen copy of the string, if necessary.
Definition string.c:1602
VALUE rb_str_concat(VALUE dst, VALUE src)
Identical to rb_str_append(), except it also accepts an integer as a codepoint.
Definition string.c:4276
#define rb_str_cat_cstr(buf, str)
Identical to rb_str_cat(), except it assumes the passed pointer is a pointer to a C string.
Definition string.h:1681
#define rb_str_new_cstr(str)
Identical to rb_str_new, except it assumes the passed pointer is a pointer to a C string.
Definition string.h:1539
int rb_thread_interrupted(VALUE thval)
Checks if the thread's execution was recently interrupted.
Definition thread.c:1664
VALUE rb_thread_local_aref(VALUE thread, ID key)
This badly named function reads from a Fiber local storage.
Definition thread.c:4083
VALUE rb_mutex_new(void)
Creates a mutex.
VALUE rb_thread_kill(VALUE thread)
Terminates the given thread.
Definition thread.c:3275
#define RUBY_UBF_IO
A special UBF for blocking IO operations.
Definition thread.h:382
VALUE rb_thread_main(void)
Obtains the "main" thread.
Definition thread.c:3514
VALUE rb_exec_recursive(VALUE(*f)(VALUE g, VALUE h, int r), VALUE g, VALUE h)
"Recursion" API entry point.
Definition thread.c:5960
void rb_thread_sleep_forever(void)
Blocks indefinitely.
Definition thread.c:1593
void rb_thread_fd_close(int fd)
This function is now a no-op.
Definition thread.c:3211
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_thread_stop(void)
Stops the current thread.
Definition thread.c:3426
VALUE rb_mutex_sleep(VALUE self, VALUE timeout)
Releases the lock held in the mutex and waits for the period of time; reacquires the lock on wakeup.
VALUE rb_exec_recursive_paired(VALUE(*f)(VALUE g, VALUE h, int r), VALUE g, VALUE p, VALUE h)
Identical to rb_exec_recursive(), except it checks for the recursion on the ordered pair of { g,...
Definition thread.c:5971
void rb_unblock_function_t(void *)
This is the type of UBFs.
Definition thread.h:336
void rb_thread_atfork_before_exec(void)
:FIXME: situation of this function is unclear.
Definition thread.c:5435
void rb_thread_check_ints(void)
Checks for interrupts.
Definition thread.c:1647
VALUE rb_thread_run(VALUE thread)
This is a rb_thread_wakeup() + rb_thread_schedule() combo.
Definition thread.c:3417
VALUE rb_thread_wakeup(VALUE thread)
Marks a given thread as eligible for scheduling.
Definition thread.c:3370
VALUE rb_mutex_unlock(VALUE mutex)
Releases the mutex.
VALUE rb_exec_recursive_paired_outer(VALUE(*f)(VALUE g, VALUE h, int r), VALUE g, VALUE p, VALUE h)
Identical to rb_exec_recursive_outer(), except it checks for the recursion on the ordered pair of { g...
Definition thread.c:6001
void rb_thread_sleep_deadly(void)
Identical to rb_thread_sleep_forever(), except the thread calling this function is considered "dead" ...
Definition thread.c:1600
void rb_thread_atfork(void)
A pthread_atfork(3posix)-like API.
Definition thread.c:5430
VALUE rb_thread_current(void)
Obtains the "current" thread.
Definition thread.c:3493
int rb_thread_alone(void)
Checks if the thread this function is running is the only thread that is currently alive.
Definition thread.c:4371
VALUE rb_thread_local_aset(VALUE thread, ID key, VALUE val)
This badly named function writes to a Fiber local storage.
Definition thread.c:4231
void rb_thread_schedule(void)
Tries to switch to another thread.
Definition thread.c:1695
#define RUBY_UBF_PROCESS
A special UBF for blocking process operations.
Definition thread.h:389
VALUE rb_exec_recursive_outer(VALUE(*f)(VALUE g, VALUE h, int r), VALUE g, VALUE h)
Identical to rb_exec_recursive(), except it calls f for outermost recursion only.
Definition thread.c:5983
VALUE rb_thread_wakeup_alive(VALUE thread)
Identical to rb_thread_wakeup(), except it doesn't raise on an already killed thread.
Definition thread.c:3379
VALUE rb_mutex_lock(VALUE mutex)
Attempts to lock the mutex.
void rb_thread_sleep(int sec)
Blocks for the given period of time.
Definition thread.c:1670
void rb_timespec_now(struct timespec *ts)
Fills the current time into the given struct.
Definition time.c:2034
struct timeval rb_time_timeval(VALUE time)
Converts an instance of rb_cTime to a struct timeval that represents the identical point of time.
Definition time.c:3026
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:2177
VALUE rb_ivar_get(VALUE obj, ID name)
Identical to rb_iv_get(), except it accepts the name as an ID instead of a C string.
Definition variable.c:1656
VALUE rb_class_path(VALUE mod)
Identical to rb_mod_name(), except it returns #<Class: ...> style inspection for anonymous modules.
Definition variable.c:388
void rb_define_alloc_func(VALUE klass, rb_alloc_func_t func)
Sets the allocator function of a class.
int rb_sourceline(void)
Resembles __LINE__.
Definition vm.c:2233
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:1334
VALUE rb_to_symbol(VALUE name)
Identical to rb_intern_str(), except it generates a dynamic symbol if necessary.
Definition string.c:16581
ID rb_to_id(VALUE str)
Identical to rb_intern_str(), except it tries to convert the parameter object to an instance of rb_cS...
Definition string.c:16571
int capa
Designed capacity of the buffer.
Definition io.h:11
#define RB_IO_POINTER(obj, fp)
Queries the underlying IO pointer.
Definition io.h:436
VALUE rb_eIOTimeoutError
Indicates that a timeout has occurred while performing an IO operation.
Definition io.c:181
#define RB_NOGVL_UBF_ASYNC_SAFE
Passing this flag to rb_nogvl() indicates that the passed UBF is async-signal-safe.
Definition thread.h:71
int ruby_thread_has_gvl_p(void)
Whether the current thread is holding the GVL.
Definition thread.c:2365
void * rb_internal_thread_specific_get(VALUE thread_val, rb_internal_thread_specific_key_t key)
Get thread and tool specific data.
Definition thread.c:6666
#define RB_NOGVL_INTR_FAIL
Passing this flag to rb_nogvl() prevents it from processing interrupts after the given function retur...
Definition thread.h:50
void rb_internal_thread_specific_set(VALUE thread_val, rb_internal_thread_specific_key_t key, void *data)
Set thread and tool specific data.
Definition thread.c:6679
rb_internal_thread_specific_key_t rb_internal_thread_specific_key_create(void)
Create a key to store thread specific data.
Definition thread.c:6638
#define RB_NOGVL_PENDING_INTR_FAIL
Passing this flag to rb_nogvl() prevents it from entering the blocking region if the current thread h...
Definition thread.h:59
void * rb_nogvl(void *(*func)(void *), void *data1, rb_unblock_function_t *ubf, void *data2, int flags)
Identical to rb_thread_call_without_gvl(), except it additionally takes "flags" that change the behav...
Definition thread.c:1775
void * rb_thread_call_with_gvl(void *(*func)(void *), void *data1)
(Re-)acquires the GVL.
Definition thread.c:2324
#define RB_NOGVL_OFFLOAD_SAFE
Passing this flag to rb_nogvl() indicates that the passed function is safe to offload to a background...
Definition thread.h:84
void * rb_thread_call_without_gvl2(void *(*func)(void *), void *data1, rb_unblock_function_t *ubf, void *data2)
Identical to rb_thread_call_without_gvl(), except it does not interface with signals etc.
Definition thread.c:1926
void * rb_thread_call_without_gvl(void *(*func)(void *), void *data1, rb_unblock_function_t *ubf, void *data2)
Allows the passed function to run in parallel with other Ruby threads.
Definition thread.c:1933
#define RB_BLOCK_CALL_FUNC_ARGLIST(yielded_arg, callback_arg)
Shim for block function parameters.
Definition iterator.h:58
VALUE rb_yield(VALUE val)
Yields the block.
Definition vm_eval.c:1409
void rb_throw_obj(VALUE tag, VALUE val)
Identical to rb_throw(), except it allows arbitrary Ruby object to become a tag.
Definition vm_eval.c:2639
static int rb_fd_max(const rb_fdset_t *f)
It seems this function has no use.
Definition largesize.h:209
void rb_fd_copy(rb_fdset_t *dst, const fd_set *src, int max)
Destructively overwrites an fdset with another.
void rb_fd_dup(rb_fdset_t *dst, const rb_fdset_t *src)
Identical to rb_fd_copy(), except it copies unlimited number of file descriptors.
void rb_fd_term(rb_fdset_t *f)
Destroys the rb_fdset_t, releasing any memory and resources it used.
static fd_set * rb_fd_ptr(const rb_fdset_t *f)
Raw pointer to fd_set.
Definition largesize.h:195
#define MEMCPY(p1, p2, type, n)
Handy macro to call memcpy.
Definition memory.h:375
#define ALLOCA_N(type, n)
Definition memory.h:295
#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_thread_create(type *q, void *w)
Creates a rb_cThread instance.
void rb_hash_foreach(VALUE q, int_type *w, VALUE e)
Iteration over the given hash.
VALUE rb_ensure(type *q, VALUE w, type *e, VALUE r)
An equivalent of ensure clause.
#define rb_fd_isset
Queries if the given fd is in the rb_fdset_t.
Definition posix.h:60
#define rb_fd_select
Waits for multiple file descriptors at once.
Definition posix.h:66
#define rb_fd_init
Initialises the :given :rb_fdset_t.
Definition posix.h:63
#define rb_fd_set
Sets the given fd to the rb_fdset_t.
Definition posix.h:54
fd_set rb_fdset_t
The data structure which wraps the fd_set bitmap used by select(2).
Definition posix.h:48
#define rb_fd_zero
Clears the given rb_fdset_t.
Definition posix.h:51
#define rb_fd_clr
Unsets the given fd from the rb_fdset_t.
Definition posix.h:57
#define RARRAY_LEN
Just another name of rb_array_len.
Definition rarray.h:51
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 RCLASS_SUPER
Just another name of rb_class_get_superclass.
Definition rclass.h:44
#define RHASH_EMPTY_P(h)
Checks if the hash is empty.
Definition rhash.h:67
#define StringValueCStr(v)
Identical to StringValuePtr, except it additionally checks for the contents for viability as a C stri...
Definition rstring.h:89
#define RUBY_TYPED_DEFAULT_FREE
This is a value you can set to rb_data_type_struct::dfree.
Definition rtypeddata.h:81
#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
#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
int rb_errno(void)
Identical to system errno.
Definition eval.c:2365
#define errno
Ractor-aware version of errno.
Definition ruby.h:388
int ruby_native_thread_p(void)
Queries if the thread which calls this function is a ruby's thread.
Definition thread.c:6184
int ruby_snprintf(char *str, size_t n, char const *fmt,...)
Our own locale-insensitive version of snprintf(3).
Definition sprintf.c:1086
#define RB_PASS_CALLED_KEYWORDS
Pass keywords if current method is called with keywords, useful for argument delegation.
Definition scan_args.h:78
int rb_thread_fd_select(int nfds, rb_fdset_t *rfds, rb_fdset_t *wfds, rb_fdset_t *efds, struct timeval *timeout)
Waits for multiple file descriptors at once.
Definition thread.c:4869
#define rb_fd_resize(n, f)
Does nothing (defined for compatibility).
Definition select.h:43
static bool RB_TEST(VALUE obj)
Emulates Ruby's "if" statement.
#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
The data structure which wraps the fd_set bitmap used by select(2).
Definition largesize.h:71
int maxfd
Maximum allowed number of FDs.
Definition largesize.h:72
fd_set * fdset
File descriptors buffer.
Definition largesize.h:73
int capa
Maximum allowed number of FDs.
Definition win32.h:50
Ruby's IO, metadata and buffers.
Definition io.h:295
VALUE self
The IO's Ruby level counterpart.
Definition io.h:298
int fd
file descriptor.
Definition io.h:306
struct ccan_list_head blocking_operations
Threads that are performing a blocking operation without the GVL using this IO.
Definition io.h:134
const rb_iseq_t * iseqptr
iseq pointer, should be separated from iseqval
Definition method.h:143
void rb_nativethread_lock_lock(rb_nativethread_lock_t *lock)
Blocks until the current thread obtains a lock.
Definition thread.c:319
void rb_native_mutex_lock(rb_nativethread_lock_t *lock)
Just another name of rb_nativethread_lock_lock.
void rb_native_cond_initialize(rb_nativethread_cond_t *cond)
Fills the passed condition variable with an initial value.
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_nativethread_lock_unlock(rb_nativethread_lock_t *lock)
Releases a lock.
Definition thread.c:325
void rb_native_mutex_destroy(rb_nativethread_lock_t *lock)
Just another name of rb_nativethread_lock_destroy.
void rb_nativethread_lock_initialize(rb_nativethread_lock_t *lock)
Fills the passed lock with an initial value.
Definition thread.c:307
void rb_nativethread_lock_destroy(rb_nativethread_lock_t *lock)
Destroys the passed mutex.
Definition thread.c:313
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 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