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