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