Tempfile document updated.
[ruby.git] / cont.c
blob8f222dfef8bc9562967ea603005c441f1d7573e5
1 /**********************************************************************
3 cont.c -
5 $Author$
6 created at: Thu May 23 09:03:43 2007
8 Copyright (C) 2007 Koichi Sasada
10 **********************************************************************/
12 #include "ruby/internal/config.h"
14 #ifndef _WIN32
15 #include <unistd.h>
16 #include <sys/mman.h>
17 #endif
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>
23 extern int madvise(caddr_t, size_t, int);
24 #endif
26 #include COROUTINE_H
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"
37 #include "ruby/fiber/scheduler.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"
45 static const int DEBUG = 0;
47 #define RB_PAGE_SIZE (pagesize)
48 #define RB_PAGE_MASK (~(RB_PAGE_SIZE - 1))
49 static long pagesize;
51 static const rb_data_type_t cont_data_type, fiber_data_type;
52 static VALUE rb_cContinuation;
53 static VALUE rb_cFiber;
54 static VALUE rb_eFiberError;
55 #ifdef RB_EXPERIMENTAL_FIBER_POOL
56 static VALUE rb_cFiberPool;
57 #endif
59 #define CAPTURE_JUST_VALID_VM_STACK 1
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
74 enum context_type {
75 CONTINUATION_CONTEXT = 0,
76 FIBER_CONTEXT = 1
79 struct cont_saved_vm_stack {
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
87 struct fiber_pool;
89 // Represents a single stack.
90 struct fiber_pool_stack {
91 // A pointer to the memory allocation (lowest address) for the stack.
92 void * base;
94 // The current stack pointer, taking into account the direction of the stack.
95 void * current;
97 // The size of the stack excluding any guard pages.
98 size_t size;
100 // The available stack capacity w.r.t. the current stack offset.
101 size_t available;
103 // The pool this stack should be allocated from.
104 struct fiber_pool * pool;
106 // If the stack is allocated, the allocation it came from.
107 struct fiber_pool_allocation * allocation;
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
113 struct fiber_pool_vacancy {
114 // Details about the vacant stack:
115 struct fiber_pool_stack stack;
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;
124 // Manages singly linked list of mapped regions of memory which contains 1 more more stack:
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
144 // +------------------------------------------------------->
146 // count
148 struct fiber_pool_allocation {
149 // A pointer to the memory mapped region.
150 void * base;
152 // The size of the individual stacks.
153 size_t size;
155 // The stride of individual stacks (including any guard pages or other accounting details).
156 size_t stride;
158 // The number of stacks that were allocated.
159 size_t count;
161 #ifdef FIBER_POOL_ALLOCATION_FREE
162 // The number of stacks used in this allocation.
163 size_t used;
164 #endif
166 struct fiber_pool * pool;
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;
175 // A fiber pool manages vacant stacks to reduce the overhead of creating fibers.
176 struct fiber_pool {
177 // A singly-linked list of allocations which contain 1 or more stacks each.
178 struct fiber_pool_allocation * allocations;
180 // Free list that provides O(1) stack "allocation".
181 struct fiber_pool_vacancy * vacancies;
183 // The size of the stack allocations (excluding any guard page).
184 size_t size;
186 // The total number of stacks that have been allocated in this pool.
187 size_t count;
189 // The initial number of stacks to allocate.
190 size_t initial_count;
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;
197 // The number of stacks that have been used in this pool.
198 size_t used;
200 // The amount to allocate for the vm_stack.
201 size_t vm_stack_size;
204 // Continuation contexts used by JITs
205 struct rb_jit_cont {
206 rb_execution_context_t *ec; // continuation ec
207 struct rb_jit_cont *prev, *next; // used to form lists
210 // Doubly linked list for enumerating all on-stack ISEQs.
211 static struct rb_jit_cont *first_jit_cont;
213 typedef struct rb_context_struct {
214 enum context_type type;
215 int argc;
216 int kw_splat;
217 VALUE self;
218 VALUE value;
220 struct cont_saved_vm_stack saved_vm_stack;
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 rb_ensure_entry_t *ensure_array;
230 struct rb_jit_cont *jit_cont; // Continuation contexts for JITs
231 } rb_context_t;
234 * Fiber status:
235 * [Fiber.new] ------> FIBER_CREATED ----> [Fiber#kill] --> |
236 * | [Fiber#resume] |
237 * v |
238 * +--> FIBER_RESUMED ----> [return] ------> |
239 * [Fiber#resume] | | [Fiber.yield/transfer] |
240 * [Fiber#transfer] | v |
241 * +--- FIBER_SUSPENDED --> [Fiber#kill] --> |
244 * FIBER_TERMINATED <-------------------+
246 enum fiber_status {
247 FIBER_CREATED,
248 FIBER_RESUMED,
249 FIBER_SUSPENDED,
250 FIBER_TERMINATED
253 #define FIBER_CREATED_P(fiber) ((fiber)->status == FIBER_CREATED)
254 #define FIBER_RESUMED_P(fiber) ((fiber)->status == FIBER_RESUMED)
255 #define FIBER_SUSPENDED_P(fiber) ((fiber)->status == FIBER_SUSPENDED)
256 #define FIBER_TERMINATED_P(fiber) ((fiber)->status == FIBER_TERMINATED)
257 #define FIBER_RUNNABLE_P(fiber) (FIBER_CREATED_P(fiber) || FIBER_SUSPENDED_P(fiber))
259 struct rb_fiber_struct {
260 rb_context_t cont;
261 VALUE first_proc;
262 struct rb_fiber_struct *prev;
263 struct rb_fiber_struct *resuming_fiber;
265 BITFIELD(enum fiber_status, status, 2);
266 /* Whether the fiber is allowed to implicitly yield. */
267 unsigned int yielding : 1;
268 unsigned int blocking : 1;
270 unsigned int killed : 1;
272 struct coroutine_context context;
273 struct fiber_pool_stack stack;
276 static struct fiber_pool shared_fiber_pool = {NULL, NULL, 0, 0, 0, 0};
278 void
279 rb_free_shared_fiber_pool(void)
281 xfree(shared_fiber_pool.allocations);
284 static ID fiber_initialize_keywords[3] = {0};
287 * FreeBSD require a first (i.e. addr) argument of mmap(2) is not NULL
288 * if MAP_STACK is passed.
289 * https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=158755
291 #if defined(MAP_STACK) && !defined(__FreeBSD__) && !defined(__FreeBSD_kernel__)
292 #define FIBER_STACK_FLAGS (MAP_PRIVATE | MAP_ANON | MAP_STACK)
293 #else
294 #define FIBER_STACK_FLAGS (MAP_PRIVATE | MAP_ANON)
295 #endif
297 #define ERRNOMSG strerror(errno)
299 // Locates the stack vacancy details for the given stack.
300 inline static struct fiber_pool_vacancy *
301 fiber_pool_vacancy_pointer(void * base, size_t size)
303 STACK_GROW_DIR_DETECTION;
305 return (struct fiber_pool_vacancy *)(
306 (char*)base + STACK_DIR_UPPER(0, size - RB_PAGE_SIZE)
310 #if defined(COROUTINE_SANITIZE_ADDRESS)
311 // Compute the base pointer for a vacant stack, for the area which can be poisoned.
312 inline static void *
313 fiber_pool_stack_poison_base(struct fiber_pool_stack * stack)
315 STACK_GROW_DIR_DETECTION;
317 return (char*)stack->base + STACK_DIR_UPPER(RB_PAGE_SIZE, 0);
320 // Compute the size of the vacant stack, for the area that can be poisoned.
321 inline static size_t
322 fiber_pool_stack_poison_size(struct fiber_pool_stack * stack)
324 return stack->size - RB_PAGE_SIZE;
326 #endif
328 // Reset the current stack pointer and available size of the given stack.
329 inline static void
330 fiber_pool_stack_reset(struct fiber_pool_stack * stack)
332 STACK_GROW_DIR_DETECTION;
334 stack->current = (char*)stack->base + STACK_DIR_UPPER(0, stack->size);
335 stack->available = stack->size;
338 // A pointer to the base of the current unused portion of the stack.
339 inline static void *
340 fiber_pool_stack_base(struct fiber_pool_stack * stack)
342 STACK_GROW_DIR_DETECTION;
344 VM_ASSERT(stack->current);
346 return STACK_DIR_UPPER(stack->current, (char*)stack->current - stack->available);
349 // Allocate some memory from the stack. Used to allocate vm_stack inline with machine stack.
350 // @sa fiber_initialize_coroutine
351 inline static void *
352 fiber_pool_stack_alloca(struct fiber_pool_stack * stack, size_t offset)
354 STACK_GROW_DIR_DETECTION;
356 if (DEBUG) fprintf(stderr, "fiber_pool_stack_alloca(%p): %"PRIuSIZE"/%"PRIuSIZE"\n", (void*)stack, offset, stack->available);
357 VM_ASSERT(stack->available >= offset);
359 // The pointer to the memory being allocated:
360 void * pointer = STACK_DIR_UPPER(stack->current, (char*)stack->current - offset);
362 // Move the stack pointer:
363 stack->current = STACK_DIR_UPPER((char*)stack->current + offset, (char*)stack->current - offset);
364 stack->available -= offset;
366 return pointer;
369 // Reset the current stack pointer and available size of the given stack.
370 inline static void
371 fiber_pool_vacancy_reset(struct fiber_pool_vacancy * vacancy)
373 fiber_pool_stack_reset(&vacancy->stack);
375 // Consume one page of the stack because it's used for the vacancy list:
376 fiber_pool_stack_alloca(&vacancy->stack, RB_PAGE_SIZE);
379 inline static struct fiber_pool_vacancy *
380 fiber_pool_vacancy_push(struct fiber_pool_vacancy * vacancy, struct fiber_pool_vacancy * head)
382 vacancy->next = head;
384 #ifdef FIBER_POOL_ALLOCATION_FREE
385 if (head) {
386 head->previous = vacancy;
387 vacancy->previous = NULL;
389 #endif
391 return vacancy;
394 #ifdef FIBER_POOL_ALLOCATION_FREE
395 static void
396 fiber_pool_vacancy_remove(struct fiber_pool_vacancy * vacancy)
398 if (vacancy->next) {
399 vacancy->next->previous = vacancy->previous;
402 if (vacancy->previous) {
403 vacancy->previous->next = vacancy->next;
405 else {
406 // It's the head of the list:
407 vacancy->stack.pool->vacancies = vacancy->next;
411 inline static struct fiber_pool_vacancy *
412 fiber_pool_vacancy_pop(struct fiber_pool * pool)
414 struct fiber_pool_vacancy * vacancy = pool->vacancies;
416 if (vacancy) {
417 fiber_pool_vacancy_remove(vacancy);
420 return vacancy;
422 #else
423 inline static struct fiber_pool_vacancy *
424 fiber_pool_vacancy_pop(struct fiber_pool * pool)
426 struct fiber_pool_vacancy * vacancy = pool->vacancies;
428 if (vacancy) {
429 pool->vacancies = vacancy->next;
432 return vacancy;
434 #endif
436 // Initialize the vacant stack. The [base, size] allocation should not include the guard page.
437 // @param base The pointer to the lowest address of the allocated memory.
438 // @param size The size of the allocated memory.
439 inline static struct fiber_pool_vacancy *
440 fiber_pool_vacancy_initialize(struct fiber_pool * fiber_pool, struct fiber_pool_vacancy * vacancies, void * base, size_t size)
442 struct fiber_pool_vacancy * vacancy = fiber_pool_vacancy_pointer(base, size);
444 vacancy->stack.base = base;
445 vacancy->stack.size = size;
447 fiber_pool_vacancy_reset(vacancy);
449 vacancy->stack.pool = fiber_pool;
451 return fiber_pool_vacancy_push(vacancy, vacancies);
454 // Allocate a maximum of count stacks, size given by stride.
455 // @param count the number of stacks to allocate / were allocated.
456 // @param stride the size of the individual stacks.
457 // @return [void *] the allocated memory or NULL if allocation failed.
458 inline static void *
459 fiber_pool_allocate_memory(size_t * count, size_t stride)
461 // We use a divide-by-2 strategy to try and allocate memory. We are trying
462 // to allocate `count` stacks. In normal situation, this won't fail. But
463 // if we ran out of address space, or we are allocating more memory than
464 // the system would allow (e.g. overcommit * physical memory + swap), we
465 // divide count by two and try again. This condition should only be
466 // encountered in edge cases, but we handle it here gracefully.
467 while (*count > 1) {
468 #if defined(_WIN32)
469 void * base = VirtualAlloc(0, (*count)*stride, MEM_COMMIT, PAGE_READWRITE);
471 if (!base) {
472 *count = (*count) >> 1;
474 else {
475 return base;
477 #else
478 errno = 0;
479 void * base = mmap(NULL, (*count)*stride, PROT_READ | PROT_WRITE, FIBER_STACK_FLAGS, -1, 0);
481 if (base == MAP_FAILED) {
482 // If the allocation fails, count = count / 2, and try again.
483 *count = (*count) >> 1;
485 else {
486 #if defined(MADV_FREE_REUSE)
487 // On Mac MADV_FREE_REUSE is necessary for the task_info api
488 // to keep the accounting accurate as possible when a page is marked as reusable
489 // it can possibly not occurring at first call thus re-iterating if necessary.
490 while (madvise(base, (*count)*stride, MADV_FREE_REUSE) == -1 && errno == EAGAIN);
491 #endif
492 return base;
494 #endif
497 return NULL;
500 // Given an existing fiber pool, expand it by the specified number of stacks.
501 // @param count the maximum number of stacks to allocate.
502 // @return the allocated fiber pool.
503 // @sa fiber_pool_allocation_free
504 static struct fiber_pool_allocation *
505 fiber_pool_expand(struct fiber_pool * fiber_pool, size_t count)
507 STACK_GROW_DIR_DETECTION;
509 size_t size = fiber_pool->size;
510 size_t stride = size + RB_PAGE_SIZE;
512 // Allocate the memory required for the stacks:
513 void * base = fiber_pool_allocate_memory(&count, stride);
515 if (base == NULL) {
516 rb_raise(rb_eFiberError, "can't alloc machine stack to fiber (%"PRIuSIZE" x %"PRIuSIZE" bytes): %s", count, size, ERRNOMSG);
519 struct fiber_pool_vacancy * vacancies = fiber_pool->vacancies;
520 struct fiber_pool_allocation * allocation = RB_ALLOC(struct fiber_pool_allocation);
522 // Initialize fiber pool allocation:
523 allocation->base = base;
524 allocation->size = size;
525 allocation->stride = stride;
526 allocation->count = count;
527 #ifdef FIBER_POOL_ALLOCATION_FREE
528 allocation->used = 0;
529 #endif
530 allocation->pool = fiber_pool;
532 if (DEBUG) {
533 fprintf(stderr, "fiber_pool_expand(%"PRIuSIZE"): %p, %"PRIuSIZE"/%"PRIuSIZE" x [%"PRIuSIZE":%"PRIuSIZE"]\n",
534 count, (void*)fiber_pool, fiber_pool->used, fiber_pool->count, size, fiber_pool->vm_stack_size);
537 // Iterate over all stacks, initializing the vacancy list:
538 for (size_t i = 0; i < count; i += 1) {
539 void * base = (char*)allocation->base + (stride * i);
540 void * page = (char*)base + STACK_DIR_UPPER(size, 0);
542 #if defined(_WIN32)
543 DWORD old_protect;
545 if (!VirtualProtect(page, RB_PAGE_SIZE, PAGE_READWRITE | PAGE_GUARD, &old_protect)) {
546 VirtualFree(allocation->base, 0, MEM_RELEASE);
547 rb_raise(rb_eFiberError, "can't set a guard page: %s", ERRNOMSG);
549 #else
550 if (mprotect(page, RB_PAGE_SIZE, PROT_NONE) < 0) {
551 munmap(allocation->base, count*stride);
552 rb_raise(rb_eFiberError, "can't set a guard page: %s", ERRNOMSG);
554 #endif
556 vacancies = fiber_pool_vacancy_initialize(
557 fiber_pool, vacancies,
558 (char*)base + STACK_DIR_UPPER(0, RB_PAGE_SIZE),
559 size
562 #ifdef FIBER_POOL_ALLOCATION_FREE
563 vacancies->stack.allocation = allocation;
564 #endif
567 // Insert the allocation into the head of the pool:
568 allocation->next = fiber_pool->allocations;
570 #ifdef FIBER_POOL_ALLOCATION_FREE
571 if (allocation->next) {
572 allocation->next->previous = allocation;
575 allocation->previous = NULL;
576 #endif
578 fiber_pool->allocations = allocation;
579 fiber_pool->vacancies = vacancies;
580 fiber_pool->count += count;
582 return allocation;
585 // Initialize the specified fiber pool with the given number of stacks.
586 // @param vm_stack_size The size of the vm stack to allocate.
587 static void
588 fiber_pool_initialize(struct fiber_pool * fiber_pool, size_t size, size_t count, size_t vm_stack_size)
590 VM_ASSERT(vm_stack_size < size);
592 fiber_pool->allocations = NULL;
593 fiber_pool->vacancies = NULL;
594 fiber_pool->size = ((size / RB_PAGE_SIZE) + 1) * RB_PAGE_SIZE;
595 fiber_pool->count = 0;
596 fiber_pool->initial_count = count;
597 fiber_pool->free_stacks = 1;
598 fiber_pool->used = 0;
600 fiber_pool->vm_stack_size = vm_stack_size;
602 fiber_pool_expand(fiber_pool, count);
605 #ifdef FIBER_POOL_ALLOCATION_FREE
606 // Free the list of fiber pool allocations.
607 static void
608 fiber_pool_allocation_free(struct fiber_pool_allocation * allocation)
610 STACK_GROW_DIR_DETECTION;
612 VM_ASSERT(allocation->used == 0);
614 if (DEBUG) fprintf(stderr, "fiber_pool_allocation_free: %p base=%p count=%"PRIuSIZE"\n", (void*)allocation, allocation->base, allocation->count);
616 size_t i;
617 for (i = 0; i < allocation->count; i += 1) {
618 void * base = (char*)allocation->base + (allocation->stride * i) + STACK_DIR_UPPER(0, RB_PAGE_SIZE);
620 struct fiber_pool_vacancy * vacancy = fiber_pool_vacancy_pointer(base, allocation->size);
622 // Pop the vacant stack off the free list:
623 fiber_pool_vacancy_remove(vacancy);
626 #ifdef _WIN32
627 VirtualFree(allocation->base, 0, MEM_RELEASE);
628 #else
629 munmap(allocation->base, allocation->stride * allocation->count);
630 #endif
632 if (allocation->previous) {
633 allocation->previous->next = allocation->next;
635 else {
636 // We are the head of the list, so update the pool:
637 allocation->pool->allocations = allocation->next;
640 if (allocation->next) {
641 allocation->next->previous = allocation->previous;
644 allocation->pool->count -= allocation->count;
646 ruby_xfree(allocation);
648 #endif
650 // Acquire a stack from the given fiber pool. If none are available, allocate more.
651 static struct fiber_pool_stack
652 fiber_pool_stack_acquire(struct fiber_pool * fiber_pool)
654 struct fiber_pool_vacancy * vacancy = fiber_pool_vacancy_pop(fiber_pool);
656 if (DEBUG) fprintf(stderr, "fiber_pool_stack_acquire: %p used=%"PRIuSIZE"\n", (void*)fiber_pool->vacancies, fiber_pool->used);
658 if (!vacancy) {
659 const size_t maximum = FIBER_POOL_ALLOCATION_MAXIMUM_SIZE;
660 const size_t minimum = fiber_pool->initial_count;
662 size_t count = fiber_pool->count;
663 if (count > maximum) count = maximum;
664 if (count < minimum) count = minimum;
666 fiber_pool_expand(fiber_pool, count);
668 // The free list should now contain some stacks:
669 VM_ASSERT(fiber_pool->vacancies);
671 vacancy = fiber_pool_vacancy_pop(fiber_pool);
674 VM_ASSERT(vacancy);
675 VM_ASSERT(vacancy->stack.base);
677 #if defined(COROUTINE_SANITIZE_ADDRESS)
678 __asan_unpoison_memory_region(fiber_pool_stack_poison_base(&vacancy->stack), fiber_pool_stack_poison_size(&vacancy->stack));
679 #endif
681 // Take the top item from the free list:
682 fiber_pool->used += 1;
684 #ifdef FIBER_POOL_ALLOCATION_FREE
685 vacancy->stack.allocation->used += 1;
686 #endif
688 fiber_pool_stack_reset(&vacancy->stack);
690 return vacancy->stack;
693 // We advise the operating system that the stack memory pages are no longer being used.
694 // This introduce some performance overhead but allows system to relaim memory when there is pressure.
695 static inline void
696 fiber_pool_stack_free(struct fiber_pool_stack * stack)
698 void * base = fiber_pool_stack_base(stack);
699 size_t size = stack->available;
701 // If this is not true, the vacancy information will almost certainly be destroyed:
702 VM_ASSERT(size <= (stack->size - RB_PAGE_SIZE));
704 int advice = stack->pool->free_stacks >> 1;
706 if (DEBUG) fprintf(stderr, "fiber_pool_stack_free: %p+%"PRIuSIZE" [base=%p, size=%"PRIuSIZE"] advice=%d\n", base, size, stack->base, stack->size, advice);
708 // The pages being used by the stack can be returned back to the system.
709 // That doesn't change the page mapping, but it does allow the system to
710 // reclaim the physical memory.
711 // Since we no longer care about the data itself, we don't need to page
712 // out to disk, since that is costly. Not all systems support that, so
713 // we try our best to select the most efficient implementation.
714 // In addition, it's actually slightly desirable to not do anything here,
715 // but that results in higher memory usage.
717 #ifdef __wasi__
718 // WebAssembly doesn't support madvise, so we just don't do anything.
719 #elif VM_CHECK_MODE > 0 && defined(MADV_DONTNEED)
720 if (!advice) advice = MADV_DONTNEED;
721 // This immediately discards the pages and the memory is reset to zero.
722 madvise(base, size, advice);
723 #elif defined(MADV_FREE_REUSABLE)
724 if (!advice) advice = MADV_FREE_REUSABLE;
725 // Darwin / macOS / iOS.
726 // Acknowledge the kernel down to the task info api we make this
727 // page reusable for future use.
728 // As for MADV_FREE_REUSABLE below we ensure in the rare occasions the task was not
729 // completed at the time of the call to re-iterate.
730 while (madvise(base, size, advice) == -1 && errno == EAGAIN);
731 #elif defined(MADV_FREE)
732 if (!advice) advice = MADV_FREE;
733 // Recent Linux.
734 madvise(base, size, advice);
735 #elif defined(MADV_DONTNEED)
736 if (!advice) advice = MADV_DONTNEED;
737 // Old Linux.
738 madvise(base, size, advice);
739 #elif defined(POSIX_MADV_DONTNEED)
740 if (!advice) advice = POSIX_MADV_DONTNEED;
741 // Solaris?
742 posix_madvise(base, size, advice);
743 #elif defined(_WIN32)
744 VirtualAlloc(base, size, MEM_RESET, PAGE_READWRITE);
745 // Not available in all versions of Windows.
746 //DiscardVirtualMemory(base, size);
747 #endif
749 #if defined(COROUTINE_SANITIZE_ADDRESS)
750 __asan_poison_memory_region(fiber_pool_stack_poison_base(stack), fiber_pool_stack_poison_size(stack));
751 #endif
754 // Release and return a stack to the vacancy list.
755 static void
756 fiber_pool_stack_release(struct fiber_pool_stack * stack)
758 struct fiber_pool * pool = stack->pool;
759 struct fiber_pool_vacancy * vacancy = fiber_pool_vacancy_pointer(stack->base, stack->size);
761 if (DEBUG) fprintf(stderr, "fiber_pool_stack_release: %p used=%"PRIuSIZE"\n", stack->base, stack->pool->used);
763 // Copy the stack details into the vacancy area:
764 vacancy->stack = *stack;
765 // After this point, be careful about updating/using state in stack, since it's copied to the vacancy area.
767 // Reset the stack pointers and reserve space for the vacancy data:
768 fiber_pool_vacancy_reset(vacancy);
770 // Push the vacancy into the vancancies list:
771 pool->vacancies = fiber_pool_vacancy_push(vacancy, pool->vacancies);
772 pool->used -= 1;
774 #ifdef FIBER_POOL_ALLOCATION_FREE
775 struct fiber_pool_allocation * allocation = stack->allocation;
777 allocation->used -= 1;
779 // Release address space and/or dirty memory:
780 if (allocation->used == 0) {
781 fiber_pool_allocation_free(allocation);
783 else if (stack->pool->free_stacks) {
784 fiber_pool_stack_free(&vacancy->stack);
786 #else
787 // This is entirely optional, but clears the dirty flag from the stack
788 // memory, so it won't get swapped to disk when there is memory pressure:
789 if (stack->pool->free_stacks) {
790 fiber_pool_stack_free(&vacancy->stack);
792 #endif
795 static inline void
796 ec_switch(rb_thread_t *th, rb_fiber_t *fiber)
798 rb_execution_context_t *ec = &fiber->cont.saved_ec;
799 #ifdef RUBY_ASAN_ENABLED
800 ec->machine.asan_fake_stack_handle = asan_get_thread_fake_stack_handle();
801 #endif
802 rb_ractor_set_current_ec(th->ractor, th->ec = ec);
803 // ruby_current_execution_context_ptr = th->ec = ec;
806 * timer-thread may set trap interrupt on previous th->ec at any time;
807 * ensure we do not delay (or lose) the trap interrupt handling.
809 if (th->vm->ractor.main_thread == th &&
810 rb_signal_buff_size() > 0) {
811 RUBY_VM_SET_TRAP_INTERRUPT(ec);
814 VM_ASSERT(ec->fiber_ptr->cont.self == 0 || ec->vm_stack != NULL);
817 static inline void
818 fiber_restore_thread(rb_thread_t *th, rb_fiber_t *fiber)
820 ec_switch(th, fiber);
821 VM_ASSERT(th->ec->fiber_ptr == fiber);
824 static COROUTINE
825 fiber_entry(struct coroutine_context * from, struct coroutine_context * to)
827 rb_fiber_t *fiber = to->argument;
829 #if defined(COROUTINE_SANITIZE_ADDRESS)
830 // Address sanitizer will copy the previous stack base and stack size into
831 // the "from" fiber. `coroutine_initialize_main` doesn't generally know the
832 // stack bounds (base + size). Therefore, the main fiber `stack_base` and
833 // `stack_size` will be NULL/0. It's specifically important in that case to
834 // get the (base+size) of the previous fiber and save it, so that later when
835 // we return to the main coroutine, we don't supply (NULL, 0) to
836 // __sanitizer_start_switch_fiber which royally messes up the internal state
837 // of ASAN and causes (sometimes) the following message:
838 // "WARNING: ASan is ignoring requested __asan_handle_no_return"
839 __sanitizer_finish_switch_fiber(to->fake_stack, (const void**)&from->stack_base, &from->stack_size);
840 #endif
842 rb_thread_t *thread = fiber->cont.saved_ec.thread_ptr;
844 #ifdef COROUTINE_PTHREAD_CONTEXT
845 ruby_thread_set_native(thread);
846 #endif
848 fiber_restore_thread(thread, fiber);
850 rb_fiber_start(fiber);
852 #ifndef COROUTINE_PTHREAD_CONTEXT
853 VM_UNREACHABLE(fiber_entry);
854 #endif
857 // Initialize a fiber's coroutine's machine stack and vm stack.
858 static VALUE *
859 fiber_initialize_coroutine(rb_fiber_t *fiber, size_t * vm_stack_size)
861 struct fiber_pool * fiber_pool = fiber->stack.pool;
862 rb_execution_context_t *sec = &fiber->cont.saved_ec;
863 void * vm_stack = NULL;
865 VM_ASSERT(fiber_pool != NULL);
867 fiber->stack = fiber_pool_stack_acquire(fiber_pool);
868 vm_stack = fiber_pool_stack_alloca(&fiber->stack, fiber_pool->vm_stack_size);
869 *vm_stack_size = fiber_pool->vm_stack_size;
871 coroutine_initialize(&fiber->context, fiber_entry, fiber_pool_stack_base(&fiber->stack), fiber->stack.available);
873 // The stack for this execution context is the one we allocated:
874 sec->machine.stack_start = fiber->stack.current;
875 sec->machine.stack_maxsize = fiber->stack.available;
877 fiber->context.argument = (void*)fiber;
879 return vm_stack;
882 // Release the stack from the fiber, it's execution context, and return it to
883 // the fiber pool.
884 static void
885 fiber_stack_release(rb_fiber_t * fiber)
887 rb_execution_context_t *ec = &fiber->cont.saved_ec;
889 if (DEBUG) fprintf(stderr, "fiber_stack_release: %p, stack.base=%p\n", (void*)fiber, fiber->stack.base);
891 // Return the stack back to the fiber pool if it wasn't already:
892 if (fiber->stack.base) {
893 fiber_pool_stack_release(&fiber->stack);
894 fiber->stack.base = NULL;
897 // The stack is no longer associated with this execution context:
898 rb_ec_clear_vm_stack(ec);
901 static const char *
902 fiber_status_name(enum fiber_status s)
904 switch (s) {
905 case FIBER_CREATED: return "created";
906 case FIBER_RESUMED: return "resumed";
907 case FIBER_SUSPENDED: return "suspended";
908 case FIBER_TERMINATED: return "terminated";
910 VM_UNREACHABLE(fiber_status_name);
911 return NULL;
914 static void
915 fiber_verify(const rb_fiber_t *fiber)
917 #if VM_CHECK_MODE > 0
918 VM_ASSERT(fiber->cont.saved_ec.fiber_ptr == fiber);
920 switch (fiber->status) {
921 case FIBER_RESUMED:
922 VM_ASSERT(fiber->cont.saved_ec.vm_stack != NULL);
923 break;
924 case FIBER_SUSPENDED:
925 VM_ASSERT(fiber->cont.saved_ec.vm_stack != NULL);
926 break;
927 case FIBER_CREATED:
928 case FIBER_TERMINATED:
929 /* TODO */
930 break;
931 default:
932 VM_UNREACHABLE(fiber_verify);
934 #endif
937 inline static void
938 fiber_status_set(rb_fiber_t *fiber, enum fiber_status s)
940 // if (DEBUG) fprintf(stderr, "fiber: %p, status: %s -> %s\n", (void *)fiber, fiber_status_name(fiber->status), fiber_status_name(s));
941 VM_ASSERT(!FIBER_TERMINATED_P(fiber));
942 VM_ASSERT(fiber->status != s);
943 fiber_verify(fiber);
944 fiber->status = s;
947 static rb_context_t *
948 cont_ptr(VALUE obj)
950 rb_context_t *cont;
952 TypedData_Get_Struct(obj, rb_context_t, &cont_data_type, cont);
954 return cont;
957 static rb_fiber_t *
958 fiber_ptr(VALUE obj)
960 rb_fiber_t *fiber;
962 TypedData_Get_Struct(obj, rb_fiber_t, &fiber_data_type, fiber);
963 if (!fiber) rb_raise(rb_eFiberError, "uninitialized fiber");
965 return fiber;
968 NOINLINE(static VALUE cont_capture(volatile int *volatile stat));
970 #define THREAD_MUST_BE_RUNNING(th) do { \
971 if (!(th)->ec->tag) rb_raise(rb_eThreadError, "not running thread"); \
972 } while (0)
974 rb_thread_t*
975 rb_fiber_threadptr(const rb_fiber_t *fiber)
977 return fiber->cont.saved_ec.thread_ptr;
980 static VALUE
981 cont_thread_value(const rb_context_t *cont)
983 return cont->saved_ec.thread_ptr->self;
986 static void
987 cont_compact(void *ptr)
989 rb_context_t *cont = ptr;
991 if (cont->self) {
992 cont->self = rb_gc_location(cont->self);
994 cont->value = rb_gc_location(cont->value);
995 rb_execution_context_update(&cont->saved_ec);
998 static void
999 cont_mark(void *ptr)
1001 rb_context_t *cont = ptr;
1003 RUBY_MARK_ENTER("cont");
1004 if (cont->self) {
1005 rb_gc_mark_movable(cont->self);
1007 rb_gc_mark_movable(cont->value);
1009 rb_execution_context_mark(&cont->saved_ec);
1010 rb_gc_mark(cont_thread_value(cont));
1012 if (cont->saved_vm_stack.ptr) {
1013 #ifdef CAPTURE_JUST_VALID_VM_STACK
1014 rb_gc_mark_locations(cont->saved_vm_stack.ptr,
1015 cont->saved_vm_stack.ptr + cont->saved_vm_stack.slen + cont->saved_vm_stack.clen);
1016 #else
1017 rb_gc_mark_locations(cont->saved_vm_stack.ptr,
1018 cont->saved_vm_stack.ptr, cont->saved_ec.stack_size);
1019 #endif
1022 if (cont->machine.stack) {
1023 if (cont->type == CONTINUATION_CONTEXT) {
1024 /* cont */
1025 rb_gc_mark_locations(cont->machine.stack,
1026 cont->machine.stack + cont->machine.stack_size);
1028 else {
1029 /* fiber machine context is marked as part of rb_execution_context_mark, no need to
1030 * do anything here. */
1034 RUBY_MARK_LEAVE("cont");
1037 #if 0
1038 static int
1039 fiber_is_root_p(const rb_fiber_t *fiber)
1041 return fiber == fiber->cont.saved_ec.thread_ptr->root_fiber;
1043 #endif
1045 static void jit_cont_free(struct rb_jit_cont *cont);
1047 static void
1048 cont_free(void *ptr)
1050 rb_context_t *cont = ptr;
1052 RUBY_FREE_ENTER("cont");
1054 if (cont->type == CONTINUATION_CONTEXT) {
1055 ruby_xfree(cont->saved_ec.vm_stack);
1056 ruby_xfree(cont->ensure_array);
1057 RUBY_FREE_UNLESS_NULL(cont->machine.stack);
1059 else {
1060 rb_fiber_t *fiber = (rb_fiber_t*)cont;
1061 coroutine_destroy(&fiber->context);
1062 fiber_stack_release(fiber);
1065 RUBY_FREE_UNLESS_NULL(cont->saved_vm_stack.ptr);
1067 VM_ASSERT(cont->jit_cont != NULL);
1068 jit_cont_free(cont->jit_cont);
1069 /* free rb_cont_t or rb_fiber_t */
1070 ruby_xfree(ptr);
1071 RUBY_FREE_LEAVE("cont");
1074 static size_t
1075 cont_memsize(const void *ptr)
1077 const rb_context_t *cont = ptr;
1078 size_t size = 0;
1080 size = sizeof(*cont);
1081 if (cont->saved_vm_stack.ptr) {
1082 #ifdef CAPTURE_JUST_VALID_VM_STACK
1083 size_t n = (cont->saved_vm_stack.slen + cont->saved_vm_stack.clen);
1084 #else
1085 size_t n = cont->saved_ec.vm_stack_size;
1086 #endif
1087 size += n * sizeof(*cont->saved_vm_stack.ptr);
1090 if (cont->machine.stack) {
1091 size += cont->machine.stack_size * sizeof(*cont->machine.stack);
1094 return size;
1097 void
1098 rb_fiber_update_self(rb_fiber_t *fiber)
1100 if (fiber->cont.self) {
1101 fiber->cont.self = rb_gc_location(fiber->cont.self);
1103 else {
1104 rb_execution_context_update(&fiber->cont.saved_ec);
1108 void
1109 rb_fiber_mark_self(const rb_fiber_t *fiber)
1111 if (fiber->cont.self) {
1112 rb_gc_mark_movable(fiber->cont.self);
1114 else {
1115 rb_execution_context_mark(&fiber->cont.saved_ec);
1119 static void
1120 fiber_compact(void *ptr)
1122 rb_fiber_t *fiber = ptr;
1123 fiber->first_proc = rb_gc_location(fiber->first_proc);
1125 if (fiber->prev) rb_fiber_update_self(fiber->prev);
1127 cont_compact(&fiber->cont);
1128 fiber_verify(fiber);
1131 static void
1132 fiber_mark(void *ptr)
1134 rb_fiber_t *fiber = ptr;
1135 RUBY_MARK_ENTER("cont");
1136 fiber_verify(fiber);
1137 rb_gc_mark_movable(fiber->first_proc);
1138 if (fiber->prev) rb_fiber_mark_self(fiber->prev);
1139 cont_mark(&fiber->cont);
1140 RUBY_MARK_LEAVE("cont");
1143 static void
1144 fiber_free(void *ptr)
1146 rb_fiber_t *fiber = ptr;
1147 RUBY_FREE_ENTER("fiber");
1149 if (DEBUG) fprintf(stderr, "fiber_free: %p[%p]\n", (void *)fiber, fiber->stack.base);
1151 if (fiber->cont.saved_ec.local_storage) {
1152 rb_id_table_free(fiber->cont.saved_ec.local_storage);
1155 cont_free(&fiber->cont);
1156 RUBY_FREE_LEAVE("fiber");
1159 static size_t
1160 fiber_memsize(const void *ptr)
1162 const rb_fiber_t *fiber = ptr;
1163 size_t size = sizeof(*fiber);
1164 const rb_execution_context_t *saved_ec = &fiber->cont.saved_ec;
1165 const rb_thread_t *th = rb_ec_thread_ptr(saved_ec);
1168 * vm.c::thread_memsize already counts th->ec->local_storage
1170 if (saved_ec->local_storage && fiber != th->root_fiber) {
1171 size += rb_id_table_memsize(saved_ec->local_storage);
1172 size += rb_obj_memsize_of(saved_ec->storage);
1175 size += cont_memsize(&fiber->cont);
1176 return size;
1179 VALUE
1180 rb_obj_is_fiber(VALUE obj)
1182 return RBOOL(rb_typeddata_is_kind_of(obj, &fiber_data_type));
1185 static void
1186 cont_save_machine_stack(rb_thread_t *th, rb_context_t *cont)
1188 size_t size;
1190 SET_MACHINE_STACK_END(&th->ec->machine.stack_end);
1192 if (th->ec->machine.stack_start > th->ec->machine.stack_end) {
1193 size = cont->machine.stack_size = th->ec->machine.stack_start - th->ec->machine.stack_end;
1194 cont->machine.stack_src = th->ec->machine.stack_end;
1196 else {
1197 size = cont->machine.stack_size = th->ec->machine.stack_end - th->ec->machine.stack_start;
1198 cont->machine.stack_src = th->ec->machine.stack_start;
1201 if (cont->machine.stack) {
1202 REALLOC_N(cont->machine.stack, VALUE, size);
1204 else {
1205 cont->machine.stack = ALLOC_N(VALUE, size);
1208 FLUSH_REGISTER_WINDOWS;
1209 asan_unpoison_memory_region(cont->machine.stack_src, size, false);
1210 MEMCPY(cont->machine.stack, cont->machine.stack_src, VALUE, size);
1213 static const rb_data_type_t cont_data_type = {
1214 "continuation",
1215 {cont_mark, cont_free, cont_memsize, cont_compact},
1216 0, 0, RUBY_TYPED_FREE_IMMEDIATELY
1219 static inline void
1220 cont_save_thread(rb_context_t *cont, rb_thread_t *th)
1222 rb_execution_context_t *sec = &cont->saved_ec;
1224 VM_ASSERT(th->status == THREAD_RUNNABLE);
1226 /* save thread context */
1227 *sec = *th->ec;
1229 /* saved_ec->machine.stack_end should be NULL */
1230 /* because it may happen GC afterward */
1231 sec->machine.stack_end = NULL;
1234 static rb_nativethread_lock_t jit_cont_lock;
1236 // Register a new continuation with execution context `ec`. Return JIT info about
1237 // the continuation.
1238 static struct rb_jit_cont *
1239 jit_cont_new(rb_execution_context_t *ec)
1241 struct rb_jit_cont *cont;
1243 // We need to use calloc instead of something like ZALLOC to avoid triggering GC here.
1244 // When this function is called from rb_thread_alloc through rb_threadptr_root_fiber_setup,
1245 // the thread is still being prepared and marking it causes SEGV.
1246 cont = calloc(1, sizeof(struct rb_jit_cont));
1247 if (cont == NULL)
1248 rb_memerror();
1249 cont->ec = ec;
1251 rb_native_mutex_lock(&jit_cont_lock);
1252 if (first_jit_cont == NULL) {
1253 cont->next = cont->prev = NULL;
1255 else {
1256 cont->prev = NULL;
1257 cont->next = first_jit_cont;
1258 first_jit_cont->prev = cont;
1260 first_jit_cont = cont;
1261 rb_native_mutex_unlock(&jit_cont_lock);
1263 return cont;
1266 // Unregister continuation `cont`.
1267 static void
1268 jit_cont_free(struct rb_jit_cont *cont)
1270 if (!cont) return;
1272 rb_native_mutex_lock(&jit_cont_lock);
1273 if (cont == first_jit_cont) {
1274 first_jit_cont = cont->next;
1275 if (first_jit_cont != NULL)
1276 first_jit_cont->prev = NULL;
1278 else {
1279 cont->prev->next = cont->next;
1280 if (cont->next != NULL)
1281 cont->next->prev = cont->prev;
1283 rb_native_mutex_unlock(&jit_cont_lock);
1285 free(cont);
1288 // Call a given callback against all on-stack ISEQs.
1289 void
1290 rb_jit_cont_each_iseq(rb_iseq_callback callback, void *data)
1292 struct rb_jit_cont *cont;
1293 for (cont = first_jit_cont; cont != NULL; cont = cont->next) {
1294 if (cont->ec->vm_stack == NULL)
1295 continue;
1297 const rb_control_frame_t *cfp = cont->ec->cfp;
1298 while (!RUBY_VM_CONTROL_FRAME_STACK_OVERFLOW_P(cont->ec, cfp)) {
1299 if (cfp->pc && cfp->iseq && imemo_type((VALUE)cfp->iseq) == imemo_iseq) {
1300 callback(cfp->iseq, data);
1302 cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp);
1307 #if USE_YJIT
1308 // Update the jit_return of all CFPs to leave_exit unless it's leave_exception or not set.
1309 // This prevents jit_exec_exception from jumping to the caller after invalidation.
1310 void
1311 rb_yjit_cancel_jit_return(void *leave_exit, void *leave_exception)
1313 struct rb_jit_cont *cont;
1314 for (cont = first_jit_cont; cont != NULL; cont = cont->next) {
1315 if (cont->ec->vm_stack == NULL)
1316 continue;
1318 const rb_control_frame_t *cfp = cont->ec->cfp;
1319 while (!RUBY_VM_CONTROL_FRAME_STACK_OVERFLOW_P(cont->ec, cfp)) {
1320 if (cfp->jit_return && cfp->jit_return != leave_exception) {
1321 ((rb_control_frame_t *)cfp)->jit_return = leave_exit;
1323 cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp);
1327 #endif
1329 // Finish working with jit_cont.
1330 void
1331 rb_jit_cont_finish(void)
1333 struct rb_jit_cont *cont, *next;
1334 for (cont = first_jit_cont; cont != NULL; cont = next) {
1335 next = cont->next;
1336 free(cont); // Don't use xfree because it's allocated by calloc.
1338 rb_native_mutex_destroy(&jit_cont_lock);
1341 static void
1342 cont_init_jit_cont(rb_context_t *cont)
1344 VM_ASSERT(cont->jit_cont == NULL);
1345 // We always allocate this since YJIT may be enabled later
1346 cont->jit_cont = jit_cont_new(&(cont->saved_ec));
1349 struct rb_execution_context_struct *
1350 rb_fiberptr_get_ec(struct rb_fiber_struct *fiber)
1352 return &fiber->cont.saved_ec;
1355 static void
1356 cont_init(rb_context_t *cont, rb_thread_t *th)
1358 /* save thread context */
1359 cont_save_thread(cont, th);
1360 cont->saved_ec.thread_ptr = th;
1361 cont->saved_ec.local_storage = NULL;
1362 cont->saved_ec.local_storage_recursive_hash = Qnil;
1363 cont->saved_ec.local_storage_recursive_hash_for_trace = Qnil;
1364 cont_init_jit_cont(cont);
1367 static rb_context_t *
1368 cont_new(VALUE klass)
1370 rb_context_t *cont;
1371 volatile VALUE contval;
1372 rb_thread_t *th = GET_THREAD();
1374 THREAD_MUST_BE_RUNNING(th);
1375 contval = TypedData_Make_Struct(klass, rb_context_t, &cont_data_type, cont);
1376 cont->self = contval;
1377 cont_init(cont, th);
1378 return cont;
1381 VALUE
1382 rb_fiberptr_self(struct rb_fiber_struct *fiber)
1384 return fiber->cont.self;
1387 unsigned int
1388 rb_fiberptr_blocking(struct rb_fiber_struct *fiber)
1390 return fiber->blocking;
1393 // Initialize the jit_cont_lock
1394 void
1395 rb_jit_cont_init(void)
1397 rb_native_mutex_initialize(&jit_cont_lock);
1400 #if 0
1401 void
1402 show_vm_stack(const rb_execution_context_t *ec)
1404 VALUE *p = ec->vm_stack;
1405 while (p < ec->cfp->sp) {
1406 fprintf(stderr, "%3d ", (int)(p - ec->vm_stack));
1407 rb_obj_info_dump(*p);
1408 p++;
1412 void
1413 show_vm_pcs(const rb_control_frame_t *cfp,
1414 const rb_control_frame_t *end_of_cfp)
1416 int i=0;
1417 while (cfp != end_of_cfp) {
1418 int pc = 0;
1419 if (cfp->iseq) {
1420 pc = cfp->pc - ISEQ_BODY(cfp->iseq)->iseq_encoded;
1422 fprintf(stderr, "%2d pc: %d\n", i++, pc);
1423 cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp);
1426 #endif
1428 static VALUE
1429 cont_capture(volatile int *volatile stat)
1431 rb_context_t *volatile cont;
1432 rb_thread_t *th = GET_THREAD();
1433 volatile VALUE contval;
1434 const rb_execution_context_t *ec = th->ec;
1436 THREAD_MUST_BE_RUNNING(th);
1437 rb_vm_stack_to_heap(th->ec);
1438 cont = cont_new(rb_cContinuation);
1439 contval = cont->self;
1441 #ifdef CAPTURE_JUST_VALID_VM_STACK
1442 cont->saved_vm_stack.slen = ec->cfp->sp - ec->vm_stack;
1443 cont->saved_vm_stack.clen = ec->vm_stack + ec->vm_stack_size - (VALUE*)ec->cfp;
1444 cont->saved_vm_stack.ptr = ALLOC_N(VALUE, cont->saved_vm_stack.slen + cont->saved_vm_stack.clen);
1445 MEMCPY(cont->saved_vm_stack.ptr,
1446 ec->vm_stack,
1447 VALUE, cont->saved_vm_stack.slen);
1448 MEMCPY(cont->saved_vm_stack.ptr + cont->saved_vm_stack.slen,
1449 (VALUE*)ec->cfp,
1450 VALUE,
1451 cont->saved_vm_stack.clen);
1452 #else
1453 cont->saved_vm_stack.ptr = ALLOC_N(VALUE, ec->vm_stack_size);
1454 MEMCPY(cont->saved_vm_stack.ptr, ec->vm_stack, VALUE, ec->vm_stack_size);
1455 #endif
1456 // At this point, `cfp` is valid but `vm_stack` should be cleared:
1457 rb_ec_set_vm_stack(&cont->saved_ec, NULL, 0);
1458 VM_ASSERT(cont->saved_ec.cfp != NULL);
1459 cont_save_machine_stack(th, cont);
1461 /* backup ensure_list to array for search in another context */
1463 rb_ensure_list_t *p;
1464 int size = 0;
1465 rb_ensure_entry_t *entry;
1466 for (p=th->ec->ensure_list; p; p=p->next)
1467 size++;
1468 entry = cont->ensure_array = ALLOC_N(rb_ensure_entry_t,size+1);
1469 for (p=th->ec->ensure_list; p; p=p->next) {
1470 if (!p->entry.marker)
1471 p->entry.marker = rb_ary_hidden_new(0); /* dummy object */
1472 *entry++ = p->entry;
1474 entry->marker = 0;
1477 if (ruby_setjmp(cont->jmpbuf)) {
1478 VALUE value;
1480 VAR_INITIALIZED(cont);
1481 value = cont->value;
1482 if (cont->argc == -1) rb_exc_raise(value);
1483 cont->value = Qnil;
1484 *stat = 1;
1485 return value;
1487 else {
1488 *stat = 0;
1489 return contval;
1493 static inline void
1494 cont_restore_thread(rb_context_t *cont)
1496 rb_thread_t *th = GET_THREAD();
1498 /* restore thread context */
1499 if (cont->type == CONTINUATION_CONTEXT) {
1500 /* continuation */
1501 rb_execution_context_t *sec = &cont->saved_ec;
1502 rb_fiber_t *fiber = NULL;
1504 if (sec->fiber_ptr != NULL) {
1505 fiber = sec->fiber_ptr;
1507 else if (th->root_fiber) {
1508 fiber = th->root_fiber;
1511 if (fiber && th->ec != &fiber->cont.saved_ec) {
1512 ec_switch(th, fiber);
1515 if (th->ec->trace_arg != sec->trace_arg) {
1516 rb_raise(rb_eRuntimeError, "can't call across trace_func");
1519 /* copy vm stack */
1520 #ifdef CAPTURE_JUST_VALID_VM_STACK
1521 MEMCPY(th->ec->vm_stack,
1522 cont->saved_vm_stack.ptr,
1523 VALUE, cont->saved_vm_stack.slen);
1524 MEMCPY(th->ec->vm_stack + th->ec->vm_stack_size - cont->saved_vm_stack.clen,
1525 cont->saved_vm_stack.ptr + cont->saved_vm_stack.slen,
1526 VALUE, cont->saved_vm_stack.clen);
1527 #else
1528 MEMCPY(th->ec->vm_stack, cont->saved_vm_stack.ptr, VALUE, sec->vm_stack_size);
1529 #endif
1530 /* other members of ec */
1532 th->ec->cfp = sec->cfp;
1533 th->ec->raised_flag = sec->raised_flag;
1534 th->ec->tag = sec->tag;
1535 th->ec->root_lep = sec->root_lep;
1536 th->ec->root_svar = sec->root_svar;
1537 th->ec->ensure_list = sec->ensure_list;
1538 th->ec->errinfo = sec->errinfo;
1540 VM_ASSERT(th->ec->vm_stack != NULL);
1542 else {
1543 /* fiber */
1544 fiber_restore_thread(th, (rb_fiber_t*)cont);
1548 NOINLINE(static void fiber_setcontext(rb_fiber_t *new_fiber, rb_fiber_t *old_fiber));
1550 static void
1551 fiber_setcontext(rb_fiber_t *new_fiber, rb_fiber_t *old_fiber)
1553 rb_thread_t *th = GET_THREAD();
1555 /* save old_fiber's machine stack - to ensure efficient garbage collection */
1556 if (!FIBER_TERMINATED_P(old_fiber)) {
1557 STACK_GROW_DIR_DETECTION;
1558 SET_MACHINE_STACK_END(&th->ec->machine.stack_end);
1559 if (STACK_DIR_UPPER(0, 1)) {
1560 old_fiber->cont.machine.stack_size = th->ec->machine.stack_start - th->ec->machine.stack_end;
1561 old_fiber->cont.machine.stack = th->ec->machine.stack_end;
1563 else {
1564 old_fiber->cont.machine.stack_size = th->ec->machine.stack_end - th->ec->machine.stack_start;
1565 old_fiber->cont.machine.stack = th->ec->machine.stack_start;
1569 /* these values are used in rb_gc_mark_machine_context to mark the fiber's stack. */
1570 old_fiber->cont.saved_ec.machine.stack_start = th->ec->machine.stack_start;
1571 old_fiber->cont.saved_ec.machine.stack_end = FIBER_TERMINATED_P(old_fiber) ? NULL : th->ec->machine.stack_end;
1574 // 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);
1576 #if defined(COROUTINE_SANITIZE_ADDRESS)
1577 __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);
1578 #endif
1580 /* swap machine context */
1581 struct coroutine_context * from = coroutine_transfer(&old_fiber->context, &new_fiber->context);
1583 #if defined(COROUTINE_SANITIZE_ADDRESS)
1584 __sanitizer_finish_switch_fiber(old_fiber->context.fake_stack, NULL, NULL);
1585 #endif
1587 if (from == NULL) {
1588 rb_syserr_fail(errno, "coroutine_transfer");
1591 /* restore thread context */
1592 fiber_restore_thread(th, old_fiber);
1594 // It's possible to get here, and new_fiber is already freed.
1595 // 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);
1598 NOINLINE(NORETURN(static void cont_restore_1(rb_context_t *)));
1600 static void
1601 cont_restore_1(rb_context_t *cont)
1603 cont_restore_thread(cont);
1605 /* restore machine stack */
1606 #if defined(_M_AMD64) && !defined(__MINGW64__)
1608 /* workaround for x64 SEH */
1609 jmp_buf buf;
1610 setjmp(buf);
1611 _JUMP_BUFFER *bp = (void*)&cont->jmpbuf;
1612 bp->Frame = ((_JUMP_BUFFER*)((void*)&buf))->Frame;
1614 #endif
1615 if (cont->machine.stack_src) {
1616 FLUSH_REGISTER_WINDOWS;
1617 MEMCPY(cont->machine.stack_src, cont->machine.stack,
1618 VALUE, cont->machine.stack_size);
1621 ruby_longjmp(cont->jmpbuf, 1);
1624 NORETURN(NOINLINE(static void cont_restore_0(rb_context_t *, VALUE *)));
1626 static void
1627 cont_restore_0(rb_context_t *cont, VALUE *addr_in_prev_frame)
1629 if (cont->machine.stack_src) {
1630 #ifdef HAVE_ALLOCA
1631 #define STACK_PAD_SIZE 1
1632 #else
1633 #define STACK_PAD_SIZE 1024
1634 #endif
1635 VALUE space[STACK_PAD_SIZE];
1637 #if !STACK_GROW_DIRECTION
1638 if (addr_in_prev_frame > &space[0]) {
1639 /* Stack grows downward */
1640 #endif
1641 #if STACK_GROW_DIRECTION <= 0
1642 volatile VALUE *const end = cont->machine.stack_src;
1643 if (&space[0] > end) {
1644 # ifdef HAVE_ALLOCA
1645 volatile VALUE *sp = ALLOCA_N(VALUE, &space[0] - end);
1646 // We need to make sure that the stack pointer is moved,
1647 // but some compilers may remove the allocation by optimization.
1648 // We hope that the following read/write will prevent such an optimization.
1649 *sp = Qfalse;
1650 space[0] = *sp;
1651 # else
1652 cont_restore_0(cont, &space[0]);
1653 # endif
1655 #endif
1656 #if !STACK_GROW_DIRECTION
1658 else {
1659 /* Stack grows upward */
1660 #endif
1661 #if STACK_GROW_DIRECTION >= 0
1662 volatile VALUE *const end = cont->machine.stack_src + cont->machine.stack_size;
1663 if (&space[STACK_PAD_SIZE] < end) {
1664 # ifdef HAVE_ALLOCA
1665 volatile VALUE *sp = ALLOCA_N(VALUE, end - &space[STACK_PAD_SIZE]);
1666 space[0] = *sp;
1667 # else
1668 cont_restore_0(cont, &space[STACK_PAD_SIZE-1]);
1669 # endif
1671 #endif
1672 #if !STACK_GROW_DIRECTION
1674 #endif
1676 cont_restore_1(cont);
1680 * Document-class: Continuation
1682 * Continuation objects are generated by Kernel#callcc,
1683 * after having +require+d <i>continuation</i>. They hold
1684 * a return address and execution context, allowing a nonlocal return
1685 * to the end of the #callcc block from anywhere within a
1686 * program. Continuations are somewhat analogous to a structured
1687 * version of C's <code>setjmp/longjmp</code> (although they contain
1688 * more state, so you might consider them closer to threads).
1690 * For instance:
1692 * require "continuation"
1693 * arr = [ "Freddie", "Herbie", "Ron", "Max", "Ringo" ]
1694 * callcc{|cc| $cc = cc}
1695 * puts(message = arr.shift)
1696 * $cc.call unless message =~ /Max/
1698 * <em>produces:</em>
1700 * Freddie
1701 * Herbie
1702 * Ron
1703 * Max
1705 * Also you can call callcc in other methods:
1707 * require "continuation"
1709 * def g
1710 * arr = [ "Freddie", "Herbie", "Ron", "Max", "Ringo" ]
1711 * cc = callcc { |cc| cc }
1712 * puts arr.shift
1713 * return cc, arr.size
1714 * end
1716 * def f
1717 * c, size = g
1718 * c.call(c) if size > 1
1719 * end
1723 * This (somewhat contrived) example allows the inner loop to abandon
1724 * processing early:
1726 * require "continuation"
1727 * callcc {|cont|
1728 * for i in 0..4
1729 * print "#{i}: "
1730 * for j in i*5...(i+1)*5
1731 * cont.call() if j == 17
1732 * printf "%3d", j
1733 * end
1734 * end
1736 * puts
1738 * <em>produces:</em>
1740 * 0: 0 1 2 3 4
1741 * 1: 5 6 7 8 9
1742 * 2: 10 11 12 13 14
1743 * 3: 15 16
1747 * call-seq:
1748 * callcc {|cont| block } -> obj
1750 * Generates a Continuation object, which it passes to
1751 * the associated block. You need to <code>require
1752 * 'continuation'</code> before using this method. Performing a
1753 * <em>cont</em><code>.call</code> will cause the #callcc
1754 * to return (as will falling through the end of the block). The
1755 * value returned by the #callcc is the value of the
1756 * block, or the value passed to <em>cont</em><code>.call</code>. See
1757 * class Continuation for more details. Also see
1758 * Kernel#throw for an alternative mechanism for
1759 * unwinding a call stack.
1762 static VALUE
1763 rb_callcc(VALUE self)
1765 volatile int called;
1766 volatile VALUE val = cont_capture(&called);
1768 if (called) {
1769 return val;
1771 else {
1772 return rb_yield(val);
1775 #ifdef RUBY_ASAN_ENABLED
1776 /* callcc can't possibly work with ASAN; see bug #20273. Also this function
1777 * definition below avoids a "defined and not used" warning. */
1778 MAYBE_UNUSED(static void notusing_callcc(void)) { rb_callcc(Qnil); }
1779 # define rb_callcc rb_f_notimplement
1780 #endif
1783 static VALUE
1784 make_passing_arg(int argc, const VALUE *argv)
1786 switch (argc) {
1787 case -1:
1788 return argv[0];
1789 case 0:
1790 return Qnil;
1791 case 1:
1792 return argv[0];
1793 default:
1794 return rb_ary_new4(argc, argv);
1798 typedef VALUE e_proc(VALUE);
1800 /* CAUTION!! : Currently, error in rollback_func is not supported */
1801 /* same as rb_protect if set rollback_func to NULL */
1802 void
1803 ruby_register_rollback_func_for_ensure(e_proc *ensure_func, e_proc *rollback_func)
1805 st_table **table_p = &GET_VM()->ensure_rollback_table;
1806 if (UNLIKELY(*table_p == NULL)) {
1807 *table_p = st_init_numtable();
1809 st_insert(*table_p, (st_data_t)ensure_func, (st_data_t)rollback_func);
1812 static inline e_proc *
1813 lookup_rollback_func(e_proc *ensure_func)
1815 st_table *table = GET_VM()->ensure_rollback_table;
1816 st_data_t val;
1817 if (table && st_lookup(table, (st_data_t)ensure_func, &val))
1818 return (e_proc *) val;
1819 return (e_proc *) Qundef;
1823 static inline void
1824 rollback_ensure_stack(VALUE self,rb_ensure_list_t *current,rb_ensure_entry_t *target)
1826 rb_ensure_list_t *p;
1827 rb_ensure_entry_t *entry;
1828 size_t i, j;
1829 size_t cur_size;
1830 size_t target_size;
1831 size_t base_point;
1832 e_proc *func;
1834 cur_size = 0;
1835 for (p=current; p; p=p->next)
1836 cur_size++;
1837 target_size = 0;
1838 for (entry=target; entry->marker; entry++)
1839 target_size++;
1841 /* search common stack point */
1842 p = current;
1843 base_point = cur_size;
1844 while (base_point) {
1845 if (target_size >= base_point &&
1846 p->entry.marker == target[target_size - base_point].marker)
1847 break;
1848 base_point --;
1849 p = p->next;
1852 /* rollback function check */
1853 for (i=0; i < target_size - base_point; i++) {
1854 if (!lookup_rollback_func(target[i].e_proc)) {
1855 rb_raise(rb_eRuntimeError, "continuation called from out of critical rb_ensure scope");
1858 /* pop ensure stack */
1859 while (cur_size > base_point) {
1860 /* escape from ensure block */
1861 (*current->entry.e_proc)(current->entry.data2);
1862 current = current->next;
1863 cur_size--;
1865 /* push ensure stack */
1866 for (j = 0; j < i; j++) {
1867 func = lookup_rollback_func(target[i - j - 1].e_proc);
1868 if (!UNDEF_P((VALUE)func)) {
1869 (*func)(target[i - j - 1].data2);
1874 NORETURN(static VALUE rb_cont_call(int argc, VALUE *argv, VALUE contval));
1877 * call-seq:
1878 * cont.call(args, ...)
1879 * cont[args, ...]
1881 * Invokes the continuation. The program continues from the end of
1882 * the #callcc block. If no arguments are given, the original #callcc
1883 * returns +nil+. If one argument is given, #callcc returns
1884 * it. Otherwise, an array containing <i>args</i> is returned.
1886 * callcc {|cont| cont.call } #=> nil
1887 * callcc {|cont| cont.call 1 } #=> 1
1888 * callcc {|cont| cont.call 1, 2, 3 } #=> [1, 2, 3]
1891 static VALUE
1892 rb_cont_call(int argc, VALUE *argv, VALUE contval)
1894 rb_context_t *cont = cont_ptr(contval);
1895 rb_thread_t *th = GET_THREAD();
1897 if (cont_thread_value(cont) != th->self) {
1898 rb_raise(rb_eRuntimeError, "continuation called across threads");
1900 if (cont->saved_ec.fiber_ptr) {
1901 if (th->ec->fiber_ptr != cont->saved_ec.fiber_ptr) {
1902 rb_raise(rb_eRuntimeError, "continuation called across fiber");
1905 rollback_ensure_stack(contval, th->ec->ensure_list, cont->ensure_array);
1907 cont->argc = argc;
1908 cont->value = make_passing_arg(argc, argv);
1910 cont_restore_0(cont, &contval);
1911 UNREACHABLE_RETURN(Qnil);
1914 /*********/
1915 /* fiber */
1916 /*********/
1919 * Document-class: Fiber
1921 * Fibers are primitives for implementing light weight cooperative
1922 * concurrency in Ruby. Basically they are a means of creating code blocks
1923 * that can be paused and resumed, much like threads. The main difference
1924 * is that they are never preempted and that the scheduling must be done by
1925 * the programmer and not the VM.
1927 * As opposed to other stackless light weight concurrency models, each fiber
1928 * comes with a stack. This enables the fiber to be paused from deeply
1929 * nested function calls within the fiber block. See the ruby(1)
1930 * manpage to configure the size of the fiber stack(s).
1932 * When a fiber is created it will not run automatically. Rather it must
1933 * be explicitly asked to run using the Fiber#resume method.
1934 * The code running inside the fiber can give up control by calling
1935 * Fiber.yield in which case it yields control back to caller (the
1936 * caller of the Fiber#resume).
1938 * Upon yielding or termination the Fiber returns the value of the last
1939 * executed expression
1941 * For instance:
1943 * fiber = Fiber.new do
1944 * Fiber.yield 1
1946 * end
1948 * puts fiber.resume
1949 * puts fiber.resume
1950 * puts fiber.resume
1952 * <em>produces</em>
1956 * FiberError: dead fiber called
1958 * The Fiber#resume method accepts an arbitrary number of parameters,
1959 * if it is the first call to #resume then they will be passed as
1960 * block arguments. Otherwise they will be the return value of the
1961 * call to Fiber.yield
1963 * Example:
1965 * fiber = Fiber.new do |first|
1966 * second = Fiber.yield first + 2
1967 * end
1969 * puts fiber.resume 10
1970 * puts fiber.resume 1_000_000
1971 * puts fiber.resume "The fiber will be dead before I can cause trouble"
1973 * <em>produces</em>
1975 * 12
1976 * 1000000
1977 * FiberError: dead fiber called
1979 * == Non-blocking Fibers
1981 * The concept of <em>non-blocking fiber</em> was introduced in Ruby 3.0.
1982 * A non-blocking fiber, when reaching a operation that would normally block
1983 * the fiber (like <code>sleep</code>, or wait for another process or I/O)
1984 * will yield control to other fibers and allow the <em>scheduler</em> to
1985 * handle blocking and waking up (resuming) this fiber when it can proceed.
1987 * For a Fiber to behave as non-blocking, it need to be created in Fiber.new with
1988 * <tt>blocking: false</tt> (which is the default), and Fiber.scheduler
1989 * should be set with Fiber.set_scheduler. If Fiber.scheduler is not set in
1990 * the current thread, blocking and non-blocking fibers' behavior is identical.
1992 * Ruby doesn't provide a scheduler class: it is expected to be implemented by
1993 * the user and correspond to Fiber::Scheduler.
1995 * There is also Fiber.schedule method, which is expected to immediately perform
1996 * the given block in a non-blocking manner. Its actual implementation is up to
1997 * the scheduler.
2001 static const rb_data_type_t fiber_data_type = {
2002 "fiber",
2003 {fiber_mark, fiber_free, fiber_memsize, fiber_compact,},
2004 0, 0, RUBY_TYPED_FREE_IMMEDIATELY
2007 static VALUE
2008 fiber_alloc(VALUE klass)
2010 return TypedData_Wrap_Struct(klass, &fiber_data_type, 0);
2013 static rb_fiber_t*
2014 fiber_t_alloc(VALUE fiber_value, unsigned int blocking)
2016 rb_fiber_t *fiber;
2017 rb_thread_t *th = GET_THREAD();
2019 if (DATA_PTR(fiber_value) != 0) {
2020 rb_raise(rb_eRuntimeError, "cannot initialize twice");
2023 THREAD_MUST_BE_RUNNING(th);
2024 fiber = ZALLOC(rb_fiber_t);
2025 fiber->cont.self = fiber_value;
2026 fiber->cont.type = FIBER_CONTEXT;
2027 fiber->blocking = blocking;
2028 fiber->killed = 0;
2029 cont_init(&fiber->cont, th);
2031 fiber->cont.saved_ec.fiber_ptr = fiber;
2032 rb_ec_clear_vm_stack(&fiber->cont.saved_ec);
2034 fiber->prev = NULL;
2036 /* fiber->status == 0 == CREATED
2037 * So that we don't need to set status: fiber_status_set(fiber, FIBER_CREATED); */
2038 VM_ASSERT(FIBER_CREATED_P(fiber));
2040 DATA_PTR(fiber_value) = fiber;
2042 return fiber;
2045 static rb_fiber_t *
2046 root_fiber_alloc(rb_thread_t *th)
2048 VALUE fiber_value = fiber_alloc(rb_cFiber);
2049 rb_fiber_t *fiber = th->ec->fiber_ptr;
2051 VM_ASSERT(DATA_PTR(fiber_value) == NULL);
2052 VM_ASSERT(fiber->cont.type == FIBER_CONTEXT);
2053 VM_ASSERT(FIBER_RESUMED_P(fiber));
2055 th->root_fiber = fiber;
2056 DATA_PTR(fiber_value) = fiber;
2057 fiber->cont.self = fiber_value;
2059 coroutine_initialize_main(&fiber->context);
2061 return fiber;
2064 static inline rb_fiber_t*
2065 fiber_current(void)
2067 rb_execution_context_t *ec = GET_EC();
2068 if (ec->fiber_ptr->cont.self == 0) {
2069 root_fiber_alloc(rb_ec_thread_ptr(ec));
2071 return ec->fiber_ptr;
2074 static inline VALUE
2075 current_fiber_storage(void)
2077 rb_execution_context_t *ec = GET_EC();
2078 return ec->storage;
2081 static inline VALUE
2082 inherit_fiber_storage(void)
2084 return rb_obj_dup(current_fiber_storage());
2087 static inline void
2088 fiber_storage_set(struct rb_fiber_struct *fiber, VALUE storage)
2090 fiber->cont.saved_ec.storage = storage;
2093 static inline VALUE
2094 fiber_storage_get(rb_fiber_t *fiber, int allocate)
2096 VALUE storage = fiber->cont.saved_ec.storage;
2097 if (storage == Qnil && allocate) {
2098 storage = rb_hash_new();
2099 fiber_storage_set(fiber, storage);
2101 return storage;
2104 static void
2105 storage_access_must_be_from_same_fiber(VALUE self)
2107 rb_fiber_t *fiber = fiber_ptr(self);
2108 rb_fiber_t *current = fiber_current();
2109 if (fiber != current) {
2110 rb_raise(rb_eArgError, "Fiber storage can only be accessed from the Fiber it belongs to");
2115 * call-seq: fiber.storage -> hash (dup)
2117 * Returns a copy of the storage hash for the fiber. The method can only be called on the
2118 * Fiber.current.
2120 static VALUE
2121 rb_fiber_storage_get(VALUE self)
2123 storage_access_must_be_from_same_fiber(self);
2125 VALUE storage = fiber_storage_get(fiber_ptr(self), FALSE);
2127 if (storage == Qnil) {
2128 return Qnil;
2130 else {
2131 return rb_obj_dup(storage);
2135 static int
2136 fiber_storage_validate_each(VALUE key, VALUE value, VALUE _argument)
2138 Check_Type(key, T_SYMBOL);
2140 return ST_CONTINUE;
2143 static void
2144 fiber_storage_validate(VALUE value)
2146 // nil is an allowed value and will be lazily initialized.
2147 if (value == Qnil) return;
2149 if (!RB_TYPE_P(value, T_HASH)) {
2150 rb_raise(rb_eTypeError, "storage must be a hash");
2153 if (RB_OBJ_FROZEN(value)) {
2154 rb_raise(rb_eFrozenError, "storage must not be frozen");
2157 rb_hash_foreach(value, fiber_storage_validate_each, Qundef);
2161 * call-seq: fiber.storage = hash
2163 * Sets the storage hash for the fiber. This feature is experimental
2164 * and may change in the future. The method can only be called on the
2165 * Fiber.current.
2167 * You should be careful about using this method as you may inadvertently clear
2168 * important fiber-storage state. You should mostly prefer to assign specific
2169 * keys in the storage using Fiber::[]=.
2171 * You can also use <tt>Fiber.new(storage: nil)</tt> to create a fiber with an empty
2172 * storage.
2174 * Example:
2176 * while request = request_queue.pop
2177 * # Reset the per-request state:
2178 * Fiber.current.storage = nil
2179 * handle_request(request)
2180 * end
2182 static VALUE
2183 rb_fiber_storage_set(VALUE self, VALUE value)
2185 if (rb_warning_category_enabled_p(RB_WARN_CATEGORY_EXPERIMENTAL)) {
2186 rb_category_warn(RB_WARN_CATEGORY_EXPERIMENTAL,
2187 "Fiber#storage= is experimental and may be removed in the future!");
2190 storage_access_must_be_from_same_fiber(self);
2191 fiber_storage_validate(value);
2193 fiber_ptr(self)->cont.saved_ec.storage = rb_obj_dup(value);
2194 return value;
2198 * call-seq: Fiber[key] -> value
2200 * Returns the value of the fiber storage variable identified by +key+.
2202 * The +key+ must be a symbol, and the value is set by Fiber#[]= or
2203 * Fiber#store.
2205 * See also Fiber::[]=.
2207 static VALUE
2208 rb_fiber_storage_aref(VALUE class, VALUE key)
2210 Check_Type(key, T_SYMBOL);
2212 VALUE storage = fiber_storage_get(fiber_current(), FALSE);
2213 if (storage == Qnil) return Qnil;
2215 return rb_hash_aref(storage, key);
2219 * call-seq: Fiber[key] = value
2221 * Assign +value+ to the fiber storage variable identified by +key+.
2222 * The variable is created if it doesn't exist.
2224 * +key+ must be a Symbol, otherwise a TypeError is raised.
2226 * See also Fiber::[].
2228 static VALUE
2229 rb_fiber_storage_aset(VALUE class, VALUE key, VALUE value)
2231 Check_Type(key, T_SYMBOL);
2233 VALUE storage = fiber_storage_get(fiber_current(), value != Qnil);
2234 if (storage == Qnil) return Qnil;
2236 if (value == Qnil) {
2237 return rb_hash_delete(storage, key);
2239 else {
2240 return rb_hash_aset(storage, key, value);
2244 static VALUE
2245 fiber_initialize(VALUE self, VALUE proc, struct fiber_pool * fiber_pool, unsigned int blocking, VALUE storage)
2247 if (storage == Qundef || storage == Qtrue) {
2248 // The default, inherit storage (dup) from the current fiber:
2249 storage = inherit_fiber_storage();
2251 else /* nil, hash, etc. */ {
2252 fiber_storage_validate(storage);
2253 storage = rb_obj_dup(storage);
2256 rb_fiber_t *fiber = fiber_t_alloc(self, blocking);
2258 fiber->cont.saved_ec.storage = storage;
2259 fiber->first_proc = proc;
2260 fiber->stack.base = NULL;
2261 fiber->stack.pool = fiber_pool;
2263 return self;
2266 static void
2267 fiber_prepare_stack(rb_fiber_t *fiber)
2269 rb_context_t *cont = &fiber->cont;
2270 rb_execution_context_t *sec = &cont->saved_ec;
2272 size_t vm_stack_size = 0;
2273 VALUE *vm_stack = fiber_initialize_coroutine(fiber, &vm_stack_size);
2275 /* initialize cont */
2276 cont->saved_vm_stack.ptr = NULL;
2277 rb_ec_initialize_vm_stack(sec, vm_stack, vm_stack_size / sizeof(VALUE));
2279 sec->tag = NULL;
2280 sec->local_storage = NULL;
2281 sec->local_storage_recursive_hash = Qnil;
2282 sec->local_storage_recursive_hash_for_trace = Qnil;
2285 static struct fiber_pool *
2286 rb_fiber_pool_default(VALUE pool)
2288 return &shared_fiber_pool;
2291 VALUE rb_fiber_inherit_storage(struct rb_execution_context_struct *ec, struct rb_fiber_struct *fiber)
2293 VALUE storage = rb_obj_dup(ec->storage);
2294 fiber->cont.saved_ec.storage = storage;
2295 return storage;
2298 /* :nodoc: */
2299 static VALUE
2300 rb_fiber_initialize_kw(int argc, VALUE* argv, VALUE self, int kw_splat)
2302 VALUE pool = Qnil;
2303 VALUE blocking = Qfalse;
2304 VALUE storage = Qundef;
2306 if (kw_splat != RB_NO_KEYWORDS) {
2307 VALUE options = Qnil;
2308 VALUE arguments[3] = {Qundef};
2310 argc = rb_scan_args_kw(kw_splat, argc, argv, ":", &options);
2311 rb_get_kwargs(options, fiber_initialize_keywords, 0, 3, arguments);
2313 if (!UNDEF_P(arguments[0])) {
2314 blocking = arguments[0];
2317 if (!UNDEF_P(arguments[1])) {
2318 pool = arguments[1];
2321 storage = arguments[2];
2324 return fiber_initialize(self, rb_block_proc(), rb_fiber_pool_default(pool), RTEST(blocking), storage);
2328 * call-seq:
2329 * Fiber.new(blocking: false, storage: true) { |*args| ... } -> fiber
2331 * Creates new Fiber. Initially, the fiber is not running and can be resumed
2332 * with #resume. Arguments to the first #resume call will be passed to the
2333 * block:
2335 * f = Fiber.new do |initial|
2336 * current = initial
2337 * loop do
2338 * puts "current: #{current.inspect}"
2339 * current = Fiber.yield
2340 * end
2341 * end
2342 * f.resume(100) # prints: current: 100
2343 * f.resume(1, 2, 3) # prints: current: [1, 2, 3]
2344 * f.resume # prints: current: nil
2345 * # ... and so on ...
2347 * If <tt>blocking: false</tt> is passed to <tt>Fiber.new</tt>, _and_ current
2348 * thread has a Fiber.scheduler defined, the Fiber becomes non-blocking (see
2349 * "Non-blocking Fibers" section in class docs).
2351 * If the <tt>storage</tt> is unspecified, the default is to inherit a copy of
2352 * the storage from the current fiber. This is the same as specifying
2353 * <tt>storage: true</tt>.
2355 * Fiber[:x] = 1
2356 * Fiber.new do
2357 * Fiber[:x] # => 1
2358 * Fiber[:x] = 2
2359 * end.resume
2360 * Fiber[:x] # => 1
2362 * If the given <tt>storage</tt> is <tt>nil</tt>, this function will lazy
2363 * initialize the internal storage, which starts as an empty hash.
2365 * Fiber[:x] = "Hello World"
2366 * Fiber.new(storage: nil) do
2367 * Fiber[:x] # nil
2368 * end
2370 * Otherwise, the given <tt>storage</tt> is used as the new fiber's storage,
2371 * and it must be an instance of Hash.
2373 * Explicitly using <tt>storage: true</tt> is currently experimental and may
2374 * change in the future.
2376 static VALUE
2377 rb_fiber_initialize(int argc, VALUE* argv, VALUE self)
2379 return rb_fiber_initialize_kw(argc, argv, self, rb_keyword_given_p());
2382 VALUE
2383 rb_fiber_new_storage(rb_block_call_func_t func, VALUE obj, VALUE storage)
2385 return fiber_initialize(fiber_alloc(rb_cFiber), rb_proc_new(func, obj), rb_fiber_pool_default(Qnil), 0, storage);
2388 VALUE
2389 rb_fiber_new(rb_block_call_func_t func, VALUE obj)
2391 return rb_fiber_new_storage(func, obj, Qtrue);
2394 static VALUE
2395 rb_fiber_s_schedule_kw(int argc, VALUE* argv, int kw_splat)
2397 rb_thread_t * th = GET_THREAD();
2398 VALUE scheduler = th->scheduler;
2399 VALUE fiber = Qnil;
2401 if (scheduler != Qnil) {
2402 fiber = rb_fiber_scheduler_fiber(scheduler, argc, argv, kw_splat);
2404 else {
2405 rb_raise(rb_eRuntimeError, "No scheduler is available!");
2408 return fiber;
2412 * call-seq:
2413 * Fiber.schedule { |*args| ... } -> fiber
2415 * The method is <em>expected</em> to immediately run the provided block of code in a
2416 * separate non-blocking fiber.
2418 * puts "Go to sleep!"
2420 * Fiber.set_scheduler(MyScheduler.new)
2422 * Fiber.schedule do
2423 * puts "Going to sleep"
2424 * sleep(1)
2425 * puts "I slept well"
2426 * end
2428 * puts "Wakey-wakey, sleepyhead"
2430 * Assuming MyScheduler is properly implemented, this program will produce:
2432 * Go to sleep!
2433 * Going to sleep
2434 * Wakey-wakey, sleepyhead
2435 * ...1 sec pause here...
2436 * I slept well
2438 * ...e.g. on the first blocking operation inside the Fiber (<tt>sleep(1)</tt>),
2439 * the control is yielded to the outside code (main fiber), and <em>at the end
2440 * of that execution</em>, the scheduler takes care of properly resuming all the
2441 * blocked fibers.
2443 * Note that the behavior described above is how the method is <em>expected</em>
2444 * to behave, actual behavior is up to the current scheduler's implementation of
2445 * Fiber::Scheduler#fiber method. Ruby doesn't enforce this method to
2446 * behave in any particular way.
2448 * If the scheduler is not set, the method raises
2449 * <tt>RuntimeError (No scheduler is available!)</tt>.
2452 static VALUE
2453 rb_fiber_s_schedule(int argc, VALUE *argv, VALUE obj)
2455 return rb_fiber_s_schedule_kw(argc, argv, rb_keyword_given_p());
2459 * call-seq:
2460 * Fiber.scheduler -> obj or nil
2462 * Returns the Fiber scheduler, that was last set for the current thread with Fiber.set_scheduler.
2463 * Returns +nil+ if no scheduler is set (which is the default), and non-blocking fibers'
2464 * behavior is the same as blocking.
2465 * (see "Non-blocking fibers" section in class docs for details about the scheduler concept).
2468 static VALUE
2469 rb_fiber_s_scheduler(VALUE klass)
2471 return rb_fiber_scheduler_get();
2475 * call-seq:
2476 * Fiber.current_scheduler -> obj or nil
2478 * Returns the Fiber scheduler, that was last set for the current thread with Fiber.set_scheduler
2479 * if and only if the current fiber is non-blocking.
2482 static VALUE
2483 rb_fiber_current_scheduler(VALUE klass)
2485 return rb_fiber_scheduler_current();
2489 * call-seq:
2490 * Fiber.set_scheduler(scheduler) -> scheduler
2492 * Sets the Fiber scheduler for the current thread. If the scheduler is set, non-blocking
2493 * fibers (created by Fiber.new with <tt>blocking: false</tt>, or by Fiber.schedule)
2494 * call that scheduler's hook methods on potentially blocking operations, and the current
2495 * thread will call scheduler's +close+ method on finalization (allowing the scheduler to
2496 * properly manage all non-finished fibers).
2498 * +scheduler+ can be an object of any class corresponding to Fiber::Scheduler. Its
2499 * implementation is up to the user.
2501 * See also the "Non-blocking fibers" section in class docs.
2504 static VALUE
2505 rb_fiber_set_scheduler(VALUE klass, VALUE scheduler)
2507 return rb_fiber_scheduler_set(scheduler);
2510 NORETURN(static void rb_fiber_terminate(rb_fiber_t *fiber, int need_interrupt, VALUE err));
2512 void
2513 rb_fiber_start(rb_fiber_t *fiber)
2515 rb_thread_t * volatile th = fiber->cont.saved_ec.thread_ptr;
2517 rb_proc_t *proc;
2518 enum ruby_tag_type state;
2520 VM_ASSERT(th->ec == GET_EC());
2521 VM_ASSERT(FIBER_RESUMED_P(fiber));
2523 if (fiber->blocking) {
2524 th->blocking += 1;
2527 EC_PUSH_TAG(th->ec);
2528 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
2529 rb_context_t *cont = &VAR_FROM_MEMORY(fiber)->cont;
2530 int argc;
2531 const VALUE *argv, args = cont->value;
2532 GetProcPtr(fiber->first_proc, proc);
2533 argv = (argc = cont->argc) > 1 ? RARRAY_CONST_PTR(args) : &args;
2534 cont->value = Qnil;
2535 th->ec->errinfo = Qnil;
2536 th->ec->root_lep = rb_vm_proc_local_ep(fiber->first_proc);
2537 th->ec->root_svar = Qfalse;
2539 EXEC_EVENT_HOOK(th->ec, RUBY_EVENT_FIBER_SWITCH, th->self, 0, 0, 0, Qnil);
2540 cont->value = rb_vm_invoke_proc(th->ec, proc, argc, argv, cont->kw_splat, VM_BLOCK_HANDLER_NONE);
2542 EC_POP_TAG();
2544 int need_interrupt = TRUE;
2545 VALUE err = Qfalse;
2546 if (state) {
2547 err = th->ec->errinfo;
2548 VM_ASSERT(FIBER_RESUMED_P(fiber));
2550 if (state == TAG_RAISE) {
2551 // noop...
2553 else if (state == TAG_FATAL && err == RUBY_FATAL_FIBER_KILLED) {
2554 need_interrupt = FALSE;
2555 err = Qfalse;
2557 else if (state == TAG_FATAL) {
2558 rb_threadptr_pending_interrupt_enque(th, err);
2560 else {
2561 err = rb_vm_make_jump_tag_but_local_jump(state, err);
2565 rb_fiber_terminate(fiber, need_interrupt, err);
2568 // Set up a "root fiber", which is the fiber that every Ractor has.
2569 void
2570 rb_threadptr_root_fiber_setup(rb_thread_t *th)
2572 rb_fiber_t *fiber = ruby_mimcalloc(1, sizeof(rb_fiber_t));
2573 if (!fiber) {
2574 rb_bug("%s", strerror(errno)); /* ... is it possible to call rb_bug here? */
2576 fiber->cont.type = FIBER_CONTEXT;
2577 fiber->cont.saved_ec.fiber_ptr = fiber;
2578 fiber->cont.saved_ec.thread_ptr = th;
2579 fiber->blocking = 1;
2580 fiber->killed = 0;
2581 fiber_status_set(fiber, FIBER_RESUMED); /* skip CREATED */
2582 th->ec = &fiber->cont.saved_ec;
2583 cont_init_jit_cont(&fiber->cont);
2586 void
2587 rb_threadptr_root_fiber_release(rb_thread_t *th)
2589 if (th->root_fiber) {
2590 /* ignore. A root fiber object will free th->ec */
2592 else {
2593 rb_execution_context_t *ec = rb_current_execution_context(false);
2595 VM_ASSERT(th->ec->fiber_ptr->cont.type == FIBER_CONTEXT);
2596 VM_ASSERT(th->ec->fiber_ptr->cont.self == 0);
2598 if (ec && th->ec == ec) {
2599 rb_ractor_set_current_ec(th->ractor, NULL);
2601 fiber_free(th->ec->fiber_ptr);
2602 th->ec = NULL;
2606 void
2607 rb_threadptr_root_fiber_terminate(rb_thread_t *th)
2609 rb_fiber_t *fiber = th->ec->fiber_ptr;
2611 fiber->status = FIBER_TERMINATED;
2613 // The vm_stack is `alloca`ed on the thread stack, so it's gone too:
2614 rb_ec_clear_vm_stack(th->ec);
2617 static inline rb_fiber_t*
2618 return_fiber(bool terminate)
2620 rb_fiber_t *fiber = fiber_current();
2621 rb_fiber_t *prev = fiber->prev;
2623 if (prev) {
2624 fiber->prev = NULL;
2625 prev->resuming_fiber = NULL;
2626 return prev;
2628 else {
2629 if (!terminate) {
2630 rb_raise(rb_eFiberError, "attempt to yield on a not resumed fiber");
2633 rb_thread_t *th = GET_THREAD();
2634 rb_fiber_t *root_fiber = th->root_fiber;
2636 VM_ASSERT(root_fiber != NULL);
2638 // search resuming fiber
2639 for (fiber = root_fiber; fiber->resuming_fiber; fiber = fiber->resuming_fiber) {
2642 return fiber;
2646 VALUE
2647 rb_fiber_current(void)
2649 return fiber_current()->cont.self;
2652 // Prepare to execute next_fiber on the given thread.
2653 static inline void
2654 fiber_store(rb_fiber_t *next_fiber, rb_thread_t *th)
2656 rb_fiber_t *fiber;
2658 if (th->ec->fiber_ptr != NULL) {
2659 fiber = th->ec->fiber_ptr;
2661 else {
2662 /* create root fiber */
2663 fiber = root_fiber_alloc(th);
2666 if (FIBER_CREATED_P(next_fiber)) {
2667 fiber_prepare_stack(next_fiber);
2670 VM_ASSERT(FIBER_RESUMED_P(fiber) || FIBER_TERMINATED_P(fiber));
2671 VM_ASSERT(FIBER_RUNNABLE_P(next_fiber));
2673 if (FIBER_RESUMED_P(fiber)) fiber_status_set(fiber, FIBER_SUSPENDED);
2675 fiber_status_set(next_fiber, FIBER_RESUMED);
2676 fiber_setcontext(next_fiber, fiber);
2679 static void
2680 fiber_check_killed(rb_fiber_t *fiber)
2682 VM_ASSERT(fiber == fiber_current());
2684 if (fiber->killed) {
2685 rb_thread_t *thread = fiber->cont.saved_ec.thread_ptr;
2687 thread->ec->errinfo = RUBY_FATAL_FIBER_KILLED;
2688 EC_JUMP_TAG(thread->ec, RUBY_TAG_FATAL);
2692 static inline VALUE
2693 fiber_switch(rb_fiber_t *fiber, int argc, const VALUE *argv, int kw_splat, rb_fiber_t *resuming_fiber, bool yielding)
2695 VALUE value;
2696 rb_context_t *cont = &fiber->cont;
2697 rb_thread_t *th = GET_THREAD();
2699 /* make sure the root_fiber object is available */
2700 if (th->root_fiber == NULL) root_fiber_alloc(th);
2702 if (th->ec->fiber_ptr == fiber) {
2703 /* ignore fiber context switch
2704 * because destination fiber is the same as current fiber
2706 return make_passing_arg(argc, argv);
2709 if (cont_thread_value(cont) != th->self) {
2710 rb_raise(rb_eFiberError, "fiber called across threads");
2713 if (FIBER_TERMINATED_P(fiber)) {
2714 value = rb_exc_new2(rb_eFiberError, "dead fiber called");
2716 if (!FIBER_TERMINATED_P(th->ec->fiber_ptr)) {
2717 rb_exc_raise(value);
2718 VM_UNREACHABLE(fiber_switch);
2720 else {
2721 /* th->ec->fiber_ptr is also dead => switch to root fiber */
2722 /* (this means we're being called from rb_fiber_terminate, */
2723 /* and the terminated fiber's return_fiber() is already dead) */
2724 VM_ASSERT(FIBER_SUSPENDED_P(th->root_fiber));
2726 cont = &th->root_fiber->cont;
2727 cont->argc = -1;
2728 cont->value = value;
2730 fiber_setcontext(th->root_fiber, th->ec->fiber_ptr);
2732 VM_UNREACHABLE(fiber_switch);
2736 VM_ASSERT(FIBER_RUNNABLE_P(fiber));
2738 rb_fiber_t *current_fiber = fiber_current();
2740 VM_ASSERT(!current_fiber->resuming_fiber);
2742 if (resuming_fiber) {
2743 current_fiber->resuming_fiber = resuming_fiber;
2744 fiber->prev = fiber_current();
2745 fiber->yielding = 0;
2748 VM_ASSERT(!current_fiber->yielding);
2749 if (yielding) {
2750 current_fiber->yielding = 1;
2753 if (current_fiber->blocking) {
2754 th->blocking -= 1;
2757 cont->argc = argc;
2758 cont->kw_splat = kw_splat;
2759 cont->value = make_passing_arg(argc, argv);
2761 fiber_store(fiber, th);
2763 // We cannot free the stack until the pthread is joined:
2764 #ifndef COROUTINE_PTHREAD_CONTEXT
2765 if (resuming_fiber && FIBER_TERMINATED_P(fiber)) {
2766 fiber_stack_release(fiber);
2768 #endif
2770 if (fiber_current()->blocking) {
2771 th->blocking += 1;
2774 RUBY_VM_CHECK_INTS(th->ec);
2776 EXEC_EVENT_HOOK(th->ec, RUBY_EVENT_FIBER_SWITCH, th->self, 0, 0, 0, Qnil);
2778 current_fiber = th->ec->fiber_ptr;
2779 value = current_fiber->cont.value;
2781 fiber_check_killed(current_fiber);
2783 if (current_fiber->cont.argc == -1) {
2784 // Fiber#raise will trigger this path.
2785 rb_exc_raise(value);
2788 return value;
2791 VALUE
2792 rb_fiber_transfer(VALUE fiber_value, int argc, const VALUE *argv)
2794 return fiber_switch(fiber_ptr(fiber_value), argc, argv, RB_NO_KEYWORDS, NULL, false);
2798 * call-seq:
2799 * fiber.blocking? -> true or false
2801 * Returns +true+ if +fiber+ is blocking and +false+ otherwise.
2802 * Fiber is non-blocking if it was created via passing <tt>blocking: false</tt>
2803 * to Fiber.new, or via Fiber.schedule.
2805 * Note that, even if the method returns +false+, the fiber behaves differently
2806 * only if Fiber.scheduler is set in the current thread.
2808 * See the "Non-blocking fibers" section in class docs for details.
2811 VALUE
2812 rb_fiber_blocking_p(VALUE fiber)
2814 return RBOOL(fiber_ptr(fiber)->blocking);
2817 static VALUE
2818 fiber_blocking_yield(VALUE fiber_value)
2820 rb_fiber_t *fiber = fiber_ptr(fiber_value);
2821 rb_thread_t * volatile th = fiber->cont.saved_ec.thread_ptr;
2823 VM_ASSERT(fiber->blocking == 0);
2825 // fiber->blocking is `unsigned int : 1`, so we use it as a boolean:
2826 fiber->blocking = 1;
2828 // Once the fiber is blocking, and current, we increment the thread blocking state:
2829 th->blocking += 1;
2831 return rb_yield(fiber_value);
2834 static VALUE
2835 fiber_blocking_ensure(VALUE fiber_value)
2837 rb_fiber_t *fiber = fiber_ptr(fiber_value);
2838 rb_thread_t * volatile th = fiber->cont.saved_ec.thread_ptr;
2840 // We are no longer blocking:
2841 fiber->blocking = 0;
2842 th->blocking -= 1;
2844 return Qnil;
2848 * call-seq:
2849 * Fiber.blocking{|fiber| ...} -> result
2851 * Forces the fiber to be blocking for the duration of the block. Returns the
2852 * result of the block.
2854 * See the "Non-blocking fibers" section in class docs for details.
2857 VALUE
2858 rb_fiber_blocking(VALUE class)
2860 VALUE fiber_value = rb_fiber_current();
2861 rb_fiber_t *fiber = fiber_ptr(fiber_value);
2863 // If we are already blocking, this is essentially a no-op:
2864 if (fiber->blocking) {
2865 return rb_yield(fiber_value);
2867 else {
2868 return rb_ensure(fiber_blocking_yield, fiber_value, fiber_blocking_ensure, fiber_value);
2873 * call-seq:
2874 * Fiber.blocking? -> false or 1
2876 * Returns +false+ if the current fiber is non-blocking.
2877 * Fiber is non-blocking if it was created via passing <tt>blocking: false</tt>
2878 * to Fiber.new, or via Fiber.schedule.
2880 * If the current Fiber is blocking, the method returns 1.
2881 * Future developments may allow for situations where larger integers
2882 * could be returned.
2884 * Note that, even if the method returns +false+, Fiber behaves differently
2885 * only if Fiber.scheduler is set in the current thread.
2887 * See the "Non-blocking fibers" section in class docs for details.
2890 static VALUE
2891 rb_fiber_s_blocking_p(VALUE klass)
2893 rb_thread_t *thread = GET_THREAD();
2894 unsigned blocking = thread->blocking;
2896 if (blocking == 0)
2897 return Qfalse;
2899 return INT2NUM(blocking);
2902 void
2903 rb_fiber_close(rb_fiber_t *fiber)
2905 fiber_status_set(fiber, FIBER_TERMINATED);
2908 static void
2909 rb_fiber_terminate(rb_fiber_t *fiber, int need_interrupt, VALUE error)
2911 VALUE value = fiber->cont.value;
2913 VM_ASSERT(FIBER_RESUMED_P(fiber));
2914 rb_fiber_close(fiber);
2916 fiber->cont.machine.stack = NULL;
2917 fiber->cont.machine.stack_size = 0;
2919 rb_fiber_t *next_fiber = return_fiber(true);
2921 if (need_interrupt) RUBY_VM_SET_INTERRUPT(&next_fiber->cont.saved_ec);
2923 if (RTEST(error))
2924 fiber_switch(next_fiber, -1, &error, RB_NO_KEYWORDS, NULL, false);
2925 else
2926 fiber_switch(next_fiber, 1, &value, RB_NO_KEYWORDS, NULL, false);
2927 ruby_stop(0);
2930 static VALUE
2931 fiber_resume_kw(rb_fiber_t *fiber, int argc, const VALUE *argv, int kw_splat)
2933 rb_fiber_t *current_fiber = fiber_current();
2935 if (argc == -1 && FIBER_CREATED_P(fiber)) {
2936 rb_raise(rb_eFiberError, "cannot raise exception on unborn fiber");
2938 else if (FIBER_TERMINATED_P(fiber)) {
2939 rb_raise(rb_eFiberError, "attempt to resume a terminated fiber");
2941 else if (fiber == current_fiber) {
2942 rb_raise(rb_eFiberError, "attempt to resume the current fiber");
2944 else if (fiber->prev != NULL) {
2945 rb_raise(rb_eFiberError, "attempt to resume a resumed fiber (double resume)");
2947 else if (fiber->resuming_fiber) {
2948 rb_raise(rb_eFiberError, "attempt to resume a resuming fiber");
2950 else if (fiber->prev == NULL &&
2951 (!fiber->yielding && fiber->status != FIBER_CREATED)) {
2952 rb_raise(rb_eFiberError, "attempt to resume a transferring fiber");
2955 return fiber_switch(fiber, argc, argv, kw_splat, fiber, false);
2958 VALUE
2959 rb_fiber_resume_kw(VALUE self, int argc, const VALUE *argv, int kw_splat)
2961 return fiber_resume_kw(fiber_ptr(self), argc, argv, kw_splat);
2964 VALUE
2965 rb_fiber_resume(VALUE self, int argc, const VALUE *argv)
2967 return fiber_resume_kw(fiber_ptr(self), argc, argv, RB_NO_KEYWORDS);
2970 VALUE
2971 rb_fiber_yield_kw(int argc, const VALUE *argv, int kw_splat)
2973 return fiber_switch(return_fiber(false), argc, argv, kw_splat, NULL, true);
2976 VALUE
2977 rb_fiber_yield(int argc, const VALUE *argv)
2979 return fiber_switch(return_fiber(false), argc, argv, RB_NO_KEYWORDS, NULL, true);
2982 void
2983 rb_fiber_reset_root_local_storage(rb_thread_t *th)
2985 if (th->root_fiber && th->root_fiber != th->ec->fiber_ptr) {
2986 th->ec->local_storage = th->root_fiber->cont.saved_ec.local_storage;
2991 * call-seq:
2992 * fiber.alive? -> true or false
2994 * Returns true if the fiber can still be resumed (or transferred
2995 * to). After finishing execution of the fiber block this method will
2996 * always return +false+.
2998 VALUE
2999 rb_fiber_alive_p(VALUE fiber_value)
3001 return RBOOL(!FIBER_TERMINATED_P(fiber_ptr(fiber_value)));
3005 * call-seq:
3006 * fiber.resume(args, ...) -> obj
3008 * Resumes the fiber from the point at which the last Fiber.yield was
3009 * called, or starts running it if it is the first call to
3010 * #resume. Arguments passed to resume will be the value of the
3011 * Fiber.yield expression or will be passed as block parameters to
3012 * the fiber's block if this is the first #resume.
3014 * Alternatively, when resume is called it evaluates to the arguments passed
3015 * to the next Fiber.yield statement inside the fiber's block
3016 * or to the block value if it runs to completion without any
3017 * Fiber.yield
3019 static VALUE
3020 rb_fiber_m_resume(int argc, VALUE *argv, VALUE fiber)
3022 return rb_fiber_resume_kw(fiber, argc, argv, rb_keyword_given_p());
3026 * call-seq:
3027 * fiber.backtrace -> array
3028 * fiber.backtrace(start) -> array
3029 * fiber.backtrace(start, count) -> array
3030 * fiber.backtrace(start..end) -> array
3032 * Returns the current execution stack of the fiber. +start+, +count+ and +end+ allow
3033 * to select only parts of the backtrace.
3035 * def level3
3036 * Fiber.yield
3037 * end
3039 * def level2
3040 * level3
3041 * end
3043 * def level1
3044 * level2
3045 * end
3047 * f = Fiber.new { level1 }
3049 * # It is empty before the fiber started
3050 * f.backtrace
3051 * #=> []
3053 * f.resume
3055 * f.backtrace
3056 * #=> ["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>'"]
3057 * p f.backtrace(1) # start from the item 1
3058 * #=> ["test.rb:2:in `level3'", "test.rb:6:in `level2'", "test.rb:10:in `level1'", "test.rb:13:in `block in <main>'"]
3059 * p f.backtrace(2, 2) # start from item 2, take 2
3060 * #=> ["test.rb:6:in `level2'", "test.rb:10:in `level1'"]
3061 * p f.backtrace(1..3) # take items from 1 to 3
3062 * #=> ["test.rb:2:in `level3'", "test.rb:6:in `level2'", "test.rb:10:in `level1'"]
3064 * f.resume
3066 * # It is nil after the fiber is finished
3067 * f.backtrace
3068 * #=> nil
3071 static VALUE
3072 rb_fiber_backtrace(int argc, VALUE *argv, VALUE fiber)
3074 return rb_vm_backtrace(argc, argv, &fiber_ptr(fiber)->cont.saved_ec);
3078 * call-seq:
3079 * fiber.backtrace_locations -> array
3080 * fiber.backtrace_locations(start) -> array
3081 * fiber.backtrace_locations(start, count) -> array
3082 * fiber.backtrace_locations(start..end) -> array
3084 * Like #backtrace, but returns each line of the execution stack as a
3085 * Thread::Backtrace::Location. Accepts the same arguments as #backtrace.
3087 * f = Fiber.new { Fiber.yield }
3088 * f.resume
3089 * loc = f.backtrace_locations.first
3090 * loc.label #=> "yield"
3091 * loc.path #=> "test.rb"
3092 * loc.lineno #=> 1
3096 static VALUE
3097 rb_fiber_backtrace_locations(int argc, VALUE *argv, VALUE fiber)
3099 return rb_vm_backtrace_locations(argc, argv, &fiber_ptr(fiber)->cont.saved_ec);
3103 * call-seq:
3104 * fiber.transfer(args, ...) -> obj
3106 * Transfer control to another fiber, resuming it from where it last
3107 * stopped or starting it if it was not resumed before. The calling
3108 * fiber will be suspended much like in a call to
3109 * Fiber.yield.
3111 * The fiber which receives the transfer call treats it much like
3112 * a resume call. Arguments passed to transfer are treated like those
3113 * passed to resume.
3115 * The two style of control passing to and from fiber (one is #resume and
3116 * Fiber::yield, another is #transfer to and from fiber) can't be freely
3117 * mixed.
3119 * * If the Fiber's lifecycle had started with transfer, it will never
3120 * be able to yield or be resumed control passing, only
3121 * finish or transfer back. (It still can resume other fibers that
3122 * are allowed to be resumed.)
3123 * * If the Fiber's lifecycle had started with resume, it can yield
3124 * or transfer to another Fiber, but can receive control back only
3125 * the way compatible with the way it was given away: if it had
3126 * transferred, it only can be transferred back, and if it had
3127 * yielded, it only can be resumed back. After that, it again can
3128 * transfer or yield.
3130 * If those rules are broken FiberError is raised.
3132 * For an individual Fiber design, yield/resume is easier to use
3133 * (the Fiber just gives away control, it doesn't need to think
3134 * about who the control is given to), while transfer is more flexible
3135 * for complex cases, allowing to build arbitrary graphs of Fibers
3136 * dependent on each other.
3139 * Example:
3141 * manager = nil # For local var to be visible inside worker block
3143 * # This fiber would be started with transfer
3144 * # It can't yield, and can't be resumed
3145 * worker = Fiber.new { |work|
3146 * puts "Worker: starts"
3147 * puts "Worker: Performed #{work.inspect}, transferring back"
3148 * # Fiber.yield # this would raise FiberError: attempt to yield on a not resumed fiber
3149 * # manager.resume # this would raise FiberError: attempt to resume a resumed fiber (double resume)
3150 * manager.transfer(work.capitalize)
3153 * # This fiber would be started with resume
3154 * # It can yield or transfer, and can be transferred
3155 * # back or resumed
3156 * manager = Fiber.new {
3157 * puts "Manager: starts"
3158 * puts "Manager: transferring 'something' to worker"
3159 * result = worker.transfer('something')
3160 * puts "Manager: worker returned #{result.inspect}"
3161 * # worker.resume # this would raise FiberError: attempt to resume a transferring fiber
3162 * Fiber.yield # this is OK, the fiber transferred from and to, now it can yield
3163 * puts "Manager: finished"
3166 * puts "Starting the manager"
3167 * manager.resume
3168 * puts "Resuming the manager"
3169 * # manager.transfer # this would raise FiberError: attempt to transfer to a yielding fiber
3170 * manager.resume
3172 * <em>produces</em>
3174 * Starting the manager
3175 * Manager: starts
3176 * Manager: transferring 'something' to worker
3177 * Worker: starts
3178 * Worker: Performed "something", transferring back
3179 * Manager: worker returned "Something"
3180 * Resuming the manager
3181 * Manager: finished
3184 static VALUE
3185 rb_fiber_m_transfer(int argc, VALUE *argv, VALUE self)
3187 return rb_fiber_transfer_kw(self, argc, argv, rb_keyword_given_p());
3190 static VALUE
3191 fiber_transfer_kw(rb_fiber_t *fiber, int argc, const VALUE *argv, int kw_splat)
3193 if (fiber->resuming_fiber) {
3194 rb_raise(rb_eFiberError, "attempt to transfer to a resuming fiber");
3197 if (fiber->yielding) {
3198 rb_raise(rb_eFiberError, "attempt to transfer to a yielding fiber");
3201 return fiber_switch(fiber, argc, argv, kw_splat, NULL, false);
3204 VALUE
3205 rb_fiber_transfer_kw(VALUE self, int argc, const VALUE *argv, int kw_splat)
3207 return fiber_transfer_kw(fiber_ptr(self), argc, argv, kw_splat);
3211 * call-seq:
3212 * Fiber.yield(args, ...) -> obj
3214 * Yields control back to the context that resumed the fiber, passing
3215 * along any arguments that were passed to it. The fiber will resume
3216 * processing at this point when #resume is called next.
3217 * Any arguments passed to the next #resume will be the value that
3218 * this Fiber.yield expression evaluates to.
3220 static VALUE
3221 rb_fiber_s_yield(int argc, VALUE *argv, VALUE klass)
3223 return rb_fiber_yield_kw(argc, argv, rb_keyword_given_p());
3226 static VALUE
3227 fiber_raise(rb_fiber_t *fiber, VALUE exception)
3229 if (fiber == fiber_current()) {
3230 rb_exc_raise(exception);
3232 else if (fiber->resuming_fiber) {
3233 return fiber_raise(fiber->resuming_fiber, exception);
3235 else if (FIBER_SUSPENDED_P(fiber) && !fiber->yielding) {
3236 return fiber_transfer_kw(fiber, -1, &exception, RB_NO_KEYWORDS);
3238 else {
3239 return fiber_resume_kw(fiber, -1, &exception, RB_NO_KEYWORDS);
3243 VALUE
3244 rb_fiber_raise(VALUE fiber, int argc, const VALUE *argv)
3246 VALUE exception = rb_make_exception(argc, argv);
3248 return fiber_raise(fiber_ptr(fiber), exception);
3252 * call-seq:
3253 * fiber.raise -> obj
3254 * fiber.raise(string) -> obj
3255 * fiber.raise(exception [, string [, array]]) -> obj
3257 * Raises an exception in the fiber at the point at which the last
3258 * +Fiber.yield+ was called. If the fiber has not been started or has
3259 * already run to completion, raises +FiberError+. If the fiber is
3260 * yielding, it is resumed. If it is transferring, it is transferred into.
3261 * But if it is resuming, raises +FiberError+.
3263 * With no arguments, raises a +RuntimeError+. With a single +String+
3264 * argument, raises a +RuntimeError+ with the string as a message. Otherwise,
3265 * the first parameter should be the name of an +Exception+ class (or an
3266 * object that returns an +Exception+ object when sent an +exception+
3267 * message). The optional second parameter sets the message associated with
3268 * the exception, and the third parameter is an array of callback information.
3269 * Exceptions are caught by the +rescue+ clause of <code>begin...end</code>
3270 * blocks.
3272 * Raises +FiberError+ if called on a Fiber belonging to another +Thread+.
3274 * See Kernel#raise for more information.
3276 static VALUE
3277 rb_fiber_m_raise(int argc, VALUE *argv, VALUE self)
3279 return rb_fiber_raise(self, argc, argv);
3283 * call-seq:
3284 * fiber.kill -> nil
3286 * Terminates the fiber by raising an uncatchable exception.
3287 * It only terminates the given fiber and no other fiber, returning +nil+ to
3288 * another fiber if that fiber was calling #resume or #transfer.
3290 * <tt>Fiber#kill</tt> only interrupts another fiber when it is in Fiber.yield.
3291 * If called on the current fiber then it raises that exception at the <tt>Fiber#kill</tt> call site.
3293 * If the fiber has not been started, transition directly to the terminated state.
3295 * If the fiber is already terminated, does nothing.
3297 * Raises FiberError if called on a fiber belonging to another thread.
3299 static VALUE
3300 rb_fiber_m_kill(VALUE self)
3302 rb_fiber_t *fiber = fiber_ptr(self);
3304 if (fiber->killed) return Qfalse;
3305 fiber->killed = 1;
3307 if (fiber->status == FIBER_CREATED) {
3308 fiber->status = FIBER_TERMINATED;
3310 else if (fiber->status != FIBER_TERMINATED) {
3311 if (fiber_current() == fiber) {
3312 fiber_check_killed(fiber);
3314 else {
3315 fiber_raise(fiber_ptr(self), Qnil);
3319 return self;
3323 * call-seq:
3324 * Fiber.current -> fiber
3326 * Returns the current fiber. If you are not running in the context of
3327 * a fiber this method will return the root fiber.
3329 static VALUE
3330 rb_fiber_s_current(VALUE klass)
3332 return rb_fiber_current();
3335 static VALUE
3336 fiber_to_s(VALUE fiber_value)
3338 const rb_fiber_t *fiber = fiber_ptr(fiber_value);
3339 const rb_proc_t *proc;
3340 char status_info[0x20];
3342 if (fiber->resuming_fiber) {
3343 snprintf(status_info, 0x20, " (%s by resuming)", fiber_status_name(fiber->status));
3345 else {
3346 snprintf(status_info, 0x20, " (%s)", fiber_status_name(fiber->status));
3349 if (!rb_obj_is_proc(fiber->first_proc)) {
3350 VALUE str = rb_any_to_s(fiber_value);
3351 strlcat(status_info, ">", sizeof(status_info));
3352 rb_str_set_len(str, RSTRING_LEN(str)-1);
3353 rb_str_cat_cstr(str, status_info);
3354 return str;
3356 GetProcPtr(fiber->first_proc, proc);
3357 return rb_block_to_s(fiber_value, &proc->block, status_info);
3360 #ifdef HAVE_WORKING_FORK
3361 void
3362 rb_fiber_atfork(rb_thread_t *th)
3364 if (th->root_fiber) {
3365 if (&th->root_fiber->cont.saved_ec != th->ec) {
3366 th->root_fiber = th->ec->fiber_ptr;
3368 th->root_fiber->prev = 0;
3371 #endif
3373 #ifdef RB_EXPERIMENTAL_FIBER_POOL
3374 static void
3375 fiber_pool_free(void *ptr)
3377 struct fiber_pool * fiber_pool = ptr;
3378 RUBY_FREE_ENTER("fiber_pool");
3380 fiber_pool_allocation_free(fiber_pool->allocations);
3381 ruby_xfree(fiber_pool);
3383 RUBY_FREE_LEAVE("fiber_pool");
3386 static size_t
3387 fiber_pool_memsize(const void *ptr)
3389 const struct fiber_pool * fiber_pool = ptr;
3390 size_t size = sizeof(*fiber_pool);
3392 size += fiber_pool->count * fiber_pool->size;
3394 return size;
3397 static const rb_data_type_t FiberPoolDataType = {
3398 "fiber_pool",
3399 {NULL, fiber_pool_free, fiber_pool_memsize,},
3400 0, 0, RUBY_TYPED_FREE_IMMEDIATELY
3403 static VALUE
3404 fiber_pool_alloc(VALUE klass)
3406 struct fiber_pool *fiber_pool;
3408 return TypedData_Make_Struct(klass, struct fiber_pool, &FiberPoolDataType, fiber_pool);
3411 static VALUE
3412 rb_fiber_pool_initialize(int argc, VALUE* argv, VALUE self)
3414 rb_thread_t *th = GET_THREAD();
3415 VALUE size = Qnil, count = Qnil, vm_stack_size = Qnil;
3416 struct fiber_pool * fiber_pool = NULL;
3418 // Maybe these should be keyword arguments.
3419 rb_scan_args(argc, argv, "03", &size, &count, &vm_stack_size);
3421 if (NIL_P(size)) {
3422 size = SIZET2NUM(th->vm->default_params.fiber_machine_stack_size);
3425 if (NIL_P(count)) {
3426 count = INT2NUM(128);
3429 if (NIL_P(vm_stack_size)) {
3430 vm_stack_size = SIZET2NUM(th->vm->default_params.fiber_vm_stack_size);
3433 TypedData_Get_Struct(self, struct fiber_pool, &FiberPoolDataType, fiber_pool);
3435 fiber_pool_initialize(fiber_pool, NUM2SIZET(size), NUM2SIZET(count), NUM2SIZET(vm_stack_size));
3437 return self;
3439 #endif
3442 * Document-class: FiberError
3444 * Raised when an invalid operation is attempted on a Fiber, in
3445 * particular when attempting to call/resume a dead fiber,
3446 * attempting to yield from the root fiber, or calling a fiber across
3447 * threads.
3449 * fiber = Fiber.new{}
3450 * fiber.resume #=> nil
3451 * fiber.resume #=> FiberError: dead fiber called
3454 void
3455 Init_Cont(void)
3457 rb_thread_t *th = GET_THREAD();
3458 size_t vm_stack_size = th->vm->default_params.fiber_vm_stack_size;
3459 size_t machine_stack_size = th->vm->default_params.fiber_machine_stack_size;
3460 size_t stack_size = machine_stack_size + vm_stack_size;
3462 #ifdef _WIN32
3463 SYSTEM_INFO info;
3464 GetSystemInfo(&info);
3465 pagesize = info.dwPageSize;
3466 #else /* not WIN32 */
3467 pagesize = sysconf(_SC_PAGESIZE);
3468 #endif
3469 SET_MACHINE_STACK_END(&th->ec->machine.stack_end);
3471 fiber_pool_initialize(&shared_fiber_pool, stack_size, FIBER_POOL_INITIAL_SIZE, vm_stack_size);
3473 fiber_initialize_keywords[0] = rb_intern_const("blocking");
3474 fiber_initialize_keywords[1] = rb_intern_const("pool");
3475 fiber_initialize_keywords[2] = rb_intern_const("storage");
3477 const char *fiber_shared_fiber_pool_free_stacks = getenv("RUBY_SHARED_FIBER_POOL_FREE_STACKS");
3478 if (fiber_shared_fiber_pool_free_stacks) {
3479 shared_fiber_pool.free_stacks = atoi(fiber_shared_fiber_pool_free_stacks);
3481 if (shared_fiber_pool.free_stacks < 0) {
3482 rb_warn("Setting RUBY_SHARED_FIBER_POOL_FREE_STACKS to a negative value is not allowed.");
3483 shared_fiber_pool.free_stacks = 0;
3486 if (shared_fiber_pool.free_stacks > 1) {
3487 rb_warn("Setting RUBY_SHARED_FIBER_POOL_FREE_STACKS to a value greater than 1 is operating system specific, and may cause crashes.");
3491 rb_cFiber = rb_define_class("Fiber", rb_cObject);
3492 rb_define_alloc_func(rb_cFiber, fiber_alloc);
3493 rb_eFiberError = rb_define_class("FiberError", rb_eStandardError);
3494 rb_define_singleton_method(rb_cFiber, "yield", rb_fiber_s_yield, -1);
3495 rb_define_singleton_method(rb_cFiber, "current", rb_fiber_s_current, 0);
3496 rb_define_singleton_method(rb_cFiber, "blocking", rb_fiber_blocking, 0);
3497 rb_define_singleton_method(rb_cFiber, "[]", rb_fiber_storage_aref, 1);
3498 rb_define_singleton_method(rb_cFiber, "[]=", rb_fiber_storage_aset, 2);
3500 rb_define_method(rb_cFiber, "initialize", rb_fiber_initialize, -1);
3501 rb_define_method(rb_cFiber, "blocking?", rb_fiber_blocking_p, 0);
3502 rb_define_method(rb_cFiber, "storage", rb_fiber_storage_get, 0);
3503 rb_define_method(rb_cFiber, "storage=", rb_fiber_storage_set, 1);
3504 rb_define_method(rb_cFiber, "resume", rb_fiber_m_resume, -1);
3505 rb_define_method(rb_cFiber, "raise", rb_fiber_m_raise, -1);
3506 rb_define_method(rb_cFiber, "kill", rb_fiber_m_kill, 0);
3507 rb_define_method(rb_cFiber, "backtrace", rb_fiber_backtrace, -1);
3508 rb_define_method(rb_cFiber, "backtrace_locations", rb_fiber_backtrace_locations, -1);
3509 rb_define_method(rb_cFiber, "to_s", fiber_to_s, 0);
3510 rb_define_alias(rb_cFiber, "inspect", "to_s");
3511 rb_define_method(rb_cFiber, "transfer", rb_fiber_m_transfer, -1);
3512 rb_define_method(rb_cFiber, "alive?", rb_fiber_alive_p, 0);
3514 rb_define_singleton_method(rb_cFiber, "blocking?", rb_fiber_s_blocking_p, 0);
3515 rb_define_singleton_method(rb_cFiber, "scheduler", rb_fiber_s_scheduler, 0);
3516 rb_define_singleton_method(rb_cFiber, "set_scheduler", rb_fiber_set_scheduler, 1);
3517 rb_define_singleton_method(rb_cFiber, "current_scheduler", rb_fiber_current_scheduler, 0);
3519 rb_define_singleton_method(rb_cFiber, "schedule", rb_fiber_s_schedule, -1);
3521 #ifdef RB_EXPERIMENTAL_FIBER_POOL
3522 rb_cFiberPool = rb_define_class_under(rb_cFiber, "Pool", rb_cObject);
3523 rb_define_alloc_func(rb_cFiberPool, fiber_pool_alloc);
3524 rb_define_method(rb_cFiberPool, "initialize", rb_fiber_pool_initialize, -1);
3525 #endif
3527 rb_provide("fiber.so");
3530 RUBY_SYMBOL_EXPORT_BEGIN
3532 void
3533 ruby_Init_Continuation_body(void)
3535 rb_cContinuation = rb_define_class("Continuation", rb_cObject);
3536 rb_undef_alloc_func(rb_cContinuation);
3537 rb_undef_method(CLASS_OF(rb_cContinuation), "new");
3538 rb_define_method(rb_cContinuation, "call", rb_cont_call, -1);
3539 rb_define_method(rb_cContinuation, "[]", rb_cont_call, -1);
3540 rb_define_global_function("callcc", rb_callcc, 0);
3543 RUBY_SYMBOL_EXPORT_END