Ruby 4.1.0dev (2026-10-18 revision c2ce8487b41adecec025f9280e4dde1b86216d34)
cont.c (c2ce8487b41adecec025f9280e4dde1b86216d34)
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__)
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_ctx(const struct rb_gc_mark_ctx *ctx, rb_context_t *cont)
1272{
1273 RUBY_MARK_ENTER("cont");
1274 if (cont->self) {
1275 rb_gc_mark_movable_ctx(ctx, cont->self);
1276 }
1277 rb_gc_mark_movable_ctx(ctx, cont->value);
1278
1279 rb_execution_context_mark_ctx(ctx, &cont->saved_ec);
1280 rb_gc_mark_ctx(ctx, cont_thread_value(cont));
1281
1282 if (cont->saved_vm_stack.ptr) {
1283#ifdef CAPTURE_JUST_VALID_VM_STACK
1284 rb_gc_mark_locations_ctx(ctx, cont->saved_vm_stack.ptr,
1285 cont->saved_vm_stack.ptr + cont->saved_vm_stack.slen + cont->saved_vm_stack.clen);
1286#else
1287 rb_gc_mark_locations_ctx(ctx, cont->saved_vm_stack.ptr,
1288 cont->saved_vm_stack.ptr, cont->saved_ec.stack_size);
1289#endif
1290 }
1291
1292 if (cont->machine.stack) {
1293 if (cont->type == CONTINUATION_CONTEXT) {
1294 /* cont */
1295 rb_gc_mark_locations_ctx(ctx, cont->machine.stack,
1296 cont->machine.stack + cont->machine.stack_size);
1297 }
1298 else {
1299 /* fiber machine context is marked as part of rb_execution_context_mark_ctx, no need
1300 * to do anything here. */
1301 }
1302 }
1303
1304 RUBY_MARK_LEAVE("cont");
1305}
1306
1307static void
1308cont_mark(void *ptr)
1309{
1310 const struct rb_gc_mark_ctx ctx = rb_gc_current_mark_ctx();
1311
1312 cont_mark_ctx(&ctx, (rb_context_t *)ptr);
1313}
1314
1315#if 0
1316static int
1317fiber_is_root_p(const rb_fiber_t *fiber)
1318{
1319 return fiber == fiber->cont.saved_ec.thread_ptr->root_fiber;
1320}
1321#endif
1322
1323static void jit_cont_free(struct rb_jit_cont *cont);
1324
1325static void
1326cont_free(void *ptr)
1327{
1328 rb_context_t *cont = ptr;
1329
1330 RUBY_FREE_ENTER("cont");
1331
1332 if (cont->type == CONTINUATION_CONTEXT) {
1333 SIZED_FREE_N(cont->saved_ec.vm_stack, cont->saved_ec.vm_stack_size);
1334 SIZED_FREE_N(cont->machine.stack, cont->machine.stack_size);
1335 }
1336 else {
1337 rb_fiber_t *fiber = (rb_fiber_t*)cont;
1338 coroutine_destroy(&fiber->context);
1339 fiber_stack_release(fiber);
1340 }
1341
1342 SIZED_FREE_N(cont->saved_vm_stack.ptr, cont->saved_vm_stack.size);
1343
1344 VM_ASSERT(cont->jit_cont != NULL);
1345 jit_cont_free(cont->jit_cont);
1346 /* free rb_cont_t or rb_fiber_t */
1347 if (cont->type == CONTINUATION_CONTEXT) {
1348 SIZED_FREE(cont);
1349 }
1350 else {
1351 SIZED_FREE((rb_fiber_t *)cont);
1352 }
1353 RUBY_FREE_LEAVE("cont");
1354}
1355
1356static size_t
1357cont_memsize(const void *ptr)
1358{
1359 const rb_context_t *cont = ptr;
1360 size_t size = 0;
1361
1362 size = sizeof(*cont);
1363 if (cont->saved_vm_stack.ptr) {
1364#ifdef CAPTURE_JUST_VALID_VM_STACK
1365 size_t n = (cont->saved_vm_stack.slen + cont->saved_vm_stack.clen);
1366#else
1367 size_t n = cont->saved_ec.vm_stack_size;
1368#endif
1369 size += n * sizeof(*cont->saved_vm_stack.ptr);
1370 }
1371
1372 if (cont->machine.stack) {
1373 size += cont->machine.stack_size * sizeof(*cont->machine.stack);
1374 }
1375
1376 return size;
1377}
1378
1379void
1380rb_fiber_update_self(rb_fiber_t *fiber)
1381{
1382 if (fiber->cont.self) {
1383 rb_gc_update_moved(&fiber->cont.self);
1384 }
1385 else {
1386 rb_execution_context_update(&fiber->cont.saved_ec);
1387 }
1388}
1389
1390void
1391rb_fiber_mark_self(const struct rb_gc_mark_ctx *ctx, const rb_fiber_t *fiber)
1392{
1393 rb_gc_mark_movable_ctx(ctx, fiber->cont.self);
1394}
1395
1396static void
1397fiber_compact(void *ptr)
1398{
1399 rb_fiber_t *fiber = ptr;
1400 rb_gc_update_moved(&fiber->first_proc);
1401
1402 if (fiber->prev) rb_fiber_update_self(fiber->prev);
1403
1404 cont_compact(&fiber->cont);
1405 fiber_verify(fiber);
1406}
1407
1408static void
1409fiber_mark(void *ptr)
1410{
1411 rb_fiber_t *fiber = ptr;
1412 const struct rb_gc_mark_ctx ctx = rb_gc_current_mark_ctx();
1413
1414 RUBY_MARK_ENTER("cont");
1415 fiber_verify(fiber);
1416 rb_gc_mark_movable_ctx(&ctx, fiber->first_proc);
1417 if (fiber->prev) rb_fiber_mark_self(&ctx, fiber->prev);
1418 cont_mark_ctx(&ctx, &fiber->cont);
1419 RUBY_MARK_LEAVE("cont");
1420}
1421
1422static void
1423fiber_free(void *ptr)
1424{
1425 rb_fiber_t *fiber = ptr;
1426
1427 /* Root fiber of the thread running the final self collection: saved_ec is the ec
1428 * that thread still executes on, so the thread frees the struct itself at its
1429 * last step (rb_ractor_postmortem_free). cont.self == 0 already means "no
1430 * wrapper" (rb_threadptr_root_fiber_release). */
1431 if (&fiber->cont.saved_ec == rb_current_execution_context(false)) {
1432 fiber->cont.self = 0;
1433 return;
1434 }
1435 rb_fiber_free_body(ptr);
1436}
1437
1438void
1439rb_fiber_free_body(void *ptr)
1440{
1441 rb_fiber_t *fiber = ptr;
1442 RUBY_FREE_ENTER("fiber");
1443
1444 if (DEBUG) fprintf(stderr, "fiber_free: %p[%p]\n", (void *)fiber, fiber->stack.base);
1445
1446 if (fiber->cont.saved_ec.local_storage) {
1447 rb_id_table_free(fiber->cont.saved_ec.local_storage);
1448 }
1449
1450 cont_free(&fiber->cont);
1451 RUBY_FREE_LEAVE("fiber");
1452}
1453
1454static size_t
1455fiber_memsize(const void *ptr)
1456{
1457 const rb_fiber_t *fiber = ptr;
1458 size_t size = sizeof(*fiber);
1459 const rb_execution_context_t *saved_ec = &fiber->cont.saved_ec;
1460
1461 /* thread_memsize in vm.c already accounts for a root fiber's local_storage.
1462 * first_proc != 0 picks the non-root fibers without dereferencing the thread
1463 * (equivalent to fiber != th->root_fiber). */
1464 if (saved_ec->local_storage && fiber->first_proc != 0) {
1465 size += rb_id_table_memsize(saved_ec->local_storage);
1466 size += rb_obj_memsize_of(saved_ec->storage);
1467 }
1468
1469 size += cont_memsize(&fiber->cont);
1470 return size;
1471}
1472
1473VALUE
1474rb_obj_is_fiber(VALUE obj)
1475{
1476 return RBOOL(rb_typeddata_is_kind_of(obj, &rb_fiber_data_type));
1477}
1478
1479static void
1480cont_save_machine_stack(rb_thread_t *th, rb_context_t *cont)
1481{
1482 const size_t old_stack_size = cont->machine.stack_size;
1483 size_t size;
1484
1485 SET_MACHINE_STACK_END(&th->ec->machine.stack_end);
1486
1487 if (th->ec->machine.stack_start > th->ec->machine.stack_end) {
1488 size = cont->machine.stack_size = th->ec->machine.stack_start - th->ec->machine.stack_end;
1489 cont->machine.stack_src = th->ec->machine.stack_end;
1490 }
1491 else {
1492 size = cont->machine.stack_size = th->ec->machine.stack_end - th->ec->machine.stack_start;
1493 cont->machine.stack_src = th->ec->machine.stack_start;
1494 }
1495
1496 if (cont->machine.stack) {
1497 SIZED_REALLOC_N(cont->machine.stack, VALUE, cont->machine.stack_size, old_stack_size);
1498 }
1499 else {
1500 cont->machine.stack = ALLOC_N(VALUE, cont->machine.stack_size);
1501 }
1502
1503 FLUSH_REGISTER_WINDOWS;
1504 asan_unpoison_memory_region(cont->machine.stack_src, size, false);
1505 MEMCPY(cont->machine.stack, cont->machine.stack_src, VALUE, size);
1506}
1507
1508static void
1509cont_handle_weak_references(void *ptr)
1510{
1511 rb_context_t *cont = ptr;
1512
1513 if (!cont) return;
1514
1515 if (!rb_gc_handle_weak_references_alive_p(cont->saved_ec.gen_fields_cache.obj) ||
1516 !rb_gc_handle_weak_references_alive_p(cont->saved_ec.gen_fields_cache.fields_obj)) {
1517 cont->saved_ec.gen_fields_cache.obj = Qundef;
1518 cont->saved_ec.gen_fields_cache.fields_obj = Qundef;
1519 }
1520}
1521
1522static const rb_data_type_t rb_cont_data_type = {
1523 "continuation",
1524 {cont_mark, cont_free, cont_memsize, cont_compact, cont_handle_weak_references},
1525 0, 0, RUBY_TYPED_THREAD_SAFE_FREE
1526};
1527
1528static inline void
1529cont_save_thread(rb_context_t *cont, rb_thread_t *th)
1530{
1531 rb_execution_context_t *sec = &cont->saved_ec;
1532
1533 VM_ASSERT(th->status == THREAD_RUNNABLE);
1534
1535 /* save thread context */
1536 *sec = *th->ec;
1537
1538 /* saved_ec->machine.stack_end should be NULL */
1539 /* because it may happen GC afterward */
1540 sec->machine.stack_end = NULL;
1541}
1542
1543static rb_nativethread_lock_t jit_cont_lock;
1544
1545// Register a new continuation with execution context `ec`. Return JIT info about
1546// the continuation.
1547static struct rb_jit_cont *
1548jit_cont_new(rb_execution_context_t *ec)
1549{
1550 struct rb_jit_cont *cont;
1551
1552 // We need to use calloc instead of something like ZALLOC to avoid triggering GC here.
1553 // When this function is called from rb_thread_alloc through rb_threadptr_root_fiber_setup,
1554 // the thread is still being prepared and marking it causes SEGV.
1555 cont = ruby_mimcalloc(1, sizeof(struct rb_jit_cont));
1556 if (cont == NULL)
1557 rb_memerror();
1558 cont->ec = ec;
1559
1560 rb_native_mutex_lock(&jit_cont_lock);
1561 if (first_jit_cont == NULL) {
1562 cont->next = cont->prev = NULL;
1563 }
1564 else {
1565 cont->prev = NULL;
1566 cont->next = first_jit_cont;
1567 first_jit_cont->prev = cont;
1568 }
1569 first_jit_cont = cont;
1570 rb_native_mutex_unlock(&jit_cont_lock);
1571
1572 return cont;
1573}
1574
1575// Unregister continuation `cont`.
1576static void
1577jit_cont_free(struct rb_jit_cont *cont)
1578{
1579 if (!cont) return;
1580
1581 rb_native_mutex_lock(&jit_cont_lock);
1582 if (cont == first_jit_cont) {
1583 first_jit_cont = cont->next;
1584 if (first_jit_cont != NULL)
1585 first_jit_cont->prev = NULL;
1586 }
1587 else {
1588 cont->prev->next = cont->next;
1589 if (cont->next != NULL)
1590 cont->next->prev = cont->prev;
1591 }
1592 rb_native_mutex_unlock(&jit_cont_lock);
1593
1594 ruby_mimfree(cont);
1595}
1596
1597// Call a given callback against all on-stack ISEQs.
1598void
1599rb_jit_cont_each_iseq(rb_iseq_callback callback, void *data)
1600{
1601 struct rb_jit_cont *cont;
1602 for (cont = first_jit_cont; cont != NULL; cont = cont->next) {
1603 if (cont->ec->vm_stack == NULL)
1604 continue;
1605
1606 const rb_control_frame_t *cfp = cont->ec->cfp;
1607 while (!RUBY_VM_CONTROL_FRAME_STACK_OVERFLOW_P(cont->ec, cfp)) {
1608 if (CFP_PC(cfp) && CFP_ISEQ(cfp)) {
1609 const rb_iseq_t *iseq = CFP_ISEQ(cfp);
1610 if (iseq && imemo_type((VALUE)iseq) == imemo_iseq) {
1611 callback(iseq, data);
1612 }
1613 }
1614 cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp);
1615 }
1616 }
1617}
1618
1619#if USE_YJIT
1620// Update the jit_return of all CFPs to leave_exit unless it's leave_exception or not set.
1621// This prevents jit_exec_exception from jumping to the caller after invalidation.
1622void
1623rb_yjit_cancel_jit_return(void *leave_exit, void *leave_exception)
1624{
1625 struct rb_jit_cont *cont;
1626 for (cont = first_jit_cont; cont != NULL; cont = cont->next) {
1627 if (cont->ec->vm_stack == NULL)
1628 continue;
1629
1630 const rb_control_frame_t *cfp = cont->ec->cfp;
1631 while (!RUBY_VM_CONTROL_FRAME_STACK_OVERFLOW_P(cont->ec, cfp)) {
1632 if (cfp->jit_return && cfp->jit_return != leave_exception) {
1633 ((rb_control_frame_t *)cfp)->jit_return = leave_exit;
1634 }
1635 cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp);
1636 }
1637 }
1638}
1639#endif
1640
1641// Finish working with jit_cont.
1642void
1643rb_jit_cont_finish(void)
1644{
1645 struct rb_jit_cont *cont, *next;
1646 for (cont = first_jit_cont; cont != NULL; cont = next) {
1647 next = cont->next;
1648 ruby_mimfree(cont); // Don't use xfree because it's allocated by mimcalloc.
1649 }
1650 rb_native_mutex_destroy(&jit_cont_lock);
1651}
1652
1653static void
1654cont_init_jit_cont(rb_context_t *cont)
1655{
1656 VM_ASSERT(cont->jit_cont == NULL);
1657 // We always allocate this since YJIT may be enabled later
1658 cont->jit_cont = jit_cont_new(&(cont->saved_ec));
1659}
1660
1662rb_fiberptr_get_ec(struct rb_fiber_struct *fiber)
1663{
1664 return &fiber->cont.saved_ec;
1665}
1666
1667static void
1668cont_init(rb_context_t *cont, rb_thread_t *th)
1669{
1670 /* save thread context */
1671 cont_save_thread(cont, th);
1672 cont->saved_ec.thread_ptr = th;
1673 cont->saved_ec.local_storage = NULL;
1674 cont->saved_ec.local_storage_recursive_hash = Qnil;
1675 cont->saved_ec.local_storage_recursive_hash_for_trace = Qnil;
1676 cont_init_jit_cont(cont);
1677}
1678
1679static rb_context_t *
1680cont_new(VALUE klass)
1681{
1682 rb_context_t *cont;
1683 volatile VALUE contval;
1684 rb_thread_t *th = GET_THREAD();
1685
1686 THREAD_MUST_BE_RUNNING(th);
1687 contval = TypedData_Make_Struct(klass, rb_context_t, &rb_cont_data_type, cont);
1688 rb_gc_declare_weak_references(contval);
1689 cont->self = contval;
1690 cont_init(cont, th);
1691 return cont;
1692}
1693
1694VALUE
1695rb_fiberptr_self(struct rb_fiber_struct *fiber)
1696{
1697 return fiber->cont.self;
1698}
1699
1700unsigned int
1701rb_fiberptr_blocking(struct rb_fiber_struct *fiber)
1702{
1703 return fiber->blocking;
1704}
1705
1706// Initialize the jit_cont_lock
1707void
1708rb_jit_cont_init(void)
1709{
1710 rb_native_mutex_initialize(&jit_cont_lock);
1711}
1712
1713#if 0
1714void
1715show_vm_stack(const rb_execution_context_t *ec)
1716{
1717 VALUE *p = ec->vm_stack;
1718 while (p < ec->cfp->sp) {
1719 fprintf(stderr, "%3d ", (int)(p - ec->vm_stack));
1720 rb_obj_info_dump(*p);
1721 p++;
1722 }
1723}
1724
1725void
1726show_vm_pcs(const rb_control_frame_t *cfp,
1727 const rb_control_frame_t *end_of_cfp)
1728{
1729 int i=0;
1730 while (cfp != end_of_cfp) {
1731 int pc = 0;
1732 if (CFP_ISEQ(cfp)) {
1733 pc = cfp->pc - ISEQ_BODY(CFP_ISEQ(cfp))->iseq_encoded;
1734 }
1735 fprintf(stderr, "%2d pc: %d\n", i++, pc);
1736 cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp);
1737 }
1738}
1739#endif
1740
1741static VALUE
1742cont_capture(volatile int *volatile stat)
1743{
1744 rb_context_t *volatile cont;
1745 rb_thread_t *th = GET_THREAD();
1746 volatile VALUE contval;
1747 const rb_execution_context_t *ec = th->ec;
1748
1749 THREAD_MUST_BE_RUNNING(th);
1750 rb_vm_stack_to_heap(th->ec);
1751 cont = cont_new(rb_cContinuation);
1752 contval = cont->self;
1753
1754#ifdef CAPTURE_JUST_VALID_VM_STACK
1755 cont->saved_vm_stack.slen = ec->cfp->sp - ec->vm_stack;
1756 cont->saved_vm_stack.clen = ec->vm_stack + ec->vm_stack_size - (VALUE*)ec->cfp;
1757 cont->saved_vm_stack.size = cont->saved_vm_stack.slen + cont->saved_vm_stack.clen;
1758 cont->saved_vm_stack.ptr = ALLOC_N(VALUE, cont->saved_vm_stack.slen + cont->saved_vm_stack.clen);
1759 MEMCPY(cont->saved_vm_stack.ptr,
1760 ec->vm_stack,
1761 VALUE, cont->saved_vm_stack.slen);
1762 MEMCPY(cont->saved_vm_stack.ptr + cont->saved_vm_stack.slen,
1763 (VALUE*)ec->cfp,
1764 VALUE,
1765 cont->saved_vm_stack.clen);
1766#else
1767 cont->saved_vm_stack.size = ec->vm_stack_size;
1768 cont->saved_vm_stack.ptr = ALLOC_N(VALUE, ec->vm_stack_size);
1769 MEMCPY(cont->saved_vm_stack.ptr, ec->vm_stack, VALUE, ec->vm_stack_size);
1770#endif
1771 // At this point, `cfp` is valid but `vm_stack` should be cleared:
1772 rb_ec_set_vm_stack(&cont->saved_ec, NULL, 0);
1773 VM_ASSERT(cont->saved_ec.cfp != NULL);
1774 cont_save_machine_stack(th, cont);
1775
1776 if (ruby_setjmp(cont->jmpbuf)) {
1777 VALUE value;
1778
1779 VAR_INITIALIZED(cont);
1780 value = cont->value;
1781 if (cont->argc == -1) rb_exc_raise(value);
1782 cont->value = Qnil;
1783 *stat = 1;
1784 return value;
1785 }
1786 else {
1787 *stat = 0;
1788 return contval;
1789 }
1790}
1791
1792static inline void
1793cont_restore_thread(rb_context_t *cont)
1794{
1795 rb_thread_t *th = GET_THREAD();
1796
1797 /* restore thread context */
1798 if (cont->type == CONTINUATION_CONTEXT) {
1799 /* continuation */
1800 rb_execution_context_t *sec = &cont->saved_ec;
1801 rb_fiber_t *fiber = NULL;
1802
1803 if (sec->fiber_ptr != NULL) {
1804 fiber = sec->fiber_ptr;
1805 }
1806 else if (th->root_fiber) {
1807 fiber = th->root_fiber;
1808 }
1809
1810 if (fiber && th->ec != &fiber->cont.saved_ec) {
1811 ec_switch(th, fiber);
1812 }
1813
1814 if (th->ec->trace_arg != sec->trace_arg) {
1815 rb_raise(rb_eRuntimeError, "can't call across trace_func");
1816 }
1817
1818#if defined(__wasm__) && !defined(__EMSCRIPTEN__)
1819 if (th->ec->tag != sec->tag) {
1820 /* find the lowest common ancestor tag of the current EC and the saved EC */
1821
1822 struct rb_vm_tag *lowest_common_ancestor = NULL;
1823 size_t num_tags = 0;
1824 size_t num_saved_tags = 0;
1825 for (struct rb_vm_tag *tag = th->ec->tag; tag != NULL; tag = tag->prev) {
1826 ++num_tags;
1827 }
1828 for (struct rb_vm_tag *tag = sec->tag; tag != NULL; tag = tag->prev) {
1829 ++num_saved_tags;
1830 }
1831
1832 size_t min_tags = num_tags <= num_saved_tags ? num_tags : num_saved_tags;
1833
1834 struct rb_vm_tag *tag = th->ec->tag;
1835 while (num_tags > min_tags) {
1836 tag = tag->prev;
1837 --num_tags;
1838 }
1839
1840 struct rb_vm_tag *saved_tag = sec->tag;
1841 while (num_saved_tags > min_tags) {
1842 saved_tag = saved_tag->prev;
1843 --num_saved_tags;
1844 }
1845
1846 while (min_tags > 0) {
1847 if (tag == saved_tag) {
1848 lowest_common_ancestor = tag;
1849 break;
1850 }
1851 tag = tag->prev;
1852 saved_tag = saved_tag->prev;
1853 --min_tags;
1854 }
1855
1856 /* free all the jump buffers between the current EC's tag and the lowest common ancestor tag */
1857 for (struct rb_vm_tag *tag = th->ec->tag; tag != lowest_common_ancestor; tag = tag->prev) {
1858 rb_vm_tag_jmpbuf_deinit(&tag->buf);
1859 }
1860 }
1861#endif
1862
1863 /* copy vm stack */
1864#ifdef CAPTURE_JUST_VALID_VM_STACK
1865 MEMCPY(th->ec->vm_stack,
1866 cont->saved_vm_stack.ptr,
1867 VALUE, cont->saved_vm_stack.slen);
1868 MEMCPY(th->ec->vm_stack + th->ec->vm_stack_size - cont->saved_vm_stack.clen,
1869 cont->saved_vm_stack.ptr + cont->saved_vm_stack.slen,
1870 VALUE, cont->saved_vm_stack.clen);
1871#else
1872 MEMCPY(th->ec->vm_stack, cont->saved_vm_stack.ptr, VALUE, sec->vm_stack_size);
1873#endif
1874 /* other members of ec */
1875
1876 th->ec->cfp = sec->cfp;
1877 th->ec->raised_flag = sec->raised_flag;
1878 th->ec->tag = sec->tag;
1879 th->ec->root_lep = sec->root_lep;
1880 th->ec->root_svar = sec->root_svar;
1881 th->ec->errinfo = sec->errinfo;
1882
1883 VM_ASSERT(th->ec->vm_stack != NULL);
1884 }
1885 else {
1886 /* fiber */
1887 fiber_restore_thread(th, (rb_fiber_t*)cont);
1888 }
1889}
1890
1891NOINLINE(static void fiber_setcontext(rb_fiber_t *new_fiber, rb_fiber_t *old_fiber));
1892
1893static void
1894fiber_setcontext(rb_fiber_t *new_fiber, rb_fiber_t *old_fiber)
1895{
1896 rb_thread_t *th = GET_THREAD();
1897
1898 /* save old_fiber's machine stack - to ensure efficient garbage collection */
1899 if (!FIBER_TERMINATED_P(old_fiber)) {
1900 STACK_GROW_DIR_DETECTION;
1901 SET_MACHINE_STACK_END(&th->ec->machine.stack_end);
1902 if (STACK_DIR_UPPER(0, 1)) {
1903 old_fiber->cont.machine.stack_size = th->ec->machine.stack_start - th->ec->machine.stack_end;
1904 old_fiber->cont.machine.stack = th->ec->machine.stack_end;
1905 }
1906 else {
1907 old_fiber->cont.machine.stack_size = th->ec->machine.stack_end - th->ec->machine.stack_start;
1908 old_fiber->cont.machine.stack = th->ec->machine.stack_start;
1909 }
1910 }
1911
1912 /* these values are used in rb_gc_mark_machine_context_ctx to mark the fiber's stack. */
1913 old_fiber->cont.saved_ec.machine.stack_start = th->ec->machine.stack_start;
1914 old_fiber->cont.saved_ec.machine.stack_end = FIBER_TERMINATED_P(old_fiber) ? NULL : th->ec->machine.stack_end;
1915
1916
1917 // 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);
1918
1919#if defined(COROUTINE_SANITIZE_ADDRESS)
1920 __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);
1921#endif
1922
1923 /* swap machine context */
1924 struct coroutine_context * from = coroutine_transfer(&old_fiber->context, &new_fiber->context);
1925
1926#if defined(COROUTINE_SANITIZE_ADDRESS)
1927 __sanitizer_finish_switch_fiber(old_fiber->context.fake_stack, NULL, NULL);
1928#endif
1929
1930 if (from == NULL) {
1931 rb_syserr_fail(errno, "coroutine_transfer");
1932 }
1933
1934 /* restore thread context */
1935 fiber_restore_thread(th, old_fiber);
1936
1937 // It's possible to get here, and new_fiber is already freed.
1938 // 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);
1939}
1940
1941NOINLINE(NORETURN(static void cont_restore_1(rb_context_t *)));
1942
1943static void
1944cont_restore_1(rb_context_t *cont)
1945{
1946 cont_restore_thread(cont);
1947
1948 /* restore machine stack */
1949#if (defined(_M_AMD64) && !defined(__MINGW64__)) || defined(_M_ARM64)
1950 {
1951 /* workaround for x64 and arm64 SEH on Windows */
1952 jmp_buf buf;
1953 setjmp(buf);
1954 _JUMP_BUFFER *bp = (void*)&cont->jmpbuf;
1955 bp->Frame = ((_JUMP_BUFFER*)((void*)&buf))->Frame;
1956 }
1957#endif
1958 if (cont->machine.stack_src) {
1959 FLUSH_REGISTER_WINDOWS;
1960 MEMCPY(cont->machine.stack_src, cont->machine.stack,
1961 VALUE, cont->machine.stack_size);
1962 }
1963
1964 ruby_longjmp(cont->jmpbuf, 1);
1965}
1966
1967NORETURN(NOINLINE(static void cont_restore_0(rb_context_t *, VALUE *)));
1968
1969static void
1970cont_restore_0(rb_context_t *cont, VALUE *addr_in_prev_frame)
1971{
1972 if (cont->machine.stack_src) {
1973#ifdef HAVE_ALLOCA
1974#define STACK_PAD_SIZE 1
1975#else
1976#define STACK_PAD_SIZE 1024
1977#endif
1978 VALUE space[STACK_PAD_SIZE];
1979
1980#if !STACK_GROW_DIRECTION
1981 if (addr_in_prev_frame > &space[0]) {
1982 /* Stack grows downward */
1983#endif
1984#if STACK_GROW_DIRECTION <= 0
1985 volatile VALUE *const end = cont->machine.stack_src;
1986 if (&space[0] > end) {
1987# ifdef HAVE_ALLOCA
1988 volatile VALUE *sp = ALLOCA_N(VALUE, &space[0] - end);
1989 // We need to make sure that the stack pointer is moved,
1990 // but some compilers may remove the allocation by optimization.
1991 // We hope that the following read/write will prevent such an optimization.
1992 *sp = Qfalse;
1993 space[0] = *sp;
1994# else
1995 cont_restore_0(cont, &space[0]);
1996# endif
1997 }
1998#endif
1999#if !STACK_GROW_DIRECTION
2000 }
2001 else {
2002 /* Stack grows upward */
2003#endif
2004#if STACK_GROW_DIRECTION >= 0
2005 volatile VALUE *const end = cont->machine.stack_src + cont->machine.stack_size;
2006 if (&space[STACK_PAD_SIZE] < end) {
2007# ifdef HAVE_ALLOCA
2008 volatile VALUE *sp = ALLOCA_N(VALUE, end - &space[STACK_PAD_SIZE]);
2009 space[0] = *sp;
2010# else
2011 cont_restore_0(cont, &space[STACK_PAD_SIZE-1]);
2012# endif
2013 }
2014#endif
2015#if !STACK_GROW_DIRECTION
2016 }
2017#endif
2018 }
2019 cont_restore_1(cont);
2020}
2021
2022/*
2023 * Document-class: Continuation
2024 *
2025 * Continuation objects are generated by Kernel#callcc,
2026 * after having +require+d <i>continuation</i>. They hold
2027 * a return address and execution context, allowing a nonlocal return
2028 * to the end of the #callcc block from anywhere within a
2029 * program. Continuations are somewhat analogous to a structured
2030 * version of C's <code>setjmp/longjmp</code> (although they contain
2031 * more state, so you might consider them closer to threads).
2032 *
2033 * For instance:
2034 *
2035 * require "continuation"
2036 * arr = [ "Freddie", "Herbie", "Ron", "Max", "Ringo" ]
2037 * callcc{|cc| $cc = cc}
2038 * puts(message = arr.shift)
2039 * $cc.call unless message =~ /Max/
2040 *
2041 * <em>produces:</em>
2042 *
2043 * Freddie
2044 * Herbie
2045 * Ron
2046 * Max
2047 *
2048 * Also you can call callcc in other methods:
2049 *
2050 * require "continuation"
2051 *
2052 * def g
2053 * arr = [ "Freddie", "Herbie", "Ron", "Max", "Ringo" ]
2054 * cc = callcc { |cc| cc }
2055 * puts arr.shift
2056 * return cc, arr.size
2057 * end
2058 *
2059 * def f
2060 * c, size = g
2061 * c.call(c) if size > 1
2062 * end
2063 *
2064 * f
2065 *
2066 * This (somewhat contrived) example allows the inner loop to abandon
2067 * processing early:
2068 *
2069 * require "continuation"
2070 * callcc {|cont|
2071 * for i in 0..4
2072 * print "#{i}: "
2073 * for j in i*5...(i+1)*5
2074 * cont.call() if j == 17
2075 * printf "%3d", j
2076 * end
2077 * end
2078 * }
2079 * puts
2080 *
2081 * <em>produces:</em>
2082 *
2083 * 0: 0 1 2 3 4
2084 * 1: 5 6 7 8 9
2085 * 2: 10 11 12 13 14
2086 * 3: 15 16
2087 */
2088
2089/*
2090 * call-seq:
2091 * callcc {|cont| block } -> obj
2092 *
2093 * Generates a Continuation object, which it passes to
2094 * the associated block. You need to <code>require
2095 * 'continuation'</code> before using this method. Performing a
2096 * <em>cont</em><code>.call</code> will cause the #callcc
2097 * to return (as will falling through the end of the block). The
2098 * value returned by the #callcc is the value of the
2099 * block, or the value passed to <em>cont</em><code>.call</code>. See
2100 * class Continuation for more details. Also see
2101 * Kernel#throw for an alternative mechanism for
2102 * unwinding a call stack.
2103 */
2104
2105static VALUE
2106rb_callcc(VALUE self)
2107{
2108 volatile int called;
2109 volatile VALUE val = cont_capture(&called);
2110
2111 if (called) {
2112 return val;
2113 }
2114 else {
2115 return rb_yield(val);
2116 }
2117}
2118#ifdef RUBY_ASAN_ENABLED
2119/* callcc can't possibly work with ASAN; see bug #20273. Also this function
2120 * definition below avoids a "defined and not used" warning. */
2121MAYBE_UNUSED(static void notusing_callcc(void)) { rb_callcc(Qnil); }
2122# define rb_callcc rb_f_notimplement
2123#endif
2124
2125
2126static VALUE
2127make_passing_arg(int argc, const VALUE *argv)
2128{
2129 switch (argc) {
2130 case -1:
2131 return argv[0];
2132 case 0:
2133 return Qnil;
2134 case 1:
2135 return argv[0];
2136 default:
2137 return rb_ary_new4(argc, argv);
2138 }
2139}
2140
2141typedef VALUE e_proc(VALUE);
2142
2143NORETURN(static VALUE rb_cont_call(int argc, VALUE *argv, VALUE contval));
2144
2145/*
2146 * call-seq:
2147 * cont.call(args, ...)
2148 * cont[args, ...]
2149 *
2150 * Invokes the continuation. The program continues from the end of
2151 * the #callcc block. If no arguments are given, the original #callcc
2152 * returns +nil+. If one argument is given, #callcc returns
2153 * it. Otherwise, an array containing <i>args</i> is returned.
2154 *
2155 * callcc {|cont| cont.call } #=> nil
2156 * callcc {|cont| cont.call 1 } #=> 1
2157 * callcc {|cont| cont.call 1, 2, 3 } #=> [1, 2, 3]
2158 */
2159
2160static VALUE
2161rb_cont_call(int argc, VALUE *argv, VALUE contval)
2162{
2163 rb_context_t *cont = cont_ptr(contval);
2164 rb_thread_t *th = GET_THREAD();
2165
2166 if (cont_thread_value(cont) != th->self) {
2167 rb_raise(rb_eRuntimeError, "continuation called across threads");
2168 }
2169 if (cont->saved_ec.fiber_ptr) {
2170 if (th->ec->fiber_ptr != cont->saved_ec.fiber_ptr) {
2171 rb_raise(rb_eRuntimeError, "continuation called across fiber");
2172 }
2173 }
2174
2175 cont->argc = argc;
2176 cont->value = make_passing_arg(argc, argv);
2177
2178 cont_restore_0(cont, &contval);
2180}
2181
2182/*********/
2183/* fiber */
2184/*********/
2185
2186/*
2187 * Document-class: Fiber
2188 *
2189 * Fibers are primitives for implementing light weight cooperative
2190 * concurrency in Ruby. Basically they are a means of creating code blocks
2191 * that can be paused and resumed, much like threads. The main difference
2192 * is that they are never preempted and that the scheduling must be done by
2193 * the programmer and not the VM.
2194 *
2195 * As opposed to other stackless light weight concurrency models, each fiber
2196 * comes with a stack. This enables the fiber to be paused from deeply
2197 * nested function calls within the fiber block. See the ruby(1)
2198 * manpage to configure the size of the fiber stack(s).
2199 *
2200 * When a fiber is created it will not run automatically. Rather it must
2201 * be explicitly asked to run using the Fiber#resume method.
2202 * The code running inside the fiber can give up control by calling
2203 * Fiber.yield in which case it yields control back to caller (the
2204 * caller of the Fiber#resume).
2205 *
2206 * Upon yielding or termination the Fiber returns the value of the last
2207 * executed expression
2208 *
2209 * For instance:
2210 *
2211 * fiber = Fiber.new do
2212 * Fiber.yield 1
2213 * 2
2214 * end
2215 *
2216 * puts fiber.resume
2217 * puts fiber.resume
2218 * puts fiber.resume
2219 *
2220 * <em>produces</em>
2221 *
2222 * 1
2223 * 2
2224 * FiberError: dead fiber called
2225 *
2226 * The Fiber#resume method accepts an arbitrary number of parameters,
2227 * if it is the first call to #resume then they will be passed as
2228 * block arguments. Otherwise they will be the return value of the
2229 * call to Fiber.yield
2230 *
2231 * Example:
2232 *
2233 * fiber = Fiber.new do |first|
2234 * second = Fiber.yield first + 2
2235 * end
2236 *
2237 * puts fiber.resume 10
2238 * puts fiber.resume 1_000_000
2239 * puts fiber.resume "The fiber will be dead before I can cause trouble"
2240 *
2241 * <em>produces</em>
2242 *
2243 * 12
2244 * 1000000
2245 * FiberError: dead fiber called
2246 *
2247 * == Non-blocking Fibers
2248 *
2249 * The concept of <em>non-blocking fiber</em> was introduced in Ruby 3.0.
2250 * A non-blocking fiber, when reaching an operation that would normally block
2251 * the fiber (like <code>sleep</code>, or wait for another process or I/O)
2252 * will yield control to other fibers and allow the <em>scheduler</em> to
2253 * handle blocking and waking up (resuming) this fiber when it can proceed.
2254 *
2255 * For a Fiber to behave as non-blocking, it need to be created in Fiber.new with
2256 * <tt>blocking: false</tt> (which is the default), and Fiber.scheduler
2257 * should be set with Fiber.set_scheduler. If Fiber.scheduler is not set in
2258 * the current thread, blocking and non-blocking fibers' behavior is identical.
2259 *
2260 * Ruby doesn't provide a scheduler class: it is expected to be implemented by
2261 * the user and correspond to Fiber::Scheduler.
2262 *
2263 * There is also Fiber.schedule method, which is expected to immediately perform
2264 * the given block in a non-blocking manner. Its actual implementation is up to
2265 * the scheduler.
2266 *
2267 */
2268
2269static void
2270fiber_handle_weak_references(void *ptr)
2271{
2272 rb_fiber_t *fiber = ptr;
2273
2274 if (!fiber) return;
2275
2276 if (!rb_gc_handle_weak_references_alive_p(fiber->cont.saved_ec.gen_fields_cache.obj) ||
2277 !rb_gc_handle_weak_references_alive_p(fiber->cont.saved_ec.gen_fields_cache.fields_obj)) {
2278 fiber->cont.saved_ec.gen_fields_cache.obj = Qundef;
2279 fiber->cont.saved_ec.gen_fields_cache.fields_obj = Qundef;
2280 }
2281}
2282
2283static const rb_data_type_t rb_fiber_data_type = {
2284 "fiber",
2285 {fiber_mark, fiber_free, fiber_memsize, fiber_compact, fiber_handle_weak_references},
2286 0, 0, RUBY_TYPED_THREAD_SAFE_FREE
2287};
2288
2289static VALUE fiber_alloc_in(VALUE klass, void *objspace);
2290
2291static VALUE
2292fiber_alloc(VALUE klass)
2293{
2294 return fiber_alloc_in(klass, GET_RACTOR()->objspace);
2295}
2296
2297static VALUE
2298fiber_alloc_in(VALUE klass, void *objspace)
2299{
2300 VALUE obj = rb_data_typed_object_wrap_in_objspace(objspace, klass, 0, &rb_fiber_data_type);
2301 rb_gc_declare_weak_references(obj);
2302 return obj;
2303}
2304
2305static rb_serial_t
2306next_ec_serial(rb_ractor_t *cr)
2307{
2308 return cr->next_ec_serial++;
2309}
2310
2311static rb_fiber_t*
2312fiber_t_alloc(VALUE fiber_value, unsigned int blocking)
2313{
2314 rb_fiber_t *fiber;
2315 rb_thread_t *th = GET_THREAD();
2316
2317 if (DATA_PTR(fiber_value) != 0) {
2318 rb_raise(rb_eRuntimeError, "cannot initialize twice");
2319 }
2320
2321 THREAD_MUST_BE_RUNNING(th);
2322 fiber = ZALLOC(rb_fiber_t);
2323 fiber->cont.self = fiber_value;
2324 fiber->cont.type = FIBER_CONTEXT;
2325 fiber->blocking = blocking;
2326 fiber->killed = 0;
2327 cont_init(&fiber->cont, th);
2328
2329 fiber->cont.saved_ec.fiber_ptr = fiber;
2330 fiber->cont.saved_ec.serial = next_ec_serial(th->ractor);
2331 rb_ec_clear_vm_stack(&fiber->cont.saved_ec);
2332
2333 fiber->prev = NULL;
2334
2335 /* fiber->status == 0 == CREATED
2336 * So that we don't need to set status: fiber_status_set(fiber, FIBER_CREATED); */
2337 VM_ASSERT(FIBER_CREATED_P(fiber));
2338
2339 DATA_PTR(fiber_value) = fiber;
2340
2341 return fiber;
2342}
2343
2344static inline rb_fiber_t*
2345fiber_current(void)
2346{
2347 /* Called right after a coroutine transfer: an inlined GET_EC() may read a
2348 * TLS pointer cached before the NT migration, so force a fresh load. */
2349 rb_execution_context_t *ec = rb_current_ec_noinline();
2350 return ec->fiber_ptr;
2351}
2352
2353static inline VALUE
2354current_fiber_storage(void)
2355{
2356 rb_execution_context_t *ec = GET_EC();
2357 return ec->storage;
2358}
2359
2360static inline VALUE
2361inherit_fiber_storage(void)
2362{
2363 return rb_obj_dup(current_fiber_storage());
2364}
2365
2366static inline void
2367fiber_storage_set(struct rb_fiber_struct *fiber, VALUE storage)
2368{
2369 fiber->cont.saved_ec.storage = storage;
2370}
2371
2372static inline VALUE
2373fiber_storage_get(rb_fiber_t *fiber, int allocate)
2374{
2375 VALUE storage = fiber->cont.saved_ec.storage;
2376 if (storage == Qnil && allocate) {
2377 storage = rb_hash_new();
2378 fiber_storage_set(fiber, storage);
2379 }
2380 return storage;
2381}
2382
2383static void
2384storage_access_must_be_from_same_fiber(VALUE self)
2385{
2386 rb_fiber_t *fiber = fiber_ptr(self);
2387 rb_fiber_t *current = fiber_current();
2388 if (fiber != current) {
2389 rb_raise(rb_eArgError, "Fiber storage can only be accessed from the Fiber it belongs to");
2390 }
2391}
2392
2399static VALUE
2400rb_fiber_storage_get(VALUE self)
2401{
2402 storage_access_must_be_from_same_fiber(self);
2403
2404 VALUE storage = fiber_storage_get(fiber_ptr(self), FALSE);
2405
2406 if (storage == Qnil) {
2407 return Qnil;
2408 }
2409 else {
2410 return rb_obj_dup(storage);
2411 }
2412}
2413
2414static int
2415fiber_storage_validate_each(VALUE key, VALUE value, VALUE _argument)
2416{
2417 Check_Type(key, T_SYMBOL);
2418
2419 return ST_CONTINUE;
2420}
2421
2422static void
2423fiber_storage_validate(VALUE value)
2424{
2425 // nil is an allowed value and will be lazily initialized.
2426 if (value == Qnil) return;
2427
2428 if (!RB_TYPE_P(value, T_HASH)) {
2429 rb_raise(rb_eTypeError, "storage must be a hash");
2430 }
2431
2432 if (RB_OBJ_FROZEN(value)) {
2433 rb_raise(rb_eFrozenError, "storage must not be frozen");
2434 }
2435
2436 rb_hash_foreach(value, fiber_storage_validate_each, Qundef);
2437}
2438
2461static VALUE
2462rb_fiber_storage_set(VALUE self, VALUE value)
2463{
2464 if (rb_warning_category_enabled_p(RB_WARN_CATEGORY_EXPERIMENTAL)) {
2466 "Fiber#storage= is experimental and may be removed in the future!");
2467 }
2468
2469 storage_access_must_be_from_same_fiber(self);
2470 fiber_storage_validate(value);
2471
2472 fiber_ptr(self)->cont.saved_ec.storage = rb_obj_dup(value);
2473 return value;
2474}
2475
2486static VALUE
2487rb_fiber_storage_aref(VALUE class, VALUE key)
2488{
2489 key = rb_to_symbol(key);
2490
2491 VALUE storage = fiber_storage_get(fiber_current(), FALSE);
2492 if (storage == Qnil) return Qnil;
2493
2494 return rb_hash_aref(storage, key);
2495}
2496
2508static VALUE
2509rb_fiber_storage_aset(VALUE class, VALUE key, VALUE value)
2510{
2511 key = rb_to_symbol(key);
2512
2513 VALUE storage = fiber_storage_get(fiber_current(), value != Qnil);
2514 if (storage == Qnil) return Qnil;
2515
2516 if (value == Qnil) {
2517 return rb_hash_delete(storage, key);
2518 }
2519 else {
2520 return rb_hash_aset(storage, key, value);
2521 }
2522}
2523
2524static VALUE
2525fiber_initialize(VALUE self, VALUE proc, struct fiber_pool * fiber_pool, unsigned int blocking, VALUE storage)
2526{
2527 if (storage == Qundef || storage == Qtrue) {
2528 // The default, inherit storage (dup) from the current fiber:
2529 storage = inherit_fiber_storage();
2530 }
2531 else /* nil, hash, etc. */ {
2532 fiber_storage_validate(storage);
2533 storage = rb_obj_dup(storage);
2534 }
2535
2536 rb_fiber_t *fiber = fiber_t_alloc(self, blocking);
2537
2538 fiber->cont.saved_ec.storage = storage;
2539 fiber->first_proc = proc;
2540 fiber->stack.base = NULL;
2541 fiber->stack.pool = fiber_pool;
2542
2543 return self;
2544}
2545
2546static void
2547fiber_prepare_stack(rb_fiber_t *fiber)
2548{
2549 rb_context_t *cont = &fiber->cont;
2550 rb_execution_context_t *sec = &cont->saved_ec;
2551
2552 size_t vm_stack_size = 0;
2553 VALUE *vm_stack = fiber_initialize_coroutine(fiber, &vm_stack_size);
2554
2555 /* initialize cont */
2556 cont->saved_vm_stack.ptr = NULL;
2557 rb_ec_initialize_vm_stack(sec, vm_stack, vm_stack_size / sizeof(VALUE));
2558
2559 sec->tag = NULL;
2560 sec->local_storage = NULL;
2561 sec->local_storage_recursive_hash = Qnil;
2562 sec->local_storage_recursive_hash_for_trace = Qnil;
2563}
2564
2565static struct fiber_pool *
2566rb_fiber_pool_default(VALUE pool)
2567{
2568 return &shared_fiber_pool;
2569}
2570
2571VALUE rb_fiber_inherit_storage(struct rb_execution_context_struct *ec, struct rb_fiber_struct *fiber)
2572{
2573 VALUE storage = rb_obj_dup(ec->storage);
2574 fiber->cont.saved_ec.storage = storage;
2575 return storage;
2576}
2577
2578/* :nodoc: */
2579static VALUE
2580rb_fiber_initialize_kw(int argc, VALUE* argv, VALUE self, int kw_splat)
2581{
2582 VALUE pool = Qnil;
2583 VALUE blocking = Qfalse;
2584 VALUE storage = Qundef;
2585
2586 if (kw_splat != RB_NO_KEYWORDS) {
2587 VALUE options = Qnil;
2588 VALUE arguments[3] = {Qundef};
2589
2590 argc = rb_scan_args_kw(kw_splat, argc, argv, ":", &options);
2591 rb_get_kwargs(options, fiber_initialize_keywords, 0, 3, arguments);
2592
2593 if (!UNDEF_P(arguments[0])) {
2594 blocking = arguments[0];
2595 }
2596
2597 if (!UNDEF_P(arguments[1])) {
2598 pool = arguments[1];
2599 }
2600
2601 storage = arguments[2];
2602 }
2603
2604 return fiber_initialize(self, rb_block_proc(), rb_fiber_pool_default(pool), RTEST(blocking), storage);
2605}
2606
2607/*
2608 * call-seq:
2609 * Fiber.new(blocking: false, storage: true) { |*args| ... } -> fiber
2610 *
2611 * Creates new Fiber. Initially, the fiber is not running and can be resumed
2612 * with #resume. Arguments to the first #resume call will be passed to the
2613 * block:
2614 *
2615 * f = Fiber.new do |initial|
2616 * current = initial
2617 * loop do
2618 * puts "current: #{current.inspect}"
2619 * current = Fiber.yield
2620 * end
2621 * end
2622 * f.resume(100) # prints: current: 100
2623 * f.resume(1, 2, 3) # prints: current: [1, 2, 3]
2624 * f.resume # prints: current: nil
2625 * # ... and so on ...
2626 *
2627 * If <tt>blocking: false</tt> is passed to <tt>Fiber.new</tt>, _and_ current
2628 * thread has a Fiber.scheduler defined, the Fiber becomes non-blocking (see
2629 * "Non-blocking Fibers" section in class docs).
2630 *
2631 * If the <tt>storage</tt> is unspecified, the default is to inherit a copy of
2632 * the storage from the current fiber. This is the same as specifying
2633 * <tt>storage: true</tt>.
2634 *
2635 * Fiber[:x] = 1
2636 * Fiber.new do
2637 * Fiber[:x] # => 1
2638 * Fiber[:x] = 2
2639 * end.resume
2640 * Fiber[:x] # => 1
2641 *
2642 * If the given <tt>storage</tt> is <tt>nil</tt>, this function will lazy
2643 * initialize the internal storage, which starts as an empty hash.
2644 *
2645 * Fiber[:x] = "Hello World"
2646 * Fiber.new(storage: nil) do
2647 * Fiber[:x] # nil
2648 * end
2649 *
2650 * Otherwise, the given <tt>storage</tt> is used as the new fiber's storage,
2651 * and it must be an instance of Hash.
2652 *
2653 * Explicitly using <tt>storage: true</tt> is currently experimental and may
2654 * change in the future.
2655 */
2656static VALUE
2657rb_fiber_initialize(int argc, VALUE* argv, VALUE self)
2658{
2659 return rb_fiber_initialize_kw(argc, argv, self, rb_keyword_given_p());
2660}
2661
2662VALUE
2663rb_fiber_new_storage(rb_block_call_func_t func, VALUE obj, VALUE storage)
2664{
2665 return fiber_initialize(fiber_alloc(rb_cFiber), rb_proc_new(func, obj), rb_fiber_pool_default(Qnil), 0, storage);
2666}
2667
2668VALUE
2669rb_fiber_new(rb_block_call_func_t func, VALUE obj)
2670{
2671 return rb_fiber_new_storage(func, obj, Qtrue);
2672}
2673
2674static VALUE
2675rb_fiber_s_schedule_kw(int argc, VALUE* argv, int kw_splat)
2676{
2677 rb_thread_t * th = GET_THREAD();
2678 VALUE scheduler = th->scheduler;
2679 VALUE fiber = Qnil;
2680
2681 if (scheduler != Qnil) {
2682 fiber = rb_fiber_scheduler_fiber(scheduler, argc, argv, kw_splat);
2683 }
2684 else {
2685 rb_raise(rb_eRuntimeError, "No scheduler is available!");
2686 }
2687
2688 return fiber;
2689}
2690
2691/*
2692 * call-seq:
2693 * Fiber.schedule { |*args| ... } -> fiber
2694 *
2695 * The method is <em>expected</em> to immediately run the provided block of code in a
2696 * separate non-blocking fiber.
2697 *
2698 * puts "Go to sleep!"
2699 *
2700 * Fiber.set_scheduler(MyScheduler.new)
2701 *
2702 * Fiber.schedule do
2703 * puts "Going to sleep"
2704 * sleep(1)
2705 * puts "I slept well"
2706 * end
2707 *
2708 * puts "Wakey-wakey, sleepyhead"
2709 *
2710 * Assuming MyScheduler is properly implemented, this program will produce:
2711 *
2712 * Go to sleep!
2713 * Going to sleep
2714 * Wakey-wakey, sleepyhead
2715 * ...1 sec pause here...
2716 * I slept well
2717 *
2718 * ...e.g. on the first blocking operation inside the Fiber (<tt>sleep(1)</tt>),
2719 * the control is yielded to the outside code (main fiber), and <em>at the end
2720 * of that execution</em>, the scheduler takes care of properly resuming all the
2721 * blocked fibers.
2722 *
2723 * Note that the behavior described above is how the method is <em>expected</em>
2724 * to behave, actual behavior is up to the current scheduler's implementation of
2725 * Fiber::Scheduler#fiber method. Ruby doesn't enforce this method to
2726 * behave in any particular way.
2727 *
2728 * If the scheduler is not set, the method raises
2729 * <tt>RuntimeError (No scheduler is available!)</tt>.
2730 *
2731 */
2732static VALUE
2733rb_fiber_s_schedule(int argc, VALUE *argv, VALUE obj)
2734{
2735 return rb_fiber_s_schedule_kw(argc, argv, rb_keyword_given_p());
2736}
2737
2738/*
2739 * call-seq:
2740 * Fiber.scheduler -> obj or nil
2741 *
2742 * Returns the Fiber scheduler, that was last set for the current thread with Fiber.set_scheduler.
2743 * Returns +nil+ if no scheduler is set (which is the default), and non-blocking fibers'
2744 * behavior is the same as blocking.
2745 * (see "Non-blocking fibers" section in class docs for details about the scheduler concept).
2746 *
2747 */
2748static VALUE
2749rb_fiber_s_scheduler(VALUE klass)
2750{
2751 return rb_fiber_scheduler_get();
2752}
2753
2754/*
2755 * call-seq:
2756 * Fiber.current_scheduler -> obj or nil
2757 *
2758 * Returns the Fiber scheduler, that was last set for the current thread with Fiber.set_scheduler
2759 * if and only if the current fiber is non-blocking.
2760 *
2761 */
2762static VALUE
2763rb_fiber_current_scheduler(VALUE klass)
2764{
2766}
2767
2768/*
2769 * call-seq:
2770 * Fiber.set_scheduler(scheduler) -> scheduler
2771 *
2772 * Sets the Fiber scheduler for the current thread. If the scheduler is set, non-blocking
2773 * fibers (created by Fiber.new with <tt>blocking: false</tt>, or by Fiber.schedule)
2774 * call that scheduler's hook methods on potentially blocking operations, and the current
2775 * thread will call scheduler's +close+ method on finalization (allowing the scheduler to
2776 * properly manage all non-finished fibers).
2777 *
2778 * +scheduler+ can be an object of any class corresponding to Fiber::Scheduler. Its
2779 * implementation is up to the user.
2780 *
2781 * See also the "Non-blocking fibers" section in class docs.
2782 *
2783 */
2784static VALUE
2785rb_fiber_set_scheduler(VALUE klass, VALUE scheduler)
2786{
2787 return rb_fiber_scheduler_set(scheduler);
2788}
2789
2790NORETURN(static void rb_fiber_terminate(rb_fiber_t *fiber, int need_interrupt, VALUE err));
2791
2792void
2793rb_fiber_start(rb_fiber_t *fiber_arg)
2794{
2795 rb_fiber_t * volatile fiber = fiber_arg;
2796 rb_thread_t * volatile th = fiber->cont.saved_ec.thread_ptr;
2797
2798 enum ruby_tag_type state;
2799
2800 VM_ASSERT(th->ec == GET_EC());
2801 VM_ASSERT(FIBER_RESUMED_P(fiber));
2802
2803 if (fiber->blocking) {
2804 th->blocking += 1;
2805 }
2806
2807 EC_PUSH_TAG(th->ec);
2808 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
2809 rb_context_t *cont = &fiber->cont;
2810 rb_proc_t *proc;
2811 int argc;
2812 const VALUE *argv, args = cont->value;
2813 GetProcPtr(fiber->first_proc, proc);
2814 argv = (argc = cont->argc) > 1 ? RARRAY_CONST_PTR(args) : &args;
2815 cont->value = Qnil;
2816 th->ec->errinfo = Qnil;
2817 th->ec->root_lep = rb_vm_proc_local_ep(fiber->first_proc);
2818 th->ec->root_svar = Qfalse;
2819
2820 EXEC_EVENT_HOOK(th->ec, RUBY_EVENT_FIBER_SWITCH, th->self, 0, 0, 0, Qnil);
2821 const rb_cref_t *cref = rb_proc_refinements_cref_for_call(fiber->first_proc);
2822 cont->value = rb_vm_invoke_proc(th->ec, proc, argc, argv, cont->kw_splat, VM_BLOCK_HANDLER_NONE, cref);
2823 }
2824 EC_POP_TAG();
2825
2826 int need_interrupt = TRUE;
2827 VALUE err = Qfalse;
2828 if (state) {
2829 err = th->ec->errinfo;
2830 VM_ASSERT(FIBER_RESUMED_P(fiber));
2831
2832 if (state == TAG_RAISE) {
2833 // noop...
2834 }
2835 else if (state == TAG_FATAL && err == RUBY_FATAL_FIBER_KILLED) {
2836 need_interrupt = FALSE;
2837 err = Qfalse;
2838 }
2839 else if (state == TAG_FATAL) {
2840 rb_threadptr_pending_interrupt_enque(th, err);
2841 }
2842 else {
2843 err = rb_vm_make_jump_tag_but_local_jump(state, err);
2844 }
2845 }
2846
2847 rb_fiber_terminate(fiber, need_interrupt, err);
2848}
2849
2850// Set up a "root fiber", which is the fiber that every Ractor has.
2851void
2852rb_threadptr_root_fiber_setup(rb_thread_t *th)
2853{
2854 rb_fiber_t *fiber = ZALLOC(rb_fiber_t);
2855 if (!fiber) {
2856 rb_bug("%s", strerror(errno)); /* ... is it possible to call rb_bug here? */
2857 }
2858
2859 fiber->cont.type = FIBER_CONTEXT;
2860 fiber->cont.saved_ec.fiber_ptr = fiber;
2861 fiber->cont.saved_ec.serial = next_ec_serial(th->ractor);
2862 fiber->cont.saved_ec.thread_ptr = th;
2863 fiber->blocking = 1;
2864 fiber->killed = 0;
2865 fiber_status_set(fiber, FIBER_RESUMED); /* skip CREATED */
2866
2867 coroutine_initialize_main(&fiber->context);
2868
2869 th->ec = &fiber->cont.saved_ec;
2870
2871 cont_init_jit_cont(&fiber->cont);
2872}
2873
2874void
2875rb_root_fiber_obj_setup(rb_thread_t *th, void *objspace)
2876{
2877 rb_fiber_t *fiber = th->ec->fiber_ptr;
2878 VALUE fiber_value = fiber_alloc_in(rb_cFiber, objspace);
2879 DATA_PTR(fiber_value) = fiber;
2880 fiber->cont.self = fiber_value;
2881}
2882
2883void
2884rb_threadptr_root_fiber_release(rb_thread_t *th)
2885{
2886 if (th->root_fiber) {
2887 /* ignore. A root fiber object will free th->ec */
2888 }
2889 else {
2890 rb_execution_context_t *ec = rb_current_execution_context(false);
2891
2892 VM_ASSERT(th->ec->fiber_ptr->cont.type == FIBER_CONTEXT);
2893 VM_ASSERT(th->ec->fiber_ptr->cont.self == 0);
2894
2895 if (ec && th->ec == ec) {
2896 rb_ractor_set_current_ec(th->ractor, NULL);
2897 }
2898 fiber_free(th->ec->fiber_ptr);
2899 th->ec = NULL;
2900 }
2901}
2902
2903void
2904rb_threadptr_root_fiber_terminate(rb_thread_t *th)
2905{
2906 rb_fiber_t *fiber = th->ec->fiber_ptr;
2907
2908 fiber->status = FIBER_TERMINATED;
2909
2910 // The vm_stack is `alloca`ed on the thread stack, so it's gone too:
2911 rb_ec_clear_vm_stack(th->ec);
2912}
2913
2914static inline rb_fiber_t*
2915return_fiber(bool terminate)
2916{
2917 rb_fiber_t *fiber = fiber_current();
2918 rb_fiber_t *prev = fiber->prev;
2919
2920 if (prev) {
2921 fiber->prev = NULL;
2922 prev->resuming_fiber = NULL;
2923 return prev;
2924 }
2925 else {
2926 if (!terminate) {
2927 rb_raise(rb_eFiberError, "attempt to yield on a not resumed fiber");
2928 }
2929
2930 rb_thread_t *th = GET_THREAD();
2931 rb_fiber_t *root_fiber = th->root_fiber;
2932
2933 VM_ASSERT(root_fiber != NULL);
2934
2935 // search resuming fiber
2936 for (fiber = root_fiber; fiber->resuming_fiber; fiber = fiber->resuming_fiber) {
2937 }
2938
2939 return fiber;
2940 }
2941}
2942
2943VALUE
2944rb_fiber_current(void)
2945{
2946 return fiber_current()->cont.self;
2947}
2948
2949// Prepare to execute next_fiber on the given thread.
2950static inline void
2951fiber_store(rb_fiber_t *next_fiber, rb_thread_t *th)
2952{
2953 rb_fiber_t *fiber = th->ec->fiber_ptr;
2954
2955 if (FIBER_CREATED_P(next_fiber)) {
2956 fiber_prepare_stack(next_fiber);
2957 }
2958
2959 VM_ASSERT(FIBER_RESUMED_P(fiber) || FIBER_TERMINATED_P(fiber));
2960 VM_ASSERT(FIBER_RUNNABLE_P(next_fiber));
2961
2962 if (FIBER_RESUMED_P(fiber)) fiber_status_set(fiber, FIBER_SUSPENDED);
2963
2964 fiber_status_set(next_fiber, FIBER_RESUMED);
2965 fiber_setcontext(next_fiber, fiber);
2966}
2967
2968static void
2969fiber_check_killed(rb_fiber_t *fiber)
2970{
2971 VM_ASSERT(fiber == fiber_current());
2972
2973 if (fiber->killed) {
2974 rb_thread_t *thread = fiber->cont.saved_ec.thread_ptr;
2975
2976 thread->ec->errinfo = RUBY_FATAL_FIBER_KILLED;
2977 EC_JUMP_TAG(thread->ec, RUBY_TAG_FATAL);
2978 }
2979}
2980
2981static inline VALUE
2982fiber_switch(rb_fiber_t *fiber, int argc, const VALUE *argv, int kw_splat, rb_fiber_t *resuming_fiber, bool yielding)
2983{
2984 VALUE value;
2985 rb_context_t *cont = &fiber->cont;
2986 rb_thread_t *th = GET_THREAD();
2987
2988 /* make sure the root_fiber object is available */
2989 if (th->root_fiber == NULL) {
2990 th->root_fiber = th->ec->fiber_ptr;
2991 }
2992
2993 if (th->ec->fiber_ptr == fiber) {
2994 /* ignore fiber context switch
2995 * because destination fiber is the same as current fiber
2996 */
2997 return make_passing_arg(argc, argv);
2998 }
2999
3000 if (cont_thread_value(cont) != th->self) {
3001 rb_raise(rb_eFiberError, "fiber called across threads");
3002 }
3003
3004 if (FIBER_TERMINATED_P(fiber)) {
3005 value = rb_exc_new2(rb_eFiberError, "dead fiber called");
3006
3007 if (!FIBER_TERMINATED_P(th->ec->fiber_ptr)) {
3008 rb_exc_raise(value);
3009 VM_UNREACHABLE(fiber_switch);
3010 }
3011 else {
3012 /* th->ec->fiber_ptr is also dead => switch to root fiber */
3013 /* (this means we're being called from rb_fiber_terminate, */
3014 /* and the terminated fiber's return_fiber() is already dead) */
3015 VM_ASSERT(FIBER_SUSPENDED_P(th->root_fiber));
3016
3017 cont = &th->root_fiber->cont;
3018 cont->argc = -1;
3019 cont->value = value;
3020
3021 fiber_setcontext(th->root_fiber, th->ec->fiber_ptr);
3022
3023 VM_UNREACHABLE(fiber_switch);
3024 }
3025 }
3026
3027 VM_ASSERT(FIBER_RUNNABLE_P(fiber));
3028
3029 /*
3030 * Keep the target fiber object alive across fiber_store. The raw
3031 * rb_fiber_t pointer is used after the coroutine switch, and GC may run
3032 * while this C frame is suspended.
3033 */
3034 VALUE fiber_value = fiber->cont.self;
3035
3036 rb_fiber_t *current_fiber = fiber_current();
3037
3038 VM_ASSERT(!current_fiber->resuming_fiber);
3039
3040 if (resuming_fiber) {
3041 current_fiber->resuming_fiber = resuming_fiber;
3042 fiber->prev = fiber_current();
3043 fiber->yielding = 0;
3044 }
3045
3046 VM_ASSERT(!current_fiber->yielding);
3047 if (yielding) {
3048 current_fiber->yielding = 1;
3049 }
3050
3051 if (current_fiber->blocking) {
3052 th->blocking -= 1;
3053 }
3054
3055 cont->argc = argc;
3056 cont->kw_splat = kw_splat;
3057 cont->value = make_passing_arg(argc, argv);
3058
3059 fiber_store(fiber, th);
3060
3061 // We cannot free the stack until the pthread is joined:
3062#ifndef COROUTINE_PTHREAD_CONTEXT
3063 if (FIBER_TERMINATED_P(fiber)) {
3064 fiber_stack_release(fiber);
3065 }
3066#endif
3067 RB_GC_GUARD(fiber_value);
3068
3069 if (fiber_current()->blocking) {
3070 th->blocking += 1;
3071 }
3072
3073 RUBY_VM_CHECK_INTS(th->ec);
3074
3075 EXEC_EVENT_HOOK(th->ec, RUBY_EVENT_FIBER_SWITCH, th->self, 0, 0, 0, Qnil);
3076
3077 current_fiber = th->ec->fiber_ptr;
3078 value = current_fiber->cont.value;
3079
3080 fiber_check_killed(current_fiber);
3081
3082 if (current_fiber->cont.argc == -1) {
3083 // Fiber#raise will trigger this path.
3084 rb_exc_raise(value);
3085 }
3086
3087 return value;
3088}
3089
3090VALUE
3091rb_fiber_transfer(VALUE fiber_value, int argc, const VALUE *argv)
3092{
3093 return fiber_switch(fiber_ptr(fiber_value), argc, argv, RB_NO_KEYWORDS, NULL, false);
3094}
3095
3096/*
3097 * call-seq:
3098 * fiber.blocking? -> true or false
3099 *
3100 * Returns +true+ if +fiber+ is blocking and +false+ otherwise.
3101 * Fiber is non-blocking if it was created via passing <tt>blocking: false</tt>
3102 * to Fiber.new, or via Fiber.schedule.
3103 *
3104 * Note that, even if the method returns +false+, the fiber behaves differently
3105 * only if Fiber.scheduler is set in the current thread.
3106 *
3107 * See the "Non-blocking fibers" section in class docs for details.
3108 *
3109 */
3110VALUE
3111rb_fiber_blocking_p(VALUE fiber)
3112{
3113 return RBOOL(fiber_ptr(fiber)->blocking);
3114}
3115
3116static VALUE
3117fiber_blocking_yield(VALUE fiber_value)
3118{
3119 rb_fiber_t *fiber = fiber_ptr(fiber_value);
3120 rb_thread_t * volatile th = fiber->cont.saved_ec.thread_ptr;
3121
3122 VM_ASSERT(fiber->blocking == 0);
3123
3124 // fiber->blocking is `unsigned int : 1`, so we use it as a boolean:
3125 fiber->blocking = 1;
3126
3127 // Once the fiber is blocking, and current, we increment the thread blocking state:
3128 th->blocking += 1;
3129
3130 return rb_yield(fiber_value);
3131}
3132
3133static VALUE
3134fiber_blocking_ensure(VALUE fiber_value)
3135{
3136 rb_fiber_t *fiber = fiber_ptr(fiber_value);
3137 rb_thread_t * volatile th = fiber->cont.saved_ec.thread_ptr;
3138
3139 // We are no longer blocking:
3140 fiber->blocking = 0;
3141 th->blocking -= 1;
3142
3143 return Qnil;
3144}
3145
3146/*
3147 * call-seq:
3148 * Fiber.blocking{|fiber| ...} -> result
3149 *
3150 * Forces the fiber to be blocking for the duration of the block. Returns the
3151 * result of the block.
3152 *
3153 * See the "Non-blocking fibers" section in class docs for details.
3154 *
3155 */
3156VALUE
3157rb_fiber_blocking(VALUE class)
3158{
3159 VALUE fiber_value = rb_fiber_current();
3160 rb_fiber_t *fiber = fiber_ptr(fiber_value);
3161
3162 // If we are already blocking, this is essentially a no-op:
3163 if (fiber->blocking) {
3164 return rb_yield(fiber_value);
3165 }
3166 else {
3167 return rb_ensure(fiber_blocking_yield, fiber_value, fiber_blocking_ensure, fiber_value);
3168 }
3169}
3170
3171/*
3172 * call-seq:
3173 * Fiber.blocking? -> false or 1
3174 *
3175 * Returns +false+ if the current fiber is non-blocking.
3176 * Fiber is non-blocking if it was created via passing <tt>blocking: false</tt>
3177 * to Fiber.new, or via Fiber.schedule.
3178 *
3179 * If the current Fiber is blocking, the method returns 1.
3180 * Future developments may allow for situations where larger integers
3181 * could be returned.
3182 *
3183 * Note that, even if the method returns +false+, Fiber behaves differently
3184 * only if Fiber.scheduler is set in the current thread.
3185 *
3186 * See the "Non-blocking fibers" section in class docs for details.
3187 *
3188 */
3189static VALUE
3190rb_fiber_s_blocking_p(VALUE klass)
3191{
3192 rb_thread_t *thread = GET_THREAD();
3193 unsigned blocking = thread->blocking;
3194
3195 if (blocking == 0)
3196 return Qfalse;
3197
3198 return INT2NUM(blocking);
3199}
3200
3201void
3202rb_fiber_close(rb_fiber_t *fiber)
3203{
3204 fiber_status_set(fiber, FIBER_TERMINATED);
3205 rb_ec_close(&fiber->cont.saved_ec);
3206}
3207
3208static void
3209rb_fiber_terminate(rb_fiber_t *fiber, int need_interrupt, VALUE error)
3210{
3211 VALUE value = fiber->cont.value;
3212
3213 VM_ASSERT(FIBER_RESUMED_P(fiber));
3214 rb_fiber_close(fiber);
3215
3216 fiber->cont.machine.stack = NULL;
3217 fiber->cont.machine.stack_size = 0;
3218
3219 rb_fiber_t *next_fiber = return_fiber(true);
3220
3221 if (need_interrupt) RUBY_VM_SET_INTERRUPT(&next_fiber->cont.saved_ec);
3222
3223 if (RTEST(error))
3224 fiber_switch(next_fiber, -1, &error, RB_NO_KEYWORDS, NULL, false);
3225 else
3226 fiber_switch(next_fiber, 1, &value, RB_NO_KEYWORDS, NULL, false);
3227 ruby_stop(0);
3228}
3229
3230static VALUE
3231fiber_resume_kw(rb_fiber_t *fiber, int argc, const VALUE *argv, int kw_splat)
3232{
3233 rb_fiber_t *current_fiber = fiber_current();
3234
3235 if (argc == -1 && FIBER_CREATED_P(fiber)) {
3236 rb_raise(rb_eFiberError, "cannot raise exception on unborn fiber");
3237 }
3238 else if (FIBER_TERMINATED_P(fiber)) {
3239 rb_raise(rb_eFiberError, "attempt to resume a terminated fiber");
3240 }
3241 else if (fiber == current_fiber) {
3242 rb_raise(rb_eFiberError, "attempt to resume the current fiber");
3243 }
3244 else if (fiber->prev != NULL) {
3245 rb_raise(rb_eFiberError, "attempt to resume a resumed fiber (double resume)");
3246 }
3247 else if (fiber->resuming_fiber) {
3248 rb_raise(rb_eFiberError, "attempt to resume a resuming fiber");
3249 }
3250 else if (fiber->prev == NULL &&
3251 (!fiber->yielding && fiber->status != FIBER_CREATED)) {
3252 rb_raise(rb_eFiberError, "attempt to resume a transferring fiber");
3253 }
3254
3255 return fiber_switch(fiber, argc, argv, kw_splat, fiber, false);
3256}
3257
3258VALUE
3259rb_fiber_resume_kw(VALUE self, int argc, const VALUE *argv, int kw_splat)
3260{
3261 return fiber_resume_kw(fiber_ptr(self), argc, argv, kw_splat);
3262}
3263
3264VALUE
3265rb_fiber_resume(VALUE self, int argc, const VALUE *argv)
3266{
3267 return fiber_resume_kw(fiber_ptr(self), argc, argv, RB_NO_KEYWORDS);
3268}
3269
3270VALUE
3271rb_fiber_yield_kw(int argc, const VALUE *argv, int kw_splat)
3272{
3273 return fiber_switch(return_fiber(false), argc, argv, kw_splat, NULL, true);
3274}
3275
3276VALUE
3277rb_fiber_yield(int argc, const VALUE *argv)
3278{
3279 return fiber_switch(return_fiber(false), argc, argv, RB_NO_KEYWORDS, NULL, true);
3280}
3281
3282void
3283rb_fiber_reset_root_local_storage(rb_thread_t *th)
3284{
3285 if (th->root_fiber && th->root_fiber != th->ec->fiber_ptr) {
3286 th->ec->local_storage = th->root_fiber->cont.saved_ec.local_storage;
3287 }
3288}
3289
3290/*
3291 * call-seq:
3292 * fiber.alive? -> true or false
3293 *
3294 * Returns true if the fiber can still be resumed (or transferred
3295 * to). After finishing execution of the fiber block this method will
3296 * always return +false+.
3297 */
3298VALUE
3299rb_fiber_alive_p(VALUE fiber_value)
3300{
3301 return RBOOL(!FIBER_TERMINATED_P(fiber_ptr(fiber_value)));
3302}
3303
3304/*
3305 * call-seq:
3306 * fiber.resume(args, ...) -> obj
3307 *
3308 * Resumes the fiber from the point at which the last Fiber.yield was
3309 * called, or starts running it if it is the first call to
3310 * #resume. Arguments passed to resume will be the value of the
3311 * Fiber.yield expression or will be passed as block parameters to
3312 * the fiber's block if this is the first #resume.
3313 *
3314 * Alternatively, when resume is called it evaluates to the arguments passed
3315 * to the next Fiber.yield statement inside the fiber's block
3316 * or to the block value if it runs to completion without any
3317 * Fiber.yield
3318 */
3319static VALUE
3320rb_fiber_m_resume(int argc, VALUE *argv, VALUE fiber)
3321{
3322 return rb_fiber_resume_kw(fiber, argc, argv, rb_keyword_given_p());
3323}
3324
3325/*
3326 * call-seq:
3327 * fiber.backtrace -> array
3328 * fiber.backtrace(start) -> array
3329 * fiber.backtrace(start, count) -> array
3330 * fiber.backtrace(start..end) -> array
3331 *
3332 * Returns the current execution stack of the fiber. +start+, +count+ and +end+ allow
3333 * to select only parts of the backtrace.
3334 *
3335 * def level3
3336 * Fiber.yield
3337 * end
3338 *
3339 * def level2
3340 * level3
3341 * end
3342 *
3343 * def level1
3344 * level2
3345 * end
3346 *
3347 * f = Fiber.new { level1 }
3348 *
3349 * # It is empty before the fiber started
3350 * f.backtrace
3351 * #=> []
3352 *
3353 * f.resume
3354 *
3355 * f.backtrace
3356 * #=> ["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>'"]
3357 * p f.backtrace(1) # start from the item 1
3358 * #=> ["test.rb:2:in `level3'", "test.rb:6:in `level2'", "test.rb:10:in `level1'", "test.rb:13:in `block in <main>'"]
3359 * p f.backtrace(2, 2) # start from item 2, take 2
3360 * #=> ["test.rb:6:in `level2'", "test.rb:10:in `level1'"]
3361 * p f.backtrace(1..3) # take items from 1 to 3
3362 * #=> ["test.rb:2:in `level3'", "test.rb:6:in `level2'", "test.rb:10:in `level1'"]
3363 *
3364 * f.resume
3365 *
3366 * # It is nil after the fiber is finished
3367 * f.backtrace
3368 * #=> nil
3369 *
3370 */
3371static VALUE
3372rb_fiber_backtrace(int argc, VALUE *argv, VALUE fiber)
3373{
3374 return rb_vm_backtrace(argc, argv, &fiber_ptr(fiber)->cont.saved_ec);
3375}
3376
3377/*
3378 * call-seq:
3379 * fiber.backtrace_locations -> array
3380 * fiber.backtrace_locations(start) -> array
3381 * fiber.backtrace_locations(start, count) -> array
3382 * fiber.backtrace_locations(start..end) -> array
3383 *
3384 * Like #backtrace, but returns each line of the execution stack as a
3385 * Thread::Backtrace::Location. Accepts the same arguments as #backtrace.
3386 *
3387 * f = Fiber.new { Fiber.yield }
3388 * f.resume
3389 * loc = f.backtrace_locations.first
3390 * loc.label #=> "yield"
3391 * loc.path #=> "test.rb"
3392 * loc.lineno #=> 1
3393 *
3394 *
3395 */
3396static VALUE
3397rb_fiber_backtrace_locations(int argc, VALUE *argv, VALUE fiber)
3398{
3399 return rb_vm_backtrace_locations(argc, argv, &fiber_ptr(fiber)->cont.saved_ec);
3400}
3401
3402/*
3403 * call-seq:
3404 * fiber.transfer(args, ...) -> obj
3405 *
3406 * Transfer control to another fiber, resuming it from where it last
3407 * stopped or starting it if it was not resumed before. The calling
3408 * fiber will be suspended much like in a call to
3409 * Fiber.yield.
3410 *
3411 * The fiber which receives the transfer call treats it much like
3412 * a resume call. Arguments passed to transfer are treated like those
3413 * passed to resume.
3414 *
3415 * The two style of control passing to and from fiber (one is #resume and
3416 * Fiber::yield, another is #transfer to and from fiber) can't be freely
3417 * mixed.
3418 *
3419 * * If the Fiber's lifecycle had started with transfer, it will never
3420 * be able to yield or be resumed control passing, only
3421 * finish or transfer back. (It still can resume other fibers that
3422 * are allowed to be resumed.)
3423 * * If the Fiber's lifecycle had started with resume, it can yield
3424 * or transfer to another Fiber, but can receive control back only
3425 * the way compatible with the way it was given away: if it had
3426 * transferred, it only can be transferred back, and if it had
3427 * yielded, it only can be resumed back. After that, it again can
3428 * transfer or yield.
3429 *
3430 * If those rules are broken FiberError is raised.
3431 *
3432 * For an individual Fiber design, yield/resume is easier to use
3433 * (the Fiber just gives away control, it doesn't need to think
3434 * about who the control is given to), while transfer is more flexible
3435 * for complex cases, allowing to build arbitrary graphs of Fibers
3436 * dependent on each other.
3437 *
3438 *
3439 * Example:
3440 *
3441 * manager = nil # For local var to be visible inside worker block
3442 *
3443 * # This fiber would be started with transfer
3444 * # It can't yield, and can't be resumed
3445 * worker = Fiber.new { |work|
3446 * puts "Worker: starts"
3447 * puts "Worker: Performed #{work.inspect}, transferring back"
3448 * # Fiber.yield # this would raise FiberError: attempt to yield on a not resumed fiber
3449 * # manager.resume # this would raise FiberError: attempt to resume a resumed fiber (double resume)
3450 * manager.transfer(work.capitalize)
3451 * }
3452 *
3453 * # This fiber would be started with resume
3454 * # It can yield or transfer, and can be transferred
3455 * # back or resumed
3456 * manager = Fiber.new {
3457 * puts "Manager: starts"
3458 * puts "Manager: transferring 'something' to worker"
3459 * result = worker.transfer('something')
3460 * puts "Manager: worker returned #{result.inspect}"
3461 * # worker.resume # this would raise FiberError: attempt to resume a transferring fiber
3462 * Fiber.yield # this is OK, the fiber transferred from and to, now it can yield
3463 * puts "Manager: finished"
3464 * }
3465 *
3466 * puts "Starting the manager"
3467 * manager.resume
3468 * puts "Resuming the manager"
3469 * # manager.transfer # this would raise FiberError: attempt to transfer to a yielding fiber
3470 * manager.resume
3471 *
3472 * <em>produces</em>
3473 *
3474 * Starting the manager
3475 * Manager: starts
3476 * Manager: transferring 'something' to worker
3477 * Worker: starts
3478 * Worker: Performed "something", transferring back
3479 * Manager: worker returned "Something"
3480 * Resuming the manager
3481 * Manager: finished
3482 *
3483 */
3484static VALUE
3485rb_fiber_m_transfer(int argc, VALUE *argv, VALUE self)
3486{
3487 return rb_fiber_transfer_kw(self, argc, argv, rb_keyword_given_p());
3488}
3489
3490static VALUE
3491fiber_transfer_kw(rb_fiber_t *fiber, int argc, const VALUE *argv, int kw_splat)
3492{
3493 if (fiber->resuming_fiber) {
3494 rb_raise(rb_eFiberError, "attempt to transfer to a resuming fiber");
3495 }
3496
3497 if (fiber->yielding) {
3498 rb_raise(rb_eFiberError, "attempt to transfer to a yielding fiber");
3499 }
3500
3501 return fiber_switch(fiber, argc, argv, kw_splat, NULL, false);
3502}
3503
3504VALUE
3505rb_fiber_transfer_kw(VALUE self, int argc, const VALUE *argv, int kw_splat)
3506{
3507 return fiber_transfer_kw(fiber_ptr(self), argc, argv, kw_splat);
3508}
3509
3510/*
3511 * call-seq:
3512 * Fiber.yield(args, ...) -> obj
3513 *
3514 * Yields control back to the context that resumed the fiber, passing
3515 * along any arguments that were passed to it. The fiber will resume
3516 * processing at this point when #resume is called next.
3517 * Any arguments passed to the next #resume will be the value that
3518 * this Fiber.yield expression evaluates to.
3519 */
3520static VALUE
3521rb_fiber_s_yield(int argc, VALUE *argv, VALUE klass)
3522{
3523 return rb_fiber_yield_kw(argc, argv, rb_keyword_given_p());
3524}
3525
3526static VALUE
3527fiber_raise(rb_fiber_t *fiber, VALUE exception)
3528{
3529 if (fiber == fiber_current()) {
3530 rb_exc_raise(exception);
3531 }
3532 else if (fiber->resuming_fiber) {
3533 return fiber_raise(fiber->resuming_fiber, exception);
3534 }
3535 else if (FIBER_SUSPENDED_P(fiber) && !fiber->yielding) {
3536 return fiber_transfer_kw(fiber, -1, &exception, RB_NO_KEYWORDS);
3537 }
3538 else {
3539 return fiber_resume_kw(fiber, -1, &exception, RB_NO_KEYWORDS);
3540 }
3541}
3542
3543VALUE
3544rb_fiber_raise(VALUE fiber, int argc, VALUE *argv)
3545{
3546 VALUE exception = rb_exception_setup(argc, argv);
3547
3548 return fiber_raise(fiber_ptr(fiber), exception);
3549}
3550
3551/*
3552 * call-seq:
3553 * raise(exception, message = exception.to_s, backtrace = nil, cause: $!)
3554 * raise(message = nil, cause: $!)
3555 *
3556 * Raises an exception in the fiber at the point at which the last
3557 * +Fiber.yield+ was called.
3558 *
3559 * f = Fiber.new {
3560 * puts "Before the yield"
3561 * Fiber.yield 1 # -- exception will be raised here
3562 * puts "After the yield"
3563 * }
3564 *
3565 * p f.resume
3566 * f.raise "Gotcha"
3567 *
3568 * Output
3569 *
3570 * Before the first yield
3571 * 1
3572 * t.rb:8:in 'Fiber.yield': Gotcha (RuntimeError)
3573 * from t.rb:8:in 'block in <main>'
3574 *
3575 * If the fiber has not been started or has
3576 * already run to completion, raises +FiberError+. If the fiber is
3577 * yielding, it is resumed. If it is transferring, it is transferred into.
3578 * But if it is resuming, raises +FiberError+.
3579 *
3580 * Raises +FiberError+ if called on a Fiber belonging to another +Thread+.
3581 *
3582 * See Kernel#raise for more information on arguments.
3583 *
3584 */
3585static VALUE
3586rb_fiber_m_raise(int argc, VALUE *argv, VALUE self)
3587{
3588 return rb_fiber_raise(self, argc, argv);
3589}
3590
3591/*
3592 * call-seq:
3593 * fiber.kill -> nil
3594 *
3595 * Terminates the fiber by raising an uncatchable exception.
3596 * It only terminates the given fiber and no other fiber, returning +nil+ to
3597 * another fiber if that fiber was calling #resume or #transfer.
3598 *
3599 * <tt>Fiber#kill</tt> only interrupts another fiber when it is in Fiber.yield.
3600 * If called on the current fiber then it raises that exception at the <tt>Fiber#kill</tt> call site.
3601 *
3602 * If the fiber has not been started, transition directly to the terminated state.
3603 *
3604 * If the fiber is already terminated, does nothing.
3605 *
3606 * Raises FiberError if called on a fiber belonging to another thread.
3607 */
3608static VALUE
3609rb_fiber_m_kill(VALUE self)
3610{
3611 rb_fiber_t *fiber = fiber_ptr(self);
3612
3613 if (fiber->killed) return Qfalse;
3614 fiber->killed = 1;
3615
3616 if (fiber->status == FIBER_CREATED) {
3617 fiber->status = FIBER_TERMINATED;
3618 }
3619 else if (fiber->status != FIBER_TERMINATED) {
3620 if (fiber_current() == fiber) {
3621 fiber_check_killed(fiber);
3622 }
3623 else {
3624 fiber_raise(fiber_ptr(self), Qnil);
3625 }
3626 }
3627
3628 return self;
3629}
3630
3631/*
3632 * call-seq:
3633 * Fiber.current -> fiber
3634 *
3635 * Returns the current fiber. If you are not running in the context of
3636 * a fiber this method will return the root fiber.
3637 */
3638static VALUE
3639rb_fiber_s_current(VALUE klass)
3640{
3641 return rb_fiber_current();
3642}
3643
3644static VALUE
3645fiber_to_s(VALUE fiber_value)
3646{
3647 const rb_fiber_t *fiber = fiber_ptr(fiber_value);
3648 const rb_proc_t *proc;
3649 char status_info[0x20];
3650
3651 if (fiber->resuming_fiber) {
3652 snprintf(status_info, 0x20, " (%s by resuming)", fiber_status_name(fiber->status));
3653 }
3654 else {
3655 snprintf(status_info, 0x20, " (%s)", fiber_status_name(fiber->status));
3656 }
3657
3658 if (!rb_obj_is_proc(fiber->first_proc)) {
3659 VALUE str = rb_any_to_s(fiber_value);
3660 strlcat(status_info, ">", sizeof(status_info));
3661 rb_str_set_len(str, RSTRING_LEN(str)-1);
3662 rb_str_cat_cstr(str, status_info);
3663 return str;
3664 }
3665 GetProcPtr(fiber->first_proc, proc);
3666 return rb_block_to_s(fiber_value, &proc->block, status_info);
3667}
3668
3669#ifdef HAVE_WORKING_FORK
3670void
3671rb_fiber_atfork(rb_thread_t *th)
3672{
3673 if (th->root_fiber) {
3674 if (&th->root_fiber->cont.saved_ec != th->ec) {
3675 th->root_fiber = th->ec->fiber_ptr;
3676 }
3677 th->root_fiber->prev = 0;
3678 th->root_fiber->blocking = 1;
3679 th->blocking = 1;
3680 }
3681}
3682#endif
3683
3684#ifdef RB_EXPERIMENTAL_FIBER_POOL
3685static void
3686fiber_pool_free(void *ptr)
3687{
3688 struct fiber_pool * fiber_pool = ptr;
3689 RUBY_FREE_ENTER("fiber_pool");
3690
3691 fiber_pool_list_remove(fiber_pool);
3692 fiber_pool_allocation_free(fiber_pool->allocations);
3694 SIZED_FREE(fiber_pool);
3695
3696 RUBY_FREE_LEAVE("fiber_pool");
3697}
3698
3699static size_t
3700fiber_pool_memsize(const void *ptr)
3701{
3702 const struct fiber_pool * fiber_pool = ptr;
3703 size_t size = sizeof(*fiber_pool);
3704
3705 size += fiber_pool->count * fiber_pool->size;
3706
3707 return size;
3708}
3709
3710static const rb_data_type_t FiberPoolDataType = {
3711 "fiber_pool",
3712 {NULL, fiber_pool_free, fiber_pool_memsize,},
3713 0, 0, RUBY_TYPED_THREAD_SAFE_FREE
3714};
3715
3716static VALUE
3717fiber_pool_alloc(VALUE klass)
3718{
3719 struct fiber_pool *fiber_pool;
3720
3721 return TypedData_Make_Struct(klass, struct fiber_pool, &FiberPoolDataType, fiber_pool);
3722}
3723
3724static VALUE
3725rb_fiber_pool_initialize(int argc, VALUE* argv, VALUE self)
3726{
3727 rb_thread_t *th = GET_THREAD();
3728 VALUE size = Qnil, count = Qnil, vm_stack_size = Qnil;
3729 struct fiber_pool * fiber_pool = NULL;
3730
3731 // Maybe these should be keyword arguments.
3732 rb_scan_args(argc, argv, "03", &size, &count, &vm_stack_size);
3733
3734 if (NIL_P(size)) {
3735 size = SIZET2NUM(th->vm->default_params.fiber_machine_stack_size);
3736 }
3737
3738 if (NIL_P(count)) {
3739 count = INT2NUM(128);
3740 }
3741
3742 if (NIL_P(vm_stack_size)) {
3743 vm_stack_size = SIZET2NUM(th->vm->default_params.fiber_vm_stack_size);
3744 }
3745
3746 TypedData_Get_Struct(self, struct fiber_pool, &FiberPoolDataType, fiber_pool);
3747
3748 fiber_pool_initialize(fiber_pool, NUM2SIZET(size), NUM2SIZET(count), 0, NUM2SIZET(vm_stack_size));
3749
3750 return self;
3751}
3752#endif
3753
3754/*
3755 * Document-class: FiberError
3756 *
3757 * Raised when an invalid operation is attempted on a Fiber, in
3758 * particular when attempting to call/resume a dead fiber,
3759 * attempting to yield from the root fiber, or calling a fiber across
3760 * threads.
3761 *
3762 * fiber = Fiber.new{}
3763 * fiber.resume #=> nil
3764 * fiber.resume #=> FiberError: dead fiber called
3765 */
3766
3767static size_t
3768shared_fiber_pool_minimum_count(void)
3769{
3770 size_t minimum_count = FIBER_POOL_MINIMUM_COUNT;
3771
3772 const char *minimum_count_env = getenv("RUBY_SHARED_FIBER_POOL_MINIMUM_COUNT");
3773 if (minimum_count_env && minimum_count_env[0]) {
3774 char *end;
3775 unsigned long value = strtoul(minimum_count_env, &end, 10);
3776 if (end != minimum_count_env && *end == '\0') {
3777 minimum_count = (size_t)value;
3778 }
3779 else {
3780 rb_warn("invalid RUBY_SHARED_FIBER_POOL_MINIMUM_COUNT=%s (expected a non-negative integer)", minimum_count_env);
3781 }
3782 }
3783
3784 return minimum_count;
3785}
3786
3787static size_t
3788shared_fiber_pool_maximum_count(void)
3789{
3790 size_t maximum_count = 0;
3791
3792 const char *maximum_count_env = getenv("RUBY_SHARED_FIBER_POOL_MAXIMUM_COUNT");
3793 if (maximum_count_env && maximum_count_env[0]) {
3794 char *end;
3795 unsigned long value = strtoul(maximum_count_env, &end, 10);
3796 if (end != maximum_count_env && *end == '\0') {
3797 maximum_count = (size_t)value;
3798 }
3799 else {
3800 rb_warn("invalid RUBY_SHARED_FIBER_POOL_MAXIMUM_COUNT=%s (expected a non-negative integer)", maximum_count_env);
3801 }
3802 }
3803
3804 return maximum_count;
3805}
3806
3807void
3808Init_Cont(void)
3809{
3810 rb_thread_t *th = GET_THREAD();
3811 size_t vm_stack_size = th->vm->default_params.fiber_vm_stack_size;
3812 size_t machine_stack_size = th->vm->default_params.fiber_machine_stack_size;
3813 size_t stack_size = machine_stack_size + vm_stack_size;
3814
3815#ifdef _WIN32
3816 SYSTEM_INFO info;
3817 GetSystemInfo(&info);
3818 pagesize = info.dwPageSize;
3819#else /* not WIN32 */
3820 pagesize = sysconf(_SC_PAGESIZE);
3821#endif
3822 SET_MACHINE_STACK_END(&th->ec->machine.stack_end);
3823
3824 rb_eFiberError = rb_define_class("FiberError", rb_eStandardError);
3825
3826 rb_native_mutex_initialize(&fiber_pool_list_lock);
3827
3828 size_t minimum_count = shared_fiber_pool_minimum_count();
3829 size_t maximum_count = shared_fiber_pool_maximum_count();
3830 fiber_pool_initialize(&shared_fiber_pool, stack_size, minimum_count, maximum_count, vm_stack_size);
3831
3832 fiber_initialize_keywords[0] = rb_intern_const("blocking");
3833 fiber_initialize_keywords[1] = rb_intern_const("pool");
3834 fiber_initialize_keywords[2] = rb_intern_const("storage");
3835
3836 const char *fiber_shared_fiber_pool_free_stacks = getenv("RUBY_SHARED_FIBER_POOL_FREE_STACKS");
3837 if (fiber_shared_fiber_pool_free_stacks) {
3838 shared_fiber_pool.free_stacks = atoi(fiber_shared_fiber_pool_free_stacks);
3839
3840 if (shared_fiber_pool.free_stacks < 0) {
3841 rb_warn("Setting RUBY_SHARED_FIBER_POOL_FREE_STACKS to a negative value is not allowed.");
3842 shared_fiber_pool.free_stacks = 0;
3843 }
3844
3845 if (shared_fiber_pool.free_stacks > 1) {
3846 rb_warn("Setting RUBY_SHARED_FIBER_POOL_FREE_STACKS to a value greater than 1 is operating system specific, and may cause crashes.");
3847 }
3848 }
3849
3850 rb_cFiber = rb_define_class("Fiber", rb_cObject);
3851 rb_define_alloc_func(rb_cFiber, fiber_alloc);
3852 rb_define_singleton_method(rb_cFiber, "yield", rb_fiber_s_yield, -1);
3853 rb_define_singleton_method(rb_cFiber, "current", rb_fiber_s_current, 0);
3854 rb_define_singleton_method(rb_cFiber, "blocking", rb_fiber_blocking, 0);
3855 rb_define_singleton_method(rb_cFiber, "[]", rb_fiber_storage_aref, 1);
3856 rb_define_singleton_method(rb_cFiber, "[]=", rb_fiber_storage_aset, 2);
3857
3858 rb_define_method(rb_cFiber, "initialize", rb_fiber_initialize, -1);
3859 rb_define_method(rb_cFiber, "blocking?", rb_fiber_blocking_p, 0);
3860 rb_define_method(rb_cFiber, "storage", rb_fiber_storage_get, 0);
3861 rb_define_method(rb_cFiber, "storage=", rb_fiber_storage_set, 1);
3862 rb_define_method(rb_cFiber, "resume", rb_fiber_m_resume, -1);
3863 rb_define_method(rb_cFiber, "raise", rb_fiber_m_raise, -1);
3864 rb_define_method(rb_cFiber, "kill", rb_fiber_m_kill, 0);
3865 rb_define_method(rb_cFiber, "backtrace", rb_fiber_backtrace, -1);
3866 rb_define_method(rb_cFiber, "backtrace_locations", rb_fiber_backtrace_locations, -1);
3867 rb_define_method(rb_cFiber, "to_s", fiber_to_s, 0);
3868 rb_define_alias(rb_cFiber, "inspect", "to_s");
3869 rb_define_method(rb_cFiber, "transfer", rb_fiber_m_transfer, -1);
3870 rb_define_method(rb_cFiber, "alive?", rb_fiber_alive_p, 0);
3871
3872 rb_define_singleton_method(rb_cFiber, "blocking?", rb_fiber_s_blocking_p, 0);
3873 rb_define_singleton_method(rb_cFiber, "scheduler", rb_fiber_s_scheduler, 0);
3874 rb_define_singleton_method(rb_cFiber, "set_scheduler", rb_fiber_set_scheduler, 1);
3875 rb_define_singleton_method(rb_cFiber, "current_scheduler", rb_fiber_current_scheduler, 0);
3876
3877 rb_define_singleton_method(rb_cFiber, "schedule", rb_fiber_s_schedule, -1);
3878
3879 rb_thread_t *current_thread = rb_current_thread();
3880 RUBY_ASSERT(CLASS_OF(current_thread->ec->fiber_ptr->cont.self) == 0);
3881 *(VALUE *)&((struct RBasic *)current_thread->ec->fiber_ptr->cont.self)->klass = rb_cFiber;
3882
3883#ifdef RB_EXPERIMENTAL_FIBER_POOL
3884 /*
3885 * Document-class: Fiber::Pool
3886 * :nodoc: experimental
3887 */
3888 rb_cFiberPool = rb_define_class_under(rb_cFiber, "Pool", rb_cObject);
3889 rb_define_alloc_func(rb_cFiberPool, fiber_pool_alloc);
3890 rb_define_method(rb_cFiberPool, "initialize", rb_fiber_pool_initialize, -1);
3891#endif
3892
3893 rb_provide("fiber.so");
3894}
3895
3896RUBY_SYMBOL_EXPORT_BEGIN
3897
3898void
3899ruby_Init_Continuation_body(void)
3900{
3901 rb_cContinuation = rb_define_class("Continuation", rb_cObject);
3902 rb_undef_alloc_func(rb_cContinuation);
3903 rb_undef_method(CLASS_OF(rb_cContinuation), "new");
3904 rb_define_method(rb_cContinuation, "call", rb_cont_call, -1);
3905 rb_define_method(rb_cContinuation, "[]", rb_cont_call, -1);
3906#ifdef COROUTINE_SHADOW_STACK
3907 if (coroutine_shadow_stack_enabled()) {
3908 /* Continuations cannot restore previously unwound shadow stack frames. */
3910 return;
3911 }
3912#endif
3913 rb_define_global_function("callcc", rb_callcc, 0);
3914}
3915
3916RUBY_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:3095
void rb_undef_method(VALUE klass, const char *name)
Defines an undef of a method.
Definition class.c:2898
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:3398
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:3385
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:3174
#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:474
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:4053
VALUE rb_eStandardError
StandardError exception.
Definition error.c:1454
VALUE rb_eFrozenError
FrozenError exception.
Definition error.c:1456
VALUE rb_eTypeError
TypeError exception.
Definition error.c:1457
VALUE rb_eRuntimeError
RuntimeError exception.
Definition error.c:1455
void rb_warn(const char *fmt,...)
Identical to rb_warning(), except it reports unless $VERBOSE is nil.
Definition error.c:464
@ 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:664
VALUE rb_obj_dup(VALUE obj)
Duplicates the given object.
Definition object.c:562
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:711
VALUE rb_block_proc(void)
Constructs a Proc object from implicitly passed components.
Definition proc.c:1580
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, rb_len_t len)
Overwrites the length of the string.
Definition string.c:3511
#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:1681
void rb_undef_alloc_func(VALUE klass)
Deletes the allocator function of a class.
Definition vm_method.c:1846
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:912
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:14158
VALUE rb_yield(VALUE val)
Yields the block.
Definition vm_eval.c:1379
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