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