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