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