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