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