Ruby 3.5.0dev (2025-05-16 revision 35000ac2ed3a1829f8d193ffb23da0e44cc6fe5f)
cont.c (35000ac2ed3a1829f8d193ffb23da0e44cc6fe5f)
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#if defined(__wasm__) && !defined(__EMSCRIPTEN__)
1515 if (th->ec->tag != sec->tag) {
1516 /* find the lowest common ancestor tag of the current EC and the saved EC */
1517
1518 struct rb_vm_tag *lowest_common_ancestor = NULL;
1519 size_t num_tags = 0;
1520 size_t num_saved_tags = 0;
1521 for (struct rb_vm_tag *tag = th->ec->tag; tag != NULL; tag = tag->prev) {
1522 ++num_tags;
1523 }
1524 for (struct rb_vm_tag *tag = sec->tag; tag != NULL; tag = tag->prev) {
1525 ++num_saved_tags;
1526 }
1527
1528 size_t min_tags = num_tags <= num_saved_tags ? num_tags : num_saved_tags;
1529
1530 struct rb_vm_tag *tag = th->ec->tag;
1531 while (num_tags > min_tags) {
1532 tag = tag->prev;
1533 --num_tags;
1534 }
1535
1536 struct rb_vm_tag *saved_tag = sec->tag;
1537 while (num_saved_tags > min_tags) {
1538 saved_tag = saved_tag->prev;
1539 --num_saved_tags;
1540 }
1541
1542 while (min_tags > 0) {
1543 if (tag == saved_tag) {
1544 lowest_common_ancestor = tag;
1545 break;
1546 }
1547 tag = tag->prev;
1548 saved_tag = saved_tag->prev;
1549 --min_tags;
1550 }
1551
1552 /* free all the jump buffers between the current EC's tag and the lowest common ancestor tag */
1553 for (struct rb_vm_tag *tag = th->ec->tag; tag != lowest_common_ancestor; tag = tag->prev) {
1554 rb_vm_tag_jmpbuf_deinit(&tag->buf);
1555 }
1556 }
1557#endif
1558
1559 /* copy vm stack */
1560#ifdef CAPTURE_JUST_VALID_VM_STACK
1561 MEMCPY(th->ec->vm_stack,
1562 cont->saved_vm_stack.ptr,
1563 VALUE, cont->saved_vm_stack.slen);
1564 MEMCPY(th->ec->vm_stack + th->ec->vm_stack_size - cont->saved_vm_stack.clen,
1565 cont->saved_vm_stack.ptr + cont->saved_vm_stack.slen,
1566 VALUE, cont->saved_vm_stack.clen);
1567#else
1568 MEMCPY(th->ec->vm_stack, cont->saved_vm_stack.ptr, VALUE, sec->vm_stack_size);
1569#endif
1570 /* other members of ec */
1571
1572 th->ec->cfp = sec->cfp;
1573 th->ec->raised_flag = sec->raised_flag;
1574 th->ec->tag = sec->tag;
1575 th->ec->root_lep = sec->root_lep;
1576 th->ec->root_svar = sec->root_svar;
1577 th->ec->errinfo = sec->errinfo;
1578
1579 VM_ASSERT(th->ec->vm_stack != NULL);
1580 }
1581 else {
1582 /* fiber */
1583 fiber_restore_thread(th, (rb_fiber_t*)cont);
1584 }
1585}
1586
1587NOINLINE(static void fiber_setcontext(rb_fiber_t *new_fiber, rb_fiber_t *old_fiber));
1588
1589static void
1590fiber_setcontext(rb_fiber_t *new_fiber, rb_fiber_t *old_fiber)
1591{
1592 rb_thread_t *th = GET_THREAD();
1593
1594 /* save old_fiber's machine stack - to ensure efficient garbage collection */
1595 if (!FIBER_TERMINATED_P(old_fiber)) {
1596 STACK_GROW_DIR_DETECTION;
1597 SET_MACHINE_STACK_END(&th->ec->machine.stack_end);
1598 if (STACK_DIR_UPPER(0, 1)) {
1599 old_fiber->cont.machine.stack_size = th->ec->machine.stack_start - th->ec->machine.stack_end;
1600 old_fiber->cont.machine.stack = th->ec->machine.stack_end;
1601 }
1602 else {
1603 old_fiber->cont.machine.stack_size = th->ec->machine.stack_end - th->ec->machine.stack_start;
1604 old_fiber->cont.machine.stack = th->ec->machine.stack_start;
1605 }
1606 }
1607
1608 /* these values are used in rb_gc_mark_machine_context to mark the fiber's stack. */
1609 old_fiber->cont.saved_ec.machine.stack_start = th->ec->machine.stack_start;
1610 old_fiber->cont.saved_ec.machine.stack_end = FIBER_TERMINATED_P(old_fiber) ? NULL : th->ec->machine.stack_end;
1611
1612
1613 // 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);
1614
1615#if defined(COROUTINE_SANITIZE_ADDRESS)
1616 __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);
1617#endif
1618
1619 /* swap machine context */
1620 struct coroutine_context * from = coroutine_transfer(&old_fiber->context, &new_fiber->context);
1621
1622#if defined(COROUTINE_SANITIZE_ADDRESS)
1623 __sanitizer_finish_switch_fiber(old_fiber->context.fake_stack, NULL, NULL);
1624#endif
1625
1626 if (from == NULL) {
1627 rb_syserr_fail(errno, "coroutine_transfer");
1628 }
1629
1630 /* restore thread context */
1631 fiber_restore_thread(th, old_fiber);
1632
1633 // It's possible to get here, and new_fiber is already freed.
1634 // if (DEBUG) fprintf(stderr, "fiber_setcontext: %p[%p] <- %p[%p]\n", (void*)old_fiber, old_fiber->stack.base, (void*)new_fiber, new_fiber->stack.base);
1635}
1636
1637NOINLINE(NORETURN(static void cont_restore_1(rb_context_t *)));
1638
1639static void
1640cont_restore_1(rb_context_t *cont)
1641{
1642 cont_restore_thread(cont);
1643
1644 /* restore machine stack */
1645#if (defined(_M_AMD64) && !defined(__MINGW64__)) || defined(_M_ARM64)
1646 {
1647 /* workaround for x64 and arm64 SEH on Windows */
1648 jmp_buf buf;
1649 setjmp(buf);
1650 _JUMP_BUFFER *bp = (void*)&cont->jmpbuf;
1651 bp->Frame = ((_JUMP_BUFFER*)((void*)&buf))->Frame;
1652 }
1653#endif
1654 if (cont->machine.stack_src) {
1655 FLUSH_REGISTER_WINDOWS;
1656 MEMCPY(cont->machine.stack_src, cont->machine.stack,
1657 VALUE, cont->machine.stack_size);
1658 }
1659
1660 ruby_longjmp(cont->jmpbuf, 1);
1661}
1662
1663NORETURN(NOINLINE(static void cont_restore_0(rb_context_t *, VALUE *)));
1664
1665static void
1666cont_restore_0(rb_context_t *cont, VALUE *addr_in_prev_frame)
1667{
1668 if (cont->machine.stack_src) {
1669#ifdef HAVE_ALLOCA
1670#define STACK_PAD_SIZE 1
1671#else
1672#define STACK_PAD_SIZE 1024
1673#endif
1674 VALUE space[STACK_PAD_SIZE];
1675
1676#if !STACK_GROW_DIRECTION
1677 if (addr_in_prev_frame > &space[0]) {
1678 /* Stack grows downward */
1679#endif
1680#if STACK_GROW_DIRECTION <= 0
1681 volatile VALUE *const end = cont->machine.stack_src;
1682 if (&space[0] > end) {
1683# ifdef HAVE_ALLOCA
1684 volatile VALUE *sp = ALLOCA_N(VALUE, &space[0] - end);
1685 // We need to make sure that the stack pointer is moved,
1686 // but some compilers may remove the allocation by optimization.
1687 // We hope that the following read/write will prevent such an optimization.
1688 *sp = Qfalse;
1689 space[0] = *sp;
1690# else
1691 cont_restore_0(cont, &space[0]);
1692# endif
1693 }
1694#endif
1695#if !STACK_GROW_DIRECTION
1696 }
1697 else {
1698 /* Stack grows upward */
1699#endif
1700#if STACK_GROW_DIRECTION >= 0
1701 volatile VALUE *const end = cont->machine.stack_src + cont->machine.stack_size;
1702 if (&space[STACK_PAD_SIZE] < end) {
1703# ifdef HAVE_ALLOCA
1704 volatile VALUE *sp = ALLOCA_N(VALUE, end - &space[STACK_PAD_SIZE]);
1705 space[0] = *sp;
1706# else
1707 cont_restore_0(cont, &space[STACK_PAD_SIZE-1]);
1708# endif
1709 }
1710#endif
1711#if !STACK_GROW_DIRECTION
1712 }
1713#endif
1714 }
1715 cont_restore_1(cont);
1716}
1717
1718/*
1719 * Document-class: Continuation
1720 *
1721 * Continuation objects are generated by Kernel#callcc,
1722 * after having +require+d <i>continuation</i>. They hold
1723 * a return address and execution context, allowing a nonlocal return
1724 * to the end of the #callcc block from anywhere within a
1725 * program. Continuations are somewhat analogous to a structured
1726 * version of C's <code>setjmp/longjmp</code> (although they contain
1727 * more state, so you might consider them closer to threads).
1728 *
1729 * For instance:
1730 *
1731 * require "continuation"
1732 * arr = [ "Freddie", "Herbie", "Ron", "Max", "Ringo" ]
1733 * callcc{|cc| $cc = cc}
1734 * puts(message = arr.shift)
1735 * $cc.call unless message =~ /Max/
1736 *
1737 * <em>produces:</em>
1738 *
1739 * Freddie
1740 * Herbie
1741 * Ron
1742 * Max
1743 *
1744 * Also you can call callcc in other methods:
1745 *
1746 * require "continuation"
1747 *
1748 * def g
1749 * arr = [ "Freddie", "Herbie", "Ron", "Max", "Ringo" ]
1750 * cc = callcc { |cc| cc }
1751 * puts arr.shift
1752 * return cc, arr.size
1753 * end
1754 *
1755 * def f
1756 * c, size = g
1757 * c.call(c) if size > 1
1758 * end
1759 *
1760 * f
1761 *
1762 * This (somewhat contrived) example allows the inner loop to abandon
1763 * processing early:
1764 *
1765 * require "continuation"
1766 * callcc {|cont|
1767 * for i in 0..4
1768 * print "#{i}: "
1769 * for j in i*5...(i+1)*5
1770 * cont.call() if j == 17
1771 * printf "%3d", j
1772 * end
1773 * end
1774 * }
1775 * puts
1776 *
1777 * <em>produces:</em>
1778 *
1779 * 0: 0 1 2 3 4
1780 * 1: 5 6 7 8 9
1781 * 2: 10 11 12 13 14
1782 * 3: 15 16
1783 */
1784
1785/*
1786 * call-seq:
1787 * callcc {|cont| block } -> obj
1788 *
1789 * Generates a Continuation object, which it passes to
1790 * the associated block. You need to <code>require
1791 * 'continuation'</code> before using this method. Performing a
1792 * <em>cont</em><code>.call</code> will cause the #callcc
1793 * to return (as will falling through the end of the block). The
1794 * value returned by the #callcc is the value of the
1795 * block, or the value passed to <em>cont</em><code>.call</code>. See
1796 * class Continuation for more details. Also see
1797 * Kernel#throw for an alternative mechanism for
1798 * unwinding a call stack.
1799 */
1800
1801static VALUE
1802rb_callcc(VALUE self)
1803{
1804 volatile int called;
1805 volatile VALUE val = cont_capture(&called);
1806
1807 if (called) {
1808 return val;
1809 }
1810 else {
1811 return rb_yield(val);
1812 }
1813}
1814#ifdef RUBY_ASAN_ENABLED
1815/* callcc can't possibly work with ASAN; see bug #20273. Also this function
1816 * definition below avoids a "defined and not used" warning. */
1817MAYBE_UNUSED(static void notusing_callcc(void)) { rb_callcc(Qnil); }
1818# define rb_callcc rb_f_notimplement
1819#endif
1820
1821
1822static VALUE
1823make_passing_arg(int argc, const VALUE *argv)
1824{
1825 switch (argc) {
1826 case -1:
1827 return argv[0];
1828 case 0:
1829 return Qnil;
1830 case 1:
1831 return argv[0];
1832 default:
1833 return rb_ary_new4(argc, argv);
1834 }
1835}
1836
1837typedef VALUE e_proc(VALUE);
1838
1839NORETURN(static VALUE rb_cont_call(int argc, VALUE *argv, VALUE contval));
1840
1841/*
1842 * call-seq:
1843 * cont.call(args, ...)
1844 * cont[args, ...]
1845 *
1846 * Invokes the continuation. The program continues from the end of
1847 * the #callcc block. If no arguments are given, the original #callcc
1848 * returns +nil+. If one argument is given, #callcc returns
1849 * it. Otherwise, an array containing <i>args</i> is returned.
1850 *
1851 * callcc {|cont| cont.call } #=> nil
1852 * callcc {|cont| cont.call 1 } #=> 1
1853 * callcc {|cont| cont.call 1, 2, 3 } #=> [1, 2, 3]
1854 */
1855
1856static VALUE
1857rb_cont_call(int argc, VALUE *argv, VALUE contval)
1858{
1859 rb_context_t *cont = cont_ptr(contval);
1860 rb_thread_t *th = GET_THREAD();
1861
1862 if (cont_thread_value(cont) != th->self) {
1863 rb_raise(rb_eRuntimeError, "continuation called across threads");
1864 }
1865 if (cont->saved_ec.fiber_ptr) {
1866 if (th->ec->fiber_ptr != cont->saved_ec.fiber_ptr) {
1867 rb_raise(rb_eRuntimeError, "continuation called across fiber");
1868 }
1869 }
1870
1871 cont->argc = argc;
1872 cont->value = make_passing_arg(argc, argv);
1873
1874 cont_restore_0(cont, &contval);
1876}
1877
1878/*********/
1879/* fiber */
1880/*********/
1881
1882/*
1883 * Document-class: Fiber
1884 *
1885 * Fibers are primitives for implementing light weight cooperative
1886 * concurrency in Ruby. Basically they are a means of creating code blocks
1887 * that can be paused and resumed, much like threads. The main difference
1888 * is that they are never preempted and that the scheduling must be done by
1889 * the programmer and not the VM.
1890 *
1891 * As opposed to other stackless light weight concurrency models, each fiber
1892 * comes with a stack. This enables the fiber to be paused from deeply
1893 * nested function calls within the fiber block. See the ruby(1)
1894 * manpage to configure the size of the fiber stack(s).
1895 *
1896 * When a fiber is created it will not run automatically. Rather it must
1897 * be explicitly asked to run using the Fiber#resume method.
1898 * The code running inside the fiber can give up control by calling
1899 * Fiber.yield in which case it yields control back to caller (the
1900 * caller of the Fiber#resume).
1901 *
1902 * Upon yielding or termination the Fiber returns the value of the last
1903 * executed expression
1904 *
1905 * For instance:
1906 *
1907 * fiber = Fiber.new do
1908 * Fiber.yield 1
1909 * 2
1910 * end
1911 *
1912 * puts fiber.resume
1913 * puts fiber.resume
1914 * puts fiber.resume
1915 *
1916 * <em>produces</em>
1917 *
1918 * 1
1919 * 2
1920 * FiberError: dead fiber called
1921 *
1922 * The Fiber#resume method accepts an arbitrary number of parameters,
1923 * if it is the first call to #resume then they will be passed as
1924 * block arguments. Otherwise they will be the return value of the
1925 * call to Fiber.yield
1926 *
1927 * Example:
1928 *
1929 * fiber = Fiber.new do |first|
1930 * second = Fiber.yield first + 2
1931 * end
1932 *
1933 * puts fiber.resume 10
1934 * puts fiber.resume 1_000_000
1935 * puts fiber.resume "The fiber will be dead before I can cause trouble"
1936 *
1937 * <em>produces</em>
1938 *
1939 * 12
1940 * 1000000
1941 * FiberError: dead fiber called
1942 *
1943 * == Non-blocking Fibers
1944 *
1945 * The concept of <em>non-blocking fiber</em> was introduced in Ruby 3.0.
1946 * A non-blocking fiber, when reaching an operation that would normally block
1947 * the fiber (like <code>sleep</code>, or wait for another process or I/O)
1948 * will yield control to other fibers and allow the <em>scheduler</em> to
1949 * handle blocking and waking up (resuming) this fiber when it can proceed.
1950 *
1951 * For a Fiber to behave as non-blocking, it need to be created in Fiber.new with
1952 * <tt>blocking: false</tt> (which is the default), and Fiber.scheduler
1953 * should be set with Fiber.set_scheduler. If Fiber.scheduler is not set in
1954 * the current thread, blocking and non-blocking fibers' behavior is identical.
1955 *
1956 * Ruby doesn't provide a scheduler class: it is expected to be implemented by
1957 * the user and correspond to Fiber::Scheduler.
1958 *
1959 * There is also Fiber.schedule method, which is expected to immediately perform
1960 * the given block in a non-blocking manner. Its actual implementation is up to
1961 * the scheduler.
1962 *
1963 */
1964
1965static const rb_data_type_t fiber_data_type = {
1966 "fiber",
1967 {fiber_mark, fiber_free, fiber_memsize, fiber_compact,},
1968 0, 0, RUBY_TYPED_FREE_IMMEDIATELY
1969};
1970
1971static VALUE
1972fiber_alloc(VALUE klass)
1973{
1974 return TypedData_Wrap_Struct(klass, &fiber_data_type, 0);
1975}
1976
1977static rb_fiber_t*
1978fiber_t_alloc(VALUE fiber_value, unsigned int blocking)
1979{
1980 rb_fiber_t *fiber;
1981 rb_thread_t *th = GET_THREAD();
1982
1983 if (DATA_PTR(fiber_value) != 0) {
1984 rb_raise(rb_eRuntimeError, "cannot initialize twice");
1985 }
1986
1987 THREAD_MUST_BE_RUNNING(th);
1988 fiber = ZALLOC(rb_fiber_t);
1989 fiber->cont.self = fiber_value;
1990 fiber->cont.type = FIBER_CONTEXT;
1991 fiber->blocking = blocking;
1992 fiber->killed = 0;
1993 cont_init(&fiber->cont, th);
1994
1995 fiber->cont.saved_ec.fiber_ptr = fiber;
1996 rb_ec_clear_vm_stack(&fiber->cont.saved_ec);
1997
1998 fiber->prev = NULL;
1999
2000 /* fiber->status == 0 == CREATED
2001 * So that we don't need to set status: fiber_status_set(fiber, FIBER_CREATED); */
2002 VM_ASSERT(FIBER_CREATED_P(fiber));
2003
2004 DATA_PTR(fiber_value) = fiber;
2005
2006 return fiber;
2007}
2008
2009static rb_fiber_t *
2010root_fiber_alloc(rb_thread_t *th)
2011{
2012 VALUE fiber_value = fiber_alloc(rb_cFiber);
2013 rb_fiber_t *fiber = th->ec->fiber_ptr;
2014
2015 VM_ASSERT(DATA_PTR(fiber_value) == NULL);
2016 VM_ASSERT(fiber->cont.type == FIBER_CONTEXT);
2017 VM_ASSERT(FIBER_RESUMED_P(fiber));
2018
2019 th->root_fiber = fiber;
2020 DATA_PTR(fiber_value) = fiber;
2021 fiber->cont.self = fiber_value;
2022
2023 coroutine_initialize_main(&fiber->context);
2024
2025 return fiber;
2026}
2027
2028static inline rb_fiber_t*
2029fiber_current(void)
2030{
2031 rb_execution_context_t *ec = GET_EC();
2032 if (ec->fiber_ptr->cont.self == 0) {
2033 root_fiber_alloc(rb_ec_thread_ptr(ec));
2034 }
2035 return ec->fiber_ptr;
2036}
2037
2038static inline VALUE
2039current_fiber_storage(void)
2040{
2041 rb_execution_context_t *ec = GET_EC();
2042 return ec->storage;
2043}
2044
2045static inline VALUE
2046inherit_fiber_storage(void)
2047{
2048 return rb_obj_dup(current_fiber_storage());
2049}
2050
2051static inline void
2052fiber_storage_set(struct rb_fiber_struct *fiber, VALUE storage)
2053{
2054 fiber->cont.saved_ec.storage = storage;
2055}
2056
2057static inline VALUE
2058fiber_storage_get(rb_fiber_t *fiber, int allocate)
2059{
2060 VALUE storage = fiber->cont.saved_ec.storage;
2061 if (storage == Qnil && allocate) {
2062 storage = rb_hash_new();
2063 fiber_storage_set(fiber, storage);
2064 }
2065 return storage;
2066}
2067
2068static void
2069storage_access_must_be_from_same_fiber(VALUE self)
2070{
2071 rb_fiber_t *fiber = fiber_ptr(self);
2072 rb_fiber_t *current = fiber_current();
2073 if (fiber != current) {
2074 rb_raise(rb_eArgError, "Fiber storage can only be accessed from the Fiber it belongs to");
2075 }
2076}
2077
2084static VALUE
2085rb_fiber_storage_get(VALUE self)
2086{
2087 storage_access_must_be_from_same_fiber(self);
2088
2089 VALUE storage = fiber_storage_get(fiber_ptr(self), FALSE);
2090
2091 if (storage == Qnil) {
2092 return Qnil;
2093 }
2094 else {
2095 return rb_obj_dup(storage);
2096 }
2097}
2098
2099static int
2100fiber_storage_validate_each(VALUE key, VALUE value, VALUE _argument)
2101{
2102 Check_Type(key, T_SYMBOL);
2103
2104 return ST_CONTINUE;
2105}
2106
2107static void
2108fiber_storage_validate(VALUE value)
2109{
2110 // nil is an allowed value and will be lazily initialized.
2111 if (value == Qnil) return;
2112
2113 if (!RB_TYPE_P(value, T_HASH)) {
2114 rb_raise(rb_eTypeError, "storage must be a hash");
2115 }
2116
2117 if (RB_OBJ_FROZEN(value)) {
2118 rb_raise(rb_eFrozenError, "storage must not be frozen");
2119 }
2120
2121 rb_hash_foreach(value, fiber_storage_validate_each, Qundef);
2122}
2123
2146static VALUE
2147rb_fiber_storage_set(VALUE self, VALUE value)
2148{
2149 if (rb_warning_category_enabled_p(RB_WARN_CATEGORY_EXPERIMENTAL)) {
2151 "Fiber#storage= is experimental and may be removed in the future!");
2152 }
2153
2154 storage_access_must_be_from_same_fiber(self);
2155 fiber_storage_validate(value);
2156
2157 fiber_ptr(self)->cont.saved_ec.storage = rb_obj_dup(value);
2158 return value;
2159}
2160
2171static VALUE
2172rb_fiber_storage_aref(VALUE class, VALUE key)
2173{
2174 key = rb_to_symbol(key);
2175
2176 VALUE storage = fiber_storage_get(fiber_current(), FALSE);
2177 if (storage == Qnil) return Qnil;
2178
2179 return rb_hash_aref(storage, key);
2180}
2181
2192static VALUE
2193rb_fiber_storage_aset(VALUE class, VALUE key, VALUE value)
2194{
2195 key = rb_to_symbol(key);
2196
2197 VALUE storage = fiber_storage_get(fiber_current(), value != Qnil);
2198 if (storage == Qnil) return Qnil;
2199
2200 if (value == Qnil) {
2201 return rb_hash_delete(storage, key);
2202 }
2203 else {
2204 return rb_hash_aset(storage, key, value);
2205 }
2206}
2207
2208static VALUE
2209fiber_initialize(VALUE self, VALUE proc, struct fiber_pool * fiber_pool, unsigned int blocking, VALUE storage)
2210{
2211 if (storage == Qundef || storage == Qtrue) {
2212 // The default, inherit storage (dup) from the current fiber:
2213 storage = inherit_fiber_storage();
2214 }
2215 else /* nil, hash, etc. */ {
2216 fiber_storage_validate(storage);
2217 storage = rb_obj_dup(storage);
2218 }
2219
2220 rb_fiber_t *fiber = fiber_t_alloc(self, blocking);
2221
2222 fiber->cont.saved_ec.storage = storage;
2223 fiber->first_proc = proc;
2224 fiber->stack.base = NULL;
2225 fiber->stack.pool = fiber_pool;
2226
2227 return self;
2228}
2229
2230static void
2231fiber_prepare_stack(rb_fiber_t *fiber)
2232{
2233 rb_context_t *cont = &fiber->cont;
2234 rb_execution_context_t *sec = &cont->saved_ec;
2235
2236 size_t vm_stack_size = 0;
2237 VALUE *vm_stack = fiber_initialize_coroutine(fiber, &vm_stack_size);
2238
2239 /* initialize cont */
2240 cont->saved_vm_stack.ptr = NULL;
2241 rb_ec_initialize_vm_stack(sec, vm_stack, vm_stack_size / sizeof(VALUE));
2242
2243 sec->tag = NULL;
2244 sec->local_storage = NULL;
2245 sec->local_storage_recursive_hash = Qnil;
2246 sec->local_storage_recursive_hash_for_trace = Qnil;
2247}
2248
2249static struct fiber_pool *
2250rb_fiber_pool_default(VALUE pool)
2251{
2252 return &shared_fiber_pool;
2253}
2254
2255VALUE rb_fiber_inherit_storage(struct rb_execution_context_struct *ec, struct rb_fiber_struct *fiber)
2256{
2257 VALUE storage = rb_obj_dup(ec->storage);
2258 fiber->cont.saved_ec.storage = storage;
2259 return storage;
2260}
2261
2262/* :nodoc: */
2263static VALUE
2264rb_fiber_initialize_kw(int argc, VALUE* argv, VALUE self, int kw_splat)
2265{
2266 VALUE pool = Qnil;
2267 VALUE blocking = Qfalse;
2268 VALUE storage = Qundef;
2269
2270 if (kw_splat != RB_NO_KEYWORDS) {
2271 VALUE options = Qnil;
2272 VALUE arguments[3] = {Qundef};
2273
2274 argc = rb_scan_args_kw(kw_splat, argc, argv, ":", &options);
2275 rb_get_kwargs(options, fiber_initialize_keywords, 0, 3, arguments);
2276
2277 if (!UNDEF_P(arguments[0])) {
2278 blocking = arguments[0];
2279 }
2280
2281 if (!UNDEF_P(arguments[1])) {
2282 pool = arguments[1];
2283 }
2284
2285 storage = arguments[2];
2286 }
2287
2288 return fiber_initialize(self, rb_block_proc(), rb_fiber_pool_default(pool), RTEST(blocking), storage);
2289}
2290
2291/*
2292 * call-seq:
2293 * Fiber.new(blocking: false, storage: true) { |*args| ... } -> fiber
2294 *
2295 * Creates new Fiber. Initially, the fiber is not running and can be resumed
2296 * with #resume. Arguments to the first #resume call will be passed to the
2297 * block:
2298 *
2299 * f = Fiber.new do |initial|
2300 * current = initial
2301 * loop do
2302 * puts "current: #{current.inspect}"
2303 * current = Fiber.yield
2304 * end
2305 * end
2306 * f.resume(100) # prints: current: 100
2307 * f.resume(1, 2, 3) # prints: current: [1, 2, 3]
2308 * f.resume # prints: current: nil
2309 * # ... and so on ...
2310 *
2311 * If <tt>blocking: false</tt> is passed to <tt>Fiber.new</tt>, _and_ current
2312 * thread has a Fiber.scheduler defined, the Fiber becomes non-blocking (see
2313 * "Non-blocking Fibers" section in class docs).
2314 *
2315 * If the <tt>storage</tt> is unspecified, the default is to inherit a copy of
2316 * the storage from the current fiber. This is the same as specifying
2317 * <tt>storage: true</tt>.
2318 *
2319 * Fiber[:x] = 1
2320 * Fiber.new do
2321 * Fiber[:x] # => 1
2322 * Fiber[:x] = 2
2323 * end.resume
2324 * Fiber[:x] # => 1
2325 *
2326 * If the given <tt>storage</tt> is <tt>nil</tt>, this function will lazy
2327 * initialize the internal storage, which starts as an empty hash.
2328 *
2329 * Fiber[:x] = "Hello World"
2330 * Fiber.new(storage: nil) do
2331 * Fiber[:x] # nil
2332 * end
2333 *
2334 * Otherwise, the given <tt>storage</tt> is used as the new fiber's storage,
2335 * and it must be an instance of Hash.
2336 *
2337 * Explicitly using <tt>storage: true</tt> is currently experimental and may
2338 * change in the future.
2339 */
2340static VALUE
2341rb_fiber_initialize(int argc, VALUE* argv, VALUE self)
2342{
2343 return rb_fiber_initialize_kw(argc, argv, self, rb_keyword_given_p());
2344}
2345
2346VALUE
2347rb_fiber_new_storage(rb_block_call_func_t func, VALUE obj, VALUE storage)
2348{
2349 return fiber_initialize(fiber_alloc(rb_cFiber), rb_proc_new(func, obj), rb_fiber_pool_default(Qnil), 0, storage);
2350}
2351
2352VALUE
2353rb_fiber_new(rb_block_call_func_t func, VALUE obj)
2354{
2355 return rb_fiber_new_storage(func, obj, Qtrue);
2356}
2357
2358static VALUE
2359rb_fiber_s_schedule_kw(int argc, VALUE* argv, int kw_splat)
2360{
2361 rb_thread_t * th = GET_THREAD();
2362 VALUE scheduler = th->scheduler;
2363 VALUE fiber = Qnil;
2364
2365 if (scheduler != Qnil) {
2366 fiber = rb_fiber_scheduler_fiber(scheduler, argc, argv, kw_splat);
2367 }
2368 else {
2369 rb_raise(rb_eRuntimeError, "No scheduler is available!");
2370 }
2371
2372 return fiber;
2373}
2374
2375/*
2376 * call-seq:
2377 * Fiber.schedule { |*args| ... } -> fiber
2378 *
2379 * The method is <em>expected</em> to immediately run the provided block of code in a
2380 * separate non-blocking fiber.
2381 *
2382 * puts "Go to sleep!"
2383 *
2384 * Fiber.set_scheduler(MyScheduler.new)
2385 *
2386 * Fiber.schedule do
2387 * puts "Going to sleep"
2388 * sleep(1)
2389 * puts "I slept well"
2390 * end
2391 *
2392 * puts "Wakey-wakey, sleepyhead"
2393 *
2394 * Assuming MyScheduler is properly implemented, this program will produce:
2395 *
2396 * Go to sleep!
2397 * Going to sleep
2398 * Wakey-wakey, sleepyhead
2399 * ...1 sec pause here...
2400 * I slept well
2401 *
2402 * ...e.g. on the first blocking operation inside the Fiber (<tt>sleep(1)</tt>),
2403 * the control is yielded to the outside code (main fiber), and <em>at the end
2404 * of that execution</em>, the scheduler takes care of properly resuming all the
2405 * blocked fibers.
2406 *
2407 * Note that the behavior described above is how the method is <em>expected</em>
2408 * to behave, actual behavior is up to the current scheduler's implementation of
2409 * Fiber::Scheduler#fiber method. Ruby doesn't enforce this method to
2410 * behave in any particular way.
2411 *
2412 * If the scheduler is not set, the method raises
2413 * <tt>RuntimeError (No scheduler is available!)</tt>.
2414 *
2415 */
2416static VALUE
2417rb_fiber_s_schedule(int argc, VALUE *argv, VALUE obj)
2418{
2419 return rb_fiber_s_schedule_kw(argc, argv, rb_keyword_given_p());
2420}
2421
2422/*
2423 * call-seq:
2424 * Fiber.scheduler -> obj or nil
2425 *
2426 * Returns the Fiber scheduler, that was last set for the current thread with Fiber.set_scheduler.
2427 * Returns +nil+ if no scheduler is set (which is the default), and non-blocking fibers'
2428 * behavior is the same as blocking.
2429 * (see "Non-blocking fibers" section in class docs for details about the scheduler concept).
2430 *
2431 */
2432static VALUE
2433rb_fiber_s_scheduler(VALUE klass)
2434{
2435 return rb_fiber_scheduler_get();
2436}
2437
2438/*
2439 * call-seq:
2440 * Fiber.current_scheduler -> obj or nil
2441 *
2442 * Returns the Fiber scheduler, that was last set for the current thread with Fiber.set_scheduler
2443 * if and only if the current fiber is non-blocking.
2444 *
2445 */
2446static VALUE
2447rb_fiber_current_scheduler(VALUE klass)
2448{
2450}
2451
2452/*
2453 * call-seq:
2454 * Fiber.set_scheduler(scheduler) -> scheduler
2455 *
2456 * Sets the Fiber scheduler for the current thread. If the scheduler is set, non-blocking
2457 * fibers (created by Fiber.new with <tt>blocking: false</tt>, or by Fiber.schedule)
2458 * call that scheduler's hook methods on potentially blocking operations, and the current
2459 * thread will call scheduler's +close+ method on finalization (allowing the scheduler to
2460 * properly manage all non-finished fibers).
2461 *
2462 * +scheduler+ can be an object of any class corresponding to Fiber::Scheduler. Its
2463 * implementation is up to the user.
2464 *
2465 * See also the "Non-blocking fibers" section in class docs.
2466 *
2467 */
2468static VALUE
2469rb_fiber_set_scheduler(VALUE klass, VALUE scheduler)
2470{
2471 return rb_fiber_scheduler_set(scheduler);
2472}
2473
2474NORETURN(static void rb_fiber_terminate(rb_fiber_t *fiber, int need_interrupt, VALUE err));
2475
2476void
2477rb_fiber_start(rb_fiber_t *fiber)
2478{
2479 rb_thread_t * volatile th = fiber->cont.saved_ec.thread_ptr;
2480
2481 rb_proc_t *proc;
2482 enum ruby_tag_type state;
2483
2484 VM_ASSERT(th->ec == GET_EC());
2485 VM_ASSERT(FIBER_RESUMED_P(fiber));
2486
2487 if (fiber->blocking) {
2488 th->blocking += 1;
2489 }
2490
2491 EC_PUSH_TAG(th->ec);
2492 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
2493 rb_context_t *cont = &VAR_FROM_MEMORY(fiber)->cont;
2494 int argc;
2495 const VALUE *argv, args = cont->value;
2496 GetProcPtr(fiber->first_proc, proc);
2497 argv = (argc = cont->argc) > 1 ? RARRAY_CONST_PTR(args) : &args;
2498 cont->value = Qnil;
2499 th->ec->errinfo = Qnil;
2500 th->ec->root_lep = rb_vm_proc_local_ep(fiber->first_proc);
2501 th->ec->root_svar = Qfalse;
2502
2503 EXEC_EVENT_HOOK(th->ec, RUBY_EVENT_FIBER_SWITCH, th->self, 0, 0, 0, Qnil);
2504 cont->value = rb_vm_invoke_proc(th->ec, proc, argc, argv, cont->kw_splat, VM_BLOCK_HANDLER_NONE);
2505 }
2506 EC_POP_TAG();
2507
2508 int need_interrupt = TRUE;
2509 VALUE err = Qfalse;
2510 if (state) {
2511 err = th->ec->errinfo;
2512 VM_ASSERT(FIBER_RESUMED_P(fiber));
2513
2514 if (state == TAG_RAISE) {
2515 // noop...
2516 }
2517 else if (state == TAG_FATAL && err == RUBY_FATAL_FIBER_KILLED) {
2518 need_interrupt = FALSE;
2519 err = Qfalse;
2520 }
2521 else if (state == TAG_FATAL) {
2522 rb_threadptr_pending_interrupt_enque(th, err);
2523 }
2524 else {
2525 err = rb_vm_make_jump_tag_but_local_jump(state, err);
2526 }
2527 }
2528
2529 rb_fiber_terminate(fiber, need_interrupt, err);
2530}
2531
2532// Set up a "root fiber", which is the fiber that every Ractor has.
2533void
2534rb_threadptr_root_fiber_setup(rb_thread_t *th)
2535{
2536 rb_fiber_t *fiber = ruby_mimcalloc(1, sizeof(rb_fiber_t));
2537 if (!fiber) {
2538 rb_bug("%s", strerror(errno)); /* ... is it possible to call rb_bug here? */
2539 }
2540 fiber->cont.type = FIBER_CONTEXT;
2541 fiber->cont.saved_ec.fiber_ptr = fiber;
2542 fiber->cont.saved_ec.thread_ptr = th;
2543 fiber->blocking = 1;
2544 fiber->killed = 0;
2545 fiber_status_set(fiber, FIBER_RESUMED); /* skip CREATED */
2546 th->ec = &fiber->cont.saved_ec;
2547 cont_init_jit_cont(&fiber->cont);
2548}
2549
2550void
2551rb_threadptr_root_fiber_release(rb_thread_t *th)
2552{
2553 if (th->root_fiber) {
2554 /* ignore. A root fiber object will free th->ec */
2555 }
2556 else {
2557 rb_execution_context_t *ec = rb_current_execution_context(false);
2558
2559 VM_ASSERT(th->ec->fiber_ptr->cont.type == FIBER_CONTEXT);
2560 VM_ASSERT(th->ec->fiber_ptr->cont.self == 0);
2561
2562 if (ec && th->ec == ec) {
2563 rb_ractor_set_current_ec(th->ractor, NULL);
2564 }
2565 fiber_free(th->ec->fiber_ptr);
2566 th->ec = NULL;
2567 }
2568}
2569
2570void
2571rb_threadptr_root_fiber_terminate(rb_thread_t *th)
2572{
2573 rb_fiber_t *fiber = th->ec->fiber_ptr;
2574
2575 fiber->status = FIBER_TERMINATED;
2576
2577 // The vm_stack is `alloca`ed on the thread stack, so it's gone too:
2578 rb_ec_clear_vm_stack(th->ec);
2579}
2580
2581static inline rb_fiber_t*
2582return_fiber(bool terminate)
2583{
2584 rb_fiber_t *fiber = fiber_current();
2585 rb_fiber_t *prev = fiber->prev;
2586
2587 if (prev) {
2588 fiber->prev = NULL;
2589 prev->resuming_fiber = NULL;
2590 return prev;
2591 }
2592 else {
2593 if (!terminate) {
2594 rb_raise(rb_eFiberError, "attempt to yield on a not resumed fiber");
2595 }
2596
2597 rb_thread_t *th = GET_THREAD();
2598 rb_fiber_t *root_fiber = th->root_fiber;
2599
2600 VM_ASSERT(root_fiber != NULL);
2601
2602 // search resuming fiber
2603 for (fiber = root_fiber; fiber->resuming_fiber; fiber = fiber->resuming_fiber) {
2604 }
2605
2606 return fiber;
2607 }
2608}
2609
2610VALUE
2611rb_fiber_current(void)
2612{
2613 return fiber_current()->cont.self;
2614}
2615
2616// Prepare to execute next_fiber on the given thread.
2617static inline void
2618fiber_store(rb_fiber_t *next_fiber, rb_thread_t *th)
2619{
2620 rb_fiber_t *fiber;
2621
2622 if (th->ec->fiber_ptr != NULL) {
2623 fiber = th->ec->fiber_ptr;
2624 }
2625 else {
2626 /* create root fiber */
2627 fiber = root_fiber_alloc(th);
2628 }
2629
2630 if (FIBER_CREATED_P(next_fiber)) {
2631 fiber_prepare_stack(next_fiber);
2632 }
2633
2634 VM_ASSERT(FIBER_RESUMED_P(fiber) || FIBER_TERMINATED_P(fiber));
2635 VM_ASSERT(FIBER_RUNNABLE_P(next_fiber));
2636
2637 if (FIBER_RESUMED_P(fiber)) fiber_status_set(fiber, FIBER_SUSPENDED);
2638
2639 fiber_status_set(next_fiber, FIBER_RESUMED);
2640 fiber_setcontext(next_fiber, fiber);
2641}
2642
2643static void
2644fiber_check_killed(rb_fiber_t *fiber)
2645{
2646 VM_ASSERT(fiber == fiber_current());
2647
2648 if (fiber->killed) {
2649 rb_thread_t *thread = fiber->cont.saved_ec.thread_ptr;
2650
2651 thread->ec->errinfo = RUBY_FATAL_FIBER_KILLED;
2652 EC_JUMP_TAG(thread->ec, RUBY_TAG_FATAL);
2653 }
2654}
2655
2656static inline VALUE
2657fiber_switch(rb_fiber_t *fiber, int argc, const VALUE *argv, int kw_splat, rb_fiber_t *resuming_fiber, bool yielding)
2658{
2659 VALUE value;
2660 rb_context_t *cont = &fiber->cont;
2661 rb_thread_t *th = GET_THREAD();
2662
2663 /* make sure the root_fiber object is available */
2664 if (th->root_fiber == NULL) root_fiber_alloc(th);
2665
2666 if (th->ec->fiber_ptr == fiber) {
2667 /* ignore fiber context switch
2668 * because destination fiber is the same as current fiber
2669 */
2670 return make_passing_arg(argc, argv);
2671 }
2672
2673 if (cont_thread_value(cont) != th->self) {
2674 rb_raise(rb_eFiberError, "fiber called across threads");
2675 }
2676
2677 if (FIBER_TERMINATED_P(fiber)) {
2678 value = rb_exc_new2(rb_eFiberError, "dead fiber called");
2679
2680 if (!FIBER_TERMINATED_P(th->ec->fiber_ptr)) {
2681 rb_exc_raise(value);
2682 VM_UNREACHABLE(fiber_switch);
2683 }
2684 else {
2685 /* th->ec->fiber_ptr is also dead => switch to root fiber */
2686 /* (this means we're being called from rb_fiber_terminate, */
2687 /* and the terminated fiber's return_fiber() is already dead) */
2688 VM_ASSERT(FIBER_SUSPENDED_P(th->root_fiber));
2689
2690 cont = &th->root_fiber->cont;
2691 cont->argc = -1;
2692 cont->value = value;
2693
2694 fiber_setcontext(th->root_fiber, th->ec->fiber_ptr);
2695
2696 VM_UNREACHABLE(fiber_switch);
2697 }
2698 }
2699
2700 VM_ASSERT(FIBER_RUNNABLE_P(fiber));
2701
2702 rb_fiber_t *current_fiber = fiber_current();
2703
2704 VM_ASSERT(!current_fiber->resuming_fiber);
2705
2706 if (resuming_fiber) {
2707 current_fiber->resuming_fiber = resuming_fiber;
2708 fiber->prev = fiber_current();
2709 fiber->yielding = 0;
2710 }
2711
2712 VM_ASSERT(!current_fiber->yielding);
2713 if (yielding) {
2714 current_fiber->yielding = 1;
2715 }
2716
2717 if (current_fiber->blocking) {
2718 th->blocking -= 1;
2719 }
2720
2721 cont->argc = argc;
2722 cont->kw_splat = kw_splat;
2723 cont->value = make_passing_arg(argc, argv);
2724
2725 fiber_store(fiber, th);
2726
2727 // We cannot free the stack until the pthread is joined:
2728#ifndef COROUTINE_PTHREAD_CONTEXT
2729 if (resuming_fiber && FIBER_TERMINATED_P(fiber)) {
2730 fiber_stack_release(fiber);
2731 }
2732#endif
2733
2734 if (fiber_current()->blocking) {
2735 th->blocking += 1;
2736 }
2737
2738 RUBY_VM_CHECK_INTS(th->ec);
2739
2740 EXEC_EVENT_HOOK(th->ec, RUBY_EVENT_FIBER_SWITCH, th->self, 0, 0, 0, Qnil);
2741
2742 current_fiber = th->ec->fiber_ptr;
2743 value = current_fiber->cont.value;
2744
2745 fiber_check_killed(current_fiber);
2746
2747 if (current_fiber->cont.argc == -1) {
2748 // Fiber#raise will trigger this path.
2749 rb_exc_raise(value);
2750 }
2751
2752 return value;
2753}
2754
2755VALUE
2756rb_fiber_transfer(VALUE fiber_value, int argc, const VALUE *argv)
2757{
2758 return fiber_switch(fiber_ptr(fiber_value), argc, argv, RB_NO_KEYWORDS, NULL, false);
2759}
2760
2761/*
2762 * call-seq:
2763 * fiber.blocking? -> true or false
2764 *
2765 * Returns +true+ if +fiber+ is blocking and +false+ otherwise.
2766 * Fiber is non-blocking if it was created via passing <tt>blocking: false</tt>
2767 * to Fiber.new, or via Fiber.schedule.
2768 *
2769 * Note that, even if the method returns +false+, the fiber behaves differently
2770 * only if Fiber.scheduler is set in the current thread.
2771 *
2772 * See the "Non-blocking fibers" section in class docs for details.
2773 *
2774 */
2775VALUE
2776rb_fiber_blocking_p(VALUE fiber)
2777{
2778 return RBOOL(fiber_ptr(fiber)->blocking);
2779}
2780
2781static VALUE
2782fiber_blocking_yield(VALUE fiber_value)
2783{
2784 rb_fiber_t *fiber = fiber_ptr(fiber_value);
2785 rb_thread_t * volatile th = fiber->cont.saved_ec.thread_ptr;
2786
2787 VM_ASSERT(fiber->blocking == 0);
2788
2789 // fiber->blocking is `unsigned int : 1`, so we use it as a boolean:
2790 fiber->blocking = 1;
2791
2792 // Once the fiber is blocking, and current, we increment the thread blocking state:
2793 th->blocking += 1;
2794
2795 return rb_yield(fiber_value);
2796}
2797
2798static VALUE
2799fiber_blocking_ensure(VALUE fiber_value)
2800{
2801 rb_fiber_t *fiber = fiber_ptr(fiber_value);
2802 rb_thread_t * volatile th = fiber->cont.saved_ec.thread_ptr;
2803
2804 // We are no longer blocking:
2805 fiber->blocking = 0;
2806 th->blocking -= 1;
2807
2808 return Qnil;
2809}
2810
2811/*
2812 * call-seq:
2813 * Fiber.blocking{|fiber| ...} -> result
2814 *
2815 * Forces the fiber to be blocking for the duration of the block. Returns the
2816 * result of the block.
2817 *
2818 * See the "Non-blocking fibers" section in class docs for details.
2819 *
2820 */
2821VALUE
2822rb_fiber_blocking(VALUE class)
2823{
2824 VALUE fiber_value = rb_fiber_current();
2825 rb_fiber_t *fiber = fiber_ptr(fiber_value);
2826
2827 // If we are already blocking, this is essentially a no-op:
2828 if (fiber->blocking) {
2829 return rb_yield(fiber_value);
2830 }
2831 else {
2832 return rb_ensure(fiber_blocking_yield, fiber_value, fiber_blocking_ensure, fiber_value);
2833 }
2834}
2835
2836/*
2837 * call-seq:
2838 * Fiber.blocking? -> false or 1
2839 *
2840 * Returns +false+ if the current fiber is non-blocking.
2841 * Fiber is non-blocking if it was created via passing <tt>blocking: false</tt>
2842 * to Fiber.new, or via Fiber.schedule.
2843 *
2844 * If the current Fiber is blocking, the method returns 1.
2845 * Future developments may allow for situations where larger integers
2846 * could be returned.
2847 *
2848 * Note that, even if the method returns +false+, Fiber behaves differently
2849 * only if Fiber.scheduler is set in the current thread.
2850 *
2851 * See the "Non-blocking fibers" section in class docs for details.
2852 *
2853 */
2854static VALUE
2855rb_fiber_s_blocking_p(VALUE klass)
2856{
2857 rb_thread_t *thread = GET_THREAD();
2858 unsigned blocking = thread->blocking;
2859
2860 if (blocking == 0)
2861 return Qfalse;
2862
2863 return INT2NUM(blocking);
2864}
2865
2866void
2867rb_fiber_close(rb_fiber_t *fiber)
2868{
2869 fiber_status_set(fiber, FIBER_TERMINATED);
2870}
2871
2872static void
2873rb_fiber_terminate(rb_fiber_t *fiber, int need_interrupt, VALUE error)
2874{
2875 VALUE value = fiber->cont.value;
2876
2877 VM_ASSERT(FIBER_RESUMED_P(fiber));
2878 rb_fiber_close(fiber);
2879
2880 fiber->cont.machine.stack = NULL;
2881 fiber->cont.machine.stack_size = 0;
2882
2883 rb_fiber_t *next_fiber = return_fiber(true);
2884
2885 if (need_interrupt) RUBY_VM_SET_INTERRUPT(&next_fiber->cont.saved_ec);
2886
2887 if (RTEST(error))
2888 fiber_switch(next_fiber, -1, &error, RB_NO_KEYWORDS, NULL, false);
2889 else
2890 fiber_switch(next_fiber, 1, &value, RB_NO_KEYWORDS, NULL, false);
2891 ruby_stop(0);
2892}
2893
2894static VALUE
2895fiber_resume_kw(rb_fiber_t *fiber, int argc, const VALUE *argv, int kw_splat)
2896{
2897 rb_fiber_t *current_fiber = fiber_current();
2898
2899 if (argc == -1 && FIBER_CREATED_P(fiber)) {
2900 rb_raise(rb_eFiberError, "cannot raise exception on unborn fiber");
2901 }
2902 else if (FIBER_TERMINATED_P(fiber)) {
2903 rb_raise(rb_eFiberError, "attempt to resume a terminated fiber");
2904 }
2905 else if (fiber == current_fiber) {
2906 rb_raise(rb_eFiberError, "attempt to resume the current fiber");
2907 }
2908 else if (fiber->prev != NULL) {
2909 rb_raise(rb_eFiberError, "attempt to resume a resumed fiber (double resume)");
2910 }
2911 else if (fiber->resuming_fiber) {
2912 rb_raise(rb_eFiberError, "attempt to resume a resuming fiber");
2913 }
2914 else if (fiber->prev == NULL &&
2915 (!fiber->yielding && fiber->status != FIBER_CREATED)) {
2916 rb_raise(rb_eFiberError, "attempt to resume a transferring fiber");
2917 }
2918
2919 return fiber_switch(fiber, argc, argv, kw_splat, fiber, false);
2920}
2921
2922VALUE
2923rb_fiber_resume_kw(VALUE self, int argc, const VALUE *argv, int kw_splat)
2924{
2925 return fiber_resume_kw(fiber_ptr(self), argc, argv, kw_splat);
2926}
2927
2928VALUE
2929rb_fiber_resume(VALUE self, int argc, const VALUE *argv)
2930{
2931 return fiber_resume_kw(fiber_ptr(self), argc, argv, RB_NO_KEYWORDS);
2932}
2933
2934VALUE
2935rb_fiber_yield_kw(int argc, const VALUE *argv, int kw_splat)
2936{
2937 return fiber_switch(return_fiber(false), argc, argv, kw_splat, NULL, true);
2938}
2939
2940VALUE
2941rb_fiber_yield(int argc, const VALUE *argv)
2942{
2943 return fiber_switch(return_fiber(false), argc, argv, RB_NO_KEYWORDS, NULL, true);
2944}
2945
2946void
2947rb_fiber_reset_root_local_storage(rb_thread_t *th)
2948{
2949 if (th->root_fiber && th->root_fiber != th->ec->fiber_ptr) {
2950 th->ec->local_storage = th->root_fiber->cont.saved_ec.local_storage;
2951 }
2952}
2953
2954/*
2955 * call-seq:
2956 * fiber.alive? -> true or false
2957 *
2958 * Returns true if the fiber can still be resumed (or transferred
2959 * to). After finishing execution of the fiber block this method will
2960 * always return +false+.
2961 */
2962VALUE
2963rb_fiber_alive_p(VALUE fiber_value)
2964{
2965 return RBOOL(!FIBER_TERMINATED_P(fiber_ptr(fiber_value)));
2966}
2967
2968/*
2969 * call-seq:
2970 * fiber.resume(args, ...) -> obj
2971 *
2972 * Resumes the fiber from the point at which the last Fiber.yield was
2973 * called, or starts running it if it is the first call to
2974 * #resume. Arguments passed to resume will be the value of the
2975 * Fiber.yield expression or will be passed as block parameters to
2976 * the fiber's block if this is the first #resume.
2977 *
2978 * Alternatively, when resume is called it evaluates to the arguments passed
2979 * to the next Fiber.yield statement inside the fiber's block
2980 * or to the block value if it runs to completion without any
2981 * Fiber.yield
2982 */
2983static VALUE
2984rb_fiber_m_resume(int argc, VALUE *argv, VALUE fiber)
2985{
2986 return rb_fiber_resume_kw(fiber, argc, argv, rb_keyword_given_p());
2987}
2988
2989/*
2990 * call-seq:
2991 * fiber.backtrace -> array
2992 * fiber.backtrace(start) -> array
2993 * fiber.backtrace(start, count) -> array
2994 * fiber.backtrace(start..end) -> array
2995 *
2996 * Returns the current execution stack of the fiber. +start+, +count+ and +end+ allow
2997 * to select only parts of the backtrace.
2998 *
2999 * def level3
3000 * Fiber.yield
3001 * end
3002 *
3003 * def level2
3004 * level3
3005 * end
3006 *
3007 * def level1
3008 * level2
3009 * end
3010 *
3011 * f = Fiber.new { level1 }
3012 *
3013 * # It is empty before the fiber started
3014 * f.backtrace
3015 * #=> []
3016 *
3017 * f.resume
3018 *
3019 * f.backtrace
3020 * #=> ["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>'"]
3021 * p f.backtrace(1) # start from the item 1
3022 * #=> ["test.rb:2:in `level3'", "test.rb:6:in `level2'", "test.rb:10:in `level1'", "test.rb:13:in `block in <main>'"]
3023 * p f.backtrace(2, 2) # start from item 2, take 2
3024 * #=> ["test.rb:6:in `level2'", "test.rb:10:in `level1'"]
3025 * p f.backtrace(1..3) # take items from 1 to 3
3026 * #=> ["test.rb:2:in `level3'", "test.rb:6:in `level2'", "test.rb:10:in `level1'"]
3027 *
3028 * f.resume
3029 *
3030 * # It is nil after the fiber is finished
3031 * f.backtrace
3032 * #=> nil
3033 *
3034 */
3035static VALUE
3036rb_fiber_backtrace(int argc, VALUE *argv, VALUE fiber)
3037{
3038 return rb_vm_backtrace(argc, argv, &fiber_ptr(fiber)->cont.saved_ec);
3039}
3040
3041/*
3042 * call-seq:
3043 * fiber.backtrace_locations -> array
3044 * fiber.backtrace_locations(start) -> array
3045 * fiber.backtrace_locations(start, count) -> array
3046 * fiber.backtrace_locations(start..end) -> array
3047 *
3048 * Like #backtrace, but returns each line of the execution stack as a
3049 * Thread::Backtrace::Location. Accepts the same arguments as #backtrace.
3050 *
3051 * f = Fiber.new { Fiber.yield }
3052 * f.resume
3053 * loc = f.backtrace_locations.first
3054 * loc.label #=> "yield"
3055 * loc.path #=> "test.rb"
3056 * loc.lineno #=> 1
3057 *
3058 *
3059 */
3060static VALUE
3061rb_fiber_backtrace_locations(int argc, VALUE *argv, VALUE fiber)
3062{
3063 return rb_vm_backtrace_locations(argc, argv, &fiber_ptr(fiber)->cont.saved_ec);
3064}
3065
3066/*
3067 * call-seq:
3068 * fiber.transfer(args, ...) -> obj
3069 *
3070 * Transfer control to another fiber, resuming it from where it last
3071 * stopped or starting it if it was not resumed before. The calling
3072 * fiber will be suspended much like in a call to
3073 * Fiber.yield.
3074 *
3075 * The fiber which receives the transfer call treats it much like
3076 * a resume call. Arguments passed to transfer are treated like those
3077 * passed to resume.
3078 *
3079 * The two style of control passing to and from fiber (one is #resume and
3080 * Fiber::yield, another is #transfer to and from fiber) can't be freely
3081 * mixed.
3082 *
3083 * * If the Fiber's lifecycle had started with transfer, it will never
3084 * be able to yield or be resumed control passing, only
3085 * finish or transfer back. (It still can resume other fibers that
3086 * are allowed to be resumed.)
3087 * * If the Fiber's lifecycle had started with resume, it can yield
3088 * or transfer to another Fiber, but can receive control back only
3089 * the way compatible with the way it was given away: if it had
3090 * transferred, it only can be transferred back, and if it had
3091 * yielded, it only can be resumed back. After that, it again can
3092 * transfer or yield.
3093 *
3094 * If those rules are broken FiberError is raised.
3095 *
3096 * For an individual Fiber design, yield/resume is easier to use
3097 * (the Fiber just gives away control, it doesn't need to think
3098 * about who the control is given to), while transfer is more flexible
3099 * for complex cases, allowing to build arbitrary graphs of Fibers
3100 * dependent on each other.
3101 *
3102 *
3103 * Example:
3104 *
3105 * manager = nil # For local var to be visible inside worker block
3106 *
3107 * # This fiber would be started with transfer
3108 * # It can't yield, and can't be resumed
3109 * worker = Fiber.new { |work|
3110 * puts "Worker: starts"
3111 * puts "Worker: Performed #{work.inspect}, transferring back"
3112 * # Fiber.yield # this would raise FiberError: attempt to yield on a not resumed fiber
3113 * # manager.resume # this would raise FiberError: attempt to resume a resumed fiber (double resume)
3114 * manager.transfer(work.capitalize)
3115 * }
3116 *
3117 * # This fiber would be started with resume
3118 * # It can yield or transfer, and can be transferred
3119 * # back or resumed
3120 * manager = Fiber.new {
3121 * puts "Manager: starts"
3122 * puts "Manager: transferring 'something' to worker"
3123 * result = worker.transfer('something')
3124 * puts "Manager: worker returned #{result.inspect}"
3125 * # worker.resume # this would raise FiberError: attempt to resume a transferring fiber
3126 * Fiber.yield # this is OK, the fiber transferred from and to, now it can yield
3127 * puts "Manager: finished"
3128 * }
3129 *
3130 * puts "Starting the manager"
3131 * manager.resume
3132 * puts "Resuming the manager"
3133 * # manager.transfer # this would raise FiberError: attempt to transfer to a yielding fiber
3134 * manager.resume
3135 *
3136 * <em>produces</em>
3137 *
3138 * Starting the manager
3139 * Manager: starts
3140 * Manager: transferring 'something' to worker
3141 * Worker: starts
3142 * Worker: Performed "something", transferring back
3143 * Manager: worker returned "Something"
3144 * Resuming the manager
3145 * Manager: finished
3146 *
3147 */
3148static VALUE
3149rb_fiber_m_transfer(int argc, VALUE *argv, VALUE self)
3150{
3151 return rb_fiber_transfer_kw(self, argc, argv, rb_keyword_given_p());
3152}
3153
3154static VALUE
3155fiber_transfer_kw(rb_fiber_t *fiber, int argc, const VALUE *argv, int kw_splat)
3156{
3157 if (fiber->resuming_fiber) {
3158 rb_raise(rb_eFiberError, "attempt to transfer to a resuming fiber");
3159 }
3160
3161 if (fiber->yielding) {
3162 rb_raise(rb_eFiberError, "attempt to transfer to a yielding fiber");
3163 }
3164
3165 return fiber_switch(fiber, argc, argv, kw_splat, NULL, false);
3166}
3167
3168VALUE
3169rb_fiber_transfer_kw(VALUE self, int argc, const VALUE *argv, int kw_splat)
3170{
3171 return fiber_transfer_kw(fiber_ptr(self), argc, argv, kw_splat);
3172}
3173
3174/*
3175 * call-seq:
3176 * Fiber.yield(args, ...) -> obj
3177 *
3178 * Yields control back to the context that resumed the fiber, passing
3179 * along any arguments that were passed to it. The fiber will resume
3180 * processing at this point when #resume is called next.
3181 * Any arguments passed to the next #resume will be the value that
3182 * this Fiber.yield expression evaluates to.
3183 */
3184static VALUE
3185rb_fiber_s_yield(int argc, VALUE *argv, VALUE klass)
3186{
3187 return rb_fiber_yield_kw(argc, argv, rb_keyword_given_p());
3188}
3189
3190static VALUE
3191fiber_raise(rb_fiber_t *fiber, VALUE exception)
3192{
3193 if (fiber == fiber_current()) {
3194 rb_exc_raise(exception);
3195 }
3196 else if (fiber->resuming_fiber) {
3197 return fiber_raise(fiber->resuming_fiber, exception);
3198 }
3199 else if (FIBER_SUSPENDED_P(fiber) && !fiber->yielding) {
3200 return fiber_transfer_kw(fiber, -1, &exception, RB_NO_KEYWORDS);
3201 }
3202 else {
3203 return fiber_resume_kw(fiber, -1, &exception, RB_NO_KEYWORDS);
3204 }
3205}
3206
3207VALUE
3208rb_fiber_raise(VALUE fiber, int argc, const VALUE *argv)
3209{
3210 VALUE exception = rb_make_exception(argc, argv);
3211
3212 return fiber_raise(fiber_ptr(fiber), exception);
3213}
3214
3215/*
3216 * call-seq:
3217 * fiber.raise -> obj
3218 * fiber.raise(string) -> obj
3219 * fiber.raise(exception [, string [, array]]) -> obj
3220 *
3221 * Raises an exception in the fiber at the point at which the last
3222 * +Fiber.yield+ was called. If the fiber has not been started or has
3223 * already run to completion, raises +FiberError+. If the fiber is
3224 * yielding, it is resumed. If it is transferring, it is transferred into.
3225 * But if it is resuming, raises +FiberError+.
3226 *
3227 * With no arguments, raises a +RuntimeError+. With a single +String+
3228 * argument, raises a +RuntimeError+ with the string as a message. Otherwise,
3229 * the first parameter should be the name of an +Exception+ class (or an
3230 * object that returns an +Exception+ object when sent an +exception+
3231 * message). The optional second parameter sets the message associated with
3232 * the exception, and the third parameter is an array of callback information.
3233 * Exceptions are caught by the +rescue+ clause of <code>begin...end</code>
3234 * blocks.
3235 *
3236 * Raises +FiberError+ if called on a Fiber belonging to another +Thread+.
3237 *
3238 * See Kernel#raise for more information.
3239 */
3240static VALUE
3241rb_fiber_m_raise(int argc, VALUE *argv, VALUE self)
3242{
3243 return rb_fiber_raise(self, argc, argv);
3244}
3245
3246/*
3247 * call-seq:
3248 * fiber.kill -> nil
3249 *
3250 * Terminates the fiber by raising an uncatchable exception.
3251 * It only terminates the given fiber and no other fiber, returning +nil+ to
3252 * another fiber if that fiber was calling #resume or #transfer.
3253 *
3254 * <tt>Fiber#kill</tt> only interrupts another fiber when it is in Fiber.yield.
3255 * If called on the current fiber then it raises that exception at the <tt>Fiber#kill</tt> call site.
3256 *
3257 * If the fiber has not been started, transition directly to the terminated state.
3258 *
3259 * If the fiber is already terminated, does nothing.
3260 *
3261 * Raises FiberError if called on a fiber belonging to another thread.
3262 */
3263static VALUE
3264rb_fiber_m_kill(VALUE self)
3265{
3266 rb_fiber_t *fiber = fiber_ptr(self);
3267
3268 if (fiber->killed) return Qfalse;
3269 fiber->killed = 1;
3270
3271 if (fiber->status == FIBER_CREATED) {
3272 fiber->status = FIBER_TERMINATED;
3273 }
3274 else if (fiber->status != FIBER_TERMINATED) {
3275 if (fiber_current() == fiber) {
3276 fiber_check_killed(fiber);
3277 }
3278 else {
3279 fiber_raise(fiber_ptr(self), Qnil);
3280 }
3281 }
3282
3283 return self;
3284}
3285
3286/*
3287 * call-seq:
3288 * Fiber.current -> fiber
3289 *
3290 * Returns the current fiber. If you are not running in the context of
3291 * a fiber this method will return the root fiber.
3292 */
3293static VALUE
3294rb_fiber_s_current(VALUE klass)
3295{
3296 return rb_fiber_current();
3297}
3298
3299static VALUE
3300fiber_to_s(VALUE fiber_value)
3301{
3302 const rb_fiber_t *fiber = fiber_ptr(fiber_value);
3303 const rb_proc_t *proc;
3304 char status_info[0x20];
3305
3306 if (fiber->resuming_fiber) {
3307 snprintf(status_info, 0x20, " (%s by resuming)", fiber_status_name(fiber->status));
3308 }
3309 else {
3310 snprintf(status_info, 0x20, " (%s)", fiber_status_name(fiber->status));
3311 }
3312
3313 if (!rb_obj_is_proc(fiber->first_proc)) {
3314 VALUE str = rb_any_to_s(fiber_value);
3315 strlcat(status_info, ">", sizeof(status_info));
3316 rb_str_set_len(str, RSTRING_LEN(str)-1);
3317 rb_str_cat_cstr(str, status_info);
3318 return str;
3319 }
3320 GetProcPtr(fiber->first_proc, proc);
3321 return rb_block_to_s(fiber_value, &proc->block, status_info);
3322}
3323
3324#ifdef HAVE_WORKING_FORK
3325void
3326rb_fiber_atfork(rb_thread_t *th)
3327{
3328 if (th->root_fiber) {
3329 if (&th->root_fiber->cont.saved_ec != th->ec) {
3330 th->root_fiber = th->ec->fiber_ptr;
3331 }
3332 th->root_fiber->prev = 0;
3333 }
3334}
3335#endif
3336
3337#ifdef RB_EXPERIMENTAL_FIBER_POOL
3338static void
3339fiber_pool_free(void *ptr)
3340{
3341 struct fiber_pool * fiber_pool = ptr;
3342 RUBY_FREE_ENTER("fiber_pool");
3343
3344 fiber_pool_allocation_free(fiber_pool->allocations);
3345 ruby_xfree(fiber_pool);
3346
3347 RUBY_FREE_LEAVE("fiber_pool");
3348}
3349
3350static size_t
3351fiber_pool_memsize(const void *ptr)
3352{
3353 const struct fiber_pool * fiber_pool = ptr;
3354 size_t size = sizeof(*fiber_pool);
3355
3356 size += fiber_pool->count * fiber_pool->size;
3357
3358 return size;
3359}
3360
3361static const rb_data_type_t FiberPoolDataType = {
3362 "fiber_pool",
3363 {NULL, fiber_pool_free, fiber_pool_memsize,},
3364 0, 0, RUBY_TYPED_FREE_IMMEDIATELY
3365};
3366
3367static VALUE
3368fiber_pool_alloc(VALUE klass)
3369{
3370 struct fiber_pool *fiber_pool;
3371
3372 return TypedData_Make_Struct(klass, struct fiber_pool, &FiberPoolDataType, fiber_pool);
3373}
3374
3375static VALUE
3376rb_fiber_pool_initialize(int argc, VALUE* argv, VALUE self)
3377{
3378 rb_thread_t *th = GET_THREAD();
3379 VALUE size = Qnil, count = Qnil, vm_stack_size = Qnil;
3380 struct fiber_pool * fiber_pool = NULL;
3381
3382 // Maybe these should be keyword arguments.
3383 rb_scan_args(argc, argv, "03", &size, &count, &vm_stack_size);
3384
3385 if (NIL_P(size)) {
3386 size = SIZET2NUM(th->vm->default_params.fiber_machine_stack_size);
3387 }
3388
3389 if (NIL_P(count)) {
3390 count = INT2NUM(128);
3391 }
3392
3393 if (NIL_P(vm_stack_size)) {
3394 vm_stack_size = SIZET2NUM(th->vm->default_params.fiber_vm_stack_size);
3395 }
3396
3397 TypedData_Get_Struct(self, struct fiber_pool, &FiberPoolDataType, fiber_pool);
3398
3399 fiber_pool_initialize(fiber_pool, NUM2SIZET(size), NUM2SIZET(count), NUM2SIZET(vm_stack_size));
3400
3401 return self;
3402}
3403#endif
3404
3405/*
3406 * Document-class: FiberError
3407 *
3408 * Raised when an invalid operation is attempted on a Fiber, in
3409 * particular when attempting to call/resume a dead fiber,
3410 * attempting to yield from the root fiber, or calling a fiber across
3411 * threads.
3412 *
3413 * fiber = Fiber.new{}
3414 * fiber.resume #=> nil
3415 * fiber.resume #=> FiberError: dead fiber called
3416 */
3417
3418void
3419Init_Cont(void)
3420{
3421 rb_thread_t *th = GET_THREAD();
3422 size_t vm_stack_size = th->vm->default_params.fiber_vm_stack_size;
3423 size_t machine_stack_size = th->vm->default_params.fiber_machine_stack_size;
3424 size_t stack_size = machine_stack_size + vm_stack_size;
3425
3426#ifdef _WIN32
3427 SYSTEM_INFO info;
3428 GetSystemInfo(&info);
3429 pagesize = info.dwPageSize;
3430#else /* not WIN32 */
3431 pagesize = sysconf(_SC_PAGESIZE);
3432#endif
3433 SET_MACHINE_STACK_END(&th->ec->machine.stack_end);
3434
3435 fiber_pool_initialize(&shared_fiber_pool, stack_size, FIBER_POOL_INITIAL_SIZE, vm_stack_size);
3436
3437 fiber_initialize_keywords[0] = rb_intern_const("blocking");
3438 fiber_initialize_keywords[1] = rb_intern_const("pool");
3439 fiber_initialize_keywords[2] = rb_intern_const("storage");
3440
3441 const char *fiber_shared_fiber_pool_free_stacks = getenv("RUBY_SHARED_FIBER_POOL_FREE_STACKS");
3442 if (fiber_shared_fiber_pool_free_stacks) {
3443 shared_fiber_pool.free_stacks = atoi(fiber_shared_fiber_pool_free_stacks);
3444
3445 if (shared_fiber_pool.free_stacks < 0) {
3446 rb_warn("Setting RUBY_SHARED_FIBER_POOL_FREE_STACKS to a negative value is not allowed.");
3447 shared_fiber_pool.free_stacks = 0;
3448 }
3449
3450 if (shared_fiber_pool.free_stacks > 1) {
3451 rb_warn("Setting RUBY_SHARED_FIBER_POOL_FREE_STACKS to a value greater than 1 is operating system specific, and may cause crashes.");
3452 }
3453 }
3454
3455 rb_cFiber = rb_define_class("Fiber", rb_cObject);
3456 rb_define_alloc_func(rb_cFiber, fiber_alloc);
3457 rb_eFiberError = rb_define_class("FiberError", rb_eStandardError);
3458 rb_define_singleton_method(rb_cFiber, "yield", rb_fiber_s_yield, -1);
3459 rb_define_singleton_method(rb_cFiber, "current", rb_fiber_s_current, 0);
3460 rb_define_singleton_method(rb_cFiber, "blocking", rb_fiber_blocking, 0);
3461 rb_define_singleton_method(rb_cFiber, "[]", rb_fiber_storage_aref, 1);
3462 rb_define_singleton_method(rb_cFiber, "[]=", rb_fiber_storage_aset, 2);
3463
3464 rb_define_method(rb_cFiber, "initialize", rb_fiber_initialize, -1);
3465 rb_define_method(rb_cFiber, "blocking?", rb_fiber_blocking_p, 0);
3466 rb_define_method(rb_cFiber, "storage", rb_fiber_storage_get, 0);
3467 rb_define_method(rb_cFiber, "storage=", rb_fiber_storage_set, 1);
3468 rb_define_method(rb_cFiber, "resume", rb_fiber_m_resume, -1);
3469 rb_define_method(rb_cFiber, "raise", rb_fiber_m_raise, -1);
3470 rb_define_method(rb_cFiber, "kill", rb_fiber_m_kill, 0);
3471 rb_define_method(rb_cFiber, "backtrace", rb_fiber_backtrace, -1);
3472 rb_define_method(rb_cFiber, "backtrace_locations", rb_fiber_backtrace_locations, -1);
3473 rb_define_method(rb_cFiber, "to_s", fiber_to_s, 0);
3474 rb_define_alias(rb_cFiber, "inspect", "to_s");
3475 rb_define_method(rb_cFiber, "transfer", rb_fiber_m_transfer, -1);
3476 rb_define_method(rb_cFiber, "alive?", rb_fiber_alive_p, 0);
3477
3478 rb_define_singleton_method(rb_cFiber, "blocking?", rb_fiber_s_blocking_p, 0);
3479 rb_define_singleton_method(rb_cFiber, "scheduler", rb_fiber_s_scheduler, 0);
3480 rb_define_singleton_method(rb_cFiber, "set_scheduler", rb_fiber_set_scheduler, 1);
3481 rb_define_singleton_method(rb_cFiber, "current_scheduler", rb_fiber_current_scheduler, 0);
3482
3483 rb_define_singleton_method(rb_cFiber, "schedule", rb_fiber_s_schedule, -1);
3484
3485#ifdef RB_EXPERIMENTAL_FIBER_POOL
3486 /*
3487 * Document-class: Fiber::Pool
3488 * :nodoc: experimental
3489 */
3490 rb_cFiberPool = rb_define_class_under(rb_cFiber, "Pool", rb_cObject);
3491 rb_define_alloc_func(rb_cFiberPool, fiber_pool_alloc);
3492 rb_define_method(rb_cFiberPool, "initialize", rb_fiber_pool_initialize, -1);
3493#endif
3494
3495 rb_provide("fiber.so");
3496}
3497
3498RUBY_SYMBOL_EXPORT_BEGIN
3499
3500void
3501ruby_Init_Continuation_body(void)
3502{
3503 rb_cContinuation = rb_define_class("Continuation", rb_cObject);
3504 rb_undef_alloc_func(rb_cContinuation);
3505 rb_undef_method(CLASS_OF(rb_cContinuation), "new");
3506 rb_define_method(rb_cContinuation, "call", rb_cont_call, -1);
3507 rb_define_method(rb_cContinuation, "[]", rb_cont_call, -1);
3508 rb_define_global_function("callcc", rb_callcc, 0);
3509}
3510
3511RUBY_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:885
VALUE rb_define_class(const char *name, VALUE super)
Defines a top-level class.
Definition class.c:1479
VALUE rb_define_class_under(VALUE outer, const char *name, VALUE super)
Defines a class under the namespace of outer.
Definition class.c:1515
void rb_define_alias(VALUE klass, const char *name1, const char *name2)
Defines an alias of a method.
Definition class.c:2843
void rb_undef_method(VALUE klass, const char *name)
Defines an undef of a method.
Definition class.c:2664
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:3146
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:3133
int rb_keyword_given_p(void)
Determines if the current method is given a keyword argument.
Definition eval.c:954
int rb_get_kwargs(VALUE keyword_hash, const ID *table, int required, int optional, VALUE *values)
Keyword argument deconstructor.
Definition class.c:2922
#define REALLOC_N
Old name of RB_REALLOC_N.
Definition memory.h:403
#define xfree
Old name of ruby_xfree.
Definition xmalloc.h:58
#define Qundef
Old name of RUBY_Qundef.
#define UNREACHABLE_RETURN
Old name of RBIMPL_UNREACHABLE_RETURN.
Definition assume.h:29
#define ZALLOC
Old name of RB_ZALLOC.
Definition memory.h:402
#define CLASS_OF
Old name of rb_class_of.
Definition globals.h:205
#define rb_ary_new4
Old name of rb_ary_new_from_values.
Definition array.h:659
#define SIZET2NUM
Old name of RB_SIZE2NUM.
Definition size_t.h:62
#define rb_exc_new2
Old name of rb_exc_new_cstr.
Definition error.h:37
#define T_HASH
Old name of RUBY_T_HASH.
Definition value_type.h:65
#define ALLOC_N
Old name of RB_ALLOC_N.
Definition memory.h:399
#define Qtrue
Old name of RUBY_Qtrue.
#define INT2NUM
Old name of RB_INT2NUM.
Definition int.h:43
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#define NIL_P
Old name of RB_NIL_P.
#define T_SYMBOL
Old name of RUBY_T_SYMBOL.
Definition value_type.h:80
#define NUM2SIZET
Old name of RB_NUM2SIZE.
Definition size_t.h:61
void ruby_stop(int ex)
Calls ruby_cleanup() and exits the process.
Definition eval.c:288
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:680
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:682
VALUE rb_obj_dup(VALUE obj)
Duplicates the given object.
Definition object.c:589
void rb_provide(const char *feature)
Declares that the given feature is already provided by someone else.
Definition load.c:765
VALUE rb_block_proc(void)
Constructs a Proc object from implicitly passed components.
Definition proc.c:842
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:3692
#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:1387
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:12946
VALUE rb_yield(VALUE val)
Yields the block.
Definition vm_eval.c:1372
rb_block_call_func * rb_block_call_func_t
Shorthand type that represents an iterator-written-in-C function pointer.
Definition iterator.h:88
#define MEMCPY(p1, p2, type, n)
Handy macro to call memcpy.
Definition memory.h:372
#define ALLOCA_N(type, n)
Definition memory.h:292
#define RB_ALLOC(type)
Shorthand of RB_ALLOC_N with n=1.
Definition memory.h:213
VALUE rb_proc_new(type *q, VALUE w)
Creates a rb_cProc instance.
void rb_hash_foreach(VALUE q, int_type *w, VALUE e)
Iteration over the given hash.
VALUE rb_ensure(type *q, VALUE w, type *e, VALUE r)
An equivalent of ensure clause.
#define RARRAY_CONST_PTR
Just another name of rb_array_const_ptr.
Definition rarray.h:52
#define DATA_PTR(obj)
Convenient getter macro.
Definition rdata.h:67
#define TypedData_Get_Struct(obj, type, data_type, sval)
Obtains a C struct from inside of a wrapper Ruby object.
Definition rtypeddata.h:516
#define TypedData_Wrap_Struct(klass, data_type, sval)
Converts sval, a pointer to your struct, into a Ruby object.
Definition rtypeddata.h:450
#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:498
#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:203
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