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