Ruby 4.1.0dev (2026-09-07 revision b57404b461ba8bf34e802d86b0db78388216e182)
thread_win32.c (b57404b461ba8bf34e802d86b0db78388216e182)
1/* -*-c-*- */
2/**********************************************************************
3
4 thread_win32.c -
5
6 $Author$
7
8 Copyright (C) 2004-2007 Koichi Sasada
9
10 Windows platform primitives for the common thread/ractor scheduler. The
11 scheduler itself is in thread_sched.c, which includes this file and then
12 builds on the primitives below; see thread_sched.h for the contract.
13
14**********************************************************************/
15
16#ifdef THREAD_SYSTEM_DEPENDENT_IMPLEMENTATION
17
18#include "internal/sanitizers.h"
19#include <process.h>
20
21#undef Sleep
22
23#define native_thread_yield() Sleep(0)
24
25// A CRITICAL_SECTION is recursive, so trylock cannot tell "held by me" from
26// "free"; see thread_sched.c.
27#define RB_NATIVE_MUTEX_TRYLOCK_DETECTS_SELF 0
28
29// M:N threads need an event backend to park a coroutine on (epoll/kqueue on
30// the POSIX side; IOCP would be the Windows counterpart). Until there is one
31// every thread here is dedicated, and this file supplies the stubs that
32// thread_sched_mn.c provides elsewhere.
33#define USE_MN_THREADS 0
34
35// Interruption is delivered through a per-native-thread event object rather
36// than a signal, but the bookkeeping is the same as everywhere else.
37#define USE_UBF_LIST 1
38
39#include COROUTINE_H
40
41// Thread event hooks are not implemented on this platform.
42#define RB_INTERNAL_THREAD_HOOK(event, th) ((void)0)
43
44// No fork(), so this never advances; it only keeps TIMER_THREAD_CREATED_P()
45// spelled the same way on both platforms.
46static rb_serial_t current_fork_gen = 1;
47
48// Always: native_cond_timedwait() below takes the rb_hrtime_t deadline and
49// converts it to the relative timeout the Win32 wait wants itself.
50#define RB_NATIVE_COND_HRTIME_DEADLINE_P() 1
51
52static volatile DWORD ruby_native_thread_key = TLS_OUT_OF_INDEXES;
53
54static int w32_wait_events(HANDLE *events, int count, DWORD timeout, rb_thread_t *th);
55static void native_thread_destroy(struct rb_native_thread *nt);
56static void timer_thread_wakeup_force(void);
57static void ubf_select(void *ptr); // thread_sched.c
58
59rb_internal_thread_event_hook_t *
60rb_internal_thread_add_event_hook(rb_internal_thread_event_callback callback, rb_event_flag_t internal_event, void *user_data)
61{
62 // not implemented
63 return NULL;
64}
65
66bool
67rb_internal_thread_remove_event_hook(rb_internal_thread_event_hook_t * hook)
68{
69 // not implemented
70 return false;
71}
72
73bool
74rb_thread_event_hooks_registered_p(void)
75{
76 return false; // hooks are not implemented on this platform
77}
78
80static void
81w32_error(const char *func)
82{
83 LPVOID lpMsgBuf;
84 DWORD err = GetLastError();
85 if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
86 FORMAT_MESSAGE_FROM_SYSTEM |
87 FORMAT_MESSAGE_IGNORE_INSERTS,
88 NULL,
89 err,
90 MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US),
91 (LPTSTR) & lpMsgBuf, 0, NULL) == 0)
92 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
93 FORMAT_MESSAGE_FROM_SYSTEM |
94 FORMAT_MESSAGE_IGNORE_INSERTS,
95 NULL,
96 err,
97 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
98 (LPTSTR) & lpMsgBuf, 0, NULL);
99 rb_bug("%s: %s", func, (char*)lpMsgBuf);
101}
102
103#define W32_EVENT_DEBUG 0
104
105#if W32_EVENT_DEBUG
106#define w32_event_debug printf
107#else
108#define w32_event_debug if (0) printf
109#endif
110
111static int
112w32_mutex_lock(HANDLE lock, bool try)
113{
114 DWORD result;
115 while (1) {
116 // RUBY_DEBUG_LOG() is not available because RUBY_DEBUG_LOG() calls it.
117 w32_event_debug("lock:%p\n", lock);
118
119 result = w32_wait_events(&lock, 1, try ? 0 : INFINITE, 0);
120 switch (result) {
121 case WAIT_OBJECT_0:
122 /* get mutex object */
123 w32_event_debug("locked lock:%p\n", lock);
124 return 0;
125
126 case WAIT_OBJECT_0 + 1:
127 /* interrupt */
128 errno = EINTR;
129 w32_event_debug("interrupted lock:%p\n", lock);
130 return 0;
131
132 case WAIT_TIMEOUT:
133 w32_event_debug("timeout locK:%p\n", lock);
134 return EBUSY;
135
136 case WAIT_ABANDONED:
137 rb_bug("win32_mutex_lock: WAIT_ABANDONED");
138 break;
139
140 default:
141 rb_bug("win32_mutex_lock: unknown result (%ld)", result);
142 break;
143 }
144 }
145 return 0;
146}
147
148static HANDLE
149w32_mutex_create(void)
150{
151 HANDLE lock = CreateMutex(NULL, FALSE, NULL);
152 if (lock == NULL) {
153 w32_error("rb_native_mutex_initialize");
154 }
155 return lock;
156}
157
158static void
159w32_close_handle(HANDLE handle)
160{
161 if (CloseHandle(handle) == 0) {
162 w32_error("w32_close_handle");
163 }
164}
165
166/* -------------------------------------------------------------------------
167 * native mutex / condition variable
168 * ------------------------------------------------------------------------- */
169
170void
171rb_native_mutex_lock(rb_nativethread_lock_t *lock)
172{
173#ifdef USE_WIN32_MUTEX
174 w32_mutex_lock(lock->mutex, false);
175#else
176 EnterCriticalSection(&lock->crit);
177#endif
178}
179
180int
181rb_native_mutex_trylock(rb_nativethread_lock_t *lock)
182{
183#ifdef USE_WIN32_MUTEX
184 return w32_mutex_lock(lock->mutex, true);
185#else
186 return TryEnterCriticalSection(&lock->crit) == 0 ? EBUSY : 0;
187#endif
188}
189
190void
191rb_native_mutex_unlock(rb_nativethread_lock_t *lock)
192{
193#ifdef USE_WIN32_MUTEX
194 RUBY_DEBUG_LOG("lock:%p", lock->mutex);
195 ReleaseMutex(lock->mutex);
196#else
197 LeaveCriticalSection(&lock->crit);
198#endif
199}
200
201void
202rb_native_mutex_initialize(rb_nativethread_lock_t *lock)
203{
204#ifdef USE_WIN32_MUTEX
205 lock->mutex = w32_mutex_create();
206 /* thread_debug("initialize mutex: %p\n", lock->mutex); */
207#else
208 InitializeCriticalSection(&lock->crit);
209#endif
210}
211
212void
213rb_native_mutex_destroy(rb_nativethread_lock_t *lock)
214{
215#ifdef USE_WIN32_MUTEX
216 w32_close_handle(lock->mutex);
217#else
218 DeleteCriticalSection(&lock->crit);
219#endif
220}
221
222struct cond_event_entry {
223 struct cond_event_entry* next;
224 struct cond_event_entry* prev;
225 HANDLE event;
226};
227
228void
229rb_native_cond_signal(rb_nativethread_cond_t *cond)
230{
231 /* cond is guarded by mutex */
232 struct cond_event_entry *e = cond->next;
233 struct cond_event_entry *head = (struct cond_event_entry*)cond;
234
235 if (e != head) {
236 struct cond_event_entry *next = e->next;
237 struct cond_event_entry *prev = e->prev;
238
239 prev->next = next;
240 next->prev = prev;
241 e->next = e->prev = e;
242
243 SetEvent(e->event);
244 }
245}
246
247void
248rb_native_cond_broadcast(rb_nativethread_cond_t *cond)
249{
250 /* cond is guarded by mutex */
251 struct cond_event_entry *e = cond->next;
252 struct cond_event_entry *head = (struct cond_event_entry*)cond;
253
254 while (e != head) {
255 struct cond_event_entry *next = e->next;
256 struct cond_event_entry *prev = e->prev;
257
258 SetEvent(e->event);
259
260 prev->next = next;
261 next->prev = prev;
262 e->next = e->prev = e;
263
264 e = next;
265 }
266}
267
268static int
269native_cond_timedwait_ms(rb_nativethread_cond_t *cond, rb_nativethread_lock_t *mutex, unsigned long msec)
270{
271 DWORD r;
272 struct cond_event_entry entry;
273 struct cond_event_entry *head = (struct cond_event_entry*)cond;
274
275 entry.event = CreateEvent(0, FALSE, FALSE, 0);
276
277 /* cond is guarded by mutex */
278 entry.next = head;
279 entry.prev = head->prev;
280 head->prev->next = &entry;
281 head->prev = &entry;
282
284 {
285 r = WaitForSingleObject(entry.event, msec);
286 if ((r != WAIT_OBJECT_0) && (r != WAIT_TIMEOUT)) {
287 rb_bug("rb_native_cond_wait: WaitForSingleObject returns %lu", r);
288 }
289 }
291
292 entry.prev->next = entry.next;
293 entry.next->prev = entry.prev;
294
295 w32_close_handle(entry.event);
296 return (r == WAIT_OBJECT_0) ? 0 : ETIMEDOUT;
297}
298
299void
300rb_native_cond_wait(rb_nativethread_cond_t *cond, rb_nativethread_lock_t *mutex)
301{
302 native_cond_timedwait_ms(cond, mutex, INFINITE);
303}
304
305void
306rb_native_cond_timedwait(rb_nativethread_cond_t *cond, rb_nativethread_lock_t *mutex, unsigned long msec)
307{
308 native_cond_timedwait_ms(cond, mutex, msec);
309}
310
311// The scheduler parks threads with an absolute deadline; on this platform the
312// wait itself is relative, so the conversion happens here.
313static rb_hrtime_t
314native_cond_timeout(rb_nativethread_cond_t *cond, const rb_hrtime_t rel)
315{
316 if (rel > 0) {
317 rb_hrtime_t now = rb_hrtime_now();
318 return (rel > RB_HRTIME_MAX - now) ? RB_HRTIME_MAX : now + rel;
319 }
320 return rb_hrtime_now();
321}
322
323static int
324native_cond_timedwait(rb_nativethread_cond_t *cond, rb_nativethread_lock_t *mutex, const rb_hrtime_t *abs)
325{
326 rb_hrtime_t now = rb_hrtime_now();
327
328 if (*abs <= now) return ETIMEDOUT;
329
330 rb_hrtime_t rel = *abs - now;
331 unsigned long msec = (unsigned long)(rel / RB_HRTIME_PER_MSEC);
332
333 // do not busy loop on a sub-millisecond deadline
334 if (msec == 0) msec = 1;
335
336 return native_cond_timedwait_ms(cond, mutex, msec);
337}
338
339void
340rb_native_cond_initialize(rb_nativethread_cond_t *cond)
341{
342 cond->next = (struct cond_event_entry *)cond;
343 cond->prev = (struct cond_event_entry *)cond;
344}
345
346void
347rb_native_cond_destroy(rb_nativethread_cond_t *cond)
348{
349 /* */
350}
351
352/* -------------------------------------------------------------------------
353 * thread local storage
354 * ------------------------------------------------------------------------- */
355
357ruby_thread_from_native(void)
358{
359 return TlsGetValue(ruby_native_thread_key);
360}
361
362int
363ruby_thread_set_native(rb_thread_t *th)
364{
365 if (th) {
366 ccan_list_node_init(&th->sched.node.ubf);
367 }
368
369 if (th && th->ec) {
370 rb_ractor_set_current_ec(th->ractor, th->ec);
371 }
372 return TlsSetValue(ruby_native_thread_key, th);
373}
374
375/* -------------------------------------------------------------------------
376 * waiting on Windows objects, with interruption
377 * ------------------------------------------------------------------------- */
378
379static int
380w32_wait_events(HANDLE *events, int count, DWORD timeout, rb_thread_t *th)
381{
382 HANDLE *targets = events;
383 HANDLE intr;
384 const int initcount = count;
385 DWORD ret;
386
387 w32_event_debug("events:%p, count:%d, timeout:%ld, th:%u\n",
388 events, count, timeout, th ? rb_th_serial(th) : UINT_MAX);
389
390 if (th && (intr = th->nt->interrupt_event)) {
391 if (ResetEvent(intr) && (!RUBY_VM_INTERRUPTED(th->ec) || SetEvent(intr))) {
392 targets = ALLOCA_N(HANDLE, count + 1);
393 memcpy(targets, events, sizeof(HANDLE) * count);
394
395 targets[count++] = intr;
396 w32_event_debug("handle:%p (count:%d, intr)\n", intr, count);
397 }
398 else if (intr == th->nt->interrupt_event) {
399 w32_error("w32_wait_events");
400 }
401 }
402
403 w32_event_debug("WaitForMultipleObjects start count:%d\n", count);
404 ret = WaitForMultipleObjects(count, targets, FALSE, timeout);
405 w32_event_debug("WaitForMultipleObjects end ret:%lu\n", ret);
406
407 if (ret == (DWORD)(WAIT_OBJECT_0 + initcount) && th) {
408 errno = EINTR;
409 }
410 if (ret == WAIT_FAILED && W32_EVENT_DEBUG) {
411 int i;
412 DWORD dmy;
413 for (i = 0; i < count; i++) {
414 w32_event_debug("i:%d %s\n", i, GetHandleInformation(targets[i], &dmy) ? "OK" : "NG");
415 }
416 }
417 return ret;
418}
419
420int
421rb_w32_wait_events_blocking(HANDLE *events, int num, DWORD timeout)
422{
423 return w32_wait_events(events, num, timeout, ruby_thread_from_native());
424}
425
426int
427rb_w32_wait_events(HANDLE *events, int num, DWORD timeout)
428{
429 int ret;
430 rb_thread_t *th = GET_THREAD();
431
432 BLOCKING_REGION(th, ret = rb_w32_wait_events_blocking(events, num, timeout),
433 ubf_select, ruby_thread_from_native(), FALSE);
434 return ret;
435}
436
437int
438rb_w32_sleep(unsigned long msec)
439{
440 return w32_wait_events(0, 0, msec, ruby_thread_from_native());
441}
442
443int WINAPI
444rb_w32_Sleep(unsigned long msec)
445{
446 int ret;
447 rb_thread_t *th = GET_THREAD();
448
449 BLOCKING_REGION(th, ret = rb_w32_sleep(msec),
450 ubf_select, ruby_thread_from_native(), FALSE);
451 return ret;
452}
453
454/* @internal */
455int
456rb_w32_check_interrupt(rb_thread_t *th)
457{
458 return w32_wait_events(0, 0, 0, th);
459}
460
461/*
462 * Pull the target thread out of a blocking w32_wait_events(). This is the
463 * counterpart of the SIGVTALRM the POSIX implementation sends.
464 */
465static void
466native_thread_interrupt(rb_thread_t *th)
467{
468 // the caller (ubf_wakeup_thread) logs this
469 if (!SetEvent(th->nt->interrupt_event)) {
470 w32_error("native_thread_interrupt");
471 }
472}
473
474/* -------------------------------------------------------------------------
475 * native thread
476 * ------------------------------------------------------------------------- */
477
478static void
479w32_resume_thread(HANDLE handle)
480{
481 if (ResumeThread(handle) == (DWORD)-1) {
482 w32_error("w32_resume_thread");
483 }
484}
485
486#ifdef _MSC_VER
487#define HAVE__BEGINTHREADEX 1
488#else
489#undef HAVE__BEGINTHREADEX
490#endif
491
492#ifdef HAVE__BEGINTHREADEX
493#define start_thread (HANDLE)_beginthreadex
494#define thread_errno errno
495typedef unsigned long (__stdcall *w32_thread_start_func)(void*);
496#else
497#define start_thread CreateThread
498#define thread_errno rb_w32_map_errno(GetLastError())
499typedef LPTHREAD_START_ROUTINE w32_thread_start_func;
500#endif
501
502static HANDLE
503w32_create_thread(DWORD stack_size, w32_thread_start_func func, void *val)
504{
505 return start_thread(0, stack_size, func, val, CREATE_SUSPENDED | STACK_SIZE_PARAM_IS_A_RESERVATION, 0);
506}
507
508static void
509native_thread_join(HANDLE th)
510{
511 w32_wait_events(&th, 1, INFINITE, 0);
512}
513
514#if !defined(_WIN32_WINNT_WIN8) || _WIN32_WINNT < 0x602
515/* declared in processthreadsapi.h only when _WIN32_WINNT >= 0x0602,
516 * but exported from kernel32.dll since Windows 8 */
517WINBASEAPI VOID WINAPI GetCurrentThreadStackLimits(PULONG_PTR, PULONG_PTR);
518#endif
519
520static void
521native_thread_init_stack(rb_thread_t *th, void *local_in_parent_frame)
522{
523 ULONG_PTR low, high;
524 SIZE_T size, space;
525
526 /* VirtualQuery against the current stack pointer may return a region
527 * that does not span the whole stack when the interpreter is
528 * initialized deep in the stack, which makes stack_check() misfire.
529 * [Bug #11438] */
530 GetCurrentThreadStackLimits(&low, &high);
531 size = high - low;
532 space = size / 5;
533 if (space > 1024*1024) space = 1024*1024;
534 th->ec->machine.stack_start = (VALUE *)high - 1;
535 th->ec->machine.stack_maxsize = size - space;
536}
537
538static void
539native_thread_setup(struct rb_native_thread *nt)
540{
541 rb_native_cond_initialize(&nt->readyq);
542 rb_native_mutex_initialize(&nt->running_th_lock);
543
544 // Created here rather than on the new thread itself: ubf can fire before
545 // that thread gets a chance to run.
546 nt->interrupt_event = CreateEvent(0, TRUE, FALSE, 0);
547 if (nt->interrupt_event == NULL) {
548 w32_error("native_thread_setup");
549 }
550}
551
552static void
553native_thread_setup_on_thread(struct rb_native_thread *nt)
554{
555 // nothing to do: there is no altstack and no thread id to cache
556}
557
558static struct rb_native_thread *
559native_thread_alloc(void)
560{
561 struct rb_native_thread *nt = ZALLOC(struct rb_native_thread);
562 native_thread_setup(nt);
563
564#if USE_RUBY_DEBUG_LOG
565 static rb_atomic_t nt_serial = 2;
566 nt->serial = RUBY_ATOMIC_FETCH_ADD(nt_serial, 1);
567#endif
568 return nt;
569}
570
571static void
572native_thread_destroy_atfork(struct rb_native_thread *nt)
573{
574 /* no fork() on this platform */
575}
576
577#ifndef InterlockedExchangePointer
578#define InterlockedExchangePointer(t, v) \
579 (void *)InterlockedExchange((long *)(t), (long)(v))
580#endif
581
582static void
583native_thread_destroy(struct rb_native_thread *nt)
584{
585 if (nt) {
586 HANDLE intr = InterlockedExchangePointer(&nt->interrupt_event, 0);
587 RUBY_DEBUG_LOG("close handle intr:%p, thid:%p\n", intr, nt->thread_id);
588 if (intr) w32_close_handle(intr);
589
590 rb_native_cond_destroy(&nt->readyq);
591 rb_native_mutex_destroy(&nt->running_th_lock);
592
593 ruby_xfree(nt);
594 }
595}
596
597static void
598native_thread_destroy_self(struct rb_native_thread *nt)
599{
600 native_thread_destroy(nt);
601}
602
603static unsigned long __stdcall
604nt_start_trampoline(void *nt_ptr)
605{
606 struct rb_native_thread *nt = (struct rb_native_thread *)nt_ptr;
607 HANDLE thread_id = nt->thread_id;
608
609 nt_start(nt);
610
611 w32_close_handle(thread_id);
612 return 0;
613}
614
615static int
616native_thread_create0(struct rb_native_thread *nt)
617{
618 const size_t stack_size = nt->vm->default_params.thread_machine_stack_size;
619
620 nt->thread_id = w32_create_thread(stack_size, nt_start_trampoline, nt);
621 if (nt->thread_id == 0) {
622 return thread_errno;
623 }
624
625 w32_resume_thread(nt->thread_id);
626
627 RUBY_DEBUG_LOG("nt:%u thid:%p stack size:%"PRIuSIZE"",
628 nt->serial, nt->thread_id, stack_size);
629 return 0;
630}
631
632static int
633native_thread_default_max_cpu(void)
634{
635 SYSTEM_INFO si;
636 GetSystemInfo(&si);
637 return si.dwNumberOfProcessors > 0 ? (int)si.dwNumberOfProcessors : 8;
638}
639
640#if USE_NATIVE_THREAD_PRIORITY
641
642static void
643native_thread_apply_priority(rb_thread_t *th)
644{
645 int priority = th->priority;
646 if (th->priority > 0) {
647 priority = THREAD_PRIORITY_ABOVE_NORMAL;
648 }
649 else if (th->priority < 0) {
650 priority = THREAD_PRIORITY_BELOW_NORMAL;
651 }
652 else {
653 priority = THREAD_PRIORITY_NORMAL;
654 }
655
656 SetThreadPriority(th->nt->thread_id, priority);
657}
658
659#endif /* USE_NATIVE_THREAD_PRIORITY */
660
661int rb_w32_select_with_thread(int, fd_set *, fd_set *, fd_set *, struct timeval *, void *); /* @internal */
662
663static int
664native_fd_select(int n, rb_fdset_t *readfds, rb_fdset_t *writefds, rb_fdset_t *exceptfds, struct timeval *timeout, rb_thread_t *th)
665{
666 fd_set *r = NULL, *w = NULL, *e = NULL;
667 if (readfds) {
668 rb_fd_resize(n - 1, readfds);
669 r = rb_fd_ptr(readfds);
670 }
671 if (writefds) {
672 rb_fd_resize(n - 1, writefds);
673 w = rb_fd_ptr(writefds);
674 }
675 if (exceptfds) {
676 rb_fd_resize(n - 1, exceptfds);
677 e = rb_fd_ptr(exceptfds);
678 }
679 return rb_w32_select_with_thread(n, r, w, e, timeout, th);
680}
681
682int rb_w32_set_thread_description(HANDLE th, const WCHAR *name);
683int rb_w32_set_thread_description_str(HANDLE th, VALUE name);
684#define native_set_another_thread_name rb_w32_set_thread_description_str
685
686static void
687native_set_thread_name(rb_thread_t *th)
688{
689}
690
691static VALUE
692native_thread_native_thread_id(rb_thread_t *th)
693{
694 DWORD tid = GetThreadId(th->nt->thread_id);
695 if (tid == 0) rb_sys_fail("GetThreadId");
696 return ULONG2NUM(tid);
697}
698#define USE_NATIVE_THREAD_NATIVE_THREAD_ID 1
699
700void
701Init_native_thread(rb_thread_t *main_th)
702{
703 if ((ruby_current_ec_key = TlsAlloc()) == TLS_OUT_OF_INDEXES) {
704 rb_bug("TlsAlloc() for ruby_current_ec_key fails");
705 }
706 if ((ruby_native_thread_key = TlsAlloc()) == TLS_OUT_OF_INDEXES) {
707 rb_bug("TlsAlloc() for ruby_native_thread_key fails");
708 }
709
710 // setup vm
711 rb_vm_t *vm = main_th->vm;
712 thread_sched_init_vm(vm);
713
714 // setup main thread
715 native_thread_setup(main_th->nt);
716 DuplicateHandle(GetCurrentProcess(),
717 GetCurrentThread(),
718 GetCurrentProcess(),
719 &main_th->nt->thread_id, 0, FALSE, DUPLICATE_SAME_ACCESS);
720 main_th->nt->serial = 1;
721 ruby_thread_set_native(main_th);
722
723 TH_SCHED(main_th)->running = main_th;
724 main_th->has_dedicated_nt = 1;
725
726 // setup main NT (before the record below: its kind decides where it goes)
727 main_th->nt->dedicated = 1;
728 main_th->nt->running_thread = main_th;
729 main_th->nt->vm = vm;
730
731 thread_sched_setup_running_threads(TH_SCHED(main_th), main_th->ractor, vm, main_th, NULL);
732
733#if USE_RUBY_DEBUG_LOG
734 vm->ractor.sched.dnt_cnt = 1;
735#endif
736
737 RUBY_DEBUG_LOG("initial thread th:%u thid:%p, event: %p",
738 rb_th_serial(main_th),
739 main_th->nt->thread_id,
740 main_th->nt->interrupt_event);
741}
742
743/* -------------------------------------------------------------------------
744 * timer thread
745 * ------------------------------------------------------------------------- */
746
747static struct {
748 rb_serial_t created_fork_gen;
749 HANDLE thread_id;
750 HANDLE wakeup_event; // manual reset; the "comm pipe" of this platform
751} timer_th = {
752 .created_fork_gen = 0,
753};
754
755#define TIMER_THREAD_CREATED_P() (timer_th.created_fork_gen == current_fork_gen)
756
757static void
758timer_thread_wakeup_force(void)
759{
760 if (timer_th.wakeup_event) {
761 SetEvent(timer_th.wakeup_event);
762 }
763}
764
765void
766rb_thread_wakeup_timer_thread(int sig)
767{
768 timer_thread_wakeup_force();
769
770 if (RUBY_ATOMIC_LOAD(system_working)) {
771 rb_vm_t *vm = GET_VM();
772 rb_thread_t *main_th = vm->ractor.main_thread;
773
774 if (main_th) {
775 volatile rb_execution_context_t *main_th_ec = ACCESS_ONCE(rb_execution_context_t *, main_th->ec);
776
777 if (main_th_ec) {
778 RUBY_VM_SET_TRAP_INTERRUPT(main_th_ec);
779
780 if (vm->ubf_async_safe && main_th->unblock.func) {
781 (main_th->unblock.func)(main_th->unblock.arg);
782 }
783 }
784 }
785 }
786}
787
788// The blocking part of the timer thread loop: this is what
789// timer_thread_wakeup_force() interrupts.
790static void
791timer_thread_polling(rb_vm_t *vm)
792{
793 int timeout = timer_thread_set_timeout(vm);
794 DWORD msec = (timeout < 0) ? INFINITE : (DWORD)timeout;
795
796 DWORD ret = WaitForSingleObject(timer_th.wakeup_event, msec);
797
798 switch (ret) {
799 case WAIT_TIMEOUT:
800 ractor_sched_lock(vm, NULL);
801 {
802 timer_thread_check_timeslice(vm);
803 }
804 ractor_sched_unlock(vm, NULL);
805 break;
806
807 case WAIT_OBJECT_0:
808 ResetEvent(timer_th.wakeup_event);
809 break;
810
811 default:
812 w32_error("timer_thread_polling");
813 }
814}
815
816static unsigned long __stdcall
817timer_thread_trampoline(void *vm_ptr)
818{
819 rb_w32_set_thread_description(GetCurrentThread(), L"ruby-timer-thread");
820 timer_thread_func(vm_ptr);
821 return 0;
822}
823
824static void
825rb_thread_create_timer_thread(void)
826{
827 timer_th.created_fork_gen = current_fork_gen;
828
829 if (timer_th.wakeup_event == NULL) {
830 timer_th.wakeup_event = CreateEvent(0, TRUE, FALSE, 0);
831 if (timer_th.wakeup_event == NULL) {
832 w32_error("rb_thread_create_timer_thread");
833 }
834 }
835
836 timer_th.thread_id = w32_create_thread(1024 + (USE_RUBY_DEBUG_LOG ? BUFSIZ : 0),
837 timer_thread_trampoline, GET_VM());
838 if (timer_th.thread_id == 0) {
839 rb_bug("rb_thread_create_timer_thread: failed to create the timer thread");
840 }
841 w32_resume_thread(timer_th.thread_id);
842}
843
844static int
845native_stop_timer_thread(void)
846{
847 RUBY_ATOMIC_SET(system_working, 0);
848
849 timer_thread_wakeup_force();
850 native_thread_join(timer_th.thread_id);
851
852 w32_close_handle(timer_th.wakeup_event);
853 timer_th.wakeup_event = NULL;
854
855 return 1;
856}
857
858static void
859native_reset_timer_thread(void)
860{
861 if (timer_th.thread_id) {
862 CloseHandle(timer_th.thread_id);
863 timer_th.thread_id = 0;
864 }
865}
866
867/* -------------------------------------------------------------------------
868 * M:N scheduler stubs
869 *
870 * These are what thread_sched_mn.c provides on platforms that have an event
871 * backend. Every thread here is dedicated, so the scheduler never reaches
872 * the ones that rb_bug().
873 * ------------------------------------------------------------------------- */
874
875static int
876native_thread_create_shared(rb_thread_t *th)
877{
878 rb_bug("unreachable");
879}
880
881static enum thread_sched_wait_result
882thread_sched_wait_events(struct rb_thread_sched *sched, rb_thread_t *th, int fd,
883 enum thread_sched_waiting_flag events, rb_hrtime_t *rel)
884{
885 return thread_sched_wait_unavailable;
886}
887
888static bool
889ractor_sched_timeout_arm(rb_thread_t *th, const rb_hrtime_t *rel)
890{
891 rb_bug("unreachable");
892}
893
894static bool
895ractor_sched_timeout_disarm(rb_thread_t *th)
896{
897 rb_bug("unreachable");
898}
899
900static int
901timer_wheel_timeout(int timeout)
902{
903 return timeout; // no M:N threads, no timed waiters
904}
905
906static void
907timer_thread_wake_fence(rb_thread_t *th)
908{
909 // no timer wheel, no wake batches
910}
911
912static void
913timer_thread_check_timeout(rb_vm_t *vm)
914{
915 // no M:N threads, no timed waiters
916}
917
918/* -------------------------------------------------------------------------
919 * misc
920 * ------------------------------------------------------------------------- */
921
922int
923ruby_stack_overflowed_p(const rb_thread_t *th, const void *addr)
924{
925 return rb_ec_raised_p(th->ec, RAISED_STACKOVERFLOW);
926}
927
928#if defined(__MINGW32__)
929LONG WINAPI
930rb_w32_stack_overflow_handler(struct _EXCEPTION_POINTERS *exception)
931{
932 if (exception->ExceptionRecord->ExceptionCode == EXCEPTION_STACK_OVERFLOW) {
933 rb_ec_raised_set(GET_EC(), RAISED_STACKOVERFLOW);
934 raise(SIGSEGV);
935 }
936 return EXCEPTION_CONTINUE_SEARCH;
937}
938#endif
939
940#ifdef RUBY_ALLOCA_CHKSTK
941void
942ruby_alloca_chkstk(size_t len, void *sp)
943{
944 if (ruby_stack_length(NULL) * sizeof(VALUE) >= len) {
945 rb_execution_context_t *ec = GET_EC();
946 if (!rb_ec_raised_p(ec, RAISED_STACKOVERFLOW)) {
947 rb_ec_raised_set(ec, RAISED_STACKOVERFLOW);
948 rb_exc_raise(sysstack_error);
949 }
950 }
951}
952#endif
953
954int
955rb_reserved_fd_p(int fd)
956{
957 return 0;
958}
959
960rb_nativethread_id_t
962{
963 return GetCurrentThread();
964}
965
966void *
967rb_thread_prevent_fork(void *(*func)(void *), void *data)
968{
969 return func(data);
970}
971
972#endif /* THREAD_SYSTEM_DEPENDENT_IMPLEMENTATION */
std::atomic< unsigned > rb_atomic_t
Type that is eligible for atomic operations.
Definition atomic.h:69
#define RUBY_ATOMIC_FETCH_ADD(var, val)
Atomically replaces the value pointed by var with the result of addition of val to the old value of v...
Definition atomic.h:118
#define RUBY_ATOMIC_LOAD(var)
Atomic load.
Definition atomic.h:175
#define RUBY_ATOMIC_SET(var, val)
Identical to RUBY_ATOMIC_EXCHANGE, except for the return type.
Definition atomic.h:185
uint32_t rb_event_flag_t
Represents event(s).
Definition event.h:108
#define UNREACHABLE
Old name of RBIMPL_UNREACHABLE.
Definition assume.h:28
#define ULONG2NUM
Old name of RB_ULONG2NUM.
Definition long.h:60
#define ZALLOC
Old name of RB_ZALLOC.
Definition memory.h:402
size_t ruby_stack_length(VALUE **p)
Queries what Ruby thinks is the machine stack.
Definition gc.c:2779
void rb_exc_raise(VALUE mesg)
Raises an exception in the current thread.
Definition eval.c:676
int rb_reserved_fd_p(int fd)
Queries if the given FD is reserved or not.
int len
Length of the buffer.
Definition io.h:8
rb_internal_thread_event_hook_t * rb_internal_thread_add_event_hook(rb_internal_thread_event_callback func, rb_event_flag_t events, void *data)
Registers a thread event hook function.
bool rb_internal_thread_remove_event_hook(rb_internal_thread_event_hook_t *hook)
Unregister the passed hook.
static fd_set * rb_fd_ptr(const rb_fdset_t *f)
Raw pointer to fd_set.
Definition largesize.h:195
#define ALLOCA_N(type, n)
Definition memory.h:292
#define RBIMPL_ATTR_NORETURN()
Wraps (or simulates) [[noreturn]]
Definition noreturn.h:38
#define errno
Ractor-aware version of errno.
Definition ruby.h:388
#define rb_fd_resize(n, f)
Does nothing (defined for compatibility).
Definition select.h:43
The data structure which wraps the fd_set bitmap used by select(2).
Definition largesize.h:71
rb_nativethread_id_t rb_nativethread_self(void)
Queries the ID of the native thread that is calling this function.
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.
int rb_native_mutex_trylock(rb_nativethread_lock_t *lock)
Identical to rb_native_mutex_lock(), except it doesn't block in case rb_native_mutex_lock() would.
void rb_native_cond_broadcast(rb_nativethread_cond_t *cond)
Signals a condition variable.
void rb_native_mutex_initialize(rb_nativethread_lock_t *lock)
Just another name of rb_nativethread_lock_initialize.
void rb_native_mutex_unlock(rb_nativethread_lock_t *lock)
Just another name of rb_nativethread_lock_unlock.
void rb_native_mutex_destroy(rb_nativethread_lock_t *lock)
Just another name of rb_nativethread_lock_destroy.
void rb_native_cond_destroy(rb_nativethread_cond_t *cond)
Destroys the passed condition variable.
void rb_native_cond_signal(rb_nativethread_cond_t *cond)
Signals a condition variable.
void rb_native_cond_wait(rb_nativethread_cond_t *cond, rb_nativethread_lock_t *mutex)
Waits for the passed condition variable to be signalled.
void rb_native_cond_timedwait(rb_nativethread_cond_t *cond, rb_nativethread_lock_t *mutex, unsigned long msec)
Identical to rb_native_cond_wait(), except it additionally takes timeout in msec resolution.
uintptr_t VALUE
Type that represents a Ruby object.
Definition value.h:40