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