Ruby 4.0.0dev (2025-12-23 revision 515119541095bcb84cb8d85db644d836eeeeef33)
cont.c (515119541095bcb84cb8d85db644d836eeeeef33)
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_serial_t
1999next_ec_serial(rb_ractor_t *cr)
2000{
2001 return cr->next_ec_serial++;
2002}
2003
2004static rb_fiber_t*
2005fiber_t_alloc(VALUE fiber_value, unsigned int blocking)
2006{
2007 rb_fiber_t *fiber;
2008 rb_thread_t *th = GET_THREAD();
2009
2010 if (DATA_PTR(fiber_value) != 0) {
2011 rb_raise(rb_eRuntimeError, "cannot initialize twice");
2012 }
2013
2014 THREAD_MUST_BE_RUNNING(th);
2015 fiber = ZALLOC(rb_fiber_t);
2016 fiber->cont.self = fiber_value;
2017 fiber->cont.type = FIBER_CONTEXT;
2018 fiber->blocking = blocking;
2019 fiber->killed = 0;
2020 cont_init(&fiber->cont, th);
2021
2022 fiber->cont.saved_ec.fiber_ptr = fiber;
2023 fiber->cont.saved_ec.serial = next_ec_serial(th->ractor);
2024 rb_ec_clear_vm_stack(&fiber->cont.saved_ec);
2025
2026 fiber->prev = NULL;
2027
2028 /* fiber->status == 0 == CREATED
2029 * So that we don't need to set status: fiber_status_set(fiber, FIBER_CREATED); */
2030 VM_ASSERT(FIBER_CREATED_P(fiber));
2031
2032 DATA_PTR(fiber_value) = fiber;
2033
2034 return fiber;
2035}
2036
2037static rb_fiber_t *
2038root_fiber_alloc(rb_thread_t *th)
2039{
2040 VALUE fiber_value = fiber_alloc(rb_cFiber);
2041 rb_fiber_t *fiber = th->ec->fiber_ptr;
2042
2043 VM_ASSERT(DATA_PTR(fiber_value) == NULL);
2044 VM_ASSERT(fiber->cont.type == FIBER_CONTEXT);
2045 VM_ASSERT(FIBER_RESUMED_P(fiber));
2046
2047 th->root_fiber = fiber;
2048 DATA_PTR(fiber_value) = fiber;
2049 fiber->cont.self = fiber_value;
2050
2051 coroutine_initialize_main(&fiber->context);
2052
2053 return fiber;
2054}
2055
2056static inline rb_fiber_t*
2057fiber_current(void)
2058{
2059 rb_execution_context_t *ec = GET_EC();
2060 if (ec->fiber_ptr->cont.self == 0) {
2061 root_fiber_alloc(rb_ec_thread_ptr(ec));
2062 }
2063 return ec->fiber_ptr;
2064}
2065
2066static inline VALUE
2067current_fiber_storage(void)
2068{
2069 rb_execution_context_t *ec = GET_EC();
2070 return ec->storage;
2071}
2072
2073static inline VALUE
2074inherit_fiber_storage(void)
2075{
2076 return rb_obj_dup(current_fiber_storage());
2077}
2078
2079static inline void
2080fiber_storage_set(struct rb_fiber_struct *fiber, VALUE storage)
2081{
2082 fiber->cont.saved_ec.storage = storage;
2083}
2084
2085static inline VALUE
2086fiber_storage_get(rb_fiber_t *fiber, int allocate)
2087{
2088 VALUE storage = fiber->cont.saved_ec.storage;
2089 if (storage == Qnil && allocate) {
2090 storage = rb_hash_new();
2091 fiber_storage_set(fiber, storage);
2092 }
2093 return storage;
2094}
2095
2096static void
2097storage_access_must_be_from_same_fiber(VALUE self)
2098{
2099 rb_fiber_t *fiber = fiber_ptr(self);
2100 rb_fiber_t *current = fiber_current();
2101 if (fiber != current) {
2102 rb_raise(rb_eArgError, "Fiber storage can only be accessed from the Fiber it belongs to");
2103 }
2104}
2105
2112static VALUE
2113rb_fiber_storage_get(VALUE self)
2114{
2115 storage_access_must_be_from_same_fiber(self);
2116
2117 VALUE storage = fiber_storage_get(fiber_ptr(self), FALSE);
2118
2119 if (storage == Qnil) {
2120 return Qnil;
2121 }
2122 else {
2123 return rb_obj_dup(storage);
2124 }
2125}
2126
2127static int
2128fiber_storage_validate_each(VALUE key, VALUE value, VALUE _argument)
2129{
2130 Check_Type(key, T_SYMBOL);
2131
2132 return ST_CONTINUE;
2133}
2134
2135static void
2136fiber_storage_validate(VALUE value)
2137{
2138 // nil is an allowed value and will be lazily initialized.
2139 if (value == Qnil) return;
2140
2141 if (!RB_TYPE_P(value, T_HASH)) {
2142 rb_raise(rb_eTypeError, "storage must be a hash");
2143 }
2144
2145 if (RB_OBJ_FROZEN(value)) {
2146 rb_raise(rb_eFrozenError, "storage must not be frozen");
2147 }
2148
2149 rb_hash_foreach(value, fiber_storage_validate_each, Qundef);
2150}
2151
2174static VALUE
2175rb_fiber_storage_set(VALUE self, VALUE value)
2176{
2177 if (rb_warning_category_enabled_p(RB_WARN_CATEGORY_EXPERIMENTAL)) {
2179 "Fiber#storage= is experimental and may be removed in the future!");
2180 }
2181
2182 storage_access_must_be_from_same_fiber(self);
2183 fiber_storage_validate(value);
2184
2185 fiber_ptr(self)->cont.saved_ec.storage = rb_obj_dup(value);
2186 return value;
2187}
2188
2199static VALUE
2200rb_fiber_storage_aref(VALUE class, VALUE key)
2201{
2202 key = rb_to_symbol(key);
2203
2204 VALUE storage = fiber_storage_get(fiber_current(), FALSE);
2205 if (storage == Qnil) return Qnil;
2206
2207 return rb_hash_aref(storage, key);
2208}
2209
2220static VALUE
2221rb_fiber_storage_aset(VALUE class, VALUE key, VALUE value)
2222{
2223 key = rb_to_symbol(key);
2224
2225 VALUE storage = fiber_storage_get(fiber_current(), value != Qnil);
2226 if (storage == Qnil) return Qnil;
2227
2228 if (value == Qnil) {
2229 return rb_hash_delete(storage, key);
2230 }
2231 else {
2232 return rb_hash_aset(storage, key, value);
2233 }
2234}
2235
2236static VALUE
2237fiber_initialize(VALUE self, VALUE proc, struct fiber_pool * fiber_pool, unsigned int blocking, VALUE storage)
2238{
2239 if (storage == Qundef || storage == Qtrue) {
2240 // The default, inherit storage (dup) from the current fiber:
2241 storage = inherit_fiber_storage();
2242 }
2243 else /* nil, hash, etc. */ {
2244 fiber_storage_validate(storage);
2245 storage = rb_obj_dup(storage);
2246 }
2247
2248 rb_fiber_t *fiber = fiber_t_alloc(self, blocking);
2249
2250 fiber->cont.saved_ec.storage = storage;
2251 fiber->first_proc = proc;
2252 fiber->stack.base = NULL;
2253 fiber->stack.pool = fiber_pool;
2254
2255 return self;
2256}
2257
2258static void
2259fiber_prepare_stack(rb_fiber_t *fiber)
2260{
2261 rb_context_t *cont = &fiber->cont;
2262 rb_execution_context_t *sec = &cont->saved_ec;
2263
2264 size_t vm_stack_size = 0;
2265 VALUE *vm_stack = fiber_initialize_coroutine(fiber, &vm_stack_size);
2266
2267 /* initialize cont */
2268 cont->saved_vm_stack.ptr = NULL;
2269 rb_ec_initialize_vm_stack(sec, vm_stack, vm_stack_size / sizeof(VALUE));
2270
2271 sec->tag = NULL;
2272 sec->local_storage = NULL;
2273 sec->local_storage_recursive_hash = Qnil;
2274 sec->local_storage_recursive_hash_for_trace = Qnil;
2275}
2276
2277static struct fiber_pool *
2278rb_fiber_pool_default(VALUE pool)
2279{
2280 return &shared_fiber_pool;
2281}
2282
2283VALUE rb_fiber_inherit_storage(struct rb_execution_context_struct *ec, struct rb_fiber_struct *fiber)
2284{
2285 VALUE storage = rb_obj_dup(ec->storage);
2286 fiber->cont.saved_ec.storage = storage;
2287 return storage;
2288}
2289
2290/* :nodoc: */
2291static VALUE
2292rb_fiber_initialize_kw(int argc, VALUE* argv, VALUE self, int kw_splat)
2293{
2294 VALUE pool = Qnil;
2295 VALUE blocking = Qfalse;
2296 VALUE storage = Qundef;
2297
2298 if (kw_splat != RB_NO_KEYWORDS) {
2299 VALUE options = Qnil;
2300 VALUE arguments[3] = {Qundef};
2301
2302 argc = rb_scan_args_kw(kw_splat, argc, argv, ":", &options);
2303 rb_get_kwargs(options, fiber_initialize_keywords, 0, 3, arguments);
2304
2305 if (!UNDEF_P(arguments[0])) {
2306 blocking = arguments[0];
2307 }
2308
2309 if (!UNDEF_P(arguments[1])) {
2310 pool = arguments[1];
2311 }
2312
2313 storage = arguments[2];
2314 }
2315
2316 return fiber_initialize(self, rb_block_proc(), rb_fiber_pool_default(pool), RTEST(blocking), storage);
2317}
2318
2319/*
2320 * call-seq:
2321 * Fiber.new(blocking: false, storage: true) { |*args| ... } -> fiber
2322 *
2323 * Creates new Fiber. Initially, the fiber is not running and can be resumed
2324 * with #resume. Arguments to the first #resume call will be passed to the
2325 * block:
2326 *
2327 * f = Fiber.new do |initial|
2328 * current = initial
2329 * loop do
2330 * puts "current: #{current.inspect}"
2331 * current = Fiber.yield
2332 * end
2333 * end
2334 * f.resume(100) # prints: current: 100
2335 * f.resume(1, 2, 3) # prints: current: [1, 2, 3]
2336 * f.resume # prints: current: nil
2337 * # ... and so on ...
2338 *
2339 * If <tt>blocking: false</tt> is passed to <tt>Fiber.new</tt>, _and_ current
2340 * thread has a Fiber.scheduler defined, the Fiber becomes non-blocking (see
2341 * "Non-blocking Fibers" section in class docs).
2342 *
2343 * If the <tt>storage</tt> is unspecified, the default is to inherit a copy of
2344 * the storage from the current fiber. This is the same as specifying
2345 * <tt>storage: true</tt>.
2346 *
2347 * Fiber[:x] = 1
2348 * Fiber.new do
2349 * Fiber[:x] # => 1
2350 * Fiber[:x] = 2
2351 * end.resume
2352 * Fiber[:x] # => 1
2353 *
2354 * If the given <tt>storage</tt> is <tt>nil</tt>, this function will lazy
2355 * initialize the internal storage, which starts as an empty hash.
2356 *
2357 * Fiber[:x] = "Hello World"
2358 * Fiber.new(storage: nil) do
2359 * Fiber[:x] # nil
2360 * end
2361 *
2362 * Otherwise, the given <tt>storage</tt> is used as the new fiber's storage,
2363 * and it must be an instance of Hash.
2364 *
2365 * Explicitly using <tt>storage: true</tt> is currently experimental and may
2366 * change in the future.
2367 */
2368static VALUE
2369rb_fiber_initialize(int argc, VALUE* argv, VALUE self)
2370{
2371 return rb_fiber_initialize_kw(argc, argv, self, rb_keyword_given_p());
2372}
2373
2374VALUE
2375rb_fiber_new_storage(rb_block_call_func_t func, VALUE obj, VALUE storage)
2376{
2377 return fiber_initialize(fiber_alloc(rb_cFiber), rb_proc_new(func, obj), rb_fiber_pool_default(Qnil), 0, storage);
2378}
2379
2380VALUE
2381rb_fiber_new(rb_block_call_func_t func, VALUE obj)
2382{
2383 return rb_fiber_new_storage(func, obj, Qtrue);
2384}
2385
2386static VALUE
2387rb_fiber_s_schedule_kw(int argc, VALUE* argv, int kw_splat)
2388{
2389 rb_thread_t * th = GET_THREAD();
2390 VALUE scheduler = th->scheduler;
2391 VALUE fiber = Qnil;
2392
2393 if (scheduler != Qnil) {
2394 fiber = rb_fiber_scheduler_fiber(scheduler, argc, argv, kw_splat);
2395 }
2396 else {
2397 rb_raise(rb_eRuntimeError, "No scheduler is available!");
2398 }
2399
2400 return fiber;
2401}
2402
2403/*
2404 * call-seq:
2405 * Fiber.schedule { |*args| ... } -> fiber
2406 *
2407 * The method is <em>expected</em> to immediately run the provided block of code in a
2408 * separate non-blocking fiber.
2409 *
2410 * puts "Go to sleep!"
2411 *
2412 * Fiber.set_scheduler(MyScheduler.new)
2413 *
2414 * Fiber.schedule do
2415 * puts "Going to sleep"
2416 * sleep(1)
2417 * puts "I slept well"
2418 * end
2419 *
2420 * puts "Wakey-wakey, sleepyhead"
2421 *
2422 * Assuming MyScheduler is properly implemented, this program will produce:
2423 *
2424 * Go to sleep!
2425 * Going to sleep
2426 * Wakey-wakey, sleepyhead
2427 * ...1 sec pause here...
2428 * I slept well
2429 *
2430 * ...e.g. on the first blocking operation inside the Fiber (<tt>sleep(1)</tt>),
2431 * the control is yielded to the outside code (main fiber), and <em>at the end
2432 * of that execution</em>, the scheduler takes care of properly resuming all the
2433 * blocked fibers.
2434 *
2435 * Note that the behavior described above is how the method is <em>expected</em>
2436 * to behave, actual behavior is up to the current scheduler's implementation of
2437 * Fiber::Scheduler#fiber method. Ruby doesn't enforce this method to
2438 * behave in any particular way.
2439 *
2440 * If the scheduler is not set, the method raises
2441 * <tt>RuntimeError (No scheduler is available!)</tt>.
2442 *
2443 */
2444static VALUE
2445rb_fiber_s_schedule(int argc, VALUE *argv, VALUE obj)
2446{
2447 return rb_fiber_s_schedule_kw(argc, argv, rb_keyword_given_p());
2448}
2449
2450/*
2451 * call-seq:
2452 * Fiber.scheduler -> obj or nil
2453 *
2454 * Returns the Fiber scheduler, that was last set for the current thread with Fiber.set_scheduler.
2455 * Returns +nil+ if no scheduler is set (which is the default), and non-blocking fibers'
2456 * behavior is the same as blocking.
2457 * (see "Non-blocking fibers" section in class docs for details about the scheduler concept).
2458 *
2459 */
2460static VALUE
2461rb_fiber_s_scheduler(VALUE klass)
2462{
2463 return rb_fiber_scheduler_get();
2464}
2465
2466/*
2467 * call-seq:
2468 * Fiber.current_scheduler -> obj or nil
2469 *
2470 * Returns the Fiber scheduler, that was last set for the current thread with Fiber.set_scheduler
2471 * if and only if the current fiber is non-blocking.
2472 *
2473 */
2474static VALUE
2475rb_fiber_current_scheduler(VALUE klass)
2476{
2478}
2479
2480/*
2481 * call-seq:
2482 * Fiber.set_scheduler(scheduler) -> scheduler
2483 *
2484 * Sets the Fiber scheduler for the current thread. If the scheduler is set, non-blocking
2485 * fibers (created by Fiber.new with <tt>blocking: false</tt>, or by Fiber.schedule)
2486 * call that scheduler's hook methods on potentially blocking operations, and the current
2487 * thread will call scheduler's +close+ method on finalization (allowing the scheduler to
2488 * properly manage all non-finished fibers).
2489 *
2490 * +scheduler+ can be an object of any class corresponding to Fiber::Scheduler. Its
2491 * implementation is up to the user.
2492 *
2493 * See also the "Non-blocking fibers" section in class docs.
2494 *
2495 */
2496static VALUE
2497rb_fiber_set_scheduler(VALUE klass, VALUE scheduler)
2498{
2499 return rb_fiber_scheduler_set(scheduler);
2500}
2501
2502NORETURN(static void rb_fiber_terminate(rb_fiber_t *fiber, int need_interrupt, VALUE err));
2503
2504void
2505rb_fiber_start(rb_fiber_t *fiber)
2506{
2507 rb_thread_t * volatile th = fiber->cont.saved_ec.thread_ptr;
2508
2509 rb_proc_t *proc;
2510 enum ruby_tag_type state;
2511
2512 VM_ASSERT(th->ec == GET_EC());
2513 VM_ASSERT(FIBER_RESUMED_P(fiber));
2514
2515 if (fiber->blocking) {
2516 th->blocking += 1;
2517 }
2518
2519 EC_PUSH_TAG(th->ec);
2520 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
2521 rb_context_t *cont = &VAR_FROM_MEMORY(fiber)->cont;
2522 int argc;
2523 const VALUE *argv, args = cont->value;
2524 GetProcPtr(fiber->first_proc, proc);
2525 argv = (argc = cont->argc) > 1 ? RARRAY_CONST_PTR(args) : &args;
2526 cont->value = Qnil;
2527 th->ec->errinfo = Qnil;
2528 th->ec->root_lep = rb_vm_proc_local_ep(fiber->first_proc);
2529 th->ec->root_svar = Qfalse;
2530
2531 EXEC_EVENT_HOOK(th->ec, RUBY_EVENT_FIBER_SWITCH, th->self, 0, 0, 0, Qnil);
2532 cont->value = rb_vm_invoke_proc(th->ec, proc, argc, argv, cont->kw_splat, VM_BLOCK_HANDLER_NONE);
2533 }
2534 EC_POP_TAG();
2535
2536 int need_interrupt = TRUE;
2537 VALUE err = Qfalse;
2538 if (state) {
2539 err = th->ec->errinfo;
2540 VM_ASSERT(FIBER_RESUMED_P(fiber));
2541
2542 if (state == TAG_RAISE) {
2543 // noop...
2544 }
2545 else if (state == TAG_FATAL && err == RUBY_FATAL_FIBER_KILLED) {
2546 need_interrupt = FALSE;
2547 err = Qfalse;
2548 }
2549 else if (state == TAG_FATAL) {
2550 rb_threadptr_pending_interrupt_enque(th, err);
2551 }
2552 else {
2553 err = rb_vm_make_jump_tag_but_local_jump(state, err);
2554 }
2555 }
2556
2557 rb_fiber_terminate(fiber, need_interrupt, err);
2558}
2559
2560// Set up a "root fiber", which is the fiber that every Ractor has.
2561void
2562rb_threadptr_root_fiber_setup(rb_thread_t *th)
2563{
2564 rb_fiber_t *fiber = ruby_mimcalloc(1, sizeof(rb_fiber_t));
2565 if (!fiber) {
2566 rb_bug("%s", strerror(errno)); /* ... is it possible to call rb_bug here? */
2567 }
2568 fiber->cont.type = FIBER_CONTEXT;
2569 fiber->cont.saved_ec.fiber_ptr = fiber;
2570 fiber->cont.saved_ec.serial = next_ec_serial(th->ractor);
2571 fiber->cont.saved_ec.thread_ptr = th;
2572 fiber->blocking = 1;
2573 fiber->killed = 0;
2574 fiber_status_set(fiber, FIBER_RESUMED); /* skip CREATED */
2575 th->ec = &fiber->cont.saved_ec;
2576 cont_init_jit_cont(&fiber->cont);
2577}
2578
2579void
2580rb_threadptr_root_fiber_release(rb_thread_t *th)
2581{
2582 if (th->root_fiber) {
2583 /* ignore. A root fiber object will free th->ec */
2584 }
2585 else {
2586 rb_execution_context_t *ec = rb_current_execution_context(false);
2587
2588 VM_ASSERT(th->ec->fiber_ptr->cont.type == FIBER_CONTEXT);
2589 VM_ASSERT(th->ec->fiber_ptr->cont.self == 0);
2590
2591 if (ec && th->ec == ec) {
2592 rb_ractor_set_current_ec(th->ractor, NULL);
2593 }
2594 fiber_free(th->ec->fiber_ptr);
2595 th->ec = NULL;
2596 }
2597}
2598
2599void
2600rb_threadptr_root_fiber_terminate(rb_thread_t *th)
2601{
2602 rb_fiber_t *fiber = th->ec->fiber_ptr;
2603
2604 fiber->status = FIBER_TERMINATED;
2605
2606 // The vm_stack is `alloca`ed on the thread stack, so it's gone too:
2607 rb_ec_clear_vm_stack(th->ec);
2608}
2609
2610static inline rb_fiber_t*
2611return_fiber(bool terminate)
2612{
2613 rb_fiber_t *fiber = fiber_current();
2614 rb_fiber_t *prev = fiber->prev;
2615
2616 if (prev) {
2617 fiber->prev = NULL;
2618 prev->resuming_fiber = NULL;
2619 return prev;
2620 }
2621 else {
2622 if (!terminate) {
2623 rb_raise(rb_eFiberError, "attempt to yield on a not resumed fiber");
2624 }
2625
2626 rb_thread_t *th = GET_THREAD();
2627 rb_fiber_t *root_fiber = th->root_fiber;
2628
2629 VM_ASSERT(root_fiber != NULL);
2630
2631 // search resuming fiber
2632 for (fiber = root_fiber; fiber->resuming_fiber; fiber = fiber->resuming_fiber) {
2633 }
2634
2635 return fiber;
2636 }
2637}
2638
2639VALUE
2640rb_fiber_current(void)
2641{
2642 return fiber_current()->cont.self;
2643}
2644
2645// Prepare to execute next_fiber on the given thread.
2646static inline void
2647fiber_store(rb_fiber_t *next_fiber, rb_thread_t *th)
2648{
2649 rb_fiber_t *fiber;
2650
2651 if (th->ec->fiber_ptr != NULL) {
2652 fiber = th->ec->fiber_ptr;
2653 }
2654 else {
2655 /* create root fiber */
2656 fiber = root_fiber_alloc(th);
2657 }
2658
2659 if (FIBER_CREATED_P(next_fiber)) {
2660 fiber_prepare_stack(next_fiber);
2661 }
2662
2663 VM_ASSERT(FIBER_RESUMED_P(fiber) || FIBER_TERMINATED_P(fiber));
2664 VM_ASSERT(FIBER_RUNNABLE_P(next_fiber));
2665
2666 if (FIBER_RESUMED_P(fiber)) fiber_status_set(fiber, FIBER_SUSPENDED);
2667
2668 fiber_status_set(next_fiber, FIBER_RESUMED);
2669 fiber_setcontext(next_fiber, fiber);
2670}
2671
2672static void
2673fiber_check_killed(rb_fiber_t *fiber)
2674{
2675 VM_ASSERT(fiber == fiber_current());
2676
2677 if (fiber->killed) {
2678 rb_thread_t *thread = fiber->cont.saved_ec.thread_ptr;
2679
2680 thread->ec->errinfo = RUBY_FATAL_FIBER_KILLED;
2681 EC_JUMP_TAG(thread->ec, RUBY_TAG_FATAL);
2682 }
2683}
2684
2685static inline VALUE
2686fiber_switch(rb_fiber_t *fiber, int argc, const VALUE *argv, int kw_splat, rb_fiber_t *resuming_fiber, bool yielding)
2687{
2688 VALUE value;
2689 rb_context_t *cont = &fiber->cont;
2690 rb_thread_t *th = GET_THREAD();
2691
2692 /* make sure the root_fiber object is available */
2693 if (th->root_fiber == NULL) root_fiber_alloc(th);
2694
2695 if (th->ec->fiber_ptr == fiber) {
2696 /* ignore fiber context switch
2697 * because destination fiber is the same as current fiber
2698 */
2699 return make_passing_arg(argc, argv);
2700 }
2701
2702 if (cont_thread_value(cont) != th->self) {
2703 rb_raise(rb_eFiberError, "fiber called across threads");
2704 }
2705
2706 if (FIBER_TERMINATED_P(fiber)) {
2707 value = rb_exc_new2(rb_eFiberError, "dead fiber called");
2708
2709 if (!FIBER_TERMINATED_P(th->ec->fiber_ptr)) {
2710 rb_exc_raise(value);
2711 VM_UNREACHABLE(fiber_switch);
2712 }
2713 else {
2714 /* th->ec->fiber_ptr is also dead => switch to root fiber */
2715 /* (this means we're being called from rb_fiber_terminate, */
2716 /* and the terminated fiber's return_fiber() is already dead) */
2717 VM_ASSERT(FIBER_SUSPENDED_P(th->root_fiber));
2718
2719 cont = &th->root_fiber->cont;
2720 cont->argc = -1;
2721 cont->value = value;
2722
2723 fiber_setcontext(th->root_fiber, th->ec->fiber_ptr);
2724
2725 VM_UNREACHABLE(fiber_switch);
2726 }
2727 }
2728
2729 VM_ASSERT(FIBER_RUNNABLE_P(fiber));
2730
2731 rb_fiber_t *current_fiber = fiber_current();
2732
2733 VM_ASSERT(!current_fiber->resuming_fiber);
2734
2735 if (resuming_fiber) {
2736 current_fiber->resuming_fiber = resuming_fiber;
2737 fiber->prev = fiber_current();
2738 fiber->yielding = 0;
2739 }
2740
2741 VM_ASSERT(!current_fiber->yielding);
2742 if (yielding) {
2743 current_fiber->yielding = 1;
2744 }
2745
2746 if (current_fiber->blocking) {
2747 th->blocking -= 1;
2748 }
2749
2750 cont->argc = argc;
2751 cont->kw_splat = kw_splat;
2752 cont->value = make_passing_arg(argc, argv);
2753
2754 fiber_store(fiber, th);
2755
2756 // We cannot free the stack until the pthread is joined:
2757#ifndef COROUTINE_PTHREAD_CONTEXT
2758 if (resuming_fiber && FIBER_TERMINATED_P(fiber)) {
2759 RB_VM_LOCKING() {
2760 fiber_stack_release(fiber);
2761 }
2762 }
2763#endif
2764
2765 if (fiber_current()->blocking) {
2766 th->blocking += 1;
2767 }
2768
2769 RUBY_VM_CHECK_INTS(th->ec);
2770
2771 EXEC_EVENT_HOOK(th->ec, RUBY_EVENT_FIBER_SWITCH, th->self, 0, 0, 0, Qnil);
2772
2773 current_fiber = th->ec->fiber_ptr;
2774 value = current_fiber->cont.value;
2775
2776 fiber_check_killed(current_fiber);
2777
2778 if (current_fiber->cont.argc == -1) {
2779 // Fiber#raise will trigger this path.
2780 rb_exc_raise(value);
2781 }
2782
2783 return value;
2784}
2785
2786VALUE
2787rb_fiber_transfer(VALUE fiber_value, int argc, const VALUE *argv)
2788{
2789 return fiber_switch(fiber_ptr(fiber_value), argc, argv, RB_NO_KEYWORDS, NULL, false);
2790}
2791
2792/*
2793 * call-seq:
2794 * fiber.blocking? -> true or false
2795 *
2796 * Returns +true+ if +fiber+ is blocking and +false+ otherwise.
2797 * Fiber is non-blocking if it was created via passing <tt>blocking: false</tt>
2798 * to Fiber.new, or via Fiber.schedule.
2799 *
2800 * Note that, even if the method returns +false+, the fiber behaves differently
2801 * only if Fiber.scheduler is set in the current thread.
2802 *
2803 * See the "Non-blocking fibers" section in class docs for details.
2804 *
2805 */
2806VALUE
2807rb_fiber_blocking_p(VALUE fiber)
2808{
2809 return RBOOL(fiber_ptr(fiber)->blocking);
2810}
2811
2812static VALUE
2813fiber_blocking_yield(VALUE fiber_value)
2814{
2815 rb_fiber_t *fiber = fiber_ptr(fiber_value);
2816 rb_thread_t * volatile th = fiber->cont.saved_ec.thread_ptr;
2817
2818 VM_ASSERT(fiber->blocking == 0);
2819
2820 // fiber->blocking is `unsigned int : 1`, so we use it as a boolean:
2821 fiber->blocking = 1;
2822
2823 // Once the fiber is blocking, and current, we increment the thread blocking state:
2824 th->blocking += 1;
2825
2826 return rb_yield(fiber_value);
2827}
2828
2829static VALUE
2830fiber_blocking_ensure(VALUE fiber_value)
2831{
2832 rb_fiber_t *fiber = fiber_ptr(fiber_value);
2833 rb_thread_t * volatile th = fiber->cont.saved_ec.thread_ptr;
2834
2835 // We are no longer blocking:
2836 fiber->blocking = 0;
2837 th->blocking -= 1;
2838
2839 return Qnil;
2840}
2841
2842/*
2843 * call-seq:
2844 * Fiber.blocking{|fiber| ...} -> result
2845 *
2846 * Forces the fiber to be blocking for the duration of the block. Returns the
2847 * result of the block.
2848 *
2849 * See the "Non-blocking fibers" section in class docs for details.
2850 *
2851 */
2852VALUE
2853rb_fiber_blocking(VALUE class)
2854{
2855 VALUE fiber_value = rb_fiber_current();
2856 rb_fiber_t *fiber = fiber_ptr(fiber_value);
2857
2858 // If we are already blocking, this is essentially a no-op:
2859 if (fiber->blocking) {
2860 return rb_yield(fiber_value);
2861 }
2862 else {
2863 return rb_ensure(fiber_blocking_yield, fiber_value, fiber_blocking_ensure, fiber_value);
2864 }
2865}
2866
2867/*
2868 * call-seq:
2869 * Fiber.blocking? -> false or 1
2870 *
2871 * Returns +false+ if the current fiber is non-blocking.
2872 * Fiber is non-blocking if it was created via passing <tt>blocking: false</tt>
2873 * to Fiber.new, or via Fiber.schedule.
2874 *
2875 * If the current Fiber is blocking, the method returns 1.
2876 * Future developments may allow for situations where larger integers
2877 * could be returned.
2878 *
2879 * Note that, even if the method returns +false+, Fiber behaves differently
2880 * only if Fiber.scheduler is set in the current thread.
2881 *
2882 * See the "Non-blocking fibers" section in class docs for details.
2883 *
2884 */
2885static VALUE
2886rb_fiber_s_blocking_p(VALUE klass)
2887{
2888 rb_thread_t *thread = GET_THREAD();
2889 unsigned blocking = thread->blocking;
2890
2891 if (blocking == 0)
2892 return Qfalse;
2893
2894 return INT2NUM(blocking);
2895}
2896
2897void
2898rb_fiber_close(rb_fiber_t *fiber)
2899{
2900 fiber_status_set(fiber, FIBER_TERMINATED);
2901 rb_ec_close(&fiber->cont.saved_ec);
2902}
2903
2904static void
2905rb_fiber_terminate(rb_fiber_t *fiber, int need_interrupt, VALUE error)
2906{
2907 VALUE value = fiber->cont.value;
2908
2909 VM_ASSERT(FIBER_RESUMED_P(fiber));
2910 rb_fiber_close(fiber);
2911
2912 fiber->cont.machine.stack = NULL;
2913 fiber->cont.machine.stack_size = 0;
2914
2915 rb_fiber_t *next_fiber = return_fiber(true);
2916
2917 if (need_interrupt) RUBY_VM_SET_INTERRUPT(&next_fiber->cont.saved_ec);
2918
2919 if (RTEST(error))
2920 fiber_switch(next_fiber, -1, &error, RB_NO_KEYWORDS, NULL, false);
2921 else
2922 fiber_switch(next_fiber, 1, &value, RB_NO_KEYWORDS, NULL, false);
2923 ruby_stop(0);
2924}
2925
2926static VALUE
2927fiber_resume_kw(rb_fiber_t *fiber, int argc, const VALUE *argv, int kw_splat)
2928{
2929 rb_fiber_t *current_fiber = fiber_current();
2930
2931 if (argc == -1 && FIBER_CREATED_P(fiber)) {
2932 rb_raise(rb_eFiberError, "cannot raise exception on unborn fiber");
2933 }
2934 else if (FIBER_TERMINATED_P(fiber)) {
2935 rb_raise(rb_eFiberError, "attempt to resume a terminated fiber");
2936 }
2937 else if (fiber == current_fiber) {
2938 rb_raise(rb_eFiberError, "attempt to resume the current fiber");
2939 }
2940 else if (fiber->prev != NULL) {
2941 rb_raise(rb_eFiberError, "attempt to resume a resumed fiber (double resume)");
2942 }
2943 else if (fiber->resuming_fiber) {
2944 rb_raise(rb_eFiberError, "attempt to resume a resuming fiber");
2945 }
2946 else if (fiber->prev == NULL &&
2947 (!fiber->yielding && fiber->status != FIBER_CREATED)) {
2948 rb_raise(rb_eFiberError, "attempt to resume a transferring fiber");
2949 }
2950
2951 return fiber_switch(fiber, argc, argv, kw_splat, fiber, false);
2952}
2953
2954VALUE
2955rb_fiber_resume_kw(VALUE self, int argc, const VALUE *argv, int kw_splat)
2956{
2957 return fiber_resume_kw(fiber_ptr(self), argc, argv, kw_splat);
2958}
2959
2960VALUE
2961rb_fiber_resume(VALUE self, int argc, const VALUE *argv)
2962{
2963 return fiber_resume_kw(fiber_ptr(self), argc, argv, RB_NO_KEYWORDS);
2964}
2965
2966VALUE
2967rb_fiber_yield_kw(int argc, const VALUE *argv, int kw_splat)
2968{
2969 return fiber_switch(return_fiber(false), argc, argv, kw_splat, NULL, true);
2970}
2971
2972VALUE
2973rb_fiber_yield(int argc, const VALUE *argv)
2974{
2975 return fiber_switch(return_fiber(false), argc, argv, RB_NO_KEYWORDS, NULL, true);
2976}
2977
2978void
2979rb_fiber_reset_root_local_storage(rb_thread_t *th)
2980{
2981 if (th->root_fiber && th->root_fiber != th->ec->fiber_ptr) {
2982 th->ec->local_storage = th->root_fiber->cont.saved_ec.local_storage;
2983 }
2984}
2985
2986/*
2987 * call-seq:
2988 * fiber.alive? -> true or false
2989 *
2990 * Returns true if the fiber can still be resumed (or transferred
2991 * to). After finishing execution of the fiber block this method will
2992 * always return +false+.
2993 */
2994VALUE
2995rb_fiber_alive_p(VALUE fiber_value)
2996{
2997 return RBOOL(!FIBER_TERMINATED_P(fiber_ptr(fiber_value)));
2998}
2999
3000/*
3001 * call-seq:
3002 * fiber.resume(args, ...) -> obj
3003 *
3004 * Resumes the fiber from the point at which the last Fiber.yield was
3005 * called, or starts running it if it is the first call to
3006 * #resume. Arguments passed to resume will be the value of the
3007 * Fiber.yield expression or will be passed as block parameters to
3008 * the fiber's block if this is the first #resume.
3009 *
3010 * Alternatively, when resume is called it evaluates to the arguments passed
3011 * to the next Fiber.yield statement inside the fiber's block
3012 * or to the block value if it runs to completion without any
3013 * Fiber.yield
3014 */
3015static VALUE
3016rb_fiber_m_resume(int argc, VALUE *argv, VALUE fiber)
3017{
3018 return rb_fiber_resume_kw(fiber, argc, argv, rb_keyword_given_p());
3019}
3020
3021/*
3022 * call-seq:
3023 * fiber.backtrace -> array
3024 * fiber.backtrace(start) -> array
3025 * fiber.backtrace(start, count) -> array
3026 * fiber.backtrace(start..end) -> array
3027 *
3028 * Returns the current execution stack of the fiber. +start+, +count+ and +end+ allow
3029 * to select only parts of the backtrace.
3030 *
3031 * def level3
3032 * Fiber.yield
3033 * end
3034 *
3035 * def level2
3036 * level3
3037 * end
3038 *
3039 * def level1
3040 * level2
3041 * end
3042 *
3043 * f = Fiber.new { level1 }
3044 *
3045 * # It is empty before the fiber started
3046 * f.backtrace
3047 * #=> []
3048 *
3049 * f.resume
3050 *
3051 * f.backtrace
3052 * #=> ["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>'"]
3053 * p f.backtrace(1) # start from the item 1
3054 * #=> ["test.rb:2:in `level3'", "test.rb:6:in `level2'", "test.rb:10:in `level1'", "test.rb:13:in `block in <main>'"]
3055 * p f.backtrace(2, 2) # start from item 2, take 2
3056 * #=> ["test.rb:6:in `level2'", "test.rb:10:in `level1'"]
3057 * p f.backtrace(1..3) # take items from 1 to 3
3058 * #=> ["test.rb:2:in `level3'", "test.rb:6:in `level2'", "test.rb:10:in `level1'"]
3059 *
3060 * f.resume
3061 *
3062 * # It is nil after the fiber is finished
3063 * f.backtrace
3064 * #=> nil
3065 *
3066 */
3067static VALUE
3068rb_fiber_backtrace(int argc, VALUE *argv, VALUE fiber)
3069{
3070 return rb_vm_backtrace(argc, argv, &fiber_ptr(fiber)->cont.saved_ec);
3071}
3072
3073/*
3074 * call-seq:
3075 * fiber.backtrace_locations -> array
3076 * fiber.backtrace_locations(start) -> array
3077 * fiber.backtrace_locations(start, count) -> array
3078 * fiber.backtrace_locations(start..end) -> array
3079 *
3080 * Like #backtrace, but returns each line of the execution stack as a
3081 * Thread::Backtrace::Location. Accepts the same arguments as #backtrace.
3082 *
3083 * f = Fiber.new { Fiber.yield }
3084 * f.resume
3085 * loc = f.backtrace_locations.first
3086 * loc.label #=> "yield"
3087 * loc.path #=> "test.rb"
3088 * loc.lineno #=> 1
3089 *
3090 *
3091 */
3092static VALUE
3093rb_fiber_backtrace_locations(int argc, VALUE *argv, VALUE fiber)
3094{
3095 return rb_vm_backtrace_locations(argc, argv, &fiber_ptr(fiber)->cont.saved_ec);
3096}
3097
3098/*
3099 * call-seq:
3100 * fiber.transfer(args, ...) -> obj
3101 *
3102 * Transfer control to another fiber, resuming it from where it last
3103 * stopped or starting it if it was not resumed before. The calling
3104 * fiber will be suspended much like in a call to
3105 * Fiber.yield.
3106 *
3107 * The fiber which receives the transfer call treats it much like
3108 * a resume call. Arguments passed to transfer are treated like those
3109 * passed to resume.
3110 *
3111 * The two style of control passing to and from fiber (one is #resume and
3112 * Fiber::yield, another is #transfer to and from fiber) can't be freely
3113 * mixed.
3114 *
3115 * * If the Fiber's lifecycle had started with transfer, it will never
3116 * be able to yield or be resumed control passing, only
3117 * finish or transfer back. (It still can resume other fibers that
3118 * are allowed to be resumed.)
3119 * * If the Fiber's lifecycle had started with resume, it can yield
3120 * or transfer to another Fiber, but can receive control back only
3121 * the way compatible with the way it was given away: if it had
3122 * transferred, it only can be transferred back, and if it had
3123 * yielded, it only can be resumed back. After that, it again can
3124 * transfer or yield.
3125 *
3126 * If those rules are broken FiberError is raised.
3127 *
3128 * For an individual Fiber design, yield/resume is easier to use
3129 * (the Fiber just gives away control, it doesn't need to think
3130 * about who the control is given to), while transfer is more flexible
3131 * for complex cases, allowing to build arbitrary graphs of Fibers
3132 * dependent on each other.
3133 *
3134 *
3135 * Example:
3136 *
3137 * manager = nil # For local var to be visible inside worker block
3138 *
3139 * # This fiber would be started with transfer
3140 * # It can't yield, and can't be resumed
3141 * worker = Fiber.new { |work|
3142 * puts "Worker: starts"
3143 * puts "Worker: Performed #{work.inspect}, transferring back"
3144 * # Fiber.yield # this would raise FiberError: attempt to yield on a not resumed fiber
3145 * # manager.resume # this would raise FiberError: attempt to resume a resumed fiber (double resume)
3146 * manager.transfer(work.capitalize)
3147 * }
3148 *
3149 * # This fiber would be started with resume
3150 * # It can yield or transfer, and can be transferred
3151 * # back or resumed
3152 * manager = Fiber.new {
3153 * puts "Manager: starts"
3154 * puts "Manager: transferring 'something' to worker"
3155 * result = worker.transfer('something')
3156 * puts "Manager: worker returned #{result.inspect}"
3157 * # worker.resume # this would raise FiberError: attempt to resume a transferring fiber
3158 * Fiber.yield # this is OK, the fiber transferred from and to, now it can yield
3159 * puts "Manager: finished"
3160 * }
3161 *
3162 * puts "Starting the manager"
3163 * manager.resume
3164 * puts "Resuming the manager"
3165 * # manager.transfer # this would raise FiberError: attempt to transfer to a yielding fiber
3166 * manager.resume
3167 *
3168 * <em>produces</em>
3169 *
3170 * Starting the manager
3171 * Manager: starts
3172 * Manager: transferring 'something' to worker
3173 * Worker: starts
3174 * Worker: Performed "something", transferring back
3175 * Manager: worker returned "Something"
3176 * Resuming the manager
3177 * Manager: finished
3178 *
3179 */
3180static VALUE
3181rb_fiber_m_transfer(int argc, VALUE *argv, VALUE self)
3182{
3183 return rb_fiber_transfer_kw(self, argc, argv, rb_keyword_given_p());
3184}
3185
3186static VALUE
3187fiber_transfer_kw(rb_fiber_t *fiber, int argc, const VALUE *argv, int kw_splat)
3188{
3189 if (fiber->resuming_fiber) {
3190 rb_raise(rb_eFiberError, "attempt to transfer to a resuming fiber");
3191 }
3192
3193 if (fiber->yielding) {
3194 rb_raise(rb_eFiberError, "attempt to transfer to a yielding fiber");
3195 }
3196
3197 return fiber_switch(fiber, argc, argv, kw_splat, NULL, false);
3198}
3199
3200VALUE
3201rb_fiber_transfer_kw(VALUE self, int argc, const VALUE *argv, int kw_splat)
3202{
3203 return fiber_transfer_kw(fiber_ptr(self), argc, argv, kw_splat);
3204}
3205
3206/*
3207 * call-seq:
3208 * Fiber.yield(args, ...) -> obj
3209 *
3210 * Yields control back to the context that resumed the fiber, passing
3211 * along any arguments that were passed to it. The fiber will resume
3212 * processing at this point when #resume is called next.
3213 * Any arguments passed to the next #resume will be the value that
3214 * this Fiber.yield expression evaluates to.
3215 */
3216static VALUE
3217rb_fiber_s_yield(int argc, VALUE *argv, VALUE klass)
3218{
3219 return rb_fiber_yield_kw(argc, argv, rb_keyword_given_p());
3220}
3221
3222static VALUE
3223fiber_raise(rb_fiber_t *fiber, VALUE exception)
3224{
3225 if (fiber == fiber_current()) {
3226 rb_exc_raise(exception);
3227 }
3228 else if (fiber->resuming_fiber) {
3229 return fiber_raise(fiber->resuming_fiber, exception);
3230 }
3231 else if (FIBER_SUSPENDED_P(fiber) && !fiber->yielding) {
3232 return fiber_transfer_kw(fiber, -1, &exception, RB_NO_KEYWORDS);
3233 }
3234 else {
3235 return fiber_resume_kw(fiber, -1, &exception, RB_NO_KEYWORDS);
3236 }
3237}
3238
3239VALUE
3240rb_fiber_raise(VALUE fiber, int argc, VALUE *argv)
3241{
3242 VALUE exception = rb_exception_setup(argc, argv);
3243
3244 return fiber_raise(fiber_ptr(fiber), exception);
3245}
3246
3247/*
3248 * call-seq:
3249 * raise(exception, message = exception.to_s, backtrace = nil, cause: $!)
3250 * raise(message = nil, cause: $!)
3251 *
3252 * Raises an exception in the fiber at the point at which the last
3253 * +Fiber.yield+ was called.
3254 *
3255 * f = Fiber.new {
3256 * puts "Before the yield"
3257 * Fiber.yield 1 # -- exception will be raised here
3258 * puts "After the yield"
3259 * }
3260 *
3261 * p f.resume
3262 * f.raise "Gotcha"
3263 *
3264 * Output
3265 *
3266 * Before the first yield
3267 * 1
3268 * t.rb:8:in 'Fiber.yield': Gotcha (RuntimeError)
3269 * from t.rb:8:in 'block in <main>'
3270 *
3271 * If the fiber has not been started or has
3272 * already run to completion, raises +FiberError+. If the fiber is
3273 * yielding, it is resumed. If it is transferring, it is transferred into.
3274 * But if it is resuming, raises +FiberError+.
3275 *
3276 * Raises +FiberError+ if called on a Fiber belonging to another +Thread+.
3277 *
3278 * See Kernel#raise for more information on arguments.
3279 *
3280 */
3281static VALUE
3282rb_fiber_m_raise(int argc, VALUE *argv, VALUE self)
3283{
3284 return rb_fiber_raise(self, argc, argv);
3285}
3286
3287/*
3288 * call-seq:
3289 * fiber.kill -> nil
3290 *
3291 * Terminates the fiber by raising an uncatchable exception.
3292 * It only terminates the given fiber and no other fiber, returning +nil+ to
3293 * another fiber if that fiber was calling #resume or #transfer.
3294 *
3295 * <tt>Fiber#kill</tt> only interrupts another fiber when it is in Fiber.yield.
3296 * If called on the current fiber then it raises that exception at the <tt>Fiber#kill</tt> call site.
3297 *
3298 * If the fiber has not been started, transition directly to the terminated state.
3299 *
3300 * If the fiber is already terminated, does nothing.
3301 *
3302 * Raises FiberError if called on a fiber belonging to another thread.
3303 */
3304static VALUE
3305rb_fiber_m_kill(VALUE self)
3306{
3307 rb_fiber_t *fiber = fiber_ptr(self);
3308
3309 if (fiber->killed) return Qfalse;
3310 fiber->killed = 1;
3311
3312 if (fiber->status == FIBER_CREATED) {
3313 fiber->status = FIBER_TERMINATED;
3314 }
3315 else if (fiber->status != FIBER_TERMINATED) {
3316 if (fiber_current() == fiber) {
3317 fiber_check_killed(fiber);
3318 }
3319 else {
3320 fiber_raise(fiber_ptr(self), Qnil);
3321 }
3322 }
3323
3324 return self;
3325}
3326
3327/*
3328 * call-seq:
3329 * Fiber.current -> fiber
3330 *
3331 * Returns the current fiber. If you are not running in the context of
3332 * a fiber this method will return the root fiber.
3333 */
3334static VALUE
3335rb_fiber_s_current(VALUE klass)
3336{
3337 return rb_fiber_current();
3338}
3339
3340static VALUE
3341fiber_to_s(VALUE fiber_value)
3342{
3343 const rb_fiber_t *fiber = fiber_ptr(fiber_value);
3344 const rb_proc_t *proc;
3345 char status_info[0x20];
3346
3347 if (fiber->resuming_fiber) {
3348 snprintf(status_info, 0x20, " (%s by resuming)", fiber_status_name(fiber->status));
3349 }
3350 else {
3351 snprintf(status_info, 0x20, " (%s)", fiber_status_name(fiber->status));
3352 }
3353
3354 if (!rb_obj_is_proc(fiber->first_proc)) {
3355 VALUE str = rb_any_to_s(fiber_value);
3356 strlcat(status_info, ">", sizeof(status_info));
3357 rb_str_set_len(str, RSTRING_LEN(str)-1);
3358 rb_str_cat_cstr(str, status_info);
3359 return str;
3360 }
3361 GetProcPtr(fiber->first_proc, proc);
3362 return rb_block_to_s(fiber_value, &proc->block, status_info);
3363}
3364
3365#ifdef HAVE_WORKING_FORK
3366void
3367rb_fiber_atfork(rb_thread_t *th)
3368{
3369 if (th->root_fiber) {
3370 if (&th->root_fiber->cont.saved_ec != th->ec) {
3371 th->root_fiber = th->ec->fiber_ptr;
3372 }
3373 th->root_fiber->prev = 0;
3374 th->root_fiber->blocking = 1;
3375 th->blocking = 1;
3376 }
3377}
3378#endif
3379
3380#ifdef RB_EXPERIMENTAL_FIBER_POOL
3381static void
3382fiber_pool_free(void *ptr)
3383{
3384 struct fiber_pool * fiber_pool = ptr;
3385 RUBY_FREE_ENTER("fiber_pool");
3386
3387 fiber_pool_allocation_free(fiber_pool->allocations);
3388 ruby_xfree(fiber_pool);
3389
3390 RUBY_FREE_LEAVE("fiber_pool");
3391}
3392
3393static size_t
3394fiber_pool_memsize(const void *ptr)
3395{
3396 const struct fiber_pool * fiber_pool = ptr;
3397 size_t size = sizeof(*fiber_pool);
3398
3399 size += fiber_pool->count * fiber_pool->size;
3400
3401 return size;
3402}
3403
3404static const rb_data_type_t FiberPoolDataType = {
3405 "fiber_pool",
3406 {NULL, fiber_pool_free, fiber_pool_memsize,},
3407 0, 0, RUBY_TYPED_FREE_IMMEDIATELY
3408};
3409
3410static VALUE
3411fiber_pool_alloc(VALUE klass)
3412{
3413 struct fiber_pool *fiber_pool;
3414
3415 return TypedData_Make_Struct(klass, struct fiber_pool, &FiberPoolDataType, fiber_pool);
3416}
3417
3418static VALUE
3419rb_fiber_pool_initialize(int argc, VALUE* argv, VALUE self)
3420{
3421 rb_thread_t *th = GET_THREAD();
3422 VALUE size = Qnil, count = Qnil, vm_stack_size = Qnil;
3423 struct fiber_pool * fiber_pool = NULL;
3424
3425 // Maybe these should be keyword arguments.
3426 rb_scan_args(argc, argv, "03", &size, &count, &vm_stack_size);
3427
3428 if (NIL_P(size)) {
3429 size = SIZET2NUM(th->vm->default_params.fiber_machine_stack_size);
3430 }
3431
3432 if (NIL_P(count)) {
3433 count = INT2NUM(128);
3434 }
3435
3436 if (NIL_P(vm_stack_size)) {
3437 vm_stack_size = SIZET2NUM(th->vm->default_params.fiber_vm_stack_size);
3438 }
3439
3440 TypedData_Get_Struct(self, struct fiber_pool, &FiberPoolDataType, fiber_pool);
3441
3442 fiber_pool_initialize(fiber_pool, NUM2SIZET(size), NUM2SIZET(count), NUM2SIZET(vm_stack_size));
3443
3444 return self;
3445}
3446#endif
3447
3448/*
3449 * Document-class: FiberError
3450 *
3451 * Raised when an invalid operation is attempted on a Fiber, in
3452 * particular when attempting to call/resume a dead fiber,
3453 * attempting to yield from the root fiber, or calling a fiber across
3454 * threads.
3455 *
3456 * fiber = Fiber.new{}
3457 * fiber.resume #=> nil
3458 * fiber.resume #=> FiberError: dead fiber called
3459 */
3460
3461void
3462Init_Cont(void)
3463{
3464 rb_thread_t *th = GET_THREAD();
3465 size_t vm_stack_size = th->vm->default_params.fiber_vm_stack_size;
3466 size_t machine_stack_size = th->vm->default_params.fiber_machine_stack_size;
3467 size_t stack_size = machine_stack_size + vm_stack_size;
3468
3469#ifdef _WIN32
3470 SYSTEM_INFO info;
3471 GetSystemInfo(&info);
3472 pagesize = info.dwPageSize;
3473#else /* not WIN32 */
3474 pagesize = sysconf(_SC_PAGESIZE);
3475#endif
3476 SET_MACHINE_STACK_END(&th->ec->machine.stack_end);
3477
3478 fiber_pool_initialize(&shared_fiber_pool, stack_size, FIBER_POOL_INITIAL_SIZE, vm_stack_size);
3479
3480 fiber_initialize_keywords[0] = rb_intern_const("blocking");
3481 fiber_initialize_keywords[1] = rb_intern_const("pool");
3482 fiber_initialize_keywords[2] = rb_intern_const("storage");
3483
3484 const char *fiber_shared_fiber_pool_free_stacks = getenv("RUBY_SHARED_FIBER_POOL_FREE_STACKS");
3485 if (fiber_shared_fiber_pool_free_stacks) {
3486 shared_fiber_pool.free_stacks = atoi(fiber_shared_fiber_pool_free_stacks);
3487
3488 if (shared_fiber_pool.free_stacks < 0) {
3489 rb_warn("Setting RUBY_SHARED_FIBER_POOL_FREE_STACKS to a negative value is not allowed.");
3490 shared_fiber_pool.free_stacks = 0;
3491 }
3492
3493 if (shared_fiber_pool.free_stacks > 1) {
3494 rb_warn("Setting RUBY_SHARED_FIBER_POOL_FREE_STACKS to a value greater than 1 is operating system specific, and may cause crashes.");
3495 }
3496 }
3497
3498 rb_cFiber = rb_define_class("Fiber", rb_cObject);
3499 rb_define_alloc_func(rb_cFiber, fiber_alloc);
3500 rb_eFiberError = rb_define_class("FiberError", rb_eStandardError);
3501 rb_define_singleton_method(rb_cFiber, "yield", rb_fiber_s_yield, -1);
3502 rb_define_singleton_method(rb_cFiber, "current", rb_fiber_s_current, 0);
3503 rb_define_singleton_method(rb_cFiber, "blocking", rb_fiber_blocking, 0);
3504 rb_define_singleton_method(rb_cFiber, "[]", rb_fiber_storage_aref, 1);
3505 rb_define_singleton_method(rb_cFiber, "[]=", rb_fiber_storage_aset, 2);
3506
3507 rb_define_method(rb_cFiber, "initialize", rb_fiber_initialize, -1);
3508 rb_define_method(rb_cFiber, "blocking?", rb_fiber_blocking_p, 0);
3509 rb_define_method(rb_cFiber, "storage", rb_fiber_storage_get, 0);
3510 rb_define_method(rb_cFiber, "storage=", rb_fiber_storage_set, 1);
3511 rb_define_method(rb_cFiber, "resume", rb_fiber_m_resume, -1);
3512 rb_define_method(rb_cFiber, "raise", rb_fiber_m_raise, -1);
3513 rb_define_method(rb_cFiber, "kill", rb_fiber_m_kill, 0);
3514 rb_define_method(rb_cFiber, "backtrace", rb_fiber_backtrace, -1);
3515 rb_define_method(rb_cFiber, "backtrace_locations", rb_fiber_backtrace_locations, -1);
3516 rb_define_method(rb_cFiber, "to_s", fiber_to_s, 0);
3517 rb_define_alias(rb_cFiber, "inspect", "to_s");
3518 rb_define_method(rb_cFiber, "transfer", rb_fiber_m_transfer, -1);
3519 rb_define_method(rb_cFiber, "alive?", rb_fiber_alive_p, 0);
3520
3521 rb_define_singleton_method(rb_cFiber, "blocking?", rb_fiber_s_blocking_p, 0);
3522 rb_define_singleton_method(rb_cFiber, "scheduler", rb_fiber_s_scheduler, 0);
3523 rb_define_singleton_method(rb_cFiber, "set_scheduler", rb_fiber_set_scheduler, 1);
3524 rb_define_singleton_method(rb_cFiber, "current_scheduler", rb_fiber_current_scheduler, 0);
3525
3526 rb_define_singleton_method(rb_cFiber, "schedule", rb_fiber_s_schedule, -1);
3527
3528#ifdef RB_EXPERIMENTAL_FIBER_POOL
3529 /*
3530 * Document-class: Fiber::Pool
3531 * :nodoc: experimental
3532 */
3533 rb_cFiberPool = rb_define_class_under(rb_cFiber, "Pool", rb_cObject);
3534 rb_define_alloc_func(rb_cFiberPool, fiber_pool_alloc);
3535 rb_define_method(rb_cFiberPool, "initialize", rb_fiber_pool_initialize, -1);
3536#endif
3537
3538 rb_provide("fiber.so");
3539}
3540
3541RUBY_SYMBOL_EXPORT_BEGIN
3542
3543void
3544ruby_Init_Continuation_body(void)
3545{
3546 rb_cContinuation = rb_define_class("Continuation", rb_cObject);
3547 rb_undef_alloc_func(rb_cContinuation);
3548 rb_undef_method(CLASS_OF(rb_cContinuation), "new");
3549 rb_define_method(rb_cContinuation, "call", rb_cont_call, -1);
3550 rb_define_method(rb_cContinuation, "[]", rb_cont_call, -1);
3551 rb_define_global_function("callcc", rb_callcc, 0);
3552}
3553
3554RUBY_SYMBOL_EXPORT_END
#define rb_define_method(klass, mid, func, arity)
Defines klass#mid.
#define rb_define_singleton_method(klass, mid, func, arity)
Defines klass.mid.
#define rb_define_global_function(mid, func, arity)
Defines rb_mKernel #mid.
#define RUBY_EVENT_FIBER_SWITCH
Encountered a Fiber#yield.
Definition event.h:59
static bool RB_OBJ_FROZEN(VALUE obj)
Checks if an object is frozen.
Definition fl_type.h:892
VALUE rb_define_class(const char *name, VALUE super)
Defines a top-level class.
Definition class.c:1589
VALUE rb_define_class_under(VALUE outer, const char *name, VALUE super)
Defines a class under the namespace of outer.
Definition class.c:1620
void rb_define_alias(VALUE klass, const char *name1, const char *name2)
Defines an alias of a method.
Definition class.c:2956
void rb_undef_method(VALUE klass, const char *name)
Defines an undef of a method.
Definition class.c:2768
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:3259
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:3246
int rb_keyword_given_p(void)
Determines if the current method is given a keyword argument.
Definition eval.c:1023
int rb_get_kwargs(VALUE keyword_hash, const ID *table, int required, int optional, VALUE *values)
Keyword argument deconstructor.
Definition class.c:3035
#define REALLOC_N
Old name of RB_REALLOC_N.
Definition memory.h:403
#define xfree
Old name of ruby_xfree.
Definition xmalloc.h:58
#define Qundef
Old name of RUBY_Qundef.
#define UNREACHABLE_RETURN
Old name of RBIMPL_UNREACHABLE_RETURN.
Definition assume.h:29
#define ZALLOC
Old name of RB_ZALLOC.
Definition memory.h:402
#define CLASS_OF
Old name of rb_class_of.
Definition globals.h:205
#define rb_ary_new4
Old name of rb_ary_new_from_values.
Definition array.h:659
#define SIZET2NUM
Old name of RB_SIZE2NUM.
Definition size_t.h:62
#define rb_exc_new2
Old name of rb_exc_new_cstr.
Definition error.h:37
#define T_HASH
Old name of RUBY_T_HASH.
Definition value_type.h:65
#define ALLOC_N
Old name of RB_ALLOC_N.
Definition memory.h:399
#define Qtrue
Old name of RUBY_Qtrue.
#define INT2NUM
Old name of RB_INT2NUM.
Definition int.h:43
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#define NIL_P
Old name of RB_NIL_P.
#define T_SYMBOL
Old name of RUBY_T_SYMBOL.
Definition value_type.h:80
#define NUM2SIZET
Old name of RB_NUM2SIZE.
Definition size_t.h:61
void ruby_stop(int ex)
Calls ruby_cleanup() and exits the process.
Definition eval.c:290
void rb_category_warn(rb_warning_category_t category, const char *fmt,...)
Identical to rb_category_warning(), except it reports unless $VERBOSE is nil.
Definition error.c:476
void rb_exc_raise(VALUE mesg)
Raises an exception in the current thread.
Definition eval.c:653
int rb_typeddata_is_kind_of(VALUE obj, const rb_data_type_t *data_type)
Checks if the given object is of given kind.
Definition error.c:1381
void rb_syserr_fail(int e, const char *mesg)
Raises appropriate exception that represents a C errno.
Definition error.c:3909
VALUE rb_eStandardError
StandardError exception.
Definition error.c:1428
VALUE rb_eFrozenError
FrozenError exception.
Definition error.c:1430
VALUE rb_eTypeError
TypeError exception.
Definition error.c:1431
VALUE rb_eRuntimeError
RuntimeError exception.
Definition error.c:1429
void rb_warn(const char *fmt,...)
Identical to rb_warning(), except it reports unless $VERBOSE is nil.
Definition error.c:466
@ RB_WARN_CATEGORY_EXPERIMENTAL
Warning is for experimental features.
Definition error.h:51
VALUE rb_any_to_s(VALUE obj)
Generates a textual representation of the given object.
Definition object.c:675
VALUE rb_obj_dup(VALUE obj)
Duplicates the given object.
Definition object.c:582
void rb_provide(const char *feature)
Declares that the given feature is already provided by someone else.
Definition load.c:695
VALUE rb_block_proc(void)
Constructs a Proc object from implicitly passed components.
Definition proc.c:983
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:3387
#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:1650
void rb_define_alloc_func(VALUE klass, rb_alloc_func_t func)
Sets the allocator function of a class.
static ID rb_intern_const(const char *str)
This is a "tiny optimisation" over rb_intern().
Definition symbol.h:285
VALUE rb_to_symbol(VALUE name)
Identical to rb_intern_str(), except it generates a dynamic symbol if necessary.
Definition string.c:12672
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:649
#define TypedData_Wrap_Struct(klass, data_type, sval)
Converts sval, a pointer to your struct, into a Ruby object.
Definition rtypeddata.h:461
#define TypedData_Make_Struct(klass, type, data_type, sval)
Identical to TypedData_Wrap_Struct, except it allocates a new data region internally instead of takin...
Definition rtypeddata.h:508
#define errno
Ractor-aware version of errno.
Definition ruby.h:388
#define RB_NO_KEYWORDS
Do not pass keywords.
Definition scan_args.h:69
Scheduler APIs.
VALUE rb_fiber_scheduler_current(void)
Identical to rb_fiber_scheduler_get(), except it also returns RUBY_Qnil in case of a blocking fiber.
Definition scheduler.c:466
VALUE rb_fiber_scheduler_set(VALUE scheduler)
Destructively assigns the passed scheduler to that of the current thread that is calling this functio...
Definition scheduler.c:428
VALUE rb_fiber_scheduler_get(void)
Queries the current scheduler of the current thread that is calling this function.
Definition scheduler.c:378
VALUE rb_fiber_scheduler_fiber(VALUE scheduler, int argc, VALUE *argv, int kw_splat)
Create and schedule a non-blocking fiber.
Definition scheduler.c:1168
#define RTEST
This is an old name of RB_TEST.
This is the struct that holds necessary info for a struct.
Definition rtypeddata.h:208
void rb_native_mutex_lock(rb_nativethread_lock_t *lock)
Just another name of rb_nativethread_lock_lock.
void rb_native_mutex_initialize(rb_nativethread_lock_t *lock)
Just another name of rb_nativethread_lock_initialize.
void rb_native_mutex_unlock(rb_nativethread_lock_t *lock)
Just another name of rb_nativethread_lock_unlock.
void rb_native_mutex_destroy(rb_nativethread_lock_t *lock)
Just another name of rb_nativethread_lock_destroy.
uintptr_t ID
Type that represents a Ruby identifier such as a variable name.
Definition value.h:52
uintptr_t VALUE
Type that represents a Ruby object.
Definition value.h:40
static void Check_Type(VALUE v, enum ruby_value_type t)
Identical to RB_TYPE_P(), except it raises exceptions on predication failure.
Definition value_type.h:433
static bool RB_TYPE_P(VALUE obj, enum ruby_value_type t)
Queries if the given object is of given type.
Definition value_type.h:376