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