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