Ruby 4.0.0dev (2025-12-06 revision 0346206d3eab2a8e659be0dd52aea6fc7b0ebb06)
cont.c (0346206d3eab2a8e659be0dd52aea6fc7b0ebb06)
1/**********************************************************************
2
3 cont.c -
4
5 $Author$
6 created at: Thu May 23 09:03:43 2007
7
8 Copyright (C) 2007 Koichi Sasada
9
10**********************************************************************/
11
12#include "ruby/internal/config.h"
13
14#ifndef _WIN32
15#include <unistd.h>
16#include <sys/mman.h>
17#endif
18
19// On Solaris, madvise() is NOT declared for SUS (XPG4v2) or later,
20// but MADV_* macros are defined when __EXTENSIONS__ is defined.
21#ifdef NEED_MADVICE_PROTOTYPE_USING_CADDR_T
22#include <sys/types.h>
23extern int madvise(caddr_t, size_t, int);
24#endif
25
26#include COROUTINE_H
27
28#include "eval_intern.h"
29#include "internal.h"
30#include "internal/cont.h"
31#include "internal/thread.h"
32#include "internal/error.h"
33#include "internal/eval.h"
34#include "internal/gc.h"
35#include "internal/proc.h"
36#include "internal/sanitizers.h"
37#include "internal/warnings.h"
39#include "yjit.h"
40#include "vm_core.h"
41#include "vm_sync.h"
42#include "id_table.h"
43#include "ractor_core.h"
44
45static const int DEBUG = 0;
46
47#define RB_PAGE_SIZE (pagesize)
48#define RB_PAGE_MASK (~(RB_PAGE_SIZE - 1))
49static long pagesize;
50
51static const rb_data_type_t cont_data_type, fiber_data_type;
52static VALUE rb_cContinuation;
53static VALUE rb_cFiber;
54static VALUE rb_eFiberError;
55#ifdef RB_EXPERIMENTAL_FIBER_POOL
56static VALUE rb_cFiberPool;
57#endif
58
59#define CAPTURE_JUST_VALID_VM_STACK 1
60
61// Defined in `coroutine/$arch/Context.h`:
62#ifdef COROUTINE_LIMITED_ADDRESS_SPACE
63#define FIBER_POOL_ALLOCATION_FREE
64#define FIBER_POOL_INITIAL_SIZE 8
65#define FIBER_POOL_ALLOCATION_MAXIMUM_SIZE 32
66#else
67#define FIBER_POOL_INITIAL_SIZE 32
68#define FIBER_POOL_ALLOCATION_MAXIMUM_SIZE 1024
69#endif
70#ifdef RB_EXPERIMENTAL_FIBER_POOL
71#define FIBER_POOL_ALLOCATION_FREE
72#endif
73
74enum context_type {
75 CONTINUATION_CONTEXT = 0,
76 FIBER_CONTEXT = 1
77};
78
80 VALUE *ptr;
81#ifdef CAPTURE_JUST_VALID_VM_STACK
82 size_t slen; /* length of stack (head of ec->vm_stack) */
83 size_t clen; /* length of control frames (tail of ec->vm_stack) */
84#endif
85};
86
87struct fiber_pool;
88
89// Represents a single stack.
91 // A pointer to the memory allocation (lowest address) for the stack.
92 void * base;
93
94 // The current stack pointer, taking into account the direction of the stack.
95 void * current;
96
97 // The size of the stack excluding any guard pages.
98 size_t size;
99
100 // The available stack capacity w.r.t. the current stack offset.
101 size_t available;
102
103 // The pool this stack should be allocated from.
104 struct fiber_pool * pool;
105
106 // If the stack is allocated, the allocation it came from.
107 struct fiber_pool_allocation * allocation;
108};
109
110// A linked list of vacant (unused) stacks.
111// This structure is stored in the first page of a stack if it is not in use.
112// @sa fiber_pool_vacancy_pointer
114 // Details about the vacant stack:
115 struct fiber_pool_stack stack;
116
117 // The vacancy linked list.
118#ifdef FIBER_POOL_ALLOCATION_FREE
119 struct fiber_pool_vacancy * previous;
120#endif
121 struct fiber_pool_vacancy * next;
122};
123
124// Manages singly linked list of mapped regions of memory which contains 1 more more stack:
125//
126// base = +-------------------------------+-----------------------+ +
127// |VM Stack |VM Stack | | |
128// | | | | |
129// | | | | |
130// +-------------------------------+ | |
131// |Machine Stack |Machine Stack | | |
132// | | | | |
133// | | | | |
134// | | | . . . . | | size
135// | | | | |
136// | | | | |
137// | | | | |
138// | | | | |
139// | | | | |
140// +-------------------------------+ | |
141// |Guard Page |Guard Page | | |
142// +-------------------------------+-----------------------+ v
143//
144// +------------------------------------------------------->
145//
146// count
147//
149 // A pointer to the memory mapped region.
150 void * base;
151
152 // The size of the individual stacks.
153 size_t size;
154
155 // The stride of individual stacks (including any guard pages or other accounting details).
156 size_t stride;
157
158 // The number of stacks that were allocated.
159 size_t count;
160
161#ifdef FIBER_POOL_ALLOCATION_FREE
162 // The number of stacks used in this allocation.
163 size_t used;
164#endif
165
166 struct fiber_pool * pool;
167
168 // The allocation linked list.
169#ifdef FIBER_POOL_ALLOCATION_FREE
170 struct fiber_pool_allocation * previous;
171#endif
172 struct fiber_pool_allocation * next;
173};
174
175// A fiber pool manages vacant stacks to reduce the overhead of creating fibers.
177 // A singly-linked list of allocations which contain 1 or more stacks each.
178 struct fiber_pool_allocation * allocations;
179
180 // Free list that provides O(1) stack "allocation".
181 struct fiber_pool_vacancy * vacancies;
182
183 // The size of the stack allocations (excluding any guard page).
184 size_t size;
185
186 // The total number of stacks that have been allocated in this pool.
187 size_t count;
188
189 // The initial number of stacks to allocate.
190 size_t initial_count;
191
192 // Whether to madvise(free) the stack or not.
193 // If this value is set to 1, the stack will be madvise(free)ed
194 // (or equivalent), where possible, when it is returned to the pool.
195 int free_stacks;
196
197 // The number of stacks that have been used in this pool.
198 size_t used;
199
200 // The amount to allocate for the vm_stack.
201 size_t vm_stack_size;
202};
203
204// Continuation contexts used by JITs
206 rb_execution_context_t *ec; // continuation ec
207 struct rb_jit_cont *prev, *next; // used to form lists
208};
209
210// Doubly linked list for enumerating all on-stack ISEQs.
211static struct rb_jit_cont *first_jit_cont;
212
213typedef struct rb_context_struct {
214 enum context_type type;
215 int argc;
216 int kw_splat;
217 VALUE self;
218 VALUE value;
219
220 struct cont_saved_vm_stack saved_vm_stack;
221
222 struct {
223 VALUE *stack;
224 VALUE *stack_src;
225 size_t stack_size;
226 } machine;
227 rb_execution_context_t saved_ec;
228 rb_jmpbuf_t jmpbuf;
229 struct rb_jit_cont *jit_cont; // Continuation contexts for JITs
231
232/*
233 * Fiber status:
234 * [Fiber.new] ------> FIBER_CREATED ----> [Fiber#kill] --> |
235 * | [Fiber#resume] |
236 * v |
237 * +--> FIBER_RESUMED ----> [return] ------> |
238 * [Fiber#resume] | | [Fiber.yield/transfer] |
239 * [Fiber#transfer] | v |
240 * +--- FIBER_SUSPENDED --> [Fiber#kill] --> |
241 * |
242 * |
243 * FIBER_TERMINATED <-------------------+
244 */
245enum fiber_status {
246 FIBER_CREATED,
247 FIBER_RESUMED,
248 FIBER_SUSPENDED,
249 FIBER_TERMINATED
250};
251
252#define FIBER_CREATED_P(fiber) ((fiber)->status == FIBER_CREATED)
253#define FIBER_RESUMED_P(fiber) ((fiber)->status == FIBER_RESUMED)
254#define FIBER_SUSPENDED_P(fiber) ((fiber)->status == FIBER_SUSPENDED)
255#define FIBER_TERMINATED_P(fiber) ((fiber)->status == FIBER_TERMINATED)
256#define FIBER_RUNNABLE_P(fiber) (FIBER_CREATED_P(fiber) || FIBER_SUSPENDED_P(fiber))
257
259 rb_context_t cont;
260 VALUE first_proc;
261 struct rb_fiber_struct *prev;
262 struct rb_fiber_struct *resuming_fiber;
263
264 BITFIELD(enum fiber_status, status, 2);
265 /* Whether the fiber is allowed to implicitly yield. */
266 unsigned int yielding : 1;
267 unsigned int blocking : 1;
268
269 unsigned int killed : 1;
270
271 rb_serial_t serial;
272
273 struct coroutine_context context;
274 struct fiber_pool_stack stack;
275};
276
277static struct fiber_pool shared_fiber_pool = {NULL, NULL, 0, 0, 0, 0};
278
279void
280rb_free_shared_fiber_pool(void)
281{
282 struct fiber_pool_allocation *allocations = shared_fiber_pool.allocations;
283 while (allocations) {
284 struct fiber_pool_allocation *next = allocations->next;
285 xfree(allocations);
286 allocations = next;
287 }
288}
289
290static ID fiber_initialize_keywords[3] = {0};
291
292/*
293 * FreeBSD require a first (i.e. addr) argument of mmap(2) is not NULL
294 * if MAP_STACK is passed.
295 * https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=158755
296 */
297#if defined(MAP_STACK) && !defined(__FreeBSD__) && !defined(__FreeBSD_kernel__)
298#define FIBER_STACK_FLAGS (MAP_PRIVATE | MAP_ANON | MAP_STACK)
299#else
300#define FIBER_STACK_FLAGS (MAP_PRIVATE | MAP_ANON)
301#endif
302
303#define ERRNOMSG strerror(errno)
304
305// Locates the stack vacancy details for the given stack.
306inline static struct fiber_pool_vacancy *
307fiber_pool_vacancy_pointer(void * base, size_t size)
308{
309 STACK_GROW_DIR_DETECTION;
310
311 return (struct fiber_pool_vacancy *)(
312 (char*)base + STACK_DIR_UPPER(0, size - RB_PAGE_SIZE)
313 );
314}
315
316#if defined(COROUTINE_SANITIZE_ADDRESS)
317// Compute the base pointer for a vacant stack, for the area which can be poisoned.
318inline static void *
319fiber_pool_stack_poison_base(struct fiber_pool_stack * stack)
320{
321 STACK_GROW_DIR_DETECTION;
322
323 return (char*)stack->base + STACK_DIR_UPPER(RB_PAGE_SIZE, 0);
324}
325
326// Compute the size of the vacant stack, for the area that can be poisoned.
327inline static size_t
328fiber_pool_stack_poison_size(struct fiber_pool_stack * stack)
329{
330 return stack->size - RB_PAGE_SIZE;
331}
332#endif
333
334// Reset the current stack pointer and available size of the given stack.
335inline static void
336fiber_pool_stack_reset(struct fiber_pool_stack * stack)
337{
338 STACK_GROW_DIR_DETECTION;
339
340 stack->current = (char*)stack->base + STACK_DIR_UPPER(0, stack->size);
341 stack->available = stack->size;
342}
343
344// A pointer to the base of the current unused portion of the stack.
345inline static void *
346fiber_pool_stack_base(struct fiber_pool_stack * stack)
347{
348 STACK_GROW_DIR_DETECTION;
349
350 VM_ASSERT(stack->current);
351
352 return STACK_DIR_UPPER(stack->current, (char*)stack->current - stack->available);
353}
354
355// Allocate some memory from the stack. Used to allocate vm_stack inline with machine stack.
356// @sa fiber_initialize_coroutine
357inline static void *
358fiber_pool_stack_alloca(struct fiber_pool_stack * stack, size_t offset)
359{
360 STACK_GROW_DIR_DETECTION;
361
362 if (DEBUG) fprintf(stderr, "fiber_pool_stack_alloca(%p): %"PRIuSIZE"/%"PRIuSIZE"\n", (void*)stack, offset, stack->available);
363 VM_ASSERT(stack->available >= offset);
364
365 // The pointer to the memory being allocated:
366 void * pointer = STACK_DIR_UPPER(stack->current, (char*)stack->current - offset);
367
368 // Move the stack pointer:
369 stack->current = STACK_DIR_UPPER((char*)stack->current + offset, (char*)stack->current - offset);
370 stack->available -= offset;
371
372 return pointer;
373}
374
375// Reset the current stack pointer and available size of the given stack.
376inline static void
377fiber_pool_vacancy_reset(struct fiber_pool_vacancy * vacancy)
378{
379 fiber_pool_stack_reset(&vacancy->stack);
380
381 // Consume one page of the stack because it's used for the vacancy list:
382 fiber_pool_stack_alloca(&vacancy->stack, RB_PAGE_SIZE);
383}
384
385inline static struct fiber_pool_vacancy *
386fiber_pool_vacancy_push(struct fiber_pool_vacancy * vacancy, struct fiber_pool_vacancy * head)
387{
388 vacancy->next = head;
389
390#ifdef FIBER_POOL_ALLOCATION_FREE
391 if (head) {
392 head->previous = vacancy;
393 vacancy->previous = NULL;
394 }
395#endif
396
397 return vacancy;
398}
399
400#ifdef FIBER_POOL_ALLOCATION_FREE
401static void
402fiber_pool_vacancy_remove(struct fiber_pool_vacancy * vacancy)
403{
404 if (vacancy->next) {
405 vacancy->next->previous = vacancy->previous;
406 }
407
408 if (vacancy->previous) {
409 vacancy->previous->next = vacancy->next;
410 }
411 else {
412 // It's the head of the list:
413 vacancy->stack.pool->vacancies = vacancy->next;
414 }
415}
416
417inline static struct fiber_pool_vacancy *
418fiber_pool_vacancy_pop(struct fiber_pool * pool)
419{
420 struct fiber_pool_vacancy * vacancy = pool->vacancies;
421
422 if (vacancy) {
423 fiber_pool_vacancy_remove(vacancy);
424 }
425
426 return vacancy;
427}
428#else
429inline static struct fiber_pool_vacancy *
430fiber_pool_vacancy_pop(struct fiber_pool * pool)
431{
432 struct fiber_pool_vacancy * vacancy = pool->vacancies;
433
434 if (vacancy) {
435 pool->vacancies = vacancy->next;
436 }
437
438 return vacancy;
439}
440#endif
441
442// Initialize the vacant stack. The [base, size] allocation should not include the guard page.
443// @param base The pointer to the lowest address of the allocated memory.
444// @param size The size of the allocated memory.
445inline static struct fiber_pool_vacancy *
446fiber_pool_vacancy_initialize(struct fiber_pool * fiber_pool, struct fiber_pool_vacancy * vacancies, void * base, size_t size)
447{
448 struct fiber_pool_vacancy * vacancy = fiber_pool_vacancy_pointer(base, size);
449
450 vacancy->stack.base = base;
451 vacancy->stack.size = size;
452
453 fiber_pool_vacancy_reset(vacancy);
454
455 vacancy->stack.pool = fiber_pool;
456
457 return fiber_pool_vacancy_push(vacancy, vacancies);
458}
459
460// Allocate a maximum of count stacks, size given by stride.
461// @param count the number of stacks to allocate / were allocated.
462// @param stride the size of the individual stacks.
463// @return [void *] the allocated memory or NULL if allocation failed.
464inline static void *
465fiber_pool_allocate_memory(size_t * count, size_t stride)
466{
467 // We use a divide-by-2 strategy to try and allocate memory. We are trying
468 // to allocate `count` stacks. In normal situation, this won't fail. But
469 // if we ran out of address space, or we are allocating more memory than
470 // the system would allow (e.g. overcommit * physical memory + swap), we
471 // divide count by two and try again. This condition should only be
472 // encountered in edge cases, but we handle it here gracefully.
473 while (*count > 1) {
474#if defined(_WIN32)
475 void * base = VirtualAlloc(0, (*count)*stride, MEM_COMMIT, PAGE_READWRITE);
476
477 if (!base) {
478 *count = (*count) >> 1;
479 }
480 else {
481 return base;
482 }
483#else
484 errno = 0;
485 size_t mmap_size = (*count)*stride;
486 void * base = mmap(NULL, mmap_size, PROT_READ | PROT_WRITE, FIBER_STACK_FLAGS, -1, 0);
487
488 if (base == MAP_FAILED) {
489 // If the allocation fails, count = count / 2, and try again.
490 *count = (*count) >> 1;
491 }
492 else {
493 ruby_annotate_mmap(base, mmap_size, "Ruby:fiber_pool_allocate_memory");
494#if defined(MADV_FREE_REUSE)
495 // On Mac MADV_FREE_REUSE is necessary for the task_info api
496 // to keep the accounting accurate as possible when a page is marked as reusable
497 // it can possibly not occurring at first call thus re-iterating if necessary.
498 while (madvise(base, mmap_size, MADV_FREE_REUSE) == -1 && errno == EAGAIN);
499#endif
500 return base;
501 }
502#endif
503 }
504
505 return NULL;
506}
507
508// Given an existing fiber pool, expand it by the specified number of stacks.
509// @param count the maximum number of stacks to allocate.
510// @return the allocated fiber pool.
511// @sa fiber_pool_allocation_free
512static struct fiber_pool_allocation *
513fiber_pool_expand(struct fiber_pool * fiber_pool, size_t count)
514{
515 struct fiber_pool_allocation * allocation;
516 RB_VM_LOCK_ENTER();
517 {
518 STACK_GROW_DIR_DETECTION;
519
520 size_t size = fiber_pool->size;
521 size_t stride = size + RB_PAGE_SIZE;
522
523 // Allocate the memory required for the stacks:
524 void * base = fiber_pool_allocate_memory(&count, stride);
525
526 if (base == NULL) {
527 rb_raise(rb_eFiberError, "can't alloc machine stack to fiber (%"PRIuSIZE" x %"PRIuSIZE" bytes): %s", count, size, ERRNOMSG);
528 }
529
530 struct fiber_pool_vacancy * vacancies = fiber_pool->vacancies;
531 allocation = RB_ALLOC(struct fiber_pool_allocation);
532
533 // Initialize fiber pool allocation:
534 allocation->base = base;
535 allocation->size = size;
536 allocation->stride = stride;
537 allocation->count = count;
538#ifdef FIBER_POOL_ALLOCATION_FREE
539 allocation->used = 0;
540#endif
541 allocation->pool = fiber_pool;
542
543 if (DEBUG) {
544 fprintf(stderr, "fiber_pool_expand(%"PRIuSIZE"): %p, %"PRIuSIZE"/%"PRIuSIZE" x [%"PRIuSIZE":%"PRIuSIZE"]\n",
545 count, (void*)fiber_pool, fiber_pool->used, fiber_pool->count, size, fiber_pool->vm_stack_size);
546 }
547
548 // Iterate over all stacks, initializing the vacancy list:
549 for (size_t i = 0; i < count; i += 1) {
550 void * base = (char*)allocation->base + (stride * i);
551 void * page = (char*)base + STACK_DIR_UPPER(size, 0);
552#if defined(_WIN32)
553 DWORD old_protect;
554
555 if (!VirtualProtect(page, RB_PAGE_SIZE, PAGE_READWRITE | PAGE_GUARD, &old_protect)) {
556 VirtualFree(allocation->base, 0, MEM_RELEASE);
557 rb_raise(rb_eFiberError, "can't set a guard page: %s", ERRNOMSG);
558 }
559#elif defined(__wasi__)
560 // wasi-libc's mprotect emulation doesn't support PROT_NONE.
561 (void)page;
562#else
563 if (mprotect(page, RB_PAGE_SIZE, PROT_NONE) < 0) {
564 munmap(allocation->base, count*stride);
565 rb_raise(rb_eFiberError, "can't set a guard page: %s", ERRNOMSG);
566 }
567#endif
568
569 vacancies = fiber_pool_vacancy_initialize(
570 fiber_pool, vacancies,
571 (char*)base + STACK_DIR_UPPER(0, RB_PAGE_SIZE),
572 size
573 );
574
575#ifdef FIBER_POOL_ALLOCATION_FREE
576 vacancies->stack.allocation = allocation;
577#endif
578 }
579
580 // Insert the allocation into the head of the pool:
581 allocation->next = fiber_pool->allocations;
582
583#ifdef FIBER_POOL_ALLOCATION_FREE
584 if (allocation->next) {
585 allocation->next->previous = allocation;
586 }
587
588 allocation->previous = NULL;
589#endif
590
591 fiber_pool->allocations = allocation;
592 fiber_pool->vacancies = vacancies;
593 fiber_pool->count += count;
594 }
595 RB_VM_LOCK_LEAVE();
596
597 return allocation;
598}
599
600// Initialize the specified fiber pool with the given number of stacks.
601// @param vm_stack_size The size of the vm stack to allocate.
602static void
603fiber_pool_initialize(struct fiber_pool * fiber_pool, size_t size, size_t count, size_t vm_stack_size)
604{
605 VM_ASSERT(vm_stack_size < size);
606
607 fiber_pool->allocations = NULL;
608 fiber_pool->vacancies = NULL;
609 fiber_pool->size = ((size / RB_PAGE_SIZE) + 1) * RB_PAGE_SIZE;
610 fiber_pool->count = 0;
611 fiber_pool->initial_count = count;
612 fiber_pool->free_stacks = 1;
613 fiber_pool->used = 0;
614
615 fiber_pool->vm_stack_size = vm_stack_size;
616
617 fiber_pool_expand(fiber_pool, count);
618}
619
620#ifdef FIBER_POOL_ALLOCATION_FREE
621// Free the list of fiber pool allocations.
622static void
623fiber_pool_allocation_free(struct fiber_pool_allocation * allocation)
624{
625 STACK_GROW_DIR_DETECTION;
626
627 VM_ASSERT(allocation->used == 0);
628
629 if (DEBUG) fprintf(stderr, "fiber_pool_allocation_free: %p base=%p count=%"PRIuSIZE"\n", (void*)allocation, allocation->base, allocation->count);
630
631 size_t i;
632 for (i = 0; i < allocation->count; i += 1) {
633 void * base = (char*)allocation->base + (allocation->stride * i) + STACK_DIR_UPPER(0, RB_PAGE_SIZE);
634
635 struct fiber_pool_vacancy * vacancy = fiber_pool_vacancy_pointer(base, allocation->size);
636
637 // Pop the vacant stack off the free list:
638 fiber_pool_vacancy_remove(vacancy);
639 }
640
641#ifdef _WIN32
642 VirtualFree(allocation->base, 0, MEM_RELEASE);
643#else
644 munmap(allocation->base, allocation->stride * allocation->count);
645#endif
646
647 if (allocation->previous) {
648 allocation->previous->next = allocation->next;
649 }
650 else {
651 // We are the head of the list, so update the pool:
652 allocation->pool->allocations = allocation->next;
653 }
654
655 if (allocation->next) {
656 allocation->next->previous = allocation->previous;
657 }
658
659 allocation->pool->count -= allocation->count;
660
661 ruby_xfree(allocation);
662}
663#endif
664
665// Acquire a stack from the given fiber pool. If none are available, allocate more.
666static struct fiber_pool_stack
667fiber_pool_stack_acquire(struct fiber_pool * fiber_pool)
668{
669 struct fiber_pool_vacancy * vacancy ;
670 RB_VM_LOCK_ENTER();
671 {
672 vacancy = fiber_pool_vacancy_pop(fiber_pool);
673
674 if (DEBUG) fprintf(stderr, "fiber_pool_stack_acquire: %p used=%"PRIuSIZE"\n", (void*)fiber_pool->vacancies, fiber_pool->used);
675
676 if (!vacancy) {
677 const size_t maximum = FIBER_POOL_ALLOCATION_MAXIMUM_SIZE;
678 const size_t minimum = fiber_pool->initial_count;
679
680 size_t count = fiber_pool->count;
681 if (count > maximum) count = maximum;
682 if (count < minimum) count = minimum;
683
684 fiber_pool_expand(fiber_pool, count);
685
686 // The free list should now contain some stacks:
687 VM_ASSERT(fiber_pool->vacancies);
688
689 vacancy = fiber_pool_vacancy_pop(fiber_pool);
690 }
691
692 VM_ASSERT(vacancy);
693 VM_ASSERT(vacancy->stack.base);
694
695#if defined(COROUTINE_SANITIZE_ADDRESS)
696 __asan_unpoison_memory_region(fiber_pool_stack_poison_base(&vacancy->stack), fiber_pool_stack_poison_size(&vacancy->stack));
697#endif
698
699 // Take the top item from the free list:
700 fiber_pool->used += 1;
701
702#ifdef FIBER_POOL_ALLOCATION_FREE
703 vacancy->stack.allocation->used += 1;
704#endif
705
706 fiber_pool_stack_reset(&vacancy->stack);
707 }
708 RB_VM_LOCK_LEAVE();
709
710 return vacancy->stack;
711}
712
713// We advise the operating system that the stack memory pages are no longer being used.
714// This introduce some performance overhead but allows system to relaim memory when there is pressure.
715static inline void
716fiber_pool_stack_free(struct fiber_pool_stack * stack)
717{
718 void * base = fiber_pool_stack_base(stack);
719 size_t size = stack->available;
720
721 // If this is not true, the vacancy information will almost certainly be destroyed:
722 VM_ASSERT(size <= (stack->size - RB_PAGE_SIZE));
723
724 int advice = stack->pool->free_stacks >> 1;
725
726 if (DEBUG) fprintf(stderr, "fiber_pool_stack_free: %p+%"PRIuSIZE" [base=%p, size=%"PRIuSIZE"] advice=%d\n", base, size, stack->base, stack->size, advice);
727
728 // The pages being used by the stack can be returned back to the system.
729 // That doesn't change the page mapping, but it does allow the system to
730 // reclaim the physical memory.
731 // Since we no longer care about the data itself, we don't need to page
732 // out to disk, since that is costly. Not all systems support that, so
733 // we try our best to select the most efficient implementation.
734 // In addition, it's actually slightly desirable to not do anything here,
735 // but that results in higher memory usage.
736
737#ifdef __wasi__
738 // WebAssembly doesn't support madvise, so we just don't do anything.
739#elif VM_CHECK_MODE > 0 && defined(MADV_DONTNEED)
740 if (!advice) advice = MADV_DONTNEED;
741 // This immediately discards the pages and the memory is reset to zero.
742 madvise(base, size, advice);
743#elif defined(MADV_FREE_REUSABLE)
744 if (!advice) advice = MADV_FREE_REUSABLE;
745 // Darwin / macOS / iOS.
746 // Acknowledge the kernel down to the task info api we make this
747 // page reusable for future use.
748 // As for MADV_FREE_REUSABLE below we ensure in the rare occasions the task was not
749 // completed at the time of the call to re-iterate.
750 while (madvise(base, size, advice) == -1 && errno == EAGAIN);
751#elif defined(MADV_FREE)
752 if (!advice) advice = MADV_FREE;
753 // Recent Linux.
754 madvise(base, size, advice);
755#elif defined(MADV_DONTNEED)
756 if (!advice) advice = MADV_DONTNEED;
757 // Old Linux.
758 madvise(base, size, advice);
759#elif defined(POSIX_MADV_DONTNEED)
760 if (!advice) advice = POSIX_MADV_DONTNEED;
761 // Solaris?
762 posix_madvise(base, size, advice);
763#elif defined(_WIN32)
764 VirtualAlloc(base, size, MEM_RESET, PAGE_READWRITE);
765 // Not available in all versions of Windows.
766 //DiscardVirtualMemory(base, size);
767#endif
768
769#if defined(COROUTINE_SANITIZE_ADDRESS)
770 __asan_poison_memory_region(fiber_pool_stack_poison_base(stack), fiber_pool_stack_poison_size(stack));
771#endif
772}
773
774// Release and return a stack to the vacancy list.
775static void
776fiber_pool_stack_release(struct fiber_pool_stack * stack)
777{
778 struct fiber_pool * pool = stack->pool;
779 struct fiber_pool_vacancy * vacancy = fiber_pool_vacancy_pointer(stack->base, stack->size);
780
781 if (DEBUG) fprintf(stderr, "fiber_pool_stack_release: %p used=%"PRIuSIZE"\n", stack->base, stack->pool->used);
782
783 // Copy the stack details into the vacancy area:
784 vacancy->stack = *stack;
785 // After this point, be careful about updating/using state in stack, since it's copied to the vacancy area.
786
787 // Reset the stack pointers and reserve space for the vacancy data:
788 fiber_pool_vacancy_reset(vacancy);
789
790 // Push the vacancy into the vancancies list:
791 pool->vacancies = fiber_pool_vacancy_push(vacancy, pool->vacancies);
792 pool->used -= 1;
793
794#ifdef FIBER_POOL_ALLOCATION_FREE
795 struct fiber_pool_allocation * allocation = stack->allocation;
796
797 allocation->used -= 1;
798
799 // Release address space and/or dirty memory:
800 if (allocation->used == 0) {
801 fiber_pool_allocation_free(allocation);
802 }
803 else if (stack->pool->free_stacks) {
804 fiber_pool_stack_free(&vacancy->stack);
805 }
806#else
807 // This is entirely optional, but clears the dirty flag from the stack
808 // memory, so it won't get swapped to disk when there is memory pressure:
809 if (stack->pool->free_stacks) {
810 fiber_pool_stack_free(&vacancy->stack);
811 }
812#endif
813}
814
815static inline void
816ec_switch(rb_thread_t *th, rb_fiber_t *fiber)
817{
818 rb_execution_context_t *ec = &fiber->cont.saved_ec;
819#ifdef RUBY_ASAN_ENABLED
820 ec->machine.asan_fake_stack_handle = asan_get_thread_fake_stack_handle();
821#endif
822 rb_ractor_set_current_ec(th->ractor, th->ec = ec);
823 // ruby_current_execution_context_ptr = th->ec = ec;
824
825 /*
826 * timer-thread may set trap interrupt on previous th->ec at any time;
827 * ensure we do not delay (or lose) the trap interrupt handling.
828 */
829 if (th->vm->ractor.main_thread == th &&
830 rb_signal_buff_size() > 0) {
831 RUBY_VM_SET_TRAP_INTERRUPT(ec);
832 }
833
834 VM_ASSERT(ec->fiber_ptr->cont.self == 0 || ec->vm_stack != NULL);
835}
836
837static inline void
838fiber_restore_thread(rb_thread_t *th, rb_fiber_t *fiber)
839{
840 ec_switch(th, fiber);
841 VM_ASSERT(th->ec->fiber_ptr == fiber);
842}
843
844#ifndef COROUTINE_DECL
845# define COROUTINE_DECL COROUTINE
846#endif
847NORETURN(static COROUTINE_DECL fiber_entry(struct coroutine_context * from, struct coroutine_context * to));
848static COROUTINE
849fiber_entry(struct coroutine_context * from, struct coroutine_context * to)
850{
851 rb_fiber_t *fiber = to->argument;
852
853#if defined(COROUTINE_SANITIZE_ADDRESS)
854 // Address sanitizer will copy the previous stack base and stack size into
855 // the "from" fiber. `coroutine_initialize_main` doesn't generally know the
856 // stack bounds (base + size). Therefore, the main fiber `stack_base` and
857 // `stack_size` will be NULL/0. It's specifically important in that case to
858 // get the (base+size) of the previous fiber and save it, so that later when
859 // we return to the main coroutine, we don't supply (NULL, 0) to
860 // __sanitizer_start_switch_fiber which royally messes up the internal state
861 // of ASAN and causes (sometimes) the following message:
862 // "WARNING: ASan is ignoring requested __asan_handle_no_return"
863 __sanitizer_finish_switch_fiber(to->fake_stack, (const void**)&from->stack_base, &from->stack_size);
864#endif
865
866 rb_thread_t *thread = fiber->cont.saved_ec.thread_ptr;
867
868#ifdef COROUTINE_PTHREAD_CONTEXT
869 ruby_thread_set_native(thread);
870#endif
871
872 fiber_restore_thread(thread, fiber);
873
874 rb_fiber_start(fiber);
875
876#ifndef COROUTINE_PTHREAD_CONTEXT
877 VM_UNREACHABLE(fiber_entry);
878#endif
879}
880
881// Initialize a fiber's coroutine's machine stack and vm stack.
882static VALUE *
883fiber_initialize_coroutine(rb_fiber_t *fiber, size_t * vm_stack_size)
884{
885 struct fiber_pool * fiber_pool = fiber->stack.pool;
886 rb_execution_context_t *sec = &fiber->cont.saved_ec;
887 void * vm_stack = NULL;
888
889 VM_ASSERT(fiber_pool != NULL);
890
891 fiber->stack = fiber_pool_stack_acquire(fiber_pool);
892 vm_stack = fiber_pool_stack_alloca(&fiber->stack, fiber_pool->vm_stack_size);
893 *vm_stack_size = fiber_pool->vm_stack_size;
894
895 coroutine_initialize(&fiber->context, fiber_entry, fiber_pool_stack_base(&fiber->stack), fiber->stack.available);
896
897 // The stack for this execution context is the one we allocated:
898 sec->machine.stack_start = fiber->stack.current;
899 sec->machine.stack_maxsize = fiber->stack.available;
900
901 fiber->context.argument = (void*)fiber;
902
903 return vm_stack;
904}
905
906// Release the stack from the fiber, it's execution context, and return it to
907// the fiber pool.
908static void
909fiber_stack_release(rb_fiber_t * fiber)
910{
911 rb_execution_context_t *ec = &fiber->cont.saved_ec;
912
913 if (DEBUG) fprintf(stderr, "fiber_stack_release: %p, stack.base=%p\n", (void*)fiber, fiber->stack.base);
914
915 // Return the stack back to the fiber pool if it wasn't already:
916 if (fiber->stack.base) {
917 fiber_pool_stack_release(&fiber->stack);
918 fiber->stack.base = NULL;
919 }
920
921 // The stack is no longer associated with this execution context:
922 rb_ec_clear_vm_stack(ec);
923}
924
925static void
926fiber_stack_release_locked(rb_fiber_t *fiber)
927{
928 if (!ruby_vm_during_cleanup) {
929 // We can't try to acquire the VM lock here because MMTK calls free in its own native thread which has no ec.
930 // This assertion will fail on MMTK but we currently don't have CI for debug releases of MMTK, so we can assert for now.
931 ASSERT_vm_locking_with_barrier();
932 }
933 fiber_stack_release(fiber);
934}
935
936static const char *
937fiber_status_name(enum fiber_status s)
938{
939 switch (s) {
940 case FIBER_CREATED: return "created";
941 case FIBER_RESUMED: return "resumed";
942 case FIBER_SUSPENDED: return "suspended";
943 case FIBER_TERMINATED: return "terminated";
944 }
945 VM_UNREACHABLE(fiber_status_name);
946 return NULL;
947}
948
949static void
950fiber_verify(const rb_fiber_t *fiber)
951{
952#if VM_CHECK_MODE > 0
953 VM_ASSERT(fiber->cont.saved_ec.fiber_ptr == fiber);
954
955 switch (fiber->status) {
956 case FIBER_RESUMED:
957 VM_ASSERT(fiber->cont.saved_ec.vm_stack != NULL);
958 break;
959 case FIBER_SUSPENDED:
960 VM_ASSERT(fiber->cont.saved_ec.vm_stack != NULL);
961 break;
962 case FIBER_CREATED:
963 case FIBER_TERMINATED:
964 /* TODO */
965 break;
966 default:
967 VM_UNREACHABLE(fiber_verify);
968 }
969#endif
970}
971
972inline static void
973fiber_status_set(rb_fiber_t *fiber, enum fiber_status s)
974{
975 // if (DEBUG) fprintf(stderr, "fiber: %p, status: %s -> %s\n", (void *)fiber, fiber_status_name(fiber->status), fiber_status_name(s));
976 VM_ASSERT(!FIBER_TERMINATED_P(fiber));
977 VM_ASSERT(fiber->status != s);
978 fiber_verify(fiber);
979 fiber->status = s;
980}
981
982static rb_context_t *
983cont_ptr(VALUE obj)
984{
985 rb_context_t *cont;
986
987 TypedData_Get_Struct(obj, rb_context_t, &cont_data_type, cont);
988
989 return cont;
990}
991
992static rb_fiber_t *
993fiber_ptr(VALUE obj)
994{
995 rb_fiber_t *fiber;
996
997 TypedData_Get_Struct(obj, rb_fiber_t, &fiber_data_type, fiber);
998 if (!fiber) rb_raise(rb_eFiberError, "uninitialized fiber");
999
1000 return fiber;
1001}
1002
1003NOINLINE(static VALUE cont_capture(volatile int *volatile stat));
1004
1005#define THREAD_MUST_BE_RUNNING(th) do { \
1006 if (!(th)->ec->tag) rb_raise(rb_eThreadError, "not running thread"); \
1007 } while (0)
1008
1010rb_fiber_threadptr(const rb_fiber_t *fiber)
1011{
1012 return fiber->cont.saved_ec.thread_ptr;
1013}
1014
1015rb_serial_t
1016rb_fiber_serial(const rb_fiber_t *fiber)
1017{
1018 VM_ASSERT(fiber->serial >= 1);
1019 return fiber->serial;
1020}
1021
1022static VALUE
1023cont_thread_value(const rb_context_t *cont)
1024{
1025 return cont->saved_ec.thread_ptr->self;
1026}
1027
1028static void
1029cont_compact(void *ptr)
1030{
1031 rb_context_t *cont = ptr;
1032
1033 if (cont->self) {
1034 cont->self = rb_gc_location(cont->self);
1035 }
1036 cont->value = rb_gc_location(cont->value);
1037 rb_execution_context_update(&cont->saved_ec);
1038}
1039
1040static void
1041cont_mark(void *ptr)
1042{
1043 rb_context_t *cont = ptr;
1044
1045 RUBY_MARK_ENTER("cont");
1046 if (cont->self) {
1047 rb_gc_mark_movable(cont->self);
1048 }
1049 rb_gc_mark_movable(cont->value);
1050
1051 rb_execution_context_mark(&cont->saved_ec);
1052 rb_gc_mark(cont_thread_value(cont));
1053
1054 if (cont->saved_vm_stack.ptr) {
1055#ifdef CAPTURE_JUST_VALID_VM_STACK
1056 rb_gc_mark_locations(cont->saved_vm_stack.ptr,
1057 cont->saved_vm_stack.ptr + cont->saved_vm_stack.slen + cont->saved_vm_stack.clen);
1058#else
1059 rb_gc_mark_locations(cont->saved_vm_stack.ptr,
1060 cont->saved_vm_stack.ptr, cont->saved_ec.stack_size);
1061#endif
1062 }
1063
1064 if (cont->machine.stack) {
1065 if (cont->type == CONTINUATION_CONTEXT) {
1066 /* cont */
1067 rb_gc_mark_locations(cont->machine.stack,
1068 cont->machine.stack + cont->machine.stack_size);
1069 }
1070 else {
1071 /* fiber machine context is marked as part of rb_execution_context_mark, no need to
1072 * do anything here. */
1073 }
1074 }
1075
1076 RUBY_MARK_LEAVE("cont");
1077}
1078
1079#if 0
1080static int
1081fiber_is_root_p(const rb_fiber_t *fiber)
1082{
1083 return fiber == fiber->cont.saved_ec.thread_ptr->root_fiber;
1084}
1085#endif
1086
1087static void jit_cont_free(struct rb_jit_cont *cont);
1088
1089static void
1090cont_free(void *ptr)
1091{
1092 rb_context_t *cont = ptr;
1093
1094 RUBY_FREE_ENTER("cont");
1095
1096 if (cont->type == CONTINUATION_CONTEXT) {
1097 ruby_xfree(cont->saved_ec.vm_stack);
1098 RUBY_FREE_UNLESS_NULL(cont->machine.stack);
1099 }
1100 else {
1101 rb_fiber_t *fiber = (rb_fiber_t*)cont;
1102 coroutine_destroy(&fiber->context);
1103 fiber_stack_release_locked(fiber);
1104 }
1105
1106 RUBY_FREE_UNLESS_NULL(cont->saved_vm_stack.ptr);
1107
1108 VM_ASSERT(cont->jit_cont != NULL);
1109 jit_cont_free(cont->jit_cont);
1110 /* free rb_cont_t or rb_fiber_t */
1111 ruby_xfree(ptr);
1112 RUBY_FREE_LEAVE("cont");
1113}
1114
1115static size_t
1116cont_memsize(const void *ptr)
1117{
1118 const rb_context_t *cont = ptr;
1119 size_t size = 0;
1120
1121 size = sizeof(*cont);
1122 if (cont->saved_vm_stack.ptr) {
1123#ifdef CAPTURE_JUST_VALID_VM_STACK
1124 size_t n = (cont->saved_vm_stack.slen + cont->saved_vm_stack.clen);
1125#else
1126 size_t n = cont->saved_ec.vm_stack_size;
1127#endif
1128 size += n * sizeof(*cont->saved_vm_stack.ptr);
1129 }
1130
1131 if (cont->machine.stack) {
1132 size += cont->machine.stack_size * sizeof(*cont->machine.stack);
1133 }
1134
1135 return size;
1136}
1137
1138void
1139rb_fiber_update_self(rb_fiber_t *fiber)
1140{
1141 if (fiber->cont.self) {
1142 fiber->cont.self = rb_gc_location(fiber->cont.self);
1143 }
1144 else {
1145 rb_execution_context_update(&fiber->cont.saved_ec);
1146 }
1147}
1148
1149void
1150rb_fiber_mark_self(const rb_fiber_t *fiber)
1151{
1152 if (fiber->cont.self) {
1153 rb_gc_mark_movable(fiber->cont.self);
1154 }
1155 else {
1156 rb_execution_context_mark(&fiber->cont.saved_ec);
1157 }
1158}
1159
1160static void
1161fiber_compact(void *ptr)
1162{
1163 rb_fiber_t *fiber = ptr;
1164 fiber->first_proc = rb_gc_location(fiber->first_proc);
1165
1166 if (fiber->prev) rb_fiber_update_self(fiber->prev);
1167
1168 cont_compact(&fiber->cont);
1169 fiber_verify(fiber);
1170}
1171
1172static void
1173fiber_mark(void *ptr)
1174{
1175 rb_fiber_t *fiber = ptr;
1176 RUBY_MARK_ENTER("cont");
1177 fiber_verify(fiber);
1178 rb_gc_mark_movable(fiber->first_proc);
1179 if (fiber->prev) rb_fiber_mark_self(fiber->prev);
1180 cont_mark(&fiber->cont);
1181 RUBY_MARK_LEAVE("cont");
1182}
1183
1184static void
1185fiber_free(void *ptr)
1186{
1187 rb_fiber_t *fiber = ptr;
1188 RUBY_FREE_ENTER("fiber");
1189
1190 if (DEBUG) fprintf(stderr, "fiber_free: %p[%p]\n", (void *)fiber, fiber->stack.base);
1191
1192 if (fiber->cont.saved_ec.local_storage) {
1193 rb_id_table_free(fiber->cont.saved_ec.local_storage);
1194 }
1195
1196 cont_free(&fiber->cont);
1197 RUBY_FREE_LEAVE("fiber");
1198}
1199
1200static size_t
1201fiber_memsize(const void *ptr)
1202{
1203 const rb_fiber_t *fiber = ptr;
1204 size_t size = sizeof(*fiber);
1205 const rb_execution_context_t *saved_ec = &fiber->cont.saved_ec;
1206 const rb_thread_t *th = rb_ec_thread_ptr(saved_ec);
1207
1208 /*
1209 * vm.c::thread_memsize already counts th->ec->local_storage
1210 */
1211 if (saved_ec->local_storage && fiber != th->root_fiber) {
1212 size += rb_id_table_memsize(saved_ec->local_storage);
1213 size += rb_obj_memsize_of(saved_ec->storage);
1214 }
1215
1216 size += cont_memsize(&fiber->cont);
1217 return size;
1218}
1219
1220VALUE
1221rb_obj_is_fiber(VALUE obj)
1222{
1223 return RBOOL(rb_typeddata_is_kind_of(obj, &fiber_data_type));
1224}
1225
1226static void
1227cont_save_machine_stack(rb_thread_t *th, rb_context_t *cont)
1228{
1229 size_t size;
1230
1231 SET_MACHINE_STACK_END(&th->ec->machine.stack_end);
1232
1233 if (th->ec->machine.stack_start > th->ec->machine.stack_end) {
1234 size = cont->machine.stack_size = th->ec->machine.stack_start - th->ec->machine.stack_end;
1235 cont->machine.stack_src = th->ec->machine.stack_end;
1236 }
1237 else {
1238 size = cont->machine.stack_size = th->ec->machine.stack_end - th->ec->machine.stack_start;
1239 cont->machine.stack_src = th->ec->machine.stack_start;
1240 }
1241
1242 if (cont->machine.stack) {
1243 REALLOC_N(cont->machine.stack, VALUE, size);
1244 }
1245 else {
1246 cont->machine.stack = ALLOC_N(VALUE, size);
1247 }
1248
1249 FLUSH_REGISTER_WINDOWS;
1250 asan_unpoison_memory_region(cont->machine.stack_src, size, false);
1251 MEMCPY(cont->machine.stack, cont->machine.stack_src, VALUE, size);
1252}
1253
1254static const rb_data_type_t cont_data_type = {
1255 "continuation",
1256 {cont_mark, cont_free, cont_memsize, cont_compact},
1257 0, 0, RUBY_TYPED_FREE_IMMEDIATELY
1258};
1259
1260static inline void
1261cont_save_thread(rb_context_t *cont, rb_thread_t *th)
1262{
1263 rb_execution_context_t *sec = &cont->saved_ec;
1264
1265 VM_ASSERT(th->status == THREAD_RUNNABLE);
1266
1267 /* save thread context */
1268 *sec = *th->ec;
1269
1270 /* saved_ec->machine.stack_end should be NULL */
1271 /* because it may happen GC afterward */
1272 sec->machine.stack_end = NULL;
1273}
1274
1275static rb_nativethread_lock_t jit_cont_lock;
1276
1277// Register a new continuation with execution context `ec`. Return JIT info about
1278// the continuation.
1279static struct rb_jit_cont *
1280jit_cont_new(rb_execution_context_t *ec)
1281{
1282 struct rb_jit_cont *cont;
1283
1284 // We need to use calloc instead of something like ZALLOC to avoid triggering GC here.
1285 // When this function is called from rb_thread_alloc through rb_threadptr_root_fiber_setup,
1286 // the thread is still being prepared and marking it causes SEGV.
1287 cont = calloc(1, sizeof(struct rb_jit_cont));
1288 if (cont == NULL)
1289 rb_memerror();
1290 cont->ec = ec;
1291
1292 rb_native_mutex_lock(&jit_cont_lock);
1293 if (first_jit_cont == NULL) {
1294 cont->next = cont->prev = NULL;
1295 }
1296 else {
1297 cont->prev = NULL;
1298 cont->next = first_jit_cont;
1299 first_jit_cont->prev = cont;
1300 }
1301 first_jit_cont = cont;
1302 rb_native_mutex_unlock(&jit_cont_lock);
1303
1304 return cont;
1305}
1306
1307// Unregister continuation `cont`.
1308static void
1309jit_cont_free(struct rb_jit_cont *cont)
1310{
1311 if (!cont) return;
1312
1313 rb_native_mutex_lock(&jit_cont_lock);
1314 if (cont == first_jit_cont) {
1315 first_jit_cont = cont->next;
1316 if (first_jit_cont != NULL)
1317 first_jit_cont->prev = NULL;
1318 }
1319 else {
1320 cont->prev->next = cont->next;
1321 if (cont->next != NULL)
1322 cont->next->prev = cont->prev;
1323 }
1324 rb_native_mutex_unlock(&jit_cont_lock);
1325
1326 free(cont);
1327}
1328
1329// Call a given callback against all on-stack ISEQs.
1330void
1331rb_jit_cont_each_iseq(rb_iseq_callback callback, void *data)
1332{
1333 struct rb_jit_cont *cont;
1334 for (cont = first_jit_cont; cont != NULL; cont = cont->next) {
1335 if (cont->ec->vm_stack == NULL)
1336 continue;
1337
1338 const rb_control_frame_t *cfp = cont->ec->cfp;
1339 while (!RUBY_VM_CONTROL_FRAME_STACK_OVERFLOW_P(cont->ec, cfp)) {
1340 if (cfp->pc && cfp->iseq && imemo_type((VALUE)cfp->iseq) == imemo_iseq) {
1341 callback(cfp->iseq, data);
1342 }
1343 cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp);
1344 }
1345 }
1346}
1347
1348#if USE_YJIT
1349// Update the jit_return of all CFPs to leave_exit unless it's leave_exception or not set.
1350// This prevents jit_exec_exception from jumping to the caller after invalidation.
1351void
1352rb_yjit_cancel_jit_return(void *leave_exit, void *leave_exception)
1353{
1354 struct rb_jit_cont *cont;
1355 for (cont = first_jit_cont; cont != NULL; cont = cont->next) {
1356 if (cont->ec->vm_stack == NULL)
1357 continue;
1358
1359 const rb_control_frame_t *cfp = cont->ec->cfp;
1360 while (!RUBY_VM_CONTROL_FRAME_STACK_OVERFLOW_P(cont->ec, cfp)) {
1361 if (cfp->jit_return && cfp->jit_return != leave_exception) {
1362 ((rb_control_frame_t *)cfp)->jit_return = leave_exit;
1363 }
1364 cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp);
1365 }
1366 }
1367}
1368#endif
1369
1370// Finish working with jit_cont.
1371void
1372rb_jit_cont_finish(void)
1373{
1374 struct rb_jit_cont *cont, *next;
1375 for (cont = first_jit_cont; cont != NULL; cont = next) {
1376 next = cont->next;
1377 free(cont); // Don't use xfree because it's allocated by calloc.
1378 }
1379 rb_native_mutex_destroy(&jit_cont_lock);
1380}
1381
1382static void
1383cont_init_jit_cont(rb_context_t *cont)
1384{
1385 VM_ASSERT(cont->jit_cont == NULL);
1386 // We always allocate this since YJIT may be enabled later
1387 cont->jit_cont = jit_cont_new(&(cont->saved_ec));
1388}
1389
1391rb_fiberptr_get_ec(struct rb_fiber_struct *fiber)
1392{
1393 return &fiber->cont.saved_ec;
1394}
1395
1396static void
1397cont_init(rb_context_t *cont, rb_thread_t *th)
1398{
1399 /* save thread context */
1400 cont_save_thread(cont, th);
1401 cont->saved_ec.thread_ptr = th;
1402 cont->saved_ec.local_storage = NULL;
1403 cont->saved_ec.local_storage_recursive_hash = Qnil;
1404 cont->saved_ec.local_storage_recursive_hash_for_trace = Qnil;
1405 cont_init_jit_cont(cont);
1406}
1407
1408static rb_context_t *
1409cont_new(VALUE klass)
1410{
1411 rb_context_t *cont;
1412 volatile VALUE contval;
1413 rb_thread_t *th = GET_THREAD();
1414
1415 THREAD_MUST_BE_RUNNING(th);
1416 contval = TypedData_Make_Struct(klass, rb_context_t, &cont_data_type, cont);
1417 cont->self = contval;
1418 cont_init(cont, th);
1419 return cont;
1420}
1421
1422VALUE
1423rb_fiberptr_self(struct rb_fiber_struct *fiber)
1424{
1425 return fiber->cont.self;
1426}
1427
1428unsigned int
1429rb_fiberptr_blocking(struct rb_fiber_struct *fiber)
1430{
1431 return fiber->blocking;
1432}
1433
1434// Initialize the jit_cont_lock
1435void
1436rb_jit_cont_init(void)
1437{
1438 rb_native_mutex_initialize(&jit_cont_lock);
1439}
1440
1441#if 0
1442void
1443show_vm_stack(const rb_execution_context_t *ec)
1444{
1445 VALUE *p = ec->vm_stack;
1446 while (p < ec->cfp->sp) {
1447 fprintf(stderr, "%3d ", (int)(p - ec->vm_stack));
1448 rb_obj_info_dump(*p);
1449 p++;
1450 }
1451}
1452
1453void
1454show_vm_pcs(const rb_control_frame_t *cfp,
1455 const rb_control_frame_t *end_of_cfp)
1456{
1457 int i=0;
1458 while (cfp != end_of_cfp) {
1459 int pc = 0;
1460 if (cfp->iseq) {
1461 pc = cfp->pc - ISEQ_BODY(cfp->iseq)->iseq_encoded;
1462 }
1463 fprintf(stderr, "%2d pc: %d\n", i++, pc);
1464 cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp);
1465 }
1466}
1467#endif
1468
1469static VALUE
1470cont_capture(volatile int *volatile stat)
1471{
1472 rb_context_t *volatile cont;
1473 rb_thread_t *th = GET_THREAD();
1474 volatile VALUE contval;
1475 const rb_execution_context_t *ec = th->ec;
1476
1477 THREAD_MUST_BE_RUNNING(th);
1478 rb_vm_stack_to_heap(th->ec);
1479 cont = cont_new(rb_cContinuation);
1480 contval = cont->self;
1481
1482#ifdef CAPTURE_JUST_VALID_VM_STACK
1483 cont->saved_vm_stack.slen = ec->cfp->sp - ec->vm_stack;
1484 cont->saved_vm_stack.clen = ec->vm_stack + ec->vm_stack_size - (VALUE*)ec->cfp;
1485 cont->saved_vm_stack.ptr = ALLOC_N(VALUE, cont->saved_vm_stack.slen + cont->saved_vm_stack.clen);
1486 MEMCPY(cont->saved_vm_stack.ptr,
1487 ec->vm_stack,
1488 VALUE, cont->saved_vm_stack.slen);
1489 MEMCPY(cont->saved_vm_stack.ptr + cont->saved_vm_stack.slen,
1490 (VALUE*)ec->cfp,
1491 VALUE,
1492 cont->saved_vm_stack.clen);
1493#else
1494 cont->saved_vm_stack.ptr = ALLOC_N(VALUE, ec->vm_stack_size);
1495 MEMCPY(cont->saved_vm_stack.ptr, ec->vm_stack, VALUE, ec->vm_stack_size);
1496#endif
1497 // At this point, `cfp` is valid but `vm_stack` should be cleared:
1498 rb_ec_set_vm_stack(&cont->saved_ec, NULL, 0);
1499 VM_ASSERT(cont->saved_ec.cfp != NULL);
1500 cont_save_machine_stack(th, cont);
1501
1502 if (ruby_setjmp(cont->jmpbuf)) {
1503 VALUE value;
1504
1505 VAR_INITIALIZED(cont);
1506 value = cont->value;
1507 if (cont->argc == -1) rb_exc_raise(value);
1508 cont->value = Qnil;
1509 *stat = 1;
1510 return value;
1511 }
1512 else {
1513 *stat = 0;
1514 return contval;
1515 }
1516}
1517
1518static inline void
1519cont_restore_thread(rb_context_t *cont)
1520{
1521 rb_thread_t *th = GET_THREAD();
1522
1523 /* restore thread context */
1524 if (cont->type == CONTINUATION_CONTEXT) {
1525 /* continuation */
1526 rb_execution_context_t *sec = &cont->saved_ec;
1527 rb_fiber_t *fiber = NULL;
1528
1529 if (sec->fiber_ptr != NULL) {
1530 fiber = sec->fiber_ptr;
1531 }
1532 else if (th->root_fiber) {
1533 fiber = th->root_fiber;
1534 }
1535
1536 if (fiber && th->ec != &fiber->cont.saved_ec) {
1537 ec_switch(th, fiber);
1538 }
1539
1540 if (th->ec->trace_arg != sec->trace_arg) {
1541 rb_raise(rb_eRuntimeError, "can't call across trace_func");
1542 }
1543
1544#if defined(__wasm__) && !defined(__EMSCRIPTEN__)
1545 if (th->ec->tag != sec->tag) {
1546 /* find the lowest common ancestor tag of the current EC and the saved EC */
1547
1548 struct rb_vm_tag *lowest_common_ancestor = NULL;
1549 size_t num_tags = 0;
1550 size_t num_saved_tags = 0;
1551 for (struct rb_vm_tag *tag = th->ec->tag; tag != NULL; tag = tag->prev) {
1552 ++num_tags;
1553 }
1554 for (struct rb_vm_tag *tag = sec->tag; tag != NULL; tag = tag->prev) {
1555 ++num_saved_tags;
1556 }
1557
1558 size_t min_tags = num_tags <= num_saved_tags ? num_tags : num_saved_tags;
1559
1560 struct rb_vm_tag *tag = th->ec->tag;
1561 while (num_tags > min_tags) {
1562 tag = tag->prev;
1563 --num_tags;
1564 }
1565
1566 struct rb_vm_tag *saved_tag = sec->tag;
1567 while (num_saved_tags > min_tags) {
1568 saved_tag = saved_tag->prev;
1569 --num_saved_tags;
1570 }
1571
1572 while (min_tags > 0) {
1573 if (tag == saved_tag) {
1574 lowest_common_ancestor = tag;
1575 break;
1576 }
1577 tag = tag->prev;
1578 saved_tag = saved_tag->prev;
1579 --min_tags;
1580 }
1581
1582 /* free all the jump buffers between the current EC's tag and the lowest common ancestor tag */
1583 for (struct rb_vm_tag *tag = th->ec->tag; tag != lowest_common_ancestor; tag = tag->prev) {
1584 rb_vm_tag_jmpbuf_deinit(&tag->buf);
1585 }
1586 }
1587#endif
1588
1589 /* copy vm stack */
1590#ifdef CAPTURE_JUST_VALID_VM_STACK
1591 MEMCPY(th->ec->vm_stack,
1592 cont->saved_vm_stack.ptr,
1593 VALUE, cont->saved_vm_stack.slen);
1594 MEMCPY(th->ec->vm_stack + th->ec->vm_stack_size - cont->saved_vm_stack.clen,
1595 cont->saved_vm_stack.ptr + cont->saved_vm_stack.slen,
1596 VALUE, cont->saved_vm_stack.clen);
1597#else
1598 MEMCPY(th->ec->vm_stack, cont->saved_vm_stack.ptr, VALUE, sec->vm_stack_size);
1599#endif
1600 /* other members of ec */
1601
1602 th->ec->cfp = sec->cfp;
1603 th->ec->raised_flag = sec->raised_flag;
1604 th->ec->tag = sec->tag;
1605 th->ec->root_lep = sec->root_lep;
1606 th->ec->root_svar = sec->root_svar;
1607 th->ec->errinfo = sec->errinfo;
1608
1609 VM_ASSERT(th->ec->vm_stack != NULL);
1610 }
1611 else {
1612 /* fiber */
1613 fiber_restore_thread(th, (rb_fiber_t*)cont);
1614 }
1615}
1616
1617NOINLINE(static void fiber_setcontext(rb_fiber_t *new_fiber, rb_fiber_t *old_fiber));
1618
1619static void
1620fiber_setcontext(rb_fiber_t *new_fiber, rb_fiber_t *old_fiber)
1621{
1622 rb_thread_t *th = GET_THREAD();
1623
1624 /* save old_fiber's machine stack - to ensure efficient garbage collection */
1625 if (!FIBER_TERMINATED_P(old_fiber)) {
1626 STACK_GROW_DIR_DETECTION;
1627 SET_MACHINE_STACK_END(&th->ec->machine.stack_end);
1628 if (STACK_DIR_UPPER(0, 1)) {
1629 old_fiber->cont.machine.stack_size = th->ec->machine.stack_start - th->ec->machine.stack_end;
1630 old_fiber->cont.machine.stack = th->ec->machine.stack_end;
1631 }
1632 else {
1633 old_fiber->cont.machine.stack_size = th->ec->machine.stack_end - th->ec->machine.stack_start;
1634 old_fiber->cont.machine.stack = th->ec->machine.stack_start;
1635 }
1636 }
1637
1638 /* these values are used in rb_gc_mark_machine_context to mark the fiber's stack. */
1639 old_fiber->cont.saved_ec.machine.stack_start = th->ec->machine.stack_start;
1640 old_fiber->cont.saved_ec.machine.stack_end = FIBER_TERMINATED_P(old_fiber) ? NULL : th->ec->machine.stack_end;
1641
1642
1643 // if (DEBUG) fprintf(stderr, "fiber_setcontext: %p[%p] -> %p[%p]\n", (void*)old_fiber, old_fiber->stack.base, (void*)new_fiber, new_fiber->stack.base);
1644
1645#if defined(COROUTINE_SANITIZE_ADDRESS)
1646 __sanitizer_start_switch_fiber(FIBER_TERMINATED_P(old_fiber) ? NULL : &old_fiber->context.fake_stack, new_fiber->context.stack_base, new_fiber->context.stack_size);
1647#endif
1648
1649 /* swap machine context */
1650 struct coroutine_context * from = coroutine_transfer(&old_fiber->context, &new_fiber->context);
1651
1652#if defined(COROUTINE_SANITIZE_ADDRESS)
1653 __sanitizer_finish_switch_fiber(old_fiber->context.fake_stack, NULL, NULL);
1654#endif
1655
1656 if (from == NULL) {
1657 rb_syserr_fail(errno, "coroutine_transfer");
1658 }
1659
1660 /* restore thread context */
1661 fiber_restore_thread(th, old_fiber);
1662
1663 // It's possible to get here, and new_fiber is already freed.
1664 // if (DEBUG) fprintf(stderr, "fiber_setcontext: %p[%p] <- %p[%p]\n", (void*)old_fiber, old_fiber->stack.base, (void*)new_fiber, new_fiber->stack.base);
1665}
1666
1667NOINLINE(NORETURN(static void cont_restore_1(rb_context_t *)));
1668
1669static void
1670cont_restore_1(rb_context_t *cont)
1671{
1672 cont_restore_thread(cont);
1673
1674 /* restore machine stack */
1675#if (defined(_M_AMD64) && !defined(__MINGW64__)) || defined(_M_ARM64)
1676 {
1677 /* workaround for x64 and arm64 SEH on Windows */
1678 jmp_buf buf;
1679 setjmp(buf);
1680 _JUMP_BUFFER *bp = (void*)&cont->jmpbuf;
1681 bp->Frame = ((_JUMP_BUFFER*)((void*)&buf))->Frame;
1682 }
1683#endif
1684 if (cont->machine.stack_src) {
1685 FLUSH_REGISTER_WINDOWS;
1686 MEMCPY(cont->machine.stack_src, cont->machine.stack,
1687 VALUE, cont->machine.stack_size);
1688 }
1689
1690 ruby_longjmp(cont->jmpbuf, 1);
1691}
1692
1693NORETURN(NOINLINE(static void cont_restore_0(rb_context_t *, VALUE *)));
1694
1695static void
1696cont_restore_0(rb_context_t *cont, VALUE *addr_in_prev_frame)
1697{
1698 if (cont->machine.stack_src) {
1699#ifdef HAVE_ALLOCA
1700#define STACK_PAD_SIZE 1
1701#else
1702#define STACK_PAD_SIZE 1024
1703#endif
1704 VALUE space[STACK_PAD_SIZE];
1705
1706#if !STACK_GROW_DIRECTION
1707 if (addr_in_prev_frame > &space[0]) {
1708 /* Stack grows downward */
1709#endif
1710#if STACK_GROW_DIRECTION <= 0
1711 volatile VALUE *const end = cont->machine.stack_src;
1712 if (&space[0] > end) {
1713# ifdef HAVE_ALLOCA
1714 volatile VALUE *sp = ALLOCA_N(VALUE, &space[0] - end);
1715 // We need to make sure that the stack pointer is moved,
1716 // but some compilers may remove the allocation by optimization.
1717 // We hope that the following read/write will prevent such an optimization.
1718 *sp = Qfalse;
1719 space[0] = *sp;
1720# else
1721 cont_restore_0(cont, &space[0]);
1722# endif
1723 }
1724#endif
1725#if !STACK_GROW_DIRECTION
1726 }
1727 else {
1728 /* Stack grows upward */
1729#endif
1730#if STACK_GROW_DIRECTION >= 0
1731 volatile VALUE *const end = cont->machine.stack_src + cont->machine.stack_size;
1732 if (&space[STACK_PAD_SIZE] < end) {
1733# ifdef HAVE_ALLOCA
1734 volatile VALUE *sp = ALLOCA_N(VALUE, end - &space[STACK_PAD_SIZE]);
1735 space[0] = *sp;
1736# else
1737 cont_restore_0(cont, &space[STACK_PAD_SIZE-1]);
1738# endif
1739 }
1740#endif
1741#if !STACK_GROW_DIRECTION
1742 }
1743#endif
1744 }
1745 cont_restore_1(cont);
1746}
1747
1748/*
1749 * Document-class: Continuation
1750 *
1751 * Continuation objects are generated by Kernel#callcc,
1752 * after having +require+d <i>continuation</i>. They hold
1753 * a return address and execution context, allowing a nonlocal return
1754 * to the end of the #callcc block from anywhere within a
1755 * program. Continuations are somewhat analogous to a structured
1756 * version of C's <code>setjmp/longjmp</code> (although they contain
1757 * more state, so you might consider them closer to threads).
1758 *
1759 * For instance:
1760 *
1761 * require "continuation"
1762 * arr = [ "Freddie", "Herbie", "Ron", "Max", "Ringo" ]
1763 * callcc{|cc| $cc = cc}
1764 * puts(message = arr.shift)
1765 * $cc.call unless message =~ /Max/
1766 *
1767 * <em>produces:</em>
1768 *
1769 * Freddie
1770 * Herbie
1771 * Ron
1772 * Max
1773 *
1774 * Also you can call callcc in other methods:
1775 *
1776 * require "continuation"
1777 *
1778 * def g
1779 * arr = [ "Freddie", "Herbie", "Ron", "Max", "Ringo" ]
1780 * cc = callcc { |cc| cc }
1781 * puts arr.shift
1782 * return cc, arr.size
1783 * end
1784 *
1785 * def f
1786 * c, size = g
1787 * c.call(c) if size > 1
1788 * end
1789 *
1790 * f
1791 *
1792 * This (somewhat contrived) example allows the inner loop to abandon
1793 * processing early:
1794 *
1795 * require "continuation"
1796 * callcc {|cont|
1797 * for i in 0..4
1798 * print "#{i}: "
1799 * for j in i*5...(i+1)*5
1800 * cont.call() if j == 17
1801 * printf "%3d", j
1802 * end
1803 * end
1804 * }
1805 * puts
1806 *
1807 * <em>produces:</em>
1808 *
1809 * 0: 0 1 2 3 4
1810 * 1: 5 6 7 8 9
1811 * 2: 10 11 12 13 14
1812 * 3: 15 16
1813 */
1814
1815/*
1816 * call-seq:
1817 * callcc {|cont| block } -> obj
1818 *
1819 * Generates a Continuation object, which it passes to
1820 * the associated block. You need to <code>require
1821 * 'continuation'</code> before using this method. Performing a
1822 * <em>cont</em><code>.call</code> will cause the #callcc
1823 * to return (as will falling through the end of the block). The
1824 * value returned by the #callcc is the value of the
1825 * block, or the value passed to <em>cont</em><code>.call</code>. See
1826 * class Continuation for more details. Also see
1827 * Kernel#throw for an alternative mechanism for
1828 * unwinding a call stack.
1829 */
1830
1831static VALUE
1832rb_callcc(VALUE self)
1833{
1834 volatile int called;
1835 volatile VALUE val = cont_capture(&called);
1836
1837 if (called) {
1838 return val;
1839 }
1840 else {
1841 return rb_yield(val);
1842 }
1843}
1844#ifdef RUBY_ASAN_ENABLED
1845/* callcc can't possibly work with ASAN; see bug #20273. Also this function
1846 * definition below avoids a "defined and not used" warning. */
1847MAYBE_UNUSED(static void notusing_callcc(void)) { rb_callcc(Qnil); }
1848# define rb_callcc rb_f_notimplement
1849#endif
1850
1851
1852static VALUE
1853make_passing_arg(int argc, const VALUE *argv)
1854{
1855 switch (argc) {
1856 case -1:
1857 return argv[0];
1858 case 0:
1859 return Qnil;
1860 case 1:
1861 return argv[0];
1862 default:
1863 return rb_ary_new4(argc, argv);
1864 }
1865}
1866
1867typedef VALUE e_proc(VALUE);
1868
1869NORETURN(static VALUE rb_cont_call(int argc, VALUE *argv, VALUE contval));
1870
1871/*
1872 * call-seq:
1873 * cont.call(args, ...)
1874 * cont[args, ...]
1875 *
1876 * Invokes the continuation. The program continues from the end of
1877 * the #callcc block. If no arguments are given, the original #callcc
1878 * returns +nil+. If one argument is given, #callcc returns
1879 * it. Otherwise, an array containing <i>args</i> is returned.
1880 *
1881 * callcc {|cont| cont.call } #=> nil
1882 * callcc {|cont| cont.call 1 } #=> 1
1883 * callcc {|cont| cont.call 1, 2, 3 } #=> [1, 2, 3]
1884 */
1885
1886static VALUE
1887rb_cont_call(int argc, VALUE *argv, VALUE contval)
1888{
1889 rb_context_t *cont = cont_ptr(contval);
1890 rb_thread_t *th = GET_THREAD();
1891
1892 if (cont_thread_value(cont) != th->self) {
1893 rb_raise(rb_eRuntimeError, "continuation called across threads");
1894 }
1895 if (cont->saved_ec.fiber_ptr) {
1896 if (th->ec->fiber_ptr != cont->saved_ec.fiber_ptr) {
1897 rb_raise(rb_eRuntimeError, "continuation called across fiber");
1898 }
1899 }
1900
1901 cont->argc = argc;
1902 cont->value = make_passing_arg(argc, argv);
1903
1904 cont_restore_0(cont, &contval);
1906}
1907
1908/*********/
1909/* fiber */
1910/*********/
1911
1912/*
1913 * Document-class: Fiber
1914 *
1915 * Fibers are primitives for implementing light weight cooperative
1916 * concurrency in Ruby. Basically they are a means of creating code blocks
1917 * that can be paused and resumed, much like threads. The main difference
1918 * is that they are never preempted and that the scheduling must be done by
1919 * the programmer and not the VM.
1920 *
1921 * As opposed to other stackless light weight concurrency models, each fiber
1922 * comes with a stack. This enables the fiber to be paused from deeply
1923 * nested function calls within the fiber block. See the ruby(1)
1924 * manpage to configure the size of the fiber stack(s).
1925 *
1926 * When a fiber is created it will not run automatically. Rather it must
1927 * be explicitly asked to run using the Fiber#resume method.
1928 * The code running inside the fiber can give up control by calling
1929 * Fiber.yield in which case it yields control back to caller (the
1930 * caller of the Fiber#resume).
1931 *
1932 * Upon yielding or termination the Fiber returns the value of the last
1933 * executed expression
1934 *
1935 * For instance:
1936 *
1937 * fiber = Fiber.new do
1938 * Fiber.yield 1
1939 * 2
1940 * end
1941 *
1942 * puts fiber.resume
1943 * puts fiber.resume
1944 * puts fiber.resume
1945 *
1946 * <em>produces</em>
1947 *
1948 * 1
1949 * 2
1950 * FiberError: dead fiber called
1951 *
1952 * The Fiber#resume method accepts an arbitrary number of parameters,
1953 * if it is the first call to #resume then they will be passed as
1954 * block arguments. Otherwise they will be the return value of the
1955 * call to Fiber.yield
1956 *
1957 * Example:
1958 *
1959 * fiber = Fiber.new do |first|
1960 * second = Fiber.yield first + 2
1961 * end
1962 *
1963 * puts fiber.resume 10
1964 * puts fiber.resume 1_000_000
1965 * puts fiber.resume "The fiber will be dead before I can cause trouble"
1966 *
1967 * <em>produces</em>
1968 *
1969 * 12
1970 * 1000000
1971 * FiberError: dead fiber called
1972 *
1973 * == Non-blocking Fibers
1974 *
1975 * The concept of <em>non-blocking fiber</em> was introduced in Ruby 3.0.
1976 * A non-blocking fiber, when reaching an operation that would normally block
1977 * the fiber (like <code>sleep</code>, or wait for another process or I/O)
1978 * will yield control to other fibers and allow the <em>scheduler</em> to
1979 * handle blocking and waking up (resuming) this fiber when it can proceed.
1980 *
1981 * For a Fiber to behave as non-blocking, it need to be created in Fiber.new with
1982 * <tt>blocking: false</tt> (which is the default), and Fiber.scheduler
1983 * should be set with Fiber.set_scheduler. If Fiber.scheduler is not set in
1984 * the current thread, blocking and non-blocking fibers' behavior is identical.
1985 *
1986 * Ruby doesn't provide a scheduler class: it is expected to be implemented by
1987 * the user and correspond to Fiber::Scheduler.
1988 *
1989 * There is also Fiber.schedule method, which is expected to immediately perform
1990 * the given block in a non-blocking manner. Its actual implementation is up to
1991 * the scheduler.
1992 *
1993 */
1994
1995static const rb_data_type_t fiber_data_type = {
1996 "fiber",
1997 {fiber_mark, fiber_free, fiber_memsize, fiber_compact,},
1998 0, 0, RUBY_TYPED_FREE_IMMEDIATELY
1999};
2000
2001static VALUE
2002fiber_alloc(VALUE klass)
2003{
2004 return TypedData_Wrap_Struct(klass, &fiber_data_type, 0);
2005}
2006
2007static rb_serial_t
2008next_fiber_serial(rb_ractor_t *cr)
2009{
2010 return cr->next_fiber_serial++;
2011}
2012
2013static rb_fiber_t*
2014fiber_t_alloc(VALUE fiber_value, unsigned int blocking)
2015{
2016 rb_fiber_t *fiber;
2017 rb_thread_t *th = GET_THREAD();
2018
2019 if (DATA_PTR(fiber_value) != 0) {
2020 rb_raise(rb_eRuntimeError, "cannot initialize twice");
2021 }
2022
2023 THREAD_MUST_BE_RUNNING(th);
2024 fiber = ZALLOC(rb_fiber_t);
2025 fiber->cont.self = fiber_value;
2026 fiber->cont.type = FIBER_CONTEXT;
2027 fiber->blocking = blocking;
2028 fiber->killed = 0;
2029 fiber->serial = next_fiber_serial(th->ractor);
2030 cont_init(&fiber->cont, th);
2031
2032 fiber->cont.saved_ec.fiber_ptr = fiber;
2033 rb_ec_clear_vm_stack(&fiber->cont.saved_ec);
2034
2035 fiber->prev = NULL;
2036
2037 /* fiber->status == 0 == CREATED
2038 * So that we don't need to set status: fiber_status_set(fiber, FIBER_CREATED); */
2039 VM_ASSERT(FIBER_CREATED_P(fiber));
2040
2041 DATA_PTR(fiber_value) = fiber;
2042
2043 return fiber;
2044}
2045
2046static rb_fiber_t *
2047root_fiber_alloc(rb_thread_t *th)
2048{
2049 VALUE fiber_value = fiber_alloc(rb_cFiber);
2050 rb_fiber_t *fiber = th->ec->fiber_ptr;
2051
2052 VM_ASSERT(DATA_PTR(fiber_value) == NULL);
2053 VM_ASSERT(fiber->cont.type == FIBER_CONTEXT);
2054 VM_ASSERT(FIBER_RESUMED_P(fiber));
2055
2056 th->root_fiber = fiber;
2057 DATA_PTR(fiber_value) = fiber;
2058 fiber->cont.self = fiber_value;
2059
2060 coroutine_initialize_main(&fiber->context);
2061
2062 return fiber;
2063}
2064
2065static inline rb_fiber_t*
2066fiber_current(void)
2067{
2068 rb_execution_context_t *ec = GET_EC();
2069 if (ec->fiber_ptr->cont.self == 0) {
2070 root_fiber_alloc(rb_ec_thread_ptr(ec));
2071 }
2072 return ec->fiber_ptr;
2073}
2074
2075static inline VALUE
2076current_fiber_storage(void)
2077{
2078 rb_execution_context_t *ec = GET_EC();
2079 return ec->storage;
2080}
2081
2082static inline VALUE
2083inherit_fiber_storage(void)
2084{
2085 return rb_obj_dup(current_fiber_storage());
2086}
2087
2088static inline void
2089fiber_storage_set(struct rb_fiber_struct *fiber, VALUE storage)
2090{
2091 fiber->cont.saved_ec.storage = storage;
2092}
2093
2094static inline VALUE
2095fiber_storage_get(rb_fiber_t *fiber, int allocate)
2096{
2097 VALUE storage = fiber->cont.saved_ec.storage;
2098 if (storage == Qnil && allocate) {
2099 storage = rb_hash_new();
2100 fiber_storage_set(fiber, storage);
2101 }
2102 return storage;
2103}
2104
2105static void
2106storage_access_must_be_from_same_fiber(VALUE self)
2107{
2108 rb_fiber_t *fiber = fiber_ptr(self);
2109 rb_fiber_t *current = fiber_current();
2110 if (fiber != current) {
2111 rb_raise(rb_eArgError, "Fiber storage can only be accessed from the Fiber it belongs to");
2112 }
2113}
2114
2121static VALUE
2122rb_fiber_storage_get(VALUE self)
2123{
2124 storage_access_must_be_from_same_fiber(self);
2125
2126 VALUE storage = fiber_storage_get(fiber_ptr(self), FALSE);
2127
2128 if (storage == Qnil) {
2129 return Qnil;
2130 }
2131 else {
2132 return rb_obj_dup(storage);
2133 }
2134}
2135
2136static int
2137fiber_storage_validate_each(VALUE key, VALUE value, VALUE _argument)
2138{
2139 Check_Type(key, T_SYMBOL);
2140
2141 return ST_CONTINUE;
2142}
2143
2144static void
2145fiber_storage_validate(VALUE value)
2146{
2147 // nil is an allowed value and will be lazily initialized.
2148 if (value == Qnil) return;
2149
2150 if (!RB_TYPE_P(value, T_HASH)) {
2151 rb_raise(rb_eTypeError, "storage must be a hash");
2152 }
2153
2154 if (RB_OBJ_FROZEN(value)) {
2155 rb_raise(rb_eFrozenError, "storage must not be frozen");
2156 }
2157
2158 rb_hash_foreach(value, fiber_storage_validate_each, Qundef);
2159}
2160
2183static VALUE
2184rb_fiber_storage_set(VALUE self, VALUE value)
2185{
2186 if (rb_warning_category_enabled_p(RB_WARN_CATEGORY_EXPERIMENTAL)) {
2188 "Fiber#storage= is experimental and may be removed in the future!");
2189 }
2190
2191 storage_access_must_be_from_same_fiber(self);
2192 fiber_storage_validate(value);
2193
2194 fiber_ptr(self)->cont.saved_ec.storage = rb_obj_dup(value);
2195 return value;
2196}
2197
2208static VALUE
2209rb_fiber_storage_aref(VALUE class, VALUE key)
2210{
2211 key = rb_to_symbol(key);
2212
2213 VALUE storage = fiber_storage_get(fiber_current(), FALSE);
2214 if (storage == Qnil) return Qnil;
2215
2216 return rb_hash_aref(storage, key);
2217}
2218
2229static VALUE
2230rb_fiber_storage_aset(VALUE class, VALUE key, VALUE value)
2231{
2232 key = rb_to_symbol(key);
2233
2234 VALUE storage = fiber_storage_get(fiber_current(), value != Qnil);
2235 if (storage == Qnil) return Qnil;
2236
2237 if (value == Qnil) {
2238 return rb_hash_delete(storage, key);
2239 }
2240 else {
2241 return rb_hash_aset(storage, key, value);
2242 }
2243}
2244
2245static VALUE
2246fiber_initialize(VALUE self, VALUE proc, struct fiber_pool * fiber_pool, unsigned int blocking, VALUE storage)
2247{
2248 if (storage == Qundef || storage == Qtrue) {
2249 // The default, inherit storage (dup) from the current fiber:
2250 storage = inherit_fiber_storage();
2251 }
2252 else /* nil, hash, etc. */ {
2253 fiber_storage_validate(storage);
2254 storage = rb_obj_dup(storage);
2255 }
2256
2257 rb_fiber_t *fiber = fiber_t_alloc(self, blocking);
2258
2259 fiber->cont.saved_ec.storage = storage;
2260 fiber->first_proc = proc;
2261 fiber->stack.base = NULL;
2262 fiber->stack.pool = fiber_pool;
2263
2264 return self;
2265}
2266
2267static void
2268fiber_prepare_stack(rb_fiber_t *fiber)
2269{
2270 rb_context_t *cont = &fiber->cont;
2271 rb_execution_context_t *sec = &cont->saved_ec;
2272
2273 size_t vm_stack_size = 0;
2274 VALUE *vm_stack = fiber_initialize_coroutine(fiber, &vm_stack_size);
2275
2276 /* initialize cont */
2277 cont->saved_vm_stack.ptr = NULL;
2278 rb_ec_initialize_vm_stack(sec, vm_stack, vm_stack_size / sizeof(VALUE));
2279
2280 sec->tag = NULL;
2281 sec->local_storage = NULL;
2282 sec->local_storage_recursive_hash = Qnil;
2283 sec->local_storage_recursive_hash_for_trace = Qnil;
2284}
2285
2286static struct fiber_pool *
2287rb_fiber_pool_default(VALUE pool)
2288{
2289 return &shared_fiber_pool;
2290}
2291
2292VALUE rb_fiber_inherit_storage(struct rb_execution_context_struct *ec, struct rb_fiber_struct *fiber)
2293{
2294 VALUE storage = rb_obj_dup(ec->storage);
2295 fiber->cont.saved_ec.storage = storage;
2296 return storage;
2297}
2298
2299/* :nodoc: */
2300static VALUE
2301rb_fiber_initialize_kw(int argc, VALUE* argv, VALUE self, int kw_splat)
2302{
2303 VALUE pool = Qnil;
2304 VALUE blocking = Qfalse;
2305 VALUE storage = Qundef;
2306
2307 if (kw_splat != RB_NO_KEYWORDS) {
2308 VALUE options = Qnil;
2309 VALUE arguments[3] = {Qundef};
2310
2311 argc = rb_scan_args_kw(kw_splat, argc, argv, ":", &options);
2312 rb_get_kwargs(options, fiber_initialize_keywords, 0, 3, arguments);
2313
2314 if (!UNDEF_P(arguments[0])) {
2315 blocking = arguments[0];
2316 }
2317
2318 if (!UNDEF_P(arguments[1])) {
2319 pool = arguments[1];
2320 }
2321
2322 storage = arguments[2];
2323 }
2324
2325 return fiber_initialize(self, rb_block_proc(), rb_fiber_pool_default(pool), RTEST(blocking), storage);
2326}
2327
2328/*
2329 * call-seq:
2330 * Fiber.new(blocking: false, storage: true) { |*args| ... } -> fiber
2331 *
2332 * Creates new Fiber. Initially, the fiber is not running and can be resumed
2333 * with #resume. Arguments to the first #resume call will be passed to the
2334 * block:
2335 *
2336 * f = Fiber.new do |initial|
2337 * current = initial
2338 * loop do
2339 * puts "current: #{current.inspect}"
2340 * current = Fiber.yield
2341 * end
2342 * end
2343 * f.resume(100) # prints: current: 100
2344 * f.resume(1, 2, 3) # prints: current: [1, 2, 3]
2345 * f.resume # prints: current: nil
2346 * # ... and so on ...
2347 *
2348 * If <tt>blocking: false</tt> is passed to <tt>Fiber.new</tt>, _and_ current
2349 * thread has a Fiber.scheduler defined, the Fiber becomes non-blocking (see
2350 * "Non-blocking Fibers" section in class docs).
2351 *
2352 * If the <tt>storage</tt> is unspecified, the default is to inherit a copy of
2353 * the storage from the current fiber. This is the same as specifying
2354 * <tt>storage: true</tt>.
2355 *
2356 * Fiber[:x] = 1
2357 * Fiber.new do
2358 * Fiber[:x] # => 1
2359 * Fiber[:x] = 2
2360 * end.resume
2361 * Fiber[:x] # => 1
2362 *
2363 * If the given <tt>storage</tt> is <tt>nil</tt>, this function will lazy
2364 * initialize the internal storage, which starts as an empty hash.
2365 *
2366 * Fiber[:x] = "Hello World"
2367 * Fiber.new(storage: nil) do
2368 * Fiber[:x] # nil
2369 * end
2370 *
2371 * Otherwise, the given <tt>storage</tt> is used as the new fiber's storage,
2372 * and it must be an instance of Hash.
2373 *
2374 * Explicitly using <tt>storage: true</tt> is currently experimental and may
2375 * change in the future.
2376 */
2377static VALUE
2378rb_fiber_initialize(int argc, VALUE* argv, VALUE self)
2379{
2380 return rb_fiber_initialize_kw(argc, argv, self, rb_keyword_given_p());
2381}
2382
2383VALUE
2384rb_fiber_new_storage(rb_block_call_func_t func, VALUE obj, VALUE storage)
2385{
2386 return fiber_initialize(fiber_alloc(rb_cFiber), rb_proc_new(func, obj), rb_fiber_pool_default(Qnil), 0, storage);
2387}
2388
2389VALUE
2390rb_fiber_new(rb_block_call_func_t func, VALUE obj)
2391{
2392 return rb_fiber_new_storage(func, obj, Qtrue);
2393}
2394
2395static VALUE
2396rb_fiber_s_schedule_kw(int argc, VALUE* argv, int kw_splat)
2397{
2398 rb_thread_t * th = GET_THREAD();
2399 VALUE scheduler = th->scheduler;
2400 VALUE fiber = Qnil;
2401
2402 if (scheduler != Qnil) {
2403 fiber = rb_fiber_scheduler_fiber(scheduler, argc, argv, kw_splat);
2404 }
2405 else {
2406 rb_raise(rb_eRuntimeError, "No scheduler is available!");
2407 }
2408
2409 return fiber;
2410}
2411
2412/*
2413 * call-seq:
2414 * Fiber.schedule { |*args| ... } -> fiber
2415 *
2416 * The method is <em>expected</em> to immediately run the provided block of code in a
2417 * separate non-blocking fiber.
2418 *
2419 * puts "Go to sleep!"
2420 *
2421 * Fiber.set_scheduler(MyScheduler.new)
2422 *
2423 * Fiber.schedule do
2424 * puts "Going to sleep"
2425 * sleep(1)
2426 * puts "I slept well"
2427 * end
2428 *
2429 * puts "Wakey-wakey, sleepyhead"
2430 *
2431 * Assuming MyScheduler is properly implemented, this program will produce:
2432 *
2433 * Go to sleep!
2434 * Going to sleep
2435 * Wakey-wakey, sleepyhead
2436 * ...1 sec pause here...
2437 * I slept well
2438 *
2439 * ...e.g. on the first blocking operation inside the Fiber (<tt>sleep(1)</tt>),
2440 * the control is yielded to the outside code (main fiber), and <em>at the end
2441 * of that execution</em>, the scheduler takes care of properly resuming all the
2442 * blocked fibers.
2443 *
2444 * Note that the behavior described above is how the method is <em>expected</em>
2445 * to behave, actual behavior is up to the current scheduler's implementation of
2446 * Fiber::Scheduler#fiber method. Ruby doesn't enforce this method to
2447 * behave in any particular way.
2448 *
2449 * If the scheduler is not set, the method raises
2450 * <tt>RuntimeError (No scheduler is available!)</tt>.
2451 *
2452 */
2453static VALUE
2454rb_fiber_s_schedule(int argc, VALUE *argv, VALUE obj)
2455{
2456 return rb_fiber_s_schedule_kw(argc, argv, rb_keyword_given_p());
2457}
2458
2459/*
2460 * call-seq:
2461 * Fiber.scheduler -> obj or nil
2462 *
2463 * Returns the Fiber scheduler, that was last set for the current thread with Fiber.set_scheduler.
2464 * Returns +nil+ if no scheduler is set (which is the default), and non-blocking fibers'
2465 * behavior is the same as blocking.
2466 * (see "Non-blocking fibers" section in class docs for details about the scheduler concept).
2467 *
2468 */
2469static VALUE
2470rb_fiber_s_scheduler(VALUE klass)
2471{
2472 return rb_fiber_scheduler_get();
2473}
2474
2475/*
2476 * call-seq:
2477 * Fiber.current_scheduler -> obj or nil
2478 *
2479 * Returns the Fiber scheduler, that was last set for the current thread with Fiber.set_scheduler
2480 * if and only if the current fiber is non-blocking.
2481 *
2482 */
2483static VALUE
2484rb_fiber_current_scheduler(VALUE klass)
2485{
2487}
2488
2489/*
2490 * call-seq:
2491 * Fiber.set_scheduler(scheduler) -> scheduler
2492 *
2493 * Sets the Fiber scheduler for the current thread. If the scheduler is set, non-blocking
2494 * fibers (created by Fiber.new with <tt>blocking: false</tt>, or by Fiber.schedule)
2495 * call that scheduler's hook methods on potentially blocking operations, and the current
2496 * thread will call scheduler's +close+ method on finalization (allowing the scheduler to
2497 * properly manage all non-finished fibers).
2498 *
2499 * +scheduler+ can be an object of any class corresponding to Fiber::Scheduler. Its
2500 * implementation is up to the user.
2501 *
2502 * See also the "Non-blocking fibers" section in class docs.
2503 *
2504 */
2505static VALUE
2506rb_fiber_set_scheduler(VALUE klass, VALUE scheduler)
2507{
2508 return rb_fiber_scheduler_set(scheduler);
2509}
2510
2511NORETURN(static void rb_fiber_terminate(rb_fiber_t *fiber, int need_interrupt, VALUE err));
2512
2513void
2514rb_fiber_start(rb_fiber_t *fiber)
2515{
2516 rb_thread_t * volatile th = fiber->cont.saved_ec.thread_ptr;
2517
2518 rb_proc_t *proc;
2519 enum ruby_tag_type state;
2520
2521 VM_ASSERT(th->ec == GET_EC());
2522 VM_ASSERT(FIBER_RESUMED_P(fiber));
2523
2524 if (fiber->blocking) {
2525 th->blocking += 1;
2526 }
2527
2528 EC_PUSH_TAG(th->ec);
2529 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
2530 rb_context_t *cont = &VAR_FROM_MEMORY(fiber)->cont;
2531 int argc;
2532 const VALUE *argv, args = cont->value;
2533 GetProcPtr(fiber->first_proc, proc);
2534 argv = (argc = cont->argc) > 1 ? RARRAY_CONST_PTR(args) : &args;
2535 cont->value = Qnil;
2536 th->ec->errinfo = Qnil;
2537 th->ec->root_lep = rb_vm_proc_local_ep(fiber->first_proc);
2538 th->ec->root_svar = Qfalse;
2539
2540 EXEC_EVENT_HOOK(th->ec, RUBY_EVENT_FIBER_SWITCH, th->self, 0, 0, 0, Qnil);
2541 cont->value = rb_vm_invoke_proc(th->ec, proc, argc, argv, cont->kw_splat, VM_BLOCK_HANDLER_NONE);
2542 }
2543 EC_POP_TAG();
2544
2545 int need_interrupt = TRUE;
2546 VALUE err = Qfalse;
2547 if (state) {
2548 err = th->ec->errinfo;
2549 VM_ASSERT(FIBER_RESUMED_P(fiber));
2550
2551 if (state == TAG_RAISE) {
2552 // noop...
2553 }
2554 else if (state == TAG_FATAL && err == RUBY_FATAL_FIBER_KILLED) {
2555 need_interrupt = FALSE;
2556 err = Qfalse;
2557 }
2558 else if (state == TAG_FATAL) {
2559 rb_threadptr_pending_interrupt_enque(th, err);
2560 }
2561 else {
2562 err = rb_vm_make_jump_tag_but_local_jump(state, err);
2563 }
2564 }
2565
2566 rb_fiber_terminate(fiber, need_interrupt, err);
2567}
2568
2569// Set up a "root fiber", which is the fiber that every Ractor has.
2570void
2571rb_threadptr_root_fiber_setup(rb_thread_t *th)
2572{
2573 rb_fiber_t *fiber = ruby_mimcalloc(1, sizeof(rb_fiber_t));
2574 if (!fiber) {
2575 rb_bug("%s", strerror(errno)); /* ... is it possible to call rb_bug here? */
2576 }
2577 fiber->cont.type = FIBER_CONTEXT;
2578 fiber->cont.saved_ec.fiber_ptr = fiber;
2579 fiber->cont.saved_ec.thread_ptr = th;
2580 fiber->blocking = 1;
2581 fiber->killed = 0;
2582 fiber->serial = next_fiber_serial(th->ractor);
2583 fiber_status_set(fiber, FIBER_RESUMED); /* skip CREATED */
2584 th->ec = &fiber->cont.saved_ec;
2585 cont_init_jit_cont(&fiber->cont);
2586}
2587
2588void
2589rb_threadptr_root_fiber_release(rb_thread_t *th)
2590{
2591 if (th->root_fiber) {
2592 /* ignore. A root fiber object will free th->ec */
2593 }
2594 else {
2595 rb_execution_context_t *ec = rb_current_execution_context(false);
2596
2597 VM_ASSERT(th->ec->fiber_ptr->cont.type == FIBER_CONTEXT);
2598 VM_ASSERT(th->ec->fiber_ptr->cont.self == 0);
2599
2600 if (ec && th->ec == ec) {
2601 rb_ractor_set_current_ec(th->ractor, NULL);
2602 }
2603 fiber_free(th->ec->fiber_ptr);
2604 th->ec = NULL;
2605 }
2606}
2607
2608void
2609rb_threadptr_root_fiber_terminate(rb_thread_t *th)
2610{
2611 rb_fiber_t *fiber = th->ec->fiber_ptr;
2612
2613 fiber->status = FIBER_TERMINATED;
2614
2615 // The vm_stack is `alloca`ed on the thread stack, so it's gone too:
2616 rb_ec_clear_vm_stack(th->ec);
2617}
2618
2619static inline rb_fiber_t*
2620return_fiber(bool terminate)
2621{
2622 rb_fiber_t *fiber = fiber_current();
2623 rb_fiber_t *prev = fiber->prev;
2624
2625 if (prev) {
2626 fiber->prev = NULL;
2627 prev->resuming_fiber = NULL;
2628 return prev;
2629 }
2630 else {
2631 if (!terminate) {
2632 rb_raise(rb_eFiberError, "attempt to yield on a not resumed fiber");
2633 }
2634
2635 rb_thread_t *th = GET_THREAD();
2636 rb_fiber_t *root_fiber = th->root_fiber;
2637
2638 VM_ASSERT(root_fiber != NULL);
2639
2640 // search resuming fiber
2641 for (fiber = root_fiber; fiber->resuming_fiber; fiber = fiber->resuming_fiber) {
2642 }
2643
2644 return fiber;
2645 }
2646}
2647
2648VALUE
2649rb_fiber_current(void)
2650{
2651 return fiber_current()->cont.self;
2652}
2653
2654// Prepare to execute next_fiber on the given thread.
2655static inline void
2656fiber_store(rb_fiber_t *next_fiber, rb_thread_t *th)
2657{
2658 rb_fiber_t *fiber;
2659
2660 if (th->ec->fiber_ptr != NULL) {
2661 fiber = th->ec->fiber_ptr;
2662 }
2663 else {
2664 /* create root fiber */
2665 fiber = root_fiber_alloc(th);
2666 }
2667
2668 if (FIBER_CREATED_P(next_fiber)) {
2669 fiber_prepare_stack(next_fiber);
2670 }
2671
2672 VM_ASSERT(FIBER_RESUMED_P(fiber) || FIBER_TERMINATED_P(fiber));
2673 VM_ASSERT(FIBER_RUNNABLE_P(next_fiber));
2674
2675 if (FIBER_RESUMED_P(fiber)) fiber_status_set(fiber, FIBER_SUSPENDED);
2676
2677 fiber_status_set(next_fiber, FIBER_RESUMED);
2678 fiber_setcontext(next_fiber, fiber);
2679}
2680
2681static void
2682fiber_check_killed(rb_fiber_t *fiber)
2683{
2684 VM_ASSERT(fiber == fiber_current());
2685
2686 if (fiber->killed) {
2687 rb_thread_t *thread = fiber->cont.saved_ec.thread_ptr;
2688
2689 thread->ec->errinfo = RUBY_FATAL_FIBER_KILLED;
2690 EC_JUMP_TAG(thread->ec, RUBY_TAG_FATAL);
2691 }
2692}
2693
2694static inline VALUE
2695fiber_switch(rb_fiber_t *fiber, int argc, const VALUE *argv, int kw_splat, rb_fiber_t *resuming_fiber, bool yielding)
2696{
2697 VALUE value;
2698 rb_context_t *cont = &fiber->cont;
2699 rb_thread_t *th = GET_THREAD();
2700
2701 /* make sure the root_fiber object is available */
2702 if (th->root_fiber == NULL) root_fiber_alloc(th);
2703
2704 if (th->ec->fiber_ptr == fiber) {
2705 /* ignore fiber context switch
2706 * because destination fiber is the same as current fiber
2707 */
2708 return make_passing_arg(argc, argv);
2709 }
2710
2711 if (cont_thread_value(cont) != th->self) {
2712 rb_raise(rb_eFiberError, "fiber called across threads");
2713 }
2714
2715 if (FIBER_TERMINATED_P(fiber)) {
2716 value = rb_exc_new2(rb_eFiberError, "dead fiber called");
2717
2718 if (!FIBER_TERMINATED_P(th->ec->fiber_ptr)) {
2719 rb_exc_raise(value);
2720 VM_UNREACHABLE(fiber_switch);
2721 }
2722 else {
2723 /* th->ec->fiber_ptr is also dead => switch to root fiber */
2724 /* (this means we're being called from rb_fiber_terminate, */
2725 /* and the terminated fiber's return_fiber() is already dead) */
2726 VM_ASSERT(FIBER_SUSPENDED_P(th->root_fiber));
2727
2728 cont = &th->root_fiber->cont;
2729 cont->argc = -1;
2730 cont->value = value;
2731
2732 fiber_setcontext(th->root_fiber, th->ec->fiber_ptr);
2733
2734 VM_UNREACHABLE(fiber_switch);
2735 }
2736 }
2737
2738 VM_ASSERT(FIBER_RUNNABLE_P(fiber));
2739
2740 rb_fiber_t *current_fiber = fiber_current();
2741
2742 VM_ASSERT(!current_fiber->resuming_fiber);
2743
2744 if (resuming_fiber) {
2745 current_fiber->resuming_fiber = resuming_fiber;
2746 fiber->prev = fiber_current();
2747 fiber->yielding = 0;
2748 }
2749
2750 VM_ASSERT(!current_fiber->yielding);
2751 if (yielding) {
2752 current_fiber->yielding = 1;
2753 }
2754
2755 if (current_fiber->blocking) {
2756 th->blocking -= 1;
2757 }
2758
2759 cont->argc = argc;
2760 cont->kw_splat = kw_splat;
2761 cont->value = make_passing_arg(argc, argv);
2762
2763 fiber_store(fiber, th);
2764
2765 // We cannot free the stack until the pthread is joined:
2766#ifndef COROUTINE_PTHREAD_CONTEXT
2767 if (resuming_fiber && FIBER_TERMINATED_P(fiber)) {
2768 RB_VM_LOCKING() {
2769 fiber_stack_release(fiber);
2770 }
2771 }
2772#endif
2773
2774 if (fiber_current()->blocking) {
2775 th->blocking += 1;
2776 }
2777
2778 RUBY_VM_CHECK_INTS(th->ec);
2779
2780 EXEC_EVENT_HOOK(th->ec, RUBY_EVENT_FIBER_SWITCH, th->self, 0, 0, 0, Qnil);
2781
2782 current_fiber = th->ec->fiber_ptr;
2783 value = current_fiber->cont.value;
2784
2785 fiber_check_killed(current_fiber);
2786
2787 if (current_fiber->cont.argc == -1) {
2788 // Fiber#raise will trigger this path.
2789 rb_exc_raise(value);
2790 }
2791
2792 return value;
2793}
2794
2795VALUE
2796rb_fiber_transfer(VALUE fiber_value, int argc, const VALUE *argv)
2797{
2798 return fiber_switch(fiber_ptr(fiber_value), argc, argv, RB_NO_KEYWORDS, NULL, false);
2799}
2800
2801/*
2802 * call-seq:
2803 * fiber.blocking? -> true or false
2804 *
2805 * Returns +true+ if +fiber+ is blocking and +false+ otherwise.
2806 * Fiber is non-blocking if it was created via passing <tt>blocking: false</tt>
2807 * to Fiber.new, or via Fiber.schedule.
2808 *
2809 * Note that, even if the method returns +false+, the fiber behaves differently
2810 * only if Fiber.scheduler is set in the current thread.
2811 *
2812 * See the "Non-blocking fibers" section in class docs for details.
2813 *
2814 */
2815VALUE
2816rb_fiber_blocking_p(VALUE fiber)
2817{
2818 return RBOOL(fiber_ptr(fiber)->blocking);
2819}
2820
2821static VALUE
2822fiber_blocking_yield(VALUE fiber_value)
2823{
2824 rb_fiber_t *fiber = fiber_ptr(fiber_value);
2825 rb_thread_t * volatile th = fiber->cont.saved_ec.thread_ptr;
2826
2827 VM_ASSERT(fiber->blocking == 0);
2828
2829 // fiber->blocking is `unsigned int : 1`, so we use it as a boolean:
2830 fiber->blocking = 1;
2831
2832 // Once the fiber is blocking, and current, we increment the thread blocking state:
2833 th->blocking += 1;
2834
2835 return rb_yield(fiber_value);
2836}
2837
2838static VALUE
2839fiber_blocking_ensure(VALUE fiber_value)
2840{
2841 rb_fiber_t *fiber = fiber_ptr(fiber_value);
2842 rb_thread_t * volatile th = fiber->cont.saved_ec.thread_ptr;
2843
2844 // We are no longer blocking:
2845 fiber->blocking = 0;
2846 th->blocking -= 1;
2847
2848 return Qnil;
2849}
2850
2851/*
2852 * call-seq:
2853 * Fiber.blocking{|fiber| ...} -> result
2854 *
2855 * Forces the fiber to be blocking for the duration of the block. Returns the
2856 * result of the block.
2857 *
2858 * See the "Non-blocking fibers" section in class docs for details.
2859 *
2860 */
2861VALUE
2862rb_fiber_blocking(VALUE class)
2863{
2864 VALUE fiber_value = rb_fiber_current();
2865 rb_fiber_t *fiber = fiber_ptr(fiber_value);
2866
2867 // If we are already blocking, this is essentially a no-op:
2868 if (fiber->blocking) {
2869 return rb_yield(fiber_value);
2870 }
2871 else {
2872 return rb_ensure(fiber_blocking_yield, fiber_value, fiber_blocking_ensure, fiber_value);
2873 }
2874}
2875
2876/*
2877 * call-seq:
2878 * Fiber.blocking? -> false or 1
2879 *
2880 * Returns +false+ if the current fiber is non-blocking.
2881 * Fiber is non-blocking if it was created via passing <tt>blocking: false</tt>
2882 * to Fiber.new, or via Fiber.schedule.
2883 *
2884 * If the current Fiber is blocking, the method returns 1.
2885 * Future developments may allow for situations where larger integers
2886 * could be returned.
2887 *
2888 * Note that, even if the method returns +false+, Fiber behaves differently
2889 * only if Fiber.scheduler is set in the current thread.
2890 *
2891 * See the "Non-blocking fibers" section in class docs for details.
2892 *
2893 */
2894static VALUE
2895rb_fiber_s_blocking_p(VALUE klass)
2896{
2897 rb_thread_t *thread = GET_THREAD();
2898 unsigned blocking = thread->blocking;
2899
2900 if (blocking == 0)
2901 return Qfalse;
2902
2903 return INT2NUM(blocking);
2904}
2905
2906void
2907rb_fiber_close(rb_fiber_t *fiber)
2908{
2909 fiber_status_set(fiber, FIBER_TERMINATED);
2910 rb_ec_close(&fiber->cont.saved_ec);
2911}
2912
2913static void
2914rb_fiber_terminate(rb_fiber_t *fiber, int need_interrupt, VALUE error)
2915{
2916 VALUE value = fiber->cont.value;
2917
2918 VM_ASSERT(FIBER_RESUMED_P(fiber));
2919 rb_fiber_close(fiber);
2920
2921 fiber->cont.machine.stack = NULL;
2922 fiber->cont.machine.stack_size = 0;
2923
2924 rb_fiber_t *next_fiber = return_fiber(true);
2925
2926 if (need_interrupt) RUBY_VM_SET_INTERRUPT(&next_fiber->cont.saved_ec);
2927
2928 if (RTEST(error))
2929 fiber_switch(next_fiber, -1, &error, RB_NO_KEYWORDS, NULL, false);
2930 else
2931 fiber_switch(next_fiber, 1, &value, RB_NO_KEYWORDS, NULL, false);
2932 ruby_stop(0);
2933}
2934
2935static VALUE
2936fiber_resume_kw(rb_fiber_t *fiber, int argc, const VALUE *argv, int kw_splat)
2937{
2938 rb_fiber_t *current_fiber = fiber_current();
2939
2940 if (argc == -1 && FIBER_CREATED_P(fiber)) {
2941 rb_raise(rb_eFiberError, "cannot raise exception on unborn fiber");
2942 }
2943 else if (FIBER_TERMINATED_P(fiber)) {
2944 rb_raise(rb_eFiberError, "attempt to resume a terminated fiber");
2945 }
2946 else if (fiber == current_fiber) {
2947 rb_raise(rb_eFiberError, "attempt to resume the current fiber");
2948 }
2949 else if (fiber->prev != NULL) {
2950 rb_raise(rb_eFiberError, "attempt to resume a resumed fiber (double resume)");
2951 }
2952 else if (fiber->resuming_fiber) {
2953 rb_raise(rb_eFiberError, "attempt to resume a resuming fiber");
2954 }
2955 else if (fiber->prev == NULL &&
2956 (!fiber->yielding && fiber->status != FIBER_CREATED)) {
2957 rb_raise(rb_eFiberError, "attempt to resume a transferring fiber");
2958 }
2959
2960 return fiber_switch(fiber, argc, argv, kw_splat, fiber, false);
2961}
2962
2963VALUE
2964rb_fiber_resume_kw(VALUE self, int argc, const VALUE *argv, int kw_splat)
2965{
2966 return fiber_resume_kw(fiber_ptr(self), argc, argv, kw_splat);
2967}
2968
2969VALUE
2970rb_fiber_resume(VALUE self, int argc, const VALUE *argv)
2971{
2972 return fiber_resume_kw(fiber_ptr(self), argc, argv, RB_NO_KEYWORDS);
2973}
2974
2975VALUE
2976rb_fiber_yield_kw(int argc, const VALUE *argv, int kw_splat)
2977{
2978 return fiber_switch(return_fiber(false), argc, argv, kw_splat, NULL, true);
2979}
2980
2981VALUE
2982rb_fiber_yield(int argc, const VALUE *argv)
2983{
2984 return fiber_switch(return_fiber(false), argc, argv, RB_NO_KEYWORDS, NULL, true);
2985}
2986
2987void
2988rb_fiber_reset_root_local_storage(rb_thread_t *th)
2989{
2990 if (th->root_fiber && th->root_fiber != th->ec->fiber_ptr) {
2991 th->ec->local_storage = th->root_fiber->cont.saved_ec.local_storage;
2992 }
2993}
2994
2995/*
2996 * call-seq:
2997 * fiber.alive? -> true or false
2998 *
2999 * Returns true if the fiber can still be resumed (or transferred
3000 * to). After finishing execution of the fiber block this method will
3001 * always return +false+.
3002 */
3003VALUE
3004rb_fiber_alive_p(VALUE fiber_value)
3005{
3006 return RBOOL(!FIBER_TERMINATED_P(fiber_ptr(fiber_value)));
3007}
3008
3009/*
3010 * call-seq:
3011 * fiber.resume(args, ...) -> obj
3012 *
3013 * Resumes the fiber from the point at which the last Fiber.yield was
3014 * called, or starts running it if it is the first call to
3015 * #resume. Arguments passed to resume will be the value of the
3016 * Fiber.yield expression or will be passed as block parameters to
3017 * the fiber's block if this is the first #resume.
3018 *
3019 * Alternatively, when resume is called it evaluates to the arguments passed
3020 * to the next Fiber.yield statement inside the fiber's block
3021 * or to the block value if it runs to completion without any
3022 * Fiber.yield
3023 */
3024static VALUE
3025rb_fiber_m_resume(int argc, VALUE *argv, VALUE fiber)
3026{
3027 return rb_fiber_resume_kw(fiber, argc, argv, rb_keyword_given_p());
3028}
3029
3030/*
3031 * call-seq:
3032 * fiber.backtrace -> array
3033 * fiber.backtrace(start) -> array
3034 * fiber.backtrace(start, count) -> array
3035 * fiber.backtrace(start..end) -> array
3036 *
3037 * Returns the current execution stack of the fiber. +start+, +count+ and +end+ allow
3038 * to select only parts of the backtrace.
3039 *
3040 * def level3
3041 * Fiber.yield
3042 * end
3043 *
3044 * def level2
3045 * level3
3046 * end
3047 *
3048 * def level1
3049 * level2
3050 * end
3051 *
3052 * f = Fiber.new { level1 }
3053 *
3054 * # It is empty before the fiber started
3055 * f.backtrace
3056 * #=> []
3057 *
3058 * f.resume
3059 *
3060 * f.backtrace
3061 * #=> ["test.rb:2:in `yield'", "test.rb:2:in `level3'", "test.rb:6:in `level2'", "test.rb:10:in `level1'", "test.rb:13:in `block in <main>'"]
3062 * p f.backtrace(1) # start from the item 1
3063 * #=> ["test.rb:2:in `level3'", "test.rb:6:in `level2'", "test.rb:10:in `level1'", "test.rb:13:in `block in <main>'"]
3064 * p f.backtrace(2, 2) # start from item 2, take 2
3065 * #=> ["test.rb:6:in `level2'", "test.rb:10:in `level1'"]
3066 * p f.backtrace(1..3) # take items from 1 to 3
3067 * #=> ["test.rb:2:in `level3'", "test.rb:6:in `level2'", "test.rb:10:in `level1'"]
3068 *
3069 * f.resume
3070 *
3071 * # It is nil after the fiber is finished
3072 * f.backtrace
3073 * #=> nil
3074 *
3075 */
3076static VALUE
3077rb_fiber_backtrace(int argc, VALUE *argv, VALUE fiber)
3078{
3079 return rb_vm_backtrace(argc, argv, &fiber_ptr(fiber)->cont.saved_ec);
3080}
3081
3082/*
3083 * call-seq:
3084 * fiber.backtrace_locations -> array
3085 * fiber.backtrace_locations(start) -> array
3086 * fiber.backtrace_locations(start, count) -> array
3087 * fiber.backtrace_locations(start..end) -> array
3088 *
3089 * Like #backtrace, but returns each line of the execution stack as a
3090 * Thread::Backtrace::Location. Accepts the same arguments as #backtrace.
3091 *
3092 * f = Fiber.new { Fiber.yield }
3093 * f.resume
3094 * loc = f.backtrace_locations.first
3095 * loc.label #=> "yield"
3096 * loc.path #=> "test.rb"
3097 * loc.lineno #=> 1
3098 *
3099 *
3100 */
3101static VALUE
3102rb_fiber_backtrace_locations(int argc, VALUE *argv, VALUE fiber)
3103{
3104 return rb_vm_backtrace_locations(argc, argv, &fiber_ptr(fiber)->cont.saved_ec);
3105}
3106
3107/*
3108 * call-seq:
3109 * fiber.transfer(args, ...) -> obj
3110 *
3111 * Transfer control to another fiber, resuming it from where it last
3112 * stopped or starting it if it was not resumed before. The calling
3113 * fiber will be suspended much like in a call to
3114 * Fiber.yield.
3115 *
3116 * The fiber which receives the transfer call treats it much like
3117 * a resume call. Arguments passed to transfer are treated like those
3118 * passed to resume.
3119 *
3120 * The two style of control passing to and from fiber (one is #resume and
3121 * Fiber::yield, another is #transfer to and from fiber) can't be freely
3122 * mixed.
3123 *
3124 * * If the Fiber's lifecycle had started with transfer, it will never
3125 * be able to yield or be resumed control passing, only
3126 * finish or transfer back. (It still can resume other fibers that
3127 * are allowed to be resumed.)
3128 * * If the Fiber's lifecycle had started with resume, it can yield
3129 * or transfer to another Fiber, but can receive control back only
3130 * the way compatible with the way it was given away: if it had
3131 * transferred, it only can be transferred back, and if it had
3132 * yielded, it only can be resumed back. After that, it again can
3133 * transfer or yield.
3134 *
3135 * If those rules are broken FiberError is raised.
3136 *
3137 * For an individual Fiber design, yield/resume is easier to use
3138 * (the Fiber just gives away control, it doesn't need to think
3139 * about who the control is given to), while transfer is more flexible
3140 * for complex cases, allowing to build arbitrary graphs of Fibers
3141 * dependent on each other.
3142 *
3143 *
3144 * Example:
3145 *
3146 * manager = nil # For local var to be visible inside worker block
3147 *
3148 * # This fiber would be started with transfer
3149 * # It can't yield, and can't be resumed
3150 * worker = Fiber.new { |work|
3151 * puts "Worker: starts"
3152 * puts "Worker: Performed #{work.inspect}, transferring back"
3153 * # Fiber.yield # this would raise FiberError: attempt to yield on a not resumed fiber
3154 * # manager.resume # this would raise FiberError: attempt to resume a resumed fiber (double resume)
3155 * manager.transfer(work.capitalize)
3156 * }
3157 *
3158 * # This fiber would be started with resume
3159 * # It can yield or transfer, and can be transferred
3160 * # back or resumed
3161 * manager = Fiber.new {
3162 * puts "Manager: starts"
3163 * puts "Manager: transferring 'something' to worker"
3164 * result = worker.transfer('something')
3165 * puts "Manager: worker returned #{result.inspect}"
3166 * # worker.resume # this would raise FiberError: attempt to resume a transferring fiber
3167 * Fiber.yield # this is OK, the fiber transferred from and to, now it can yield
3168 * puts "Manager: finished"
3169 * }
3170 *
3171 * puts "Starting the manager"
3172 * manager.resume
3173 * puts "Resuming the manager"
3174 * # manager.transfer # this would raise FiberError: attempt to transfer to a yielding fiber
3175 * manager.resume
3176 *
3177 * <em>produces</em>
3178 *
3179 * Starting the manager
3180 * Manager: starts
3181 * Manager: transferring 'something' to worker
3182 * Worker: starts
3183 * Worker: Performed "something", transferring back
3184 * Manager: worker returned "Something"
3185 * Resuming the manager
3186 * Manager: finished
3187 *
3188 */
3189static VALUE
3190rb_fiber_m_transfer(int argc, VALUE *argv, VALUE self)
3191{
3192 return rb_fiber_transfer_kw(self, argc, argv, rb_keyword_given_p());
3193}
3194
3195static VALUE
3196fiber_transfer_kw(rb_fiber_t *fiber, int argc, const VALUE *argv, int kw_splat)
3197{
3198 if (fiber->resuming_fiber) {
3199 rb_raise(rb_eFiberError, "attempt to transfer to a resuming fiber");
3200 }
3201
3202 if (fiber->yielding) {
3203 rb_raise(rb_eFiberError, "attempt to transfer to a yielding fiber");
3204 }
3205
3206 return fiber_switch(fiber, argc, argv, kw_splat, NULL, false);
3207}
3208
3209VALUE
3210rb_fiber_transfer_kw(VALUE self, int argc, const VALUE *argv, int kw_splat)
3211{
3212 return fiber_transfer_kw(fiber_ptr(self), argc, argv, kw_splat);
3213}
3214
3215/*
3216 * call-seq:
3217 * Fiber.yield(args, ...) -> obj
3218 *
3219 * Yields control back to the context that resumed the fiber, passing
3220 * along any arguments that were passed to it. The fiber will resume
3221 * processing at this point when #resume is called next.
3222 * Any arguments passed to the next #resume will be the value that
3223 * this Fiber.yield expression evaluates to.
3224 */
3225static VALUE
3226rb_fiber_s_yield(int argc, VALUE *argv, VALUE klass)
3227{
3228 return rb_fiber_yield_kw(argc, argv, rb_keyword_given_p());
3229}
3230
3231static VALUE
3232fiber_raise(rb_fiber_t *fiber, VALUE exception)
3233{
3234 if (fiber == fiber_current()) {
3235 rb_exc_raise(exception);
3236 }
3237 else if (fiber->resuming_fiber) {
3238 return fiber_raise(fiber->resuming_fiber, exception);
3239 }
3240 else if (FIBER_SUSPENDED_P(fiber) && !fiber->yielding) {
3241 return fiber_transfer_kw(fiber, -1, &exception, RB_NO_KEYWORDS);
3242 }
3243 else {
3244 return fiber_resume_kw(fiber, -1, &exception, RB_NO_KEYWORDS);
3245 }
3246}
3247
3248VALUE
3249rb_fiber_raise(VALUE fiber, int argc, VALUE *argv)
3250{
3251 VALUE exception = rb_exception_setup(argc, argv);
3252
3253 return fiber_raise(fiber_ptr(fiber), exception);
3254}
3255
3256/*
3257 * call-seq:
3258 * fiber.raise -> obj
3259 * fiber.raise(string) -> obj
3260 * fiber.raise(exception [, string [, array]]) -> obj
3261 *
3262 * Raises an exception in the fiber at the point at which the last
3263 * +Fiber.yield+ was called. If the fiber has not been started or has
3264 * already run to completion, raises +FiberError+. If the fiber is
3265 * yielding, it is resumed. If it is transferring, it is transferred into.
3266 * But if it is resuming, raises +FiberError+.
3267 *
3268 * With no arguments, raises a +RuntimeError+. With a single +String+
3269 * argument, raises a +RuntimeError+ with the string as a message. Otherwise,
3270 * the first parameter should be the name of an +Exception+ class (or an
3271 * object that returns an +Exception+ object when sent an +exception+
3272 * message). The optional second parameter sets the message associated with
3273 * the exception, and the third parameter is an array of callback information.
3274 * Exceptions are caught by the +rescue+ clause of <code>begin...end</code>
3275 * blocks.
3276 *
3277 * Raises +FiberError+ if called on a Fiber belonging to another +Thread+.
3278 *
3279 * See Kernel#raise for more information.
3280 */
3281static VALUE
3282rb_fiber_m_raise(int argc, VALUE *argv, VALUE self)
3283{
3284 return rb_fiber_raise(self, argc, argv);
3285}
3286
3287/*
3288 * call-seq:
3289 * fiber.kill -> nil
3290 *
3291 * Terminates the fiber by raising an uncatchable exception.
3292 * It only terminates the given fiber and no other fiber, returning +nil+ to
3293 * another fiber if that fiber was calling #resume or #transfer.
3294 *
3295 * <tt>Fiber#kill</tt> only interrupts another fiber when it is in Fiber.yield.
3296 * If called on the current fiber then it raises that exception at the <tt>Fiber#kill</tt> call site.
3297 *
3298 * If the fiber has not been started, transition directly to the terminated state.
3299 *
3300 * If the fiber is already terminated, does nothing.
3301 *
3302 * Raises FiberError if called on a fiber belonging to another thread.
3303 */
3304static VALUE
3305rb_fiber_m_kill(VALUE self)
3306{
3307 rb_fiber_t *fiber = fiber_ptr(self);
3308
3309 if (fiber->killed) return Qfalse;
3310 fiber->killed = 1;
3311
3312 if (fiber->status == FIBER_CREATED) {
3313 fiber->status = FIBER_TERMINATED;
3314 }
3315 else if (fiber->status != FIBER_TERMINATED) {
3316 if (fiber_current() == fiber) {
3317 fiber_check_killed(fiber);
3318 }
3319 else {
3320 fiber_raise(fiber_ptr(self), Qnil);
3321 }
3322 }
3323
3324 return self;
3325}
3326
3327/*
3328 * call-seq:
3329 * Fiber.current -> fiber
3330 *
3331 * Returns the current fiber. If you are not running in the context of
3332 * a fiber this method will return the root fiber.
3333 */
3334static VALUE
3335rb_fiber_s_current(VALUE klass)
3336{
3337 return rb_fiber_current();
3338}
3339
3340static VALUE
3341fiber_to_s(VALUE fiber_value)
3342{
3343 const rb_fiber_t *fiber = fiber_ptr(fiber_value);
3344 const rb_proc_t *proc;
3345 char status_info[0x20];
3346
3347 if (fiber->resuming_fiber) {
3348 snprintf(status_info, 0x20, " (%s by resuming)", fiber_status_name(fiber->status));
3349 }
3350 else {
3351 snprintf(status_info, 0x20, " (%s)", fiber_status_name(fiber->status));
3352 }
3353
3354 if (!rb_obj_is_proc(fiber->first_proc)) {
3355 VALUE str = rb_any_to_s(fiber_value);
3356 strlcat(status_info, ">", sizeof(status_info));
3357 rb_str_set_len(str, RSTRING_LEN(str)-1);
3358 rb_str_cat_cstr(str, status_info);
3359 return str;
3360 }
3361 GetProcPtr(fiber->first_proc, proc);
3362 return rb_block_to_s(fiber_value, &proc->block, status_info);
3363}
3364
3365#ifdef HAVE_WORKING_FORK
3366void
3367rb_fiber_atfork(rb_thread_t *th)
3368{
3369 if (th->root_fiber) {
3370 if (&th->root_fiber->cont.saved_ec != th->ec) {
3371 th->root_fiber = th->ec->fiber_ptr;
3372 }
3373 th->root_fiber->prev = 0;
3374 th->root_fiber->blocking = 1;
3375 th->blocking = 1;
3376 }
3377}
3378#endif
3379
3380#ifdef RB_EXPERIMENTAL_FIBER_POOL
3381static void
3382fiber_pool_free(void *ptr)
3383{
3384 struct fiber_pool * fiber_pool = ptr;
3385 RUBY_FREE_ENTER("fiber_pool");
3386
3387 fiber_pool_allocation_free(fiber_pool->allocations);
3388 ruby_xfree(fiber_pool);
3389
3390 RUBY_FREE_LEAVE("fiber_pool");
3391}
3392
3393static size_t
3394fiber_pool_memsize(const void *ptr)
3395{
3396 const struct fiber_pool * fiber_pool = ptr;
3397 size_t size = sizeof(*fiber_pool);
3398
3399 size += fiber_pool->count * fiber_pool->size;
3400
3401 return size;
3402}
3403
3404static const rb_data_type_t FiberPoolDataType = {
3405 "fiber_pool",
3406 {NULL, fiber_pool_free, fiber_pool_memsize,},
3407 0, 0, RUBY_TYPED_FREE_IMMEDIATELY
3408};
3409
3410static VALUE
3411fiber_pool_alloc(VALUE klass)
3412{
3413 struct fiber_pool *fiber_pool;
3414
3415 return TypedData_Make_Struct(klass, struct fiber_pool, &FiberPoolDataType, fiber_pool);
3416}
3417
3418static VALUE
3419rb_fiber_pool_initialize(int argc, VALUE* argv, VALUE self)
3420{
3421 rb_thread_t *th = GET_THREAD();
3422 VALUE size = Qnil, count = Qnil, vm_stack_size = Qnil;
3423 struct fiber_pool * fiber_pool = NULL;
3424
3425 // Maybe these should be keyword arguments.
3426 rb_scan_args(argc, argv, "03", &size, &count, &vm_stack_size);
3427
3428 if (NIL_P(size)) {
3429 size = SIZET2NUM(th->vm->default_params.fiber_machine_stack_size);
3430 }
3431
3432 if (NIL_P(count)) {
3433 count = INT2NUM(128);
3434 }
3435
3436 if (NIL_P(vm_stack_size)) {
3437 vm_stack_size = SIZET2NUM(th->vm->default_params.fiber_vm_stack_size);
3438 }
3439
3440 TypedData_Get_Struct(self, struct fiber_pool, &FiberPoolDataType, fiber_pool);
3441
3442 fiber_pool_initialize(fiber_pool, NUM2SIZET(size), NUM2SIZET(count), NUM2SIZET(vm_stack_size));
3443
3444 return self;
3445}
3446#endif
3447
3448/*
3449 * Document-class: FiberError
3450 *
3451 * Raised when an invalid operation is attempted on a Fiber, in
3452 * particular when attempting to call/resume a dead fiber,
3453 * attempting to yield from the root fiber, or calling a fiber across
3454 * threads.
3455 *
3456 * fiber = Fiber.new{}
3457 * fiber.resume #=> nil
3458 * fiber.resume #=> FiberError: dead fiber called
3459 */
3460
3461void
3462Init_Cont(void)
3463{
3464 rb_thread_t *th = GET_THREAD();
3465 size_t vm_stack_size = th->vm->default_params.fiber_vm_stack_size;
3466 size_t machine_stack_size = th->vm->default_params.fiber_machine_stack_size;
3467 size_t stack_size = machine_stack_size + vm_stack_size;
3468
3469#ifdef _WIN32
3470 SYSTEM_INFO info;
3471 GetSystemInfo(&info);
3472 pagesize = info.dwPageSize;
3473#else /* not WIN32 */
3474 pagesize = sysconf(_SC_PAGESIZE);
3475#endif
3476 SET_MACHINE_STACK_END(&th->ec->machine.stack_end);
3477
3478 fiber_pool_initialize(&shared_fiber_pool, stack_size, FIBER_POOL_INITIAL_SIZE, vm_stack_size);
3479
3480 fiber_initialize_keywords[0] = rb_intern_const("blocking");
3481 fiber_initialize_keywords[1] = rb_intern_const("pool");
3482 fiber_initialize_keywords[2] = rb_intern_const("storage");
3483
3484 const char *fiber_shared_fiber_pool_free_stacks = getenv("RUBY_SHARED_FIBER_POOL_FREE_STACKS");
3485 if (fiber_shared_fiber_pool_free_stacks) {
3486 shared_fiber_pool.free_stacks = atoi(fiber_shared_fiber_pool_free_stacks);
3487
3488 if (shared_fiber_pool.free_stacks < 0) {
3489 rb_warn("Setting RUBY_SHARED_FIBER_POOL_FREE_STACKS to a negative value is not allowed.");
3490 shared_fiber_pool.free_stacks = 0;
3491 }
3492
3493 if (shared_fiber_pool.free_stacks > 1) {
3494 rb_warn("Setting RUBY_SHARED_FIBER_POOL_FREE_STACKS to a value greater than 1 is operating system specific, and may cause crashes.");
3495 }
3496 }
3497
3498 rb_cFiber = rb_define_class("Fiber", rb_cObject);
3499 rb_define_alloc_func(rb_cFiber, fiber_alloc);
3500 rb_eFiberError = rb_define_class("FiberError", rb_eStandardError);
3501 rb_define_singleton_method(rb_cFiber, "yield", rb_fiber_s_yield, -1);
3502 rb_define_singleton_method(rb_cFiber, "current", rb_fiber_s_current, 0);
3503 rb_define_singleton_method(rb_cFiber, "blocking", rb_fiber_blocking, 0);
3504 rb_define_singleton_method(rb_cFiber, "[]", rb_fiber_storage_aref, 1);
3505 rb_define_singleton_method(rb_cFiber, "[]=", rb_fiber_storage_aset, 2);
3506
3507 rb_define_method(rb_cFiber, "initialize", rb_fiber_initialize, -1);
3508 rb_define_method(rb_cFiber, "blocking?", rb_fiber_blocking_p, 0);
3509 rb_define_method(rb_cFiber, "storage", rb_fiber_storage_get, 0);
3510 rb_define_method(rb_cFiber, "storage=", rb_fiber_storage_set, 1);
3511 rb_define_method(rb_cFiber, "resume", rb_fiber_m_resume, -1);
3512 rb_define_method(rb_cFiber, "raise", rb_fiber_m_raise, -1);
3513 rb_define_method(rb_cFiber, "kill", rb_fiber_m_kill, 0);
3514 rb_define_method(rb_cFiber, "backtrace", rb_fiber_backtrace, -1);
3515 rb_define_method(rb_cFiber, "backtrace_locations", rb_fiber_backtrace_locations, -1);
3516 rb_define_method(rb_cFiber, "to_s", fiber_to_s, 0);
3517 rb_define_alias(rb_cFiber, "inspect", "to_s");
3518 rb_define_method(rb_cFiber, "transfer", rb_fiber_m_transfer, -1);
3519 rb_define_method(rb_cFiber, "alive?", rb_fiber_alive_p, 0);
3520
3521 rb_define_singleton_method(rb_cFiber, "blocking?", rb_fiber_s_blocking_p, 0);
3522 rb_define_singleton_method(rb_cFiber, "scheduler", rb_fiber_s_scheduler, 0);
3523 rb_define_singleton_method(rb_cFiber, "set_scheduler", rb_fiber_set_scheduler, 1);
3524 rb_define_singleton_method(rb_cFiber, "current_scheduler", rb_fiber_current_scheduler, 0);
3525
3526 rb_define_singleton_method(rb_cFiber, "schedule", rb_fiber_s_schedule, -1);
3527
3528#ifdef RB_EXPERIMENTAL_FIBER_POOL
3529 /*
3530 * Document-class: Fiber::Pool
3531 * :nodoc: experimental
3532 */
3533 rb_cFiberPool = rb_define_class_under(rb_cFiber, "Pool", rb_cObject);
3534 rb_define_alloc_func(rb_cFiberPool, fiber_pool_alloc);
3535 rb_define_method(rb_cFiberPool, "initialize", rb_fiber_pool_initialize, -1);
3536#endif
3537
3538 rb_provide("fiber.so");
3539}
3540
3541RUBY_SYMBOL_EXPORT_BEGIN
3542
3543void
3544ruby_Init_Continuation_body(void)
3545{
3546 rb_cContinuation = rb_define_class("Continuation", rb_cObject);
3547 rb_undef_alloc_func(rb_cContinuation);
3548 rb_undef_method(CLASS_OF(rb_cContinuation), "new");
3549 rb_define_method(rb_cContinuation, "call", rb_cont_call, -1);
3550 rb_define_method(rb_cContinuation, "[]", rb_cont_call, -1);
3551 rb_define_global_function("callcc", rb_callcc, 0);
3552}
3553
3554RUBY_SYMBOL_EXPORT_END
#define rb_define_method(klass, mid, func, arity)
Defines klass#mid.
#define rb_define_singleton_method(klass, mid, func, arity)
Defines klass.mid.
#define rb_define_global_function(mid, func, arity)
Defines rb_mKernel #mid.
#define RUBY_EVENT_FIBER_SWITCH
Encountered a Fiber#yield.
Definition event.h:59
static bool RB_OBJ_FROZEN(VALUE obj)
Checks if an object is frozen.
Definition fl_type.h:892
VALUE rb_define_class(const char *name, VALUE super)
Defines a top-level class.
Definition class.c:1588
VALUE rb_define_class_under(VALUE outer, const char *name, VALUE super)
Defines a class under the namespace of outer.
Definition class.c:1619
void rb_define_alias(VALUE klass, const char *name1, const char *name2)
Defines an alias of a method.
Definition class.c:2947
void rb_undef_method(VALUE klass, const char *name)
Defines an undef of a method.
Definition class.c:2767
int rb_scan_args_kw(int kw_flag, int argc, const VALUE *argv, const char *fmt,...)
Identical to rb_scan_args(), except it also accepts kw_splat.
Definition class.c:3250
int rb_scan_args(int argc, const VALUE *argv, const char *fmt,...)
Retrieves argument from argc and argv to given VALUE references according to the format string.
Definition class.c:3237
int rb_keyword_given_p(void)
Determines if the current method is given a keyword argument.
Definition eval.c:1050
int rb_get_kwargs(VALUE keyword_hash, const ID *table, int required, int optional, VALUE *values)
Keyword argument deconstructor.
Definition class.c:3026
#define REALLOC_N
Old name of RB_REALLOC_N.
Definition memory.h:403
#define xfree
Old name of ruby_xfree.
Definition xmalloc.h:58
#define Qundef
Old name of RUBY_Qundef.
#define UNREACHABLE_RETURN
Old name of RBIMPL_UNREACHABLE_RETURN.
Definition assume.h:29
#define ZALLOC
Old name of RB_ZALLOC.
Definition memory.h:402
#define CLASS_OF
Old name of rb_class_of.
Definition globals.h:205
#define rb_ary_new4
Old name of rb_ary_new_from_values.
Definition array.h:659
#define SIZET2NUM
Old name of RB_SIZE2NUM.
Definition size_t.h:62
#define rb_exc_new2
Old name of rb_exc_new_cstr.
Definition error.h:37
#define T_HASH
Old name of RUBY_T_HASH.
Definition value_type.h:65
#define ALLOC_N
Old name of RB_ALLOC_N.
Definition memory.h:399
#define Qtrue
Old name of RUBY_Qtrue.
#define INT2NUM
Old name of RB_INT2NUM.
Definition int.h:43
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#define NIL_P
Old name of RB_NIL_P.
#define T_SYMBOL
Old name of RUBY_T_SYMBOL.
Definition value_type.h:80
#define NUM2SIZET
Old name of RB_NUM2SIZE.
Definition size_t.h:61
void ruby_stop(int ex)
Calls ruby_cleanup() and exits the process.
Definition eval.c:290
void rb_category_warn(rb_warning_category_t category, const char *fmt,...)
Identical to rb_category_warning(), except it reports unless $VERBOSE is nil.
Definition error.c:476
void rb_exc_raise(VALUE mesg)
Raises an exception in the current thread.
Definition eval.c:683
int rb_typeddata_is_kind_of(VALUE obj, const rb_data_type_t *data_type)
Checks if the given object is of given kind.
Definition error.c:1381
void rb_syserr_fail(int e, const char *mesg)
Raises appropriate exception that represents a C errno.
Definition error.c:3909
VALUE rb_eStandardError
StandardError exception.
Definition error.c:1428
VALUE rb_eFrozenError
FrozenError exception.
Definition error.c:1430
VALUE rb_eTypeError
TypeError exception.
Definition error.c:1431
VALUE rb_eRuntimeError
RuntimeError exception.
Definition error.c:1429
void rb_warn(const char *fmt,...)
Identical to rb_warning(), except it reports unless $VERBOSE is nil.
Definition error.c:466
@ RB_WARN_CATEGORY_EXPERIMENTAL
Warning is for experimental features.
Definition error.h:51
VALUE rb_any_to_s(VALUE obj)
Generates a textual representation of the given object.
Definition object.c:675
VALUE rb_obj_dup(VALUE obj)
Duplicates the given object.
Definition object.c:582
void rb_provide(const char *feature)
Declares that the given feature is already provided by someone else.
Definition load.c:705
VALUE rb_block_proc(void)
Constructs a Proc object from implicitly passed components.
Definition proc.c:847
VALUE rb_obj_is_proc(VALUE recv)
Queries if the given object is a proc.
Definition proc.c:120
void rb_str_set_len(VALUE str, long len)
Overwrites the length of the string.
Definition string.c:3385
#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:1655
void rb_undef_alloc_func(VALUE klass)
Deletes the allocator function of a class.
Definition vm_method.c:1624
void rb_define_alloc_func(VALUE klass, rb_alloc_func_t func)
Sets the allocator function of a class.
static ID rb_intern_const(const char *str)
This is a "tiny optimisation" over rb_intern().
Definition symbol.h:284
VALUE rb_to_symbol(VALUE name)
Identical to rb_intern_str(), except it generates a dynamic symbol if necessary.
Definition string.c:12504
VALUE rb_yield(VALUE val)
Yields the block.
Definition vm_eval.c:1372
rb_block_call_func * rb_block_call_func_t
Shorthand type that represents an iterator-written-in-C function pointer.
Definition iterator.h:88
#define MEMCPY(p1, p2, type, n)
Handy macro to call memcpy.
Definition memory.h:372
#define ALLOCA_N(type, n)
Definition memory.h:292
#define RB_ALLOC(type)
Shorthand of RB_ALLOC_N with n=1.
Definition memory.h:213
VALUE rb_proc_new(type *q, VALUE w)
Creates a rb_cProc 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 RARRAY_CONST_PTR
Just another name of rb_array_const_ptr.
Definition rarray.h:52
#define DATA_PTR(obj)
Convenient getter macro.
Definition rdata.h:67
#define TypedData_Get_Struct(obj, type, data_type, sval)
Obtains a C struct from inside of a wrapper Ruby object.
Definition rtypeddata.h:639
#define TypedData_Wrap_Struct(klass, data_type, sval)
Converts sval, a pointer to your struct, into a Ruby object.
Definition rtypeddata.h:461
#define TypedData_Make_Struct(klass, type, data_type, sval)
Identical to TypedData_Wrap_Struct, except it allocates a new data region internally instead of takin...
Definition rtypeddata.h:508
#define errno
Ractor-aware version of errno.
Definition ruby.h:388
#define RB_NO_KEYWORDS
Do not pass keywords.
Definition scan_args.h:69
Scheduler APIs.
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:466
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:428
VALUE rb_fiber_scheduler_get(void)
Queries the current scheduler of the current thread that is calling this function.
Definition scheduler.c:378
VALUE rb_fiber_scheduler_fiber(VALUE scheduler, int argc, VALUE *argv, int kw_splat)
Create and schedule a non-blocking fiber.
Definition scheduler.c:1163
#define RTEST
This is an old name of RB_TEST.
This is the struct that holds necessary info for a struct.
Definition rtypeddata.h:208
void rb_native_mutex_lock(rb_nativethread_lock_t *lock)
Just another name of rb_nativethread_lock_lock.
void rb_native_mutex_initialize(rb_nativethread_lock_t *lock)
Just another name of rb_nativethread_lock_initialize.
void rb_native_mutex_unlock(rb_nativethread_lock_t *lock)
Just another name of rb_nativethread_lock_unlock.
void rb_native_mutex_destroy(rb_nativethread_lock_t *lock)
Just another name of rb_nativethread_lock_destroy.
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 void Check_Type(VALUE v, enum ruby_value_type t)
Identical to RB_TYPE_P(), except it raises exceptions on predication failure.
Definition value_type.h:433
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