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