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