Ruby  3.4.0dev (2024-11-05 revision 348a53415339076afc4a02fcd09f3ae36e9c4c61)
vm.c (348a53415339076afc4a02fcd09f3ae36e9c4c61)
1 /**********************************************************************
2 
3  Vm.c -
4 
5  $Author$
6 
7  Copyright (C) 2004-2007 Koichi Sasada
8 
9 **********************************************************************/
10 
11 #define vm_exec rb_vm_exec
12 
13 #include "eval_intern.h"
14 #include "internal.h"
15 #include "internal/class.h"
16 #include "internal/compile.h"
17 #include "internal/cont.h"
18 #include "internal/error.h"
19 #include "internal/encoding.h"
20 #include "internal/eval.h"
21 #include "internal/gc.h"
22 #include "internal/inits.h"
23 #include "internal/missing.h"
24 #include "internal/object.h"
25 #include "internal/proc.h"
26 #include "internal/re.h"
27 #include "internal/ruby_parser.h"
28 #include "internal/symbol.h"
29 #include "internal/thread.h"
30 #include "internal/transcode.h"
31 #include "internal/vm.h"
32 #include "internal/sanitizers.h"
33 #include "internal/variable.h"
34 #include "iseq.h"
35 #include "rjit.h"
36 #include "yjit.h"
37 #include "ruby/st.h"
38 #include "ruby/vm.h"
39 #include "vm_core.h"
40 #include "vm_callinfo.h"
41 #include "vm_debug.h"
42 #include "vm_exec.h"
43 #include "vm_insnhelper.h"
44 #include "ractor_core.h"
45 #include "vm_sync.h"
46 #include "shape.h"
47 
48 #include "builtin.h"
49 
50 #include "probes.h"
51 #include "probes_helper.h"
52 
53 #ifdef RUBY_ASSERT_CRITICAL_SECTION
54 int ruby_assert_critical_section_entered = 0;
55 #endif
56 
57 static void *native_main_thread_stack_top;
58 
59 VALUE rb_str_concat_literals(size_t, const VALUE*);
60 
61 VALUE vm_exec(rb_execution_context_t *);
62 
63 extern const char *const rb_debug_counter_names[];
64 
65 PUREFUNC(static inline const VALUE *VM_EP_LEP(const VALUE *));
66 static inline const VALUE *
67 VM_EP_LEP(const VALUE *ep)
68 {
69  while (!VM_ENV_LOCAL_P(ep)) {
70  ep = VM_ENV_PREV_EP(ep);
71  }
72  return ep;
73 }
74 
75 static inline const rb_control_frame_t *
76 rb_vm_search_cf_from_ep(const rb_execution_context_t *ec, const rb_control_frame_t *cfp, const VALUE * const ep)
77 {
78  if (!ep) {
79  return NULL;
80  }
81  else {
82  const rb_control_frame_t * const eocfp = RUBY_VM_END_CONTROL_FRAME(ec); /* end of control frame pointer */
83 
84  while (cfp < eocfp) {
85  if (cfp->ep == ep) {
86  return cfp;
87  }
88  cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp);
89  }
90 
91  return NULL;
92  }
93 }
94 
95 const VALUE *
96 rb_vm_ep_local_ep(const VALUE *ep)
97 {
98  return VM_EP_LEP(ep);
99 }
100 
101 PUREFUNC(static inline const VALUE *VM_CF_LEP(const rb_control_frame_t * const cfp));
102 static inline const VALUE *
103 VM_CF_LEP(const rb_control_frame_t * const cfp)
104 {
105  return VM_EP_LEP(cfp->ep);
106 }
107 
108 static inline const VALUE *
109 VM_CF_PREV_EP(const rb_control_frame_t * const cfp)
110 {
111  return VM_ENV_PREV_EP(cfp->ep);
112 }
113 
114 PUREFUNC(static inline VALUE VM_CF_BLOCK_HANDLER(const rb_control_frame_t * const cfp));
115 static inline VALUE
116 VM_CF_BLOCK_HANDLER(const rb_control_frame_t * const cfp)
117 {
118  const VALUE *ep = VM_CF_LEP(cfp);
119  return VM_ENV_BLOCK_HANDLER(ep);
120 }
121 
122 int
123 rb_vm_cframe_keyword_p(const rb_control_frame_t *cfp)
124 {
125  return VM_FRAME_CFRAME_KW_P(cfp);
126 }
127 
128 VALUE
129 rb_vm_frame_block_handler(const rb_control_frame_t *cfp)
130 {
131  return VM_CF_BLOCK_HANDLER(cfp);
132 }
133 
134 #if VM_CHECK_MODE > 0
135 static int
136 VM_CFP_IN_HEAP_P(const rb_execution_context_t *ec, const rb_control_frame_t *cfp)
137 {
138  const VALUE *start = ec->vm_stack;
139  const VALUE *end = (VALUE *)ec->vm_stack + ec->vm_stack_size;
140  VM_ASSERT(start != NULL);
141 
142  if (start <= (VALUE *)cfp && (VALUE *)cfp < end) {
143  return FALSE;
144  }
145  else {
146  return TRUE;
147  }
148 }
149 
150 static int
151 VM_EP_IN_HEAP_P(const rb_execution_context_t *ec, const VALUE *ep)
152 {
153  const VALUE *start = ec->vm_stack;
154  const VALUE *end = (VALUE *)ec->cfp;
155  VM_ASSERT(start != NULL);
156 
157  if (start <= ep && ep < end) {
158  return FALSE;
159  }
160  else {
161  return TRUE;
162  }
163 }
164 
165 static int
166 vm_ep_in_heap_p_(const rb_execution_context_t *ec, const VALUE *ep)
167 {
168  if (VM_EP_IN_HEAP_P(ec, ep)) {
169  VALUE envval = ep[VM_ENV_DATA_INDEX_ENV]; /* VM_ENV_ENVVAL(ep); */
170 
171  if (!UNDEF_P(envval)) {
172  const rb_env_t *env = (const rb_env_t *)envval;
173 
174  VM_ASSERT(imemo_type_p(envval, imemo_env));
175  VM_ASSERT(VM_ENV_FLAGS(ep, VM_ENV_FLAG_ESCAPED));
176  VM_ASSERT(env->ep == ep);
177  }
178  return TRUE;
179  }
180  else {
181  return FALSE;
182  }
183 }
184 
185 int
186 rb_vm_ep_in_heap_p(const VALUE *ep)
187 {
188  const rb_execution_context_t *ec = GET_EC();
189  if (ec->vm_stack == NULL) return TRUE;
190  return vm_ep_in_heap_p_(ec, ep);
191 }
192 #endif
193 
194 static struct rb_captured_block *
195 VM_CFP_TO_CAPTURED_BLOCK(const rb_control_frame_t *cfp)
196 {
197  VM_ASSERT(!VM_CFP_IN_HEAP_P(GET_EC(), cfp));
198  return (struct rb_captured_block *)&cfp->self;
199 }
200 
201 static rb_control_frame_t *
202 VM_CAPTURED_BLOCK_TO_CFP(const struct rb_captured_block *captured)
203 {
204  rb_control_frame_t *cfp = ((rb_control_frame_t *)((VALUE *)(captured) - 3));
205  VM_ASSERT(!VM_CFP_IN_HEAP_P(GET_EC(), cfp));
206  VM_ASSERT(sizeof(rb_control_frame_t)/sizeof(VALUE) == 7 + VM_DEBUG_BP_CHECK ? 1 : 0);
207  return cfp;
208 }
209 
210 static int
211 VM_BH_FROM_CFP_P(VALUE block_handler, const rb_control_frame_t *cfp)
212 {
213  const struct rb_captured_block *captured = VM_CFP_TO_CAPTURED_BLOCK(cfp);
214  return VM_TAGGED_PTR_REF(block_handler, 0x03) == captured;
215 }
216 
217 static VALUE
218 vm_passed_block_handler(rb_execution_context_t *ec)
219 {
220  VALUE block_handler = ec->passed_block_handler;
221  ec->passed_block_handler = VM_BLOCK_HANDLER_NONE;
222  vm_block_handler_verify(block_handler);
223  return block_handler;
224 }
225 
226 static rb_cref_t *
227 vm_cref_new0(VALUE klass, rb_method_visibility_t visi, int module_func, rb_cref_t *prev_cref, int pushed_by_eval, int use_prev_prev, int singleton)
228 {
229  VALUE refinements = Qnil;
230  int omod_shared = FALSE;
231 
232  /* scope */
233  union {
235  VALUE value;
236  } scope_visi;
237 
238  scope_visi.visi.method_visi = visi;
239  scope_visi.visi.module_func = module_func;
240 
241  /* refinements */
242  if (prev_cref != NULL && prev_cref != (void *)1 /* TODO: why CREF_NEXT(cref) is 1? */) {
243  refinements = CREF_REFINEMENTS(prev_cref);
244 
245  if (!NIL_P(refinements)) {
246  omod_shared = TRUE;
247  CREF_OMOD_SHARED_SET(prev_cref);
248  }
249  }
250 
251  VM_ASSERT(singleton || klass);
252 
253  rb_cref_t *cref = IMEMO_NEW(rb_cref_t, imemo_cref, refinements);
254  cref->klass_or_self = klass;
255  cref->next = use_prev_prev ? CREF_NEXT(prev_cref) : prev_cref;
256  *((rb_scope_visibility_t *)&cref->scope_visi) = scope_visi.visi;
257 
258  if (pushed_by_eval) CREF_PUSHED_BY_EVAL_SET(cref);
259  if (omod_shared) CREF_OMOD_SHARED_SET(cref);
260  if (singleton) CREF_SINGLETON_SET(cref);
261 
262  return cref;
263 }
264 
265 static rb_cref_t *
266 vm_cref_new(VALUE klass, rb_method_visibility_t visi, int module_func, rb_cref_t *prev_cref, int pushed_by_eval, int singleton)
267 {
268  return vm_cref_new0(klass, visi, module_func, prev_cref, pushed_by_eval, FALSE, singleton);
269 }
270 
271 static rb_cref_t *
272 vm_cref_new_use_prev(VALUE klass, rb_method_visibility_t visi, int module_func, rb_cref_t *prev_cref, int pushed_by_eval)
273 {
274  return vm_cref_new0(klass, visi, module_func, prev_cref, pushed_by_eval, TRUE, FALSE);
275 }
276 
277 static int
278 ref_delete_symkey(VALUE key, VALUE value, VALUE unused)
279 {
280  return SYMBOL_P(key) ? ST_DELETE : ST_CONTINUE;
281 }
282 
283 static rb_cref_t *
284 vm_cref_dup(const rb_cref_t *cref)
285 {
286  const rb_scope_visibility_t *visi = CREF_SCOPE_VISI(cref);
287  rb_cref_t *next_cref = CREF_NEXT(cref), *new_cref;
288  int pushed_by_eval = CREF_PUSHED_BY_EVAL(cref);
289  int singleton = CREF_SINGLETON(cref);
290 
291  new_cref = vm_cref_new(cref->klass_or_self, visi->method_visi, visi->module_func, next_cref, pushed_by_eval, singleton);
292 
293  if (!NIL_P(CREF_REFINEMENTS(cref))) {
294  VALUE ref = rb_hash_dup(CREF_REFINEMENTS(cref));
295  rb_hash_foreach(ref, ref_delete_symkey, Qnil);
296  CREF_REFINEMENTS_SET(new_cref, ref);
297  CREF_OMOD_SHARED_UNSET(new_cref);
298  }
299 
300  return new_cref;
301 }
302 
303 
304 rb_cref_t *
305 rb_vm_cref_dup_without_refinements(const rb_cref_t *cref)
306 {
307  const rb_scope_visibility_t *visi = CREF_SCOPE_VISI(cref);
308  rb_cref_t *next_cref = CREF_NEXT(cref), *new_cref;
309  int pushed_by_eval = CREF_PUSHED_BY_EVAL(cref);
310  int singleton = CREF_SINGLETON(cref);
311 
312  new_cref = vm_cref_new(cref->klass_or_self, visi->method_visi, visi->module_func, next_cref, pushed_by_eval, singleton);
313 
314  if (!NIL_P(CREF_REFINEMENTS(cref))) {
315  CREF_REFINEMENTS_SET(new_cref, Qnil);
316  CREF_OMOD_SHARED_UNSET(new_cref);
317  }
318 
319  return new_cref;
320 }
321 
322 static rb_cref_t *
323 vm_cref_new_toplevel(rb_execution_context_t *ec)
324 {
325  rb_cref_t *cref = vm_cref_new(rb_cObject, METHOD_VISI_PRIVATE /* toplevel visibility is private */, FALSE, NULL, FALSE, FALSE);
326  VALUE top_wrapper = rb_ec_thread_ptr(ec)->top_wrapper;
327 
328  if (top_wrapper) {
329  cref = vm_cref_new(top_wrapper, METHOD_VISI_PRIVATE, FALSE, cref, FALSE, FALSE);
330  }
331 
332  return cref;
333 }
334 
335 rb_cref_t *
336 rb_vm_cref_new_toplevel(void)
337 {
338  return vm_cref_new_toplevel(GET_EC());
339 }
340 
341 static void
342 vm_cref_dump(const char *mesg, const rb_cref_t *cref)
343 {
344  ruby_debug_printf("vm_cref_dump: %s (%p)\n", mesg, (void *)cref);
345 
346  while (cref) {
347  ruby_debug_printf("= cref| klass: %s\n", RSTRING_PTR(rb_class_path(CREF_CLASS(cref))));
348  cref = CREF_NEXT(cref);
349  }
350 }
351 
352 void
353 rb_vm_block_ep_update(VALUE obj, const struct rb_block *dst, const VALUE *ep)
354 {
355  *((const VALUE **)&dst->as.captured.ep) = ep;
356  RB_OBJ_WRITTEN(obj, Qundef, VM_ENV_ENVVAL(ep));
357 }
358 
359 static void
360 vm_bind_update_env(VALUE bindval, rb_binding_t *bind, VALUE envval)
361 {
362  const rb_env_t *env = (rb_env_t *)envval;
363  RB_OBJ_WRITE(bindval, &bind->block.as.captured.code.iseq, env->iseq);
364  rb_vm_block_ep_update(bindval, &bind->block, env->ep);
365 }
366 
367 #if VM_COLLECT_USAGE_DETAILS
368 static void vm_collect_usage_operand(int insn, int n, VALUE op);
369 static void vm_collect_usage_insn(int insn);
370 static void vm_collect_usage_register(int reg, int isset);
371 #endif
372 
373 static VALUE vm_make_env_object(const rb_execution_context_t *ec, rb_control_frame_t *cfp);
374 static VALUE vm_invoke_bmethod(rb_execution_context_t *ec, rb_proc_t *proc, VALUE self,
375  int argc, const VALUE *argv, int kw_splat, VALUE block_handler,
376  const rb_callable_method_entry_t *me);
377 static VALUE vm_invoke_proc(rb_execution_context_t *ec, rb_proc_t *proc, VALUE self, int argc, const VALUE *argv, int kw_splat, VALUE block_handler);
378 
379 #if USE_YJIT
380 // Counter to serve as a proxy for execution time, total number of calls
381 static uint64_t yjit_total_entry_hits = 0;
382 
383 // Number of calls used to estimate how hot an ISEQ is
384 #define YJIT_CALL_COUNT_INTERV 20u
385 
387 static inline bool
388 rb_yjit_threshold_hit(const rb_iseq_t *iseq, uint64_t entry_calls)
389 {
390  yjit_total_entry_hits += 1;
391 
392  // Record the number of calls at the beginning of the interval
393  if (entry_calls + YJIT_CALL_COUNT_INTERV == rb_yjit_call_threshold) {
394  iseq->body->yjit_calls_at_interv = yjit_total_entry_hits;
395  }
396 
397  // Try to estimate the total time taken (total number of calls) to reach 20 calls to this ISEQ
398  // This give us a ratio of how hot/cold this ISEQ is
399  if (entry_calls == rb_yjit_call_threshold) {
400  // We expect threshold 1 to compile everything immediately
401  if (rb_yjit_call_threshold < YJIT_CALL_COUNT_INTERV) {
402  return true;
403  }
404 
405  uint64_t num_calls = yjit_total_entry_hits - iseq->body->yjit_calls_at_interv;
406 
407  // Reject ISEQs that don't get called often enough
408  if (num_calls > rb_yjit_cold_threshold) {
409  rb_yjit_incr_counter("cold_iseq_entry");
410  return false;
411  }
412 
413  return true;
414  }
415 
416  return false;
417 }
418 #else
419 #define rb_yjit_threshold_hit(iseq, entry_calls) false
420 #endif
421 
422 #if USE_RJIT || USE_YJIT
423 // Generate JIT code that supports the following kinds of ISEQ entries:
424 // * The first ISEQ on vm_exec (e.g. <main>, or Ruby methods/blocks
425 // called by a C method). The current frame has VM_FRAME_FLAG_FINISH.
426 // The current vm_exec stops if JIT code returns a non-Qundef value.
427 // * ISEQs called by the interpreter on vm_sendish (e.g. Ruby methods or
428 // blocks called by a Ruby frame that isn't compiled or side-exited).
429 // The current frame doesn't have VM_FRAME_FLAG_FINISH. The current
430 // vm_exec does NOT stop whether JIT code returns Qundef or not.
431 static inline rb_jit_func_t
432 jit_compile(rb_execution_context_t *ec)
433 {
434  const rb_iseq_t *iseq = ec->cfp->iseq;
435  struct rb_iseq_constant_body *body = ISEQ_BODY(iseq);
436  bool yjit_enabled = rb_yjit_enabled_p;
437  if (!(yjit_enabled || rb_rjit_call_p)) {
438  return NULL;
439  }
440 
441  // Increment the ISEQ's call counter and trigger JIT compilation if not compiled
442  if (body->jit_entry == NULL) {
443  body->jit_entry_calls++;
444  if (yjit_enabled) {
445  if (rb_yjit_threshold_hit(iseq, body->jit_entry_calls)) {
446  rb_yjit_compile_iseq(iseq, ec, false);
447  }
448  }
449  else if (body->jit_entry_calls == rb_rjit_call_threshold()) {
450  rb_rjit_compile(iseq);
451  }
452  }
453  return body->jit_entry;
454 }
455 
456 // Execute JIT code compiled by jit_compile()
457 static inline VALUE
458 jit_exec(rb_execution_context_t *ec)
459 {
460  rb_jit_func_t func = jit_compile(ec);
461  if (func) {
462  // Call the JIT code
463  return func(ec, ec->cfp);
464  }
465  else {
466  return Qundef;
467  }
468 }
469 #else
470 # define jit_compile(ec) ((rb_jit_func_t)0)
471 # define jit_exec(ec) Qundef
472 #endif
473 
474 #if USE_YJIT
475 // Generate JIT code that supports the following kind of ISEQ entry:
476 // * The first ISEQ pushed by vm_exec_handle_exception. The frame would
477 // point to a location specified by a catch table, and it doesn't have
478 // VM_FRAME_FLAG_FINISH. The current vm_exec stops if JIT code returns
479 // a non-Qundef value. So you should not return a non-Qundef value
480 // until ec->cfp is changed to a frame with VM_FRAME_FLAG_FINISH.
481 static inline rb_jit_func_t
482 jit_compile_exception(rb_execution_context_t *ec)
483 {
484  const rb_iseq_t *iseq = ec->cfp->iseq;
485  struct rb_iseq_constant_body *body = ISEQ_BODY(iseq);
486  if (!rb_yjit_enabled_p) {
487  return NULL;
488  }
489 
490  // Increment the ISEQ's call counter and trigger JIT compilation if not compiled
491  if (body->jit_exception == NULL) {
492  body->jit_exception_calls++;
493  if (body->jit_exception_calls == rb_yjit_call_threshold) {
494  rb_yjit_compile_iseq(iseq, ec, true);
495  }
496  }
497 
498  return body->jit_exception;
499 }
500 
501 // Execute JIT code compiled by jit_compile_exception()
502 static inline VALUE
503 jit_exec_exception(rb_execution_context_t *ec)
504 {
505  rb_jit_func_t func = jit_compile_exception(ec);
506  if (func) {
507  // Call the JIT code
508  return func(ec, ec->cfp);
509  }
510  else {
511  return Qundef;
512  }
513 }
514 #else
515 # define jit_compile_exception(ec) ((rb_jit_func_t)0)
516 # define jit_exec_exception(ec) Qundef
517 #endif
518 
519 static void add_opt_method_entry(const rb_method_entry_t *me);
520 
521 #define RB_TYPE_2_P(obj, type1, type2) \
522  (RB_TYPE_P(obj, type1) || RB_TYPE_P(obj, type2))
523 #define RB_TYPE_3_P(obj, type1, type2, type3) \
524  (RB_TYPE_P(obj, type1) || RB_TYPE_P(obj, type2) || RB_TYPE_P(obj, type3))
525 
526 #define VM_ASSERT_TYPE(obj, type) \
527  VM_ASSERT(RB_TYPE_P(obj, type), #obj ": %s", rb_obj_info(obj))
528 #define VM_ASSERT_TYPE2(obj, type1, type2) \
529  VM_ASSERT(RB_TYPE_2_P(obj, type1, type2), #obj ": %s", rb_obj_info(obj))
530 #define VM_ASSERT_TYPE3(obj, type1, type2, type3) \
531  VM_ASSERT(RB_TYPE_3_P(obj, type1, type2, type3), #obj ": %s", rb_obj_info(obj))
532 
533 #include "vm_insnhelper.c"
534 
535 #include "vm_exec.c"
536 
537 #include "vm_method.c"
538 #include "vm_eval.c"
539 
540 #define PROCDEBUG 0
541 
542 VALUE rb_cRubyVM;
544 VALUE rb_mRubyVMFrozenCore;
545 VALUE rb_block_param_proxy;
546 
547 VALUE ruby_vm_const_missing_count = 0;
548 rb_vm_t *ruby_current_vm_ptr = NULL;
549 rb_ractor_t *ruby_single_main_ractor;
550 bool ruby_vm_keep_script_lines;
551 
552 #ifdef RB_THREAD_LOCAL_SPECIFIER
553 RB_THREAD_LOCAL_SPECIFIER rb_execution_context_t *ruby_current_ec;
554 
555 #ifdef RUBY_NT_SERIAL
556 RB_THREAD_LOCAL_SPECIFIER rb_atomic_t ruby_nt_serial;
557 #endif
558 
559 // no-inline decl on thread_pthread.h
561 rb_current_ec_noinline(void)
562 {
563  return ruby_current_ec;
564 }
565 
566 void
567 rb_current_ec_set(rb_execution_context_t *ec)
568 {
569  ruby_current_ec = ec;
570 }
571 
572 
573 #ifdef __APPLE__
575 rb_current_ec(void)
576 {
577  return ruby_current_ec;
578 }
579 
580 #endif
581 #else
582 native_tls_key_t ruby_current_ec_key;
583 #endif
584 
585 rb_event_flag_t ruby_vm_event_flags;
586 rb_event_flag_t ruby_vm_event_enabled_global_flags;
587 unsigned int ruby_vm_event_local_num;
588 
589 rb_serial_t ruby_vm_constant_cache_invalidations = 0;
590 rb_serial_t ruby_vm_constant_cache_misses = 0;
591 rb_serial_t ruby_vm_global_cvar_state = 1;
592 
593 static const struct rb_callcache vm_empty_cc = {
594  .flags = T_IMEMO | (imemo_callcache << FL_USHIFT) | VM_CALLCACHE_UNMARKABLE,
595  .klass = Qfalse,
596  .cme_ = NULL,
597  .call_ = vm_call_general,
598  .aux_ = {
599  .v = Qfalse,
600  }
601 };
602 
603 static const struct rb_callcache vm_empty_cc_for_super = {
604  .flags = T_IMEMO | (imemo_callcache << FL_USHIFT) | VM_CALLCACHE_UNMARKABLE,
605  .klass = Qfalse,
606  .cme_ = NULL,
607  .call_ = vm_call_super_method,
608  .aux_ = {
609  .v = Qfalse,
610  }
611 };
612 
613 static void thread_free(void *ptr);
614 
615 void
616 rb_vm_inc_const_missing_count(void)
617 {
618  ruby_vm_const_missing_count +=1;
619 }
620 
621 int
622 rb_dtrace_setup(rb_execution_context_t *ec, VALUE klass, ID id,
623  struct ruby_dtrace_method_hook_args *args)
624 {
625  enum ruby_value_type type;
626  if (!klass) {
627  if (!ec) ec = GET_EC();
628  if (!rb_ec_frame_method_id_and_class(ec, &id, 0, &klass) || !klass)
629  return FALSE;
630  }
631  if (RB_TYPE_P(klass, T_ICLASS)) {
632  klass = RBASIC(klass)->klass;
633  }
634  else if (RCLASS_SINGLETON_P(klass)) {
635  klass = RCLASS_ATTACHED_OBJECT(klass);
636  if (NIL_P(klass)) return FALSE;
637  }
638  type = BUILTIN_TYPE(klass);
639  if (type == T_CLASS || type == T_ICLASS || type == T_MODULE) {
640  VALUE name = rb_class_path(klass);
641  const char *classname, *filename;
642  const char *methodname = rb_id2name(id);
643  if (methodname && (filename = rb_source_location_cstr(&args->line_no)) != 0) {
644  if (NIL_P(name) || !(classname = StringValuePtr(name)))
645  classname = "<unknown>";
646  args->classname = classname;
647  args->methodname = methodname;
648  args->filename = filename;
649  args->klass = klass;
650  args->name = name;
651  return TRUE;
652  }
653  }
654  return FALSE;
655 }
656 
657 extern unsigned int redblack_buffer_size;
658 
659 /*
660  * call-seq:
661  * RubyVM.stat -> Hash
662  * RubyVM.stat(hsh) -> hsh
663  * RubyVM.stat(Symbol) -> Numeric
664  *
665  * Returns a Hash containing implementation-dependent counters inside the VM.
666  *
667  * This hash includes information about method/constant caches:
668  *
669  * {
670  * :constant_cache_invalidations=>2,
671  * :constant_cache_misses=>14,
672  * :global_cvar_state=>27
673  * }
674  *
675  * If <tt>USE_DEBUG_COUNTER</tt> is enabled, debug counters will be included.
676  *
677  * The contents of the hash are implementation specific and may be changed in
678  * the future.
679  *
680  * This method is only expected to work on C Ruby.
681  */
682 static VALUE
683 vm_stat(int argc, VALUE *argv, VALUE self)
684 {
685  static VALUE sym_constant_cache_invalidations, sym_constant_cache_misses, sym_global_cvar_state, sym_next_shape_id;
686  static VALUE sym_shape_cache_size;
687  VALUE arg = Qnil;
688  VALUE hash = Qnil, key = Qnil;
689 
690  if (rb_check_arity(argc, 0, 1) == 1) {
691  arg = argv[0];
692  if (SYMBOL_P(arg))
693  key = arg;
694  else if (RB_TYPE_P(arg, T_HASH))
695  hash = arg;
696  else
697  rb_raise(rb_eTypeError, "non-hash or symbol given");
698  }
699  else {
700  hash = rb_hash_new();
701  }
702 
703 #define S(s) sym_##s = ID2SYM(rb_intern_const(#s))
704  S(constant_cache_invalidations);
705  S(constant_cache_misses);
706  S(global_cvar_state);
707  S(next_shape_id);
708  S(shape_cache_size);
709 #undef S
710 
711 #define SET(name, attr) \
712  if (key == sym_##name) \
713  return SERIALT2NUM(attr); \
714  else if (hash != Qnil) \
715  rb_hash_aset(hash, sym_##name, SERIALT2NUM(attr));
716 
717  SET(constant_cache_invalidations, ruby_vm_constant_cache_invalidations);
718  SET(constant_cache_misses, ruby_vm_constant_cache_misses);
719  SET(global_cvar_state, ruby_vm_global_cvar_state);
720  SET(next_shape_id, (rb_serial_t)GET_SHAPE_TREE()->next_shape_id);
721  SET(shape_cache_size, (rb_serial_t)GET_SHAPE_TREE()->cache_size);
722 #undef SET
723 
724 #if USE_DEBUG_COUNTER
725  ruby_debug_counter_show_at_exit(FALSE);
726  for (size_t i = 0; i < RB_DEBUG_COUNTER_MAX; i++) {
727  const VALUE name = rb_sym_intern_ascii_cstr(rb_debug_counter_names[i]);
728  const VALUE boxed_value = SIZET2NUM(rb_debug_counter[i]);
729 
730  if (key == name) {
731  return boxed_value;
732  }
733  else if (hash != Qnil) {
734  rb_hash_aset(hash, name, boxed_value);
735  }
736  }
737 #endif
738 
739  if (!NIL_P(key)) { /* matched key should return above */
740  rb_raise(rb_eArgError, "unknown key: %"PRIsVALUE, rb_sym2str(key));
741  }
742 
743  return hash;
744 }
745 
746 /* control stack frame */
747 
748 static void
749 vm_set_top_stack(rb_execution_context_t *ec, const rb_iseq_t *iseq)
750 {
751  if (ISEQ_BODY(iseq)->type != ISEQ_TYPE_TOP) {
752  rb_raise(rb_eTypeError, "Not a toplevel InstructionSequence");
753  }
754 
755  /* for return */
756  vm_push_frame(ec, iseq, VM_FRAME_MAGIC_TOP | VM_ENV_FLAG_LOCAL | VM_FRAME_FLAG_FINISH, rb_ec_thread_ptr(ec)->top_self,
757  VM_BLOCK_HANDLER_NONE,
758  (VALUE)vm_cref_new_toplevel(ec), /* cref or me */
759  ISEQ_BODY(iseq)->iseq_encoded, ec->cfp->sp,
760  ISEQ_BODY(iseq)->local_table_size, ISEQ_BODY(iseq)->stack_max);
761 }
762 
763 static void
764 vm_set_eval_stack(rb_execution_context_t *ec, const rb_iseq_t *iseq, const rb_cref_t *cref, const struct rb_block *base_block)
765 {
766  vm_push_frame(ec, iseq, VM_FRAME_MAGIC_EVAL | VM_FRAME_FLAG_FINISH,
767  vm_block_self(base_block), VM_GUARDED_PREV_EP(vm_block_ep(base_block)),
768  (VALUE)cref, /* cref or me */
769  ISEQ_BODY(iseq)->iseq_encoded,
770  ec->cfp->sp, ISEQ_BODY(iseq)->local_table_size,
771  ISEQ_BODY(iseq)->stack_max);
772 }
773 
774 static void
775 vm_set_main_stack(rb_execution_context_t *ec, const rb_iseq_t *iseq)
776 {
777  VALUE toplevel_binding = rb_const_get(rb_cObject, rb_intern("TOPLEVEL_BINDING"));
778  rb_binding_t *bind;
779 
780  GetBindingPtr(toplevel_binding, bind);
781  RUBY_ASSERT_MESG(bind, "TOPLEVEL_BINDING is not built");
782 
783  vm_set_eval_stack(ec, iseq, 0, &bind->block);
784 
785  /* save binding */
786  if (ISEQ_BODY(iseq)->local_table_size > 0) {
787  vm_bind_update_env(toplevel_binding, bind, vm_make_env_object(ec, ec->cfp));
788  }
789 }
790 
792 rb_vm_get_binding_creatable_next_cfp(const rb_execution_context_t *ec, const rb_control_frame_t *cfp)
793 {
794  while (!RUBY_VM_CONTROL_FRAME_STACK_OVERFLOW_P(ec, cfp)) {
795  if (cfp->iseq) {
796  return (rb_control_frame_t *)cfp;
797  }
798  cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp);
799  }
800  return 0;
801 }
802 
804 rb_vm_get_ruby_level_next_cfp(const rb_execution_context_t *ec, const rb_control_frame_t *cfp)
805 {
806  while (!RUBY_VM_CONTROL_FRAME_STACK_OVERFLOW_P(ec, cfp)) {
807  if (VM_FRAME_RUBYFRAME_P(cfp)) {
808  return (rb_control_frame_t *)cfp;
809  }
810  cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp);
811  }
812  return 0;
813 }
814 
815 static rb_control_frame_t *
816 vm_get_ruby_level_caller_cfp(const rb_execution_context_t *ec, const rb_control_frame_t *cfp)
817 {
818  if (VM_FRAME_RUBYFRAME_P(cfp)) {
819  return (rb_control_frame_t *)cfp;
820  }
821 
822  cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp);
823 
824  while (!RUBY_VM_CONTROL_FRAME_STACK_OVERFLOW_P(ec, cfp)) {
825  if (VM_FRAME_RUBYFRAME_P(cfp)) {
826  return (rb_control_frame_t *)cfp;
827  }
828 
829  if (VM_ENV_FLAGS(cfp->ep, VM_FRAME_FLAG_PASSED) == FALSE) {
830  break;
831  }
832  cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp);
833  }
834  return 0;
835 }
836 
837 void
838 rb_vm_pop_cfunc_frame(void)
839 {
840  rb_execution_context_t *ec = GET_EC();
841  rb_control_frame_t *cfp = ec->cfp;
842  const rb_callable_method_entry_t *me = rb_vm_frame_method_entry(cfp);
843 
844  EXEC_EVENT_HOOK(ec, RUBY_EVENT_C_RETURN, cfp->self, me->def->original_id, me->called_id, me->owner, Qnil);
845  RUBY_DTRACE_CMETHOD_RETURN_HOOK(ec, me->owner, me->def->original_id);
846  vm_pop_frame(ec, cfp, cfp->ep);
847 }
848 
849 void
850 rb_vm_rewind_cfp(rb_execution_context_t *ec, rb_control_frame_t *cfp)
851 {
852  /* check skipped frame */
853  while (ec->cfp != cfp) {
854 #if VMDEBUG
855  printf("skipped frame: %s\n", vm_frametype_name(ec->cfp));
856 #endif
857  if (VM_FRAME_TYPE(ec->cfp) != VM_FRAME_MAGIC_CFUNC) {
858  rb_vm_pop_frame(ec);
859  }
860  else { /* unlikely path */
861  rb_vm_pop_cfunc_frame();
862  }
863  }
864 }
865 
866 /* at exit */
867 
868 void
869 ruby_vm_at_exit(void (*func)(rb_vm_t *))
870 {
871  rb_vm_t *vm = GET_VM();
873  nl->func = func;
874  nl->next = vm->at_exit;
875  vm->at_exit = nl;
876 }
877 
878 static void
879 ruby_vm_run_at_exit_hooks(rb_vm_t *vm)
880 {
881  rb_at_exit_list *l = vm->at_exit;
882 
883  while (l) {
884  rb_at_exit_list* t = l->next;
885  rb_vm_at_exit_func *func = l->func;
886  ruby_xfree(l);
887  l = t;
888  (*func)(vm);
889  }
890 }
891 
892 /* Env */
893 
894 static VALUE check_env_value(const rb_env_t *env);
895 
896 static int
897 check_env(const rb_env_t *env)
898 {
899  fputs("---\n", stderr);
900  ruby_debug_printf("envptr: %p\n", (void *)&env->ep[0]);
901  ruby_debug_printf("envval: %10p ", (void *)env->ep[1]);
902  dp(env->ep[1]);
903  ruby_debug_printf("ep: %10p\n", (void *)env->ep);
904  if (rb_vm_env_prev_env(env)) {
905  fputs(">>\n", stderr);
906  check_env_value(rb_vm_env_prev_env(env));
907  fputs("<<\n", stderr);
908  }
909  return 1;
910 }
911 
912 static VALUE
913 check_env_value(const rb_env_t *env)
914 {
915  if (check_env(env)) {
916  return (VALUE)env;
917  }
918  rb_bug("invalid env");
919  return Qnil; /* unreachable */
920 }
921 
922 static VALUE
923 vm_block_handler_escape(const rb_execution_context_t *ec, VALUE block_handler)
924 {
925  switch (vm_block_handler_type(block_handler)) {
926  case block_handler_type_ifunc:
927  case block_handler_type_iseq:
928  return rb_vm_make_proc(ec, VM_BH_TO_CAPT_BLOCK(block_handler), rb_cProc);
929 
930  case block_handler_type_symbol:
931  case block_handler_type_proc:
932  return block_handler;
933  }
934  VM_UNREACHABLE(vm_block_handler_escape);
935  return Qnil;
936 }
937 
938 static VALUE
939 vm_make_env_each(const rb_execution_context_t * const ec, rb_control_frame_t *const cfp)
940 {
941  const VALUE * const ep = cfp->ep;
942  VALUE *env_body, *env_ep;
943  int local_size, env_size;
944 
945  if (VM_ENV_ESCAPED_P(ep)) {
946  return VM_ENV_ENVVAL(ep);
947  }
948 
949  if (!VM_ENV_LOCAL_P(ep)) {
950  const VALUE *prev_ep = VM_ENV_PREV_EP(ep);
951  if (!VM_ENV_ESCAPED_P(prev_ep)) {
952  rb_control_frame_t *prev_cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp);
953 
954  while (prev_cfp->ep != prev_ep) {
955  prev_cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(prev_cfp);
956  VM_ASSERT(prev_cfp->ep != NULL);
957  }
958 
959  vm_make_env_each(ec, prev_cfp);
960  VM_FORCE_WRITE_SPECIAL_CONST(&ep[VM_ENV_DATA_INDEX_SPECVAL], VM_GUARDED_PREV_EP(prev_cfp->ep));
961  }
962  }
963  else {
964  VALUE block_handler = VM_ENV_BLOCK_HANDLER(ep);
965 
966  if (block_handler != VM_BLOCK_HANDLER_NONE) {
967  VALUE blockprocval = vm_block_handler_escape(ec, block_handler);
968  VM_STACK_ENV_WRITE(ep, VM_ENV_DATA_INDEX_SPECVAL, blockprocval);
969  }
970  }
971 
972  if (!VM_FRAME_RUBYFRAME_P(cfp)) {
973  local_size = VM_ENV_DATA_SIZE;
974  }
975  else {
976  local_size = ISEQ_BODY(cfp->iseq)->local_table_size;
977  if (ISEQ_BODY(cfp->iseq)->param.flags.forwardable && VM_ENV_LOCAL_P(cfp->ep)) {
978  int ci_offset = local_size - ISEQ_BODY(cfp->iseq)->param.size + VM_ENV_DATA_SIZE;
979 
980  CALL_INFO ci = (CALL_INFO)VM_CF_LEP(cfp)[-ci_offset];
981  local_size += vm_ci_argc(ci);
982  }
983  local_size += VM_ENV_DATA_SIZE;
984  }
985 
986  /*
987  * # local variables on a stack frame (N == local_size)
988  * [lvar1, lvar2, ..., lvarN, SPECVAL]
989  * ^
990  * ep[0]
991  *
992  * # moved local variables
993  * [lvar1, lvar2, ..., lvarN, SPECVAL, Envval, BlockProcval (if needed)]
994  * ^ ^
995  * env->env[0] ep[0]
996  */
997 
998  env_size = local_size +
999  1 /* envval */;
1000 
1001  // Careful with order in the following sequence. Each allocation can move objects.
1002  env_body = ALLOC_N(VALUE, env_size);
1003  rb_env_t *env = IMEMO_NEW(rb_env_t, imemo_env, 0);
1004 
1005  // Set up env without WB since it's brand new (similar to newobj_init(), newobj_fill())
1006  MEMCPY(env_body, ep - (local_size - 1 /* specval */), VALUE, local_size);
1007 
1008  env_ep = &env_body[local_size - 1 /* specval */];
1009  env_ep[VM_ENV_DATA_INDEX_ENV] = (VALUE)env;
1010 
1011  env->iseq = (rb_iseq_t *)(VM_FRAME_RUBYFRAME_P(cfp) ? cfp->iseq : NULL);
1012  env->ep = env_ep;
1013  env->env = env_body;
1014  env->env_size = env_size;
1015 
1016  cfp->ep = env_ep;
1017  VM_ENV_FLAGS_SET(env_ep, VM_ENV_FLAG_ESCAPED | VM_ENV_FLAG_WB_REQUIRED);
1018  VM_STACK_ENV_WRITE(ep, 0, (VALUE)env); /* GC mark */
1019 
1020 #if 0
1021  for (i = 0; i < local_size; i++) {
1022  if (VM_FRAME_RUBYFRAME_P(cfp)) {
1023  /* clear value stack for GC */
1024  ep[-local_size + i] = 0;
1025  }
1026  }
1027 #endif
1028 
1029  // Invalidate JIT code that assumes cfp->ep == vm_base_ptr(cfp).
1030  if (env->iseq) {
1031  rb_yjit_invalidate_ep_is_bp(env->iseq);
1032  }
1033 
1034  return (VALUE)env;
1035 }
1036 
1037 static VALUE
1038 vm_make_env_object(const rb_execution_context_t *ec, rb_control_frame_t *cfp)
1039 {
1040  VALUE envval = vm_make_env_each(ec, cfp);
1041 
1042  if (PROCDEBUG) {
1043  check_env_value((const rb_env_t *)envval);
1044  }
1045 
1046  return envval;
1047 }
1048 
1049 void
1050 rb_vm_stack_to_heap(rb_execution_context_t *ec)
1051 {
1052  rb_control_frame_t *cfp = ec->cfp;
1053  while ((cfp = rb_vm_get_binding_creatable_next_cfp(ec, cfp)) != 0) {
1054  vm_make_env_object(ec, cfp);
1055  cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp);
1056  }
1057 }
1058 
1059 const rb_env_t *
1060 rb_vm_env_prev_env(const rb_env_t *env)
1061 {
1062  const VALUE *ep = env->ep;
1063 
1064  if (VM_ENV_LOCAL_P(ep)) {
1065  return NULL;
1066  }
1067  else {
1068  const VALUE *prev_ep = VM_ENV_PREV_EP(ep);
1069  return VM_ENV_ENVVAL_PTR(prev_ep);
1070  }
1071 }
1072 
1073 static int
1074 collect_local_variables_in_iseq(const rb_iseq_t *iseq, const struct local_var_list *vars)
1075 {
1076  unsigned int i;
1077  if (!iseq) return 0;
1078  for (i = 0; i < ISEQ_BODY(iseq)->local_table_size; i++) {
1079  local_var_list_add(vars, ISEQ_BODY(iseq)->local_table[i]);
1080  }
1081  return 1;
1082 }
1083 
1084 static void
1085 collect_local_variables_in_env(const rb_env_t *env, const struct local_var_list *vars)
1086 {
1087  do {
1088  if (VM_ENV_FLAGS(env->ep, VM_ENV_FLAG_ISOLATED)) break;
1089  collect_local_variables_in_iseq(env->iseq, vars);
1090  } while ((env = rb_vm_env_prev_env(env)) != NULL);
1091 }
1092 
1093 static int
1094 vm_collect_local_variables_in_heap(const VALUE *ep, const struct local_var_list *vars)
1095 {
1096  if (VM_ENV_ESCAPED_P(ep)) {
1097  collect_local_variables_in_env(VM_ENV_ENVVAL_PTR(ep), vars);
1098  return 1;
1099  }
1100  else {
1101  return 0;
1102  }
1103 }
1104 
1105 VALUE
1106 rb_vm_env_local_variables(const rb_env_t *env)
1107 {
1108  struct local_var_list vars;
1109  local_var_list_init(&vars);
1110  collect_local_variables_in_env(env, &vars);
1111  return local_var_list_finish(&vars);
1112 }
1113 
1114 VALUE
1115 rb_iseq_local_variables(const rb_iseq_t *iseq)
1116 {
1117  struct local_var_list vars;
1118  local_var_list_init(&vars);
1119  while (collect_local_variables_in_iseq(iseq, &vars)) {
1120  iseq = ISEQ_BODY(iseq)->parent_iseq;
1121  }
1122  return local_var_list_finish(&vars);
1123 }
1124 
1125 /* Proc */
1126 
1127 static VALUE
1128 vm_proc_create_from_captured(VALUE klass,
1129  const struct rb_captured_block *captured,
1130  enum rb_block_type block_type,
1131  int8_t is_from_method, int8_t is_lambda)
1132 {
1133  VALUE procval = rb_proc_alloc(klass);
1134  rb_proc_t *proc = RTYPEDDATA_DATA(procval);
1135 
1136  VM_ASSERT(VM_EP_IN_HEAP_P(GET_EC(), captured->ep));
1137 
1138  /* copy block */
1139  RB_OBJ_WRITE(procval, &proc->block.as.captured.code.val, captured->code.val);
1140  RB_OBJ_WRITE(procval, &proc->block.as.captured.self, captured->self);
1141  rb_vm_block_ep_update(procval, &proc->block, captured->ep);
1142 
1143  vm_block_type_set(&proc->block, block_type);
1144  proc->is_from_method = is_from_method;
1145  proc->is_lambda = is_lambda;
1146 
1147  return procval;
1148 }
1149 
1150 void
1151 rb_vm_block_copy(VALUE obj, const struct rb_block *dst, const struct rb_block *src)
1152 {
1153  /* copy block */
1154  switch (vm_block_type(src)) {
1155  case block_type_iseq:
1156  case block_type_ifunc:
1157  RB_OBJ_WRITE(obj, &dst->as.captured.self, src->as.captured.self);
1158  RB_OBJ_WRITE(obj, &dst->as.captured.code.val, src->as.captured.code.val);
1159  rb_vm_block_ep_update(obj, dst, src->as.captured.ep);
1160  break;
1161  case block_type_symbol:
1162  RB_OBJ_WRITE(obj, &dst->as.symbol, src->as.symbol);
1163  break;
1164  case block_type_proc:
1165  RB_OBJ_WRITE(obj, &dst->as.proc, src->as.proc);
1166  break;
1167  }
1168 }
1169 
1170 static VALUE
1171 proc_create(VALUE klass, const struct rb_block *block, int8_t is_from_method, int8_t is_lambda)
1172 {
1173  VALUE procval = rb_proc_alloc(klass);
1174  rb_proc_t *proc = RTYPEDDATA_DATA(procval);
1175 
1176  VM_ASSERT(VM_EP_IN_HEAP_P(GET_EC(), vm_block_ep(block)));
1177  rb_vm_block_copy(procval, &proc->block, block);
1178  vm_block_type_set(&proc->block, block->type);
1179  proc->is_from_method = is_from_method;
1180  proc->is_lambda = is_lambda;
1181 
1182  return procval;
1183 }
1184 
1185 VALUE
1186 rb_proc_dup(VALUE self)
1187 {
1188  VALUE procval;
1189  rb_proc_t *src;
1190 
1191  GetProcPtr(self, src);
1192  procval = proc_create(rb_obj_class(self), &src->block, src->is_from_method, src->is_lambda);
1193  if (RB_OBJ_SHAREABLE_P(self)) FL_SET_RAW(procval, RUBY_FL_SHAREABLE);
1194  RB_GC_GUARD(self); /* for: body = rb_proc_dup(body) */
1195  return procval;
1196 }
1197 
1199  VALUE ary;
1200  VALUE read_only;
1201  bool yield;
1202  bool isolate;
1203 };
1204 
1205 static VALUE
1206 ID2NUM(ID id)
1207 {
1208  if (SIZEOF_VOIDP > SIZEOF_LONG)
1209  return ULL2NUM(id);
1210  else
1211  return ULONG2NUM(id);
1212 }
1213 
1214 static ID
1215 NUM2ID(VALUE num)
1216 {
1217  if (SIZEOF_VOIDP > SIZEOF_LONG)
1218  return (ID)NUM2ULL(num);
1219  else
1220  return (ID)NUM2ULONG(num);
1221 }
1222 
1223 static enum rb_id_table_iterator_result
1224 collect_outer_variable_names(ID id, VALUE val, void *ptr)
1225 {
1227 
1228  if (id == rb_intern("yield")) {
1229  data->yield = true;
1230  }
1231  else {
1232  VALUE *store;
1233  if (data->isolate ||
1234  val == Qtrue /* write */) {
1235  store = &data->ary;
1236  }
1237  else {
1238  store = &data->read_only;
1239  }
1240  if (*store == Qfalse) *store = rb_ary_new();
1241  rb_ary_push(*store, ID2NUM(id));
1242  }
1243  return ID_TABLE_CONTINUE;
1244 }
1245 
1246 static const rb_env_t *
1247 env_copy(const VALUE *src_ep, VALUE read_only_variables)
1248 {
1249  const rb_env_t *src_env = (rb_env_t *)VM_ENV_ENVVAL(src_ep);
1250  VM_ASSERT(src_env->ep == src_ep);
1251 
1252  VALUE *env_body = ZALLOC_N(VALUE, src_env->env_size); // fill with Qfalse
1253  VALUE *ep = &env_body[src_env->env_size - 2];
1254  const rb_env_t *copied_env = vm_env_new(ep, env_body, src_env->env_size, src_env->iseq);
1255 
1256  // Copy after allocations above, since they can move objects in src_ep.
1257  RB_OBJ_WRITE(copied_env, &ep[VM_ENV_DATA_INDEX_ME_CREF], src_ep[VM_ENV_DATA_INDEX_ME_CREF]);
1258  ep[VM_ENV_DATA_INDEX_FLAGS] = src_ep[VM_ENV_DATA_INDEX_FLAGS] | VM_ENV_FLAG_ISOLATED;
1259  if (!VM_ENV_LOCAL_P(src_ep)) {
1260  VM_ENV_FLAGS_SET(ep, VM_ENV_FLAG_LOCAL);
1261  }
1262 
1263  if (read_only_variables) {
1264  for (int i=RARRAY_LENINT(read_only_variables)-1; i>=0; i--) {
1265  ID id = NUM2ID(RARRAY_AREF(read_only_variables, i));
1266 
1267  for (unsigned int j=0; j<ISEQ_BODY(src_env->iseq)->local_table_size; j++) {
1268  if (id == ISEQ_BODY(src_env->iseq)->local_table[j]) {
1269  VALUE v = src_env->env[j];
1270  if (!rb_ractor_shareable_p(v)) {
1271  VALUE name = rb_id2str(id);
1272  VALUE msg = rb_sprintf("can not make shareable Proc because it can refer"
1273  " unshareable object %+" PRIsVALUE " from ", v);
1274  if (name)
1275  rb_str_catf(msg, "variable '%" PRIsVALUE "'", name);
1276  else
1277  rb_str_cat_cstr(msg, "a hidden variable");
1278  rb_exc_raise(rb_exc_new_str(rb_eRactorIsolationError, msg));
1279  }
1280  RB_OBJ_WRITE((VALUE)copied_env, &env_body[j], v);
1281  rb_ary_delete_at(read_only_variables, i);
1282  break;
1283  }
1284  }
1285  }
1286  }
1287 
1288  if (!VM_ENV_LOCAL_P(src_ep)) {
1289  const VALUE *prev_ep = VM_ENV_PREV_EP(src_env->ep);
1290  const rb_env_t *new_prev_env = env_copy(prev_ep, read_only_variables);
1291  ep[VM_ENV_DATA_INDEX_SPECVAL] = VM_GUARDED_PREV_EP(new_prev_env->ep);
1292  RB_OBJ_WRITTEN(copied_env, Qundef, new_prev_env);
1293  VM_ENV_FLAGS_UNSET(ep, VM_ENV_FLAG_LOCAL);
1294  }
1295  else {
1296  ep[VM_ENV_DATA_INDEX_SPECVAL] = VM_BLOCK_HANDLER_NONE;
1297  }
1298 
1299  return copied_env;
1300 }
1301 
1302 static void
1303 proc_isolate_env(VALUE self, rb_proc_t *proc, VALUE read_only_variables)
1304 {
1305  const struct rb_captured_block *captured = &proc->block.as.captured;
1306  const rb_env_t *env = env_copy(captured->ep, read_only_variables);
1307  *((const VALUE **)&proc->block.as.captured.ep) = env->ep;
1308  RB_OBJ_WRITTEN(self, Qundef, env);
1309 }
1310 
1311 static VALUE
1312 proc_shared_outer_variables(struct rb_id_table *outer_variables, bool isolate, const char *message)
1313 {
1314  struct collect_outer_variable_name_data data = {
1315  .isolate = isolate,
1316  .ary = Qfalse,
1317  .read_only = Qfalse,
1318  .yield = false,
1319  };
1320  rb_id_table_foreach(outer_variables, collect_outer_variable_names, (void *)&data);
1321 
1322  if (data.ary != Qfalse) {
1323  VALUE str = rb_sprintf("can not %s because it accesses outer variables", message);
1324  VALUE ary = data.ary;
1325  const char *sep = " (";
1326  for (long i = 0; i < RARRAY_LEN(ary); i++) {
1327  VALUE name = rb_id2str(NUM2ID(RARRAY_AREF(ary, i)));
1328  if (!name) continue;
1329  rb_str_cat_cstr(str, sep);
1330  sep = ", ";
1331  rb_str_append(str, name);
1332  }
1333  if (*sep == ',') rb_str_cat_cstr(str, ")");
1334  rb_str_cat_cstr(str, data.yield ? " and uses 'yield'." : ".");
1336  }
1337  else if (data.yield) {
1338  rb_raise(rb_eArgError, "can not %s because it uses 'yield'.", message);
1339  }
1340 
1341  return data.read_only;
1342 }
1343 
1344 VALUE
1345 rb_proc_isolate_bang(VALUE self)
1346 {
1347  const rb_iseq_t *iseq = vm_proc_iseq(self);
1348 
1349  if (iseq) {
1350  rb_proc_t *proc = (rb_proc_t *)RTYPEDDATA_DATA(self);
1351  if (proc->block.type != block_type_iseq) rb_raise(rb_eRuntimeError, "not supported yet");
1352 
1353  if (ISEQ_BODY(iseq)->outer_variables) {
1354  proc_shared_outer_variables(ISEQ_BODY(iseq)->outer_variables, true, "isolate a Proc");
1355  }
1356 
1357  proc_isolate_env(self, proc, Qfalse);
1358  proc->is_isolated = TRUE;
1359  }
1360 
1362  return self;
1363 }
1364 
1365 VALUE
1366 rb_proc_isolate(VALUE self)
1367 {
1368  VALUE dst = rb_proc_dup(self);
1369  rb_proc_isolate_bang(dst);
1370  return dst;
1371 }
1372 
1373 VALUE
1374 rb_proc_ractor_make_shareable(VALUE self)
1375 {
1376  const rb_iseq_t *iseq = vm_proc_iseq(self);
1377 
1378  if (iseq) {
1379  rb_proc_t *proc = (rb_proc_t *)RTYPEDDATA_DATA(self);
1380  if (proc->block.type != block_type_iseq) rb_raise(rb_eRuntimeError, "not supported yet");
1381 
1382  if (!rb_ractor_shareable_p(vm_block_self(&proc->block))) {
1383  rb_raise(rb_eRactorIsolationError,
1384  "Proc's self is not shareable: %" PRIsVALUE,
1385  self);
1386  }
1387 
1388  VALUE read_only_variables = Qfalse;
1389 
1390  if (ISEQ_BODY(iseq)->outer_variables) {
1391  read_only_variables =
1392  proc_shared_outer_variables(ISEQ_BODY(iseq)->outer_variables, false, "make a Proc shareable");
1393  }
1394 
1395  proc_isolate_env(self, proc, read_only_variables);
1396  proc->is_isolated = TRUE;
1397  }
1398 
1400  return self;
1401 }
1402 
1403 VALUE
1404 rb_vm_make_proc_lambda(const rb_execution_context_t *ec, const struct rb_captured_block *captured, VALUE klass, int8_t is_lambda)
1405 {
1406  VALUE procval;
1407  enum imemo_type code_type = imemo_type(captured->code.val);
1408 
1409  if (!VM_ENV_ESCAPED_P(captured->ep)) {
1410  rb_control_frame_t *cfp = VM_CAPTURED_BLOCK_TO_CFP(captured);
1411  vm_make_env_object(ec, cfp);
1412  }
1413 
1414  VM_ASSERT(VM_EP_IN_HEAP_P(ec, captured->ep));
1415  VM_ASSERT(code_type == imemo_iseq || code_type == imemo_ifunc);
1416 
1417  procval = vm_proc_create_from_captured(klass, captured,
1418  code_type == imemo_iseq ? block_type_iseq : block_type_ifunc,
1419  FALSE, is_lambda);
1420 
1421  if (code_type == imemo_ifunc) {
1422  struct vm_ifunc *ifunc = (struct vm_ifunc *)captured->code.val;
1423  if (ifunc->svar_lep) {
1424  VALUE ep0 = ifunc->svar_lep[0];
1425  if (RB_TYPE_P(ep0, T_IMEMO) && imemo_type_p(ep0, imemo_env)) {
1426  // `ep0 == imemo_env` means this ep is escaped to heap (in env object).
1427  const rb_env_t *env = (const rb_env_t *)ep0;
1428  ifunc->svar_lep = (VALUE *)env->ep;
1429  }
1430  else {
1431  VM_ASSERT(FIXNUM_P(ep0));
1432  if (ep0 & VM_ENV_FLAG_ESCAPED) {
1433  // ok. do nothing
1434  }
1435  else {
1436  ifunc->svar_lep = NULL;
1437  }
1438  }
1439  }
1440  }
1441 
1442  return procval;
1443 }
1444 
1445 /* Binding */
1446 
1447 VALUE
1448 rb_vm_make_binding(const rb_execution_context_t *ec, const rb_control_frame_t *src_cfp)
1449 {
1450  rb_control_frame_t *cfp = rb_vm_get_binding_creatable_next_cfp(ec, src_cfp);
1451  rb_control_frame_t *ruby_level_cfp = rb_vm_get_ruby_level_next_cfp(ec, src_cfp);
1452  VALUE bindval, envval;
1453  rb_binding_t *bind;
1454 
1455  if (cfp == 0 || ruby_level_cfp == 0) {
1456  rb_raise(rb_eRuntimeError, "Can't create Binding Object on top of Fiber.");
1457  }
1458  if (!VM_FRAME_RUBYFRAME_P(src_cfp) &&
1459  !VM_FRAME_RUBYFRAME_P(RUBY_VM_PREVIOUS_CONTROL_FRAME(src_cfp))) {
1460  rb_raise(rb_eRuntimeError, "Cannot create Binding object for non-Ruby caller");
1461  }
1462 
1463  envval = vm_make_env_object(ec, cfp);
1464  bindval = rb_binding_alloc(rb_cBinding);
1465  GetBindingPtr(bindval, bind);
1466  vm_bind_update_env(bindval, bind, envval);
1467  RB_OBJ_WRITE(bindval, &bind->block.as.captured.self, cfp->self);
1468  RB_OBJ_WRITE(bindval, &bind->block.as.captured.code.iseq, cfp->iseq);
1469  RB_OBJ_WRITE(bindval, &bind->pathobj, ISEQ_BODY(ruby_level_cfp->iseq)->location.pathobj);
1470  bind->first_lineno = rb_vm_get_sourceline(ruby_level_cfp);
1471 
1472  return bindval;
1473 }
1474 
1475 const VALUE *
1476 rb_binding_add_dynavars(VALUE bindval, rb_binding_t *bind, int dyncount, const ID *dynvars)
1477 {
1478  VALUE envval, pathobj = bind->pathobj;
1479  VALUE path = pathobj_path(pathobj);
1480  VALUE realpath = pathobj_realpath(pathobj);
1481  const struct rb_block *base_block;
1482  const rb_env_t *env;
1483  rb_execution_context_t *ec = GET_EC();
1484  const rb_iseq_t *base_iseq, *iseq;
1485  rb_node_scope_t tmp_node;
1486 
1487  if (dyncount < 0) return 0;
1488 
1489  base_block = &bind->block;
1490  base_iseq = vm_block_iseq(base_block);
1491 
1492  VALUE idtmp = 0;
1493  rb_ast_id_table_t *dyns = ALLOCV(idtmp, sizeof(rb_ast_id_table_t) + dyncount * sizeof(ID));
1494  dyns->size = dyncount;
1495  MEMCPY(dyns->ids, dynvars, ID, dyncount);
1496 
1497  rb_node_init(RNODE(&tmp_node), NODE_SCOPE);
1498  tmp_node.nd_tbl = dyns;
1499  tmp_node.nd_body = 0;
1500  tmp_node.nd_args = 0;
1501 
1502  VALUE ast_value = rb_ruby_ast_new(RNODE(&tmp_node));
1503 
1504  if (base_iseq) {
1505  iseq = rb_iseq_new(ast_value, ISEQ_BODY(base_iseq)->location.label, path, realpath, base_iseq, ISEQ_TYPE_EVAL);
1506  }
1507  else {
1508  VALUE tempstr = rb_fstring_lit("<temp>");
1509  iseq = rb_iseq_new_top(ast_value, tempstr, tempstr, tempstr, NULL);
1510  }
1511  tmp_node.nd_tbl = 0; /* reset table */
1512  ALLOCV_END(idtmp);
1513 
1514  vm_set_eval_stack(ec, iseq, 0, base_block);
1515  vm_bind_update_env(bindval, bind, envval = vm_make_env_object(ec, ec->cfp));
1516  rb_vm_pop_frame(ec);
1517 
1518  env = (const rb_env_t *)envval;
1519  return env->env;
1520 }
1521 
1522 /* C -> Ruby: block */
1523 
1524 static inline void
1525 invoke_block(rb_execution_context_t *ec, const rb_iseq_t *iseq, VALUE self, const struct rb_captured_block *captured, const rb_cref_t *cref, VALUE type, int opt_pc)
1526 {
1527  int arg_size = ISEQ_BODY(iseq)->param.size;
1528 
1529  vm_push_frame(ec, iseq, type | VM_FRAME_FLAG_FINISH, self,
1530  VM_GUARDED_PREV_EP(captured->ep),
1531  (VALUE)cref, /* cref or method */
1532  ISEQ_BODY(iseq)->iseq_encoded + opt_pc,
1533  ec->cfp->sp + arg_size,
1534  ISEQ_BODY(iseq)->local_table_size - arg_size,
1535  ISEQ_BODY(iseq)->stack_max);
1536 }
1537 
1538 static inline void
1539 invoke_bmethod(rb_execution_context_t *ec, const rb_iseq_t *iseq, VALUE self, const struct rb_captured_block *captured, const rb_callable_method_entry_t *me, VALUE type, int opt_pc)
1540 {
1541  /* bmethod call from outside the VM */
1542  int arg_size = ISEQ_BODY(iseq)->param.size;
1543 
1544  VM_ASSERT(me->def->type == VM_METHOD_TYPE_BMETHOD);
1545 
1546  vm_push_frame(ec, iseq, type | VM_FRAME_FLAG_BMETHOD, self,
1547  VM_GUARDED_PREV_EP(captured->ep),
1548  (VALUE)me,
1549  ISEQ_BODY(iseq)->iseq_encoded + opt_pc,
1550  ec->cfp->sp + 1 /* self */ + arg_size,
1551  ISEQ_BODY(iseq)->local_table_size - arg_size,
1552  ISEQ_BODY(iseq)->stack_max);
1553 
1554  VM_ENV_FLAGS_SET(ec->cfp->ep, VM_FRAME_FLAG_FINISH);
1555 }
1556 
1557 ALWAYS_INLINE(static VALUE
1558  invoke_iseq_block_from_c(rb_execution_context_t *ec, const struct rb_captured_block *captured,
1559  VALUE self, int argc, const VALUE *argv, int kw_splat, VALUE passed_block_handler,
1560  const rb_cref_t *cref, int is_lambda, const rb_callable_method_entry_t *me));
1561 
1562 static inline VALUE
1563 invoke_iseq_block_from_c(rb_execution_context_t *ec, const struct rb_captured_block *captured,
1564  VALUE self, int argc, const VALUE *argv, int kw_splat, VALUE passed_block_handler,
1565  const rb_cref_t *cref, int is_lambda, const rb_callable_method_entry_t *me)
1566 {
1567  const rb_iseq_t *iseq = rb_iseq_check(captured->code.iseq);
1568  int opt_pc;
1569  VALUE type = VM_FRAME_MAGIC_BLOCK | (is_lambda ? VM_FRAME_FLAG_LAMBDA : 0);
1570  rb_control_frame_t *cfp = ec->cfp;
1571  VALUE *sp = cfp->sp;
1572  int flags = (kw_splat ? VM_CALL_KW_SPLAT : 0);
1573  VALUE *use_argv = (VALUE *)argv;
1574  VALUE av[2];
1575 
1576  stack_check(ec);
1577 
1578  if (UNLIKELY(argc > VM_ARGC_STACK_MAX) &&
1579  (VM_ARGC_STACK_MAX >= 1 ||
1580  /* Skip ruby array for potential autosplat case */
1581  (argc != 1 || is_lambda))) {
1582  use_argv = vm_argv_ruby_array(av, argv, &flags, &argc, kw_splat);
1583  }
1584 
1585  CHECK_VM_STACK_OVERFLOW(cfp, argc + 1);
1586  vm_check_canary(ec, sp);
1587 
1588  VALUE *stack_argv = sp;
1589  if (me) {
1590  *sp = self; // bemthods need `self` on the VM stack
1591  stack_argv++;
1592  }
1593  cfp->sp = stack_argv + argc;
1594  MEMCPY(stack_argv, use_argv, VALUE, argc); // restrict: new stack space
1595 
1596  opt_pc = vm_yield_setup_args(ec, iseq, argc, stack_argv, flags, passed_block_handler,
1597  (is_lambda ? arg_setup_method : arg_setup_block));
1598  cfp->sp = sp;
1599 
1600  if (me == NULL) {
1601  invoke_block(ec, iseq, self, captured, cref, type, opt_pc);
1602  }
1603  else {
1604  invoke_bmethod(ec, iseq, self, captured, me, type, opt_pc);
1605  }
1606 
1607  return vm_exec(ec);
1608 }
1609 
1610 static VALUE
1611 invoke_block_from_c_bh(rb_execution_context_t *ec, VALUE block_handler,
1612  int argc, const VALUE *argv,
1613  int kw_splat, VALUE passed_block_handler, const rb_cref_t *cref,
1614  int is_lambda, int force_blockarg)
1615 {
1616  again:
1617  switch (vm_block_handler_type(block_handler)) {
1618  case block_handler_type_iseq:
1619  {
1620  const struct rb_captured_block *captured = VM_BH_TO_ISEQ_BLOCK(block_handler);
1621  return invoke_iseq_block_from_c(ec, captured, captured->self,
1622  argc, argv, kw_splat, passed_block_handler,
1623  cref, is_lambda, NULL);
1624  }
1625  case block_handler_type_ifunc:
1626  return vm_yield_with_cfunc(ec, VM_BH_TO_IFUNC_BLOCK(block_handler),
1627  VM_BH_TO_IFUNC_BLOCK(block_handler)->self,
1628  argc, argv, kw_splat, passed_block_handler, NULL);
1629  case block_handler_type_symbol:
1630  return vm_yield_with_symbol(ec, VM_BH_TO_SYMBOL(block_handler),
1631  argc, argv, kw_splat, passed_block_handler);
1632  case block_handler_type_proc:
1633  if (force_blockarg == FALSE) {
1634  is_lambda = block_proc_is_lambda(VM_BH_TO_PROC(block_handler));
1635  }
1636  block_handler = vm_proc_to_block_handler(VM_BH_TO_PROC(block_handler));
1637  goto again;
1638  }
1639  VM_UNREACHABLE(invoke_block_from_c_splattable);
1640  return Qundef;
1641 }
1642 
1643 static inline VALUE
1644 check_block_handler(rb_execution_context_t *ec)
1645 {
1646  VALUE block_handler = VM_CF_BLOCK_HANDLER(ec->cfp);
1647  vm_block_handler_verify(block_handler);
1648  if (UNLIKELY(block_handler == VM_BLOCK_HANDLER_NONE)) {
1649  rb_vm_localjump_error("no block given", Qnil, 0);
1650  }
1651 
1652  return block_handler;
1653 }
1654 
1655 static VALUE
1656 vm_yield_with_cref(rb_execution_context_t *ec, int argc, const VALUE *argv, int kw_splat, const rb_cref_t *cref, int is_lambda)
1657 {
1658  return invoke_block_from_c_bh(ec, check_block_handler(ec),
1659  argc, argv, kw_splat, VM_BLOCK_HANDLER_NONE,
1660  cref, is_lambda, FALSE);
1661 }
1662 
1663 static VALUE
1664 vm_yield(rb_execution_context_t *ec, int argc, const VALUE *argv, int kw_splat)
1665 {
1666  return vm_yield_with_cref(ec, argc, argv, kw_splat, NULL, FALSE);
1667 }
1668 
1669 static VALUE
1670 vm_yield_with_block(rb_execution_context_t *ec, int argc, const VALUE *argv, VALUE block_handler, int kw_splat)
1671 {
1672  return invoke_block_from_c_bh(ec, check_block_handler(ec),
1673  argc, argv, kw_splat, block_handler,
1674  NULL, FALSE, FALSE);
1675 }
1676 
1677 static VALUE
1678 vm_yield_force_blockarg(rb_execution_context_t *ec, VALUE args)
1679 {
1680  return invoke_block_from_c_bh(ec, check_block_handler(ec), 1, &args,
1681  RB_NO_KEYWORDS, VM_BLOCK_HANDLER_NONE, NULL, FALSE, TRUE);
1682 }
1683 
1684 ALWAYS_INLINE(static VALUE
1685  invoke_block_from_c_proc(rb_execution_context_t *ec, const rb_proc_t *proc,
1686  VALUE self, int argc, const VALUE *argv,
1687  int kw_splat, VALUE passed_block_handler, int is_lambda,
1688  const rb_callable_method_entry_t *me));
1689 
1690 static inline VALUE
1691 invoke_block_from_c_proc(rb_execution_context_t *ec, const rb_proc_t *proc,
1692  VALUE self, int argc, const VALUE *argv,
1693  int kw_splat, VALUE passed_block_handler, int is_lambda,
1694  const rb_callable_method_entry_t *me)
1695 {
1696  const struct rb_block *block = &proc->block;
1697 
1698  again:
1699  switch (vm_block_type(block)) {
1700  case block_type_iseq:
1701  return invoke_iseq_block_from_c(ec, &block->as.captured, self, argc, argv, kw_splat, passed_block_handler, NULL, is_lambda, me);
1702  case block_type_ifunc:
1703  if (kw_splat == 1) {
1704  VALUE keyword_hash = argv[argc-1];
1705  if (!RB_TYPE_P(keyword_hash, T_HASH)) {
1706  keyword_hash = rb_to_hash_type(keyword_hash);
1707  }
1708  if (RHASH_EMPTY_P(keyword_hash)) {
1709  argc--;
1710  }
1711  else {
1712  ((VALUE *)argv)[argc-1] = rb_hash_dup(keyword_hash);
1713  }
1714  }
1715  return vm_yield_with_cfunc(ec, &block->as.captured, self, argc, argv, kw_splat, passed_block_handler, me);
1716  case block_type_symbol:
1717  return vm_yield_with_symbol(ec, block->as.symbol, argc, argv, kw_splat, passed_block_handler);
1718  case block_type_proc:
1719  is_lambda = block_proc_is_lambda(block->as.proc);
1720  block = vm_proc_block(block->as.proc);
1721  goto again;
1722  }
1723  VM_UNREACHABLE(invoke_block_from_c_proc);
1724  return Qundef;
1725 }
1726 
1727 static VALUE
1728 vm_invoke_proc(rb_execution_context_t *ec, rb_proc_t *proc, VALUE self,
1729  int argc, const VALUE *argv, int kw_splat, VALUE passed_block_handler)
1730 {
1731  return invoke_block_from_c_proc(ec, proc, self, argc, argv, kw_splat, passed_block_handler, proc->is_lambda, NULL);
1732 }
1733 
1734 static VALUE
1735 vm_invoke_bmethod(rb_execution_context_t *ec, rb_proc_t *proc, VALUE self,
1736  int argc, const VALUE *argv, int kw_splat, VALUE block_handler, const rb_callable_method_entry_t *me)
1737 {
1738  return invoke_block_from_c_proc(ec, proc, self, argc, argv, kw_splat, block_handler, TRUE, me);
1739 }
1740 
1741 VALUE
1742 rb_vm_invoke_proc(rb_execution_context_t *ec, rb_proc_t *proc,
1743  int argc, const VALUE *argv, int kw_splat, VALUE passed_block_handler)
1744 {
1745  VALUE self = vm_block_self(&proc->block);
1746  vm_block_handler_verify(passed_block_handler);
1747 
1748  if (proc->is_from_method) {
1749  return vm_invoke_bmethod(ec, proc, self, argc, argv, kw_splat, passed_block_handler, NULL);
1750  }
1751  else {
1752  return vm_invoke_proc(ec, proc, self, argc, argv, kw_splat, passed_block_handler);
1753  }
1754 }
1755 
1756 VALUE
1757 rb_vm_invoke_proc_with_self(rb_execution_context_t *ec, rb_proc_t *proc, VALUE self,
1758  int argc, const VALUE *argv, int kw_splat, VALUE passed_block_handler)
1759 {
1760  vm_block_handler_verify(passed_block_handler);
1761 
1762  if (proc->is_from_method) {
1763  return vm_invoke_bmethod(ec, proc, self, argc, argv, kw_splat, passed_block_handler, NULL);
1764  }
1765  else {
1766  return vm_invoke_proc(ec, proc, self, argc, argv, kw_splat, passed_block_handler);
1767  }
1768 }
1769 
1770 /* special variable */
1771 
1772 VALUE *
1773 rb_vm_svar_lep(const rb_execution_context_t *ec, const rb_control_frame_t *cfp)
1774 {
1775  while (cfp->pc == 0 || cfp->iseq == 0) {
1776  if (VM_FRAME_TYPE(cfp) == VM_FRAME_MAGIC_IFUNC) {
1777  struct vm_ifunc *ifunc = (struct vm_ifunc *)cfp->iseq;
1778  return ifunc->svar_lep;
1779  }
1780  else {
1781  cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp);
1782  }
1783 
1784  if (RUBY_VM_CONTROL_FRAME_STACK_OVERFLOW_P(ec, cfp)) {
1785  return NULL;
1786  }
1787  }
1788 
1789  return (VALUE *)VM_CF_LEP(cfp);
1790 }
1791 
1792 static VALUE
1793 vm_cfp_svar_get(const rb_execution_context_t *ec, rb_control_frame_t *cfp, VALUE key)
1794 {
1795  return lep_svar_get(ec, rb_vm_svar_lep(ec, cfp), key);
1796 }
1797 
1798 static void
1799 vm_cfp_svar_set(const rb_execution_context_t *ec, rb_control_frame_t *cfp, VALUE key, const VALUE val)
1800 {
1801  lep_svar_set(ec, rb_vm_svar_lep(ec, cfp), key, val);
1802 }
1803 
1804 static VALUE
1805 vm_svar_get(const rb_execution_context_t *ec, VALUE key)
1806 {
1807  return vm_cfp_svar_get(ec, ec->cfp, key);
1808 }
1809 
1810 static void
1811 vm_svar_set(const rb_execution_context_t *ec, VALUE key, VALUE val)
1812 {
1813  vm_cfp_svar_set(ec, ec->cfp, key, val);
1814 }
1815 
1816 VALUE
1818 {
1819  return vm_svar_get(GET_EC(), VM_SVAR_BACKREF);
1820 }
1821 
1822 void
1824 {
1825  vm_svar_set(GET_EC(), VM_SVAR_BACKREF, val);
1826 }
1827 
1828 VALUE
1830 {
1831  return vm_svar_get(GET_EC(), VM_SVAR_LASTLINE);
1832 }
1833 
1834 void
1836 {
1837  vm_svar_set(GET_EC(), VM_SVAR_LASTLINE, val);
1838 }
1839 
1840 void
1841 rb_lastline_set_up(VALUE val, unsigned int up)
1842 {
1843  rb_control_frame_t * cfp = GET_EC()->cfp;
1844 
1845  for(unsigned int i = 0; i < up; i++) {
1846  cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp);
1847  }
1848  vm_cfp_svar_set(GET_EC(), cfp, VM_SVAR_LASTLINE, val);
1849 }
1850 
1851 /* misc */
1852 
1853 const char *
1855 {
1856  const rb_execution_context_t *ec = GET_EC();
1857  const rb_control_frame_t *cfp = rb_vm_get_ruby_level_next_cfp(ec, ec->cfp);
1858 
1859  if (cfp) {
1860  return RSTRING_PTR(rb_iseq_path(cfp->iseq));
1861  }
1862  else {
1863  return 0;
1864  }
1865 }
1866 
1867 int
1869 {
1870  const rb_execution_context_t *ec = GET_EC();
1871  const rb_control_frame_t *cfp = rb_vm_get_ruby_level_next_cfp(ec, ec->cfp);
1872 
1873  if (cfp) {
1874  return rb_vm_get_sourceline(cfp);
1875  }
1876  else {
1877  return 0;
1878  }
1879 }
1880 
1881 VALUE
1882 rb_source_location(int *pline)
1883 {
1884  const rb_execution_context_t *ec = GET_EC();
1885  const rb_control_frame_t *cfp = rb_vm_get_ruby_level_next_cfp(ec, ec->cfp);
1886 
1887  if (cfp && VM_FRAME_RUBYFRAME_P(cfp)) {
1888  if (pline) *pline = rb_vm_get_sourceline(cfp);
1889  return rb_iseq_path(cfp->iseq);
1890  }
1891  else {
1892  if (pline) *pline = 0;
1893  return Qnil;
1894  }
1895 }
1896 
1897 const char *
1898 rb_source_location_cstr(int *pline)
1899 {
1900  VALUE path = rb_source_location(pline);
1901  if (NIL_P(path)) return NULL;
1902  return RSTRING_PTR(path);
1903 }
1904 
1905 rb_cref_t *
1906 rb_vm_cref(void)
1907 {
1908  const rb_execution_context_t *ec = GET_EC();
1909  return vm_ec_cref(ec);
1910 }
1911 
1912 rb_cref_t *
1913 rb_vm_cref_replace_with_duplicated_cref(void)
1914 {
1915  const rb_execution_context_t *ec = GET_EC();
1916  const rb_control_frame_t *cfp = rb_vm_get_ruby_level_next_cfp(ec, ec->cfp);
1917  rb_cref_t *cref = vm_cref_replace_with_duplicated_cref(cfp->ep);
1918  ASSUME(cref);
1919  return cref;
1920 }
1921 
1922 const rb_cref_t *
1923 rb_vm_cref_in_context(VALUE self, VALUE cbase)
1924 {
1925  const rb_execution_context_t *ec = GET_EC();
1926  const rb_control_frame_t *cfp = rb_vm_get_ruby_level_next_cfp(ec, ec->cfp);
1927  const rb_cref_t *cref;
1928  if (!cfp || cfp->self != self) return NULL;
1929  if (!vm_env_cref_by_cref(cfp->ep)) return NULL;
1930  cref = vm_get_cref(cfp->ep);
1931  if (CREF_CLASS(cref) != cbase) return NULL;
1932  return cref;
1933 }
1934 
1935 #if 0
1936 void
1937 debug_cref(rb_cref_t *cref)
1938 {
1939  while (cref) {
1940  dp(CREF_CLASS(cref));
1941  printf("%ld\n", CREF_VISI(cref));
1942  cref = CREF_NEXT(cref);
1943  }
1944 }
1945 #endif
1946 
1947 VALUE
1948 rb_vm_cbase(void)
1949 {
1950  const rb_execution_context_t *ec = GET_EC();
1951  const rb_control_frame_t *cfp = rb_vm_get_ruby_level_next_cfp(ec, ec->cfp);
1952 
1953  if (cfp == 0) {
1954  rb_raise(rb_eRuntimeError, "Can't call on top of Fiber or Thread");
1955  }
1956  return vm_get_cbase(cfp->ep);
1957 }
1958 
1959 /* jump */
1960 
1961 static VALUE
1962 make_localjump_error(const char *mesg, VALUE value, int reason)
1963 {
1964  extern VALUE rb_eLocalJumpError;
1965  VALUE exc = rb_exc_new2(rb_eLocalJumpError, mesg);
1966  ID id;
1967 
1968  switch (reason) {
1969  case TAG_BREAK:
1970  CONST_ID(id, "break");
1971  break;
1972  case TAG_REDO:
1973  CONST_ID(id, "redo");
1974  break;
1975  case TAG_RETRY:
1976  CONST_ID(id, "retry");
1977  break;
1978  case TAG_NEXT:
1979  CONST_ID(id, "next");
1980  break;
1981  case TAG_RETURN:
1982  CONST_ID(id, "return");
1983  break;
1984  default:
1985  CONST_ID(id, "noreason");
1986  break;
1987  }
1988  rb_iv_set(exc, "@exit_value", value);
1989  rb_iv_set(exc, "@reason", ID2SYM(id));
1990  return exc;
1991 }
1992 
1993 void
1994 rb_vm_localjump_error(const char *mesg, VALUE value, int reason)
1995 {
1996  VALUE exc = make_localjump_error(mesg, value, reason);
1997  rb_exc_raise(exc);
1998 }
1999 
2000 VALUE
2001 rb_vm_make_jump_tag_but_local_jump(enum ruby_tag_type state, VALUE val)
2002 {
2003  const char *mesg;
2004 
2005  switch (state) {
2006  case TAG_RETURN:
2007  mesg = "unexpected return";
2008  break;
2009  case TAG_BREAK:
2010  mesg = "unexpected break";
2011  break;
2012  case TAG_NEXT:
2013  mesg = "unexpected next";
2014  break;
2015  case TAG_REDO:
2016  mesg = "unexpected redo";
2017  val = Qnil;
2018  break;
2019  case TAG_RETRY:
2020  mesg = "retry outside of rescue clause";
2021  val = Qnil;
2022  break;
2023  default:
2024  return Qnil;
2025  }
2026  if (UNDEF_P(val)) {
2027  val = GET_EC()->tag->retval;
2028  }
2029  return make_localjump_error(mesg, val, state);
2030 }
2031 
2032 void
2033 rb_vm_jump_tag_but_local_jump(enum ruby_tag_type state)
2034 {
2035  VALUE exc = rb_vm_make_jump_tag_but_local_jump(state, Qundef);
2036  if (!NIL_P(exc)) rb_exc_raise(exc);
2037  EC_JUMP_TAG(GET_EC(), state);
2038 }
2039 
2040 static rb_control_frame_t *
2041 next_not_local_frame(rb_control_frame_t *cfp)
2042 {
2043  while (VM_ENV_LOCAL_P(cfp->ep)) {
2044  cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp);
2045  }
2046  return cfp;
2047 }
2048 
2049 NORETURN(static void vm_iter_break(rb_execution_context_t *ec, VALUE val));
2050 
2051 static void
2052 vm_iter_break(rb_execution_context_t *ec, VALUE val)
2053 {
2054  rb_control_frame_t *cfp = next_not_local_frame(ec->cfp);
2055  const VALUE *ep = VM_CF_PREV_EP(cfp);
2056  const rb_control_frame_t *target_cfp = rb_vm_search_cf_from_ep(ec, cfp, ep);
2057 
2058  if (!target_cfp) {
2059  rb_vm_localjump_error("unexpected break", val, TAG_BREAK);
2060  }
2061 
2062  ec->errinfo = (VALUE)THROW_DATA_NEW(val, target_cfp, TAG_BREAK);
2063  EC_JUMP_TAG(ec, TAG_BREAK);
2064 }
2065 
2066 void
2068 {
2069  vm_iter_break(GET_EC(), Qnil);
2070 }
2071 
2072 void
2074 {
2075  vm_iter_break(GET_EC(), val);
2076 }
2077 
2078 /* optimization: redefine management */
2079 
2080 short ruby_vm_redefined_flag[BOP_LAST_];
2081 static st_table *vm_opt_method_def_table = 0;
2082 static st_table *vm_opt_mid_table = 0;
2083 
2084 void
2085 rb_free_vm_opt_tables(void)
2086 {
2087  st_free_table(vm_opt_method_def_table);
2088  st_free_table(vm_opt_mid_table);
2089 }
2090 
2091 static int
2092 vm_redefinition_check_flag(VALUE klass)
2093 {
2094  if (klass == rb_cInteger) return INTEGER_REDEFINED_OP_FLAG;
2095  if (klass == rb_cFloat) return FLOAT_REDEFINED_OP_FLAG;
2096  if (klass == rb_cString) return STRING_REDEFINED_OP_FLAG;
2097  if (klass == rb_cArray) return ARRAY_REDEFINED_OP_FLAG;
2098  if (klass == rb_cHash) return HASH_REDEFINED_OP_FLAG;
2099  if (klass == rb_cSymbol) return SYMBOL_REDEFINED_OP_FLAG;
2100 #if 0
2101  if (klass == rb_cTime) return TIME_REDEFINED_OP_FLAG;
2102 #endif
2103  if (klass == rb_cRegexp) return REGEXP_REDEFINED_OP_FLAG;
2104  if (klass == rb_cNilClass) return NIL_REDEFINED_OP_FLAG;
2105  if (klass == rb_cTrueClass) return TRUE_REDEFINED_OP_FLAG;
2106  if (klass == rb_cFalseClass) return FALSE_REDEFINED_OP_FLAG;
2107  if (klass == rb_cProc) return PROC_REDEFINED_OP_FLAG;
2108  return 0;
2109 }
2110 
2111 int
2112 rb_vm_check_optimizable_mid(VALUE mid)
2113 {
2114  if (!vm_opt_mid_table) {
2115  return FALSE;
2116  }
2117 
2118  return st_lookup(vm_opt_mid_table, mid, NULL);
2119 }
2120 
2121 static int
2122 vm_redefinition_check_method_type(const rb_method_entry_t *me)
2123 {
2124  if (me->called_id != me->def->original_id) {
2125  return FALSE;
2126  }
2127 
2128  if (METHOD_ENTRY_BASIC(me)) return TRUE;
2129 
2130  const rb_method_definition_t *def = me->def;
2131  switch (def->type) {
2132  case VM_METHOD_TYPE_CFUNC:
2133  case VM_METHOD_TYPE_OPTIMIZED:
2134  return TRUE;
2135  default:
2136  return FALSE;
2137  }
2138 }
2139 
2140 static void
2141 rb_vm_check_redefinition_opt_method(const rb_method_entry_t *me, VALUE klass)
2142 {
2143  st_data_t bop;
2144  if (RB_TYPE_P(klass, T_ICLASS) && FL_TEST(klass, RICLASS_IS_ORIGIN) &&
2145  RB_TYPE_P(RBASIC_CLASS(klass), T_CLASS)) {
2146  klass = RBASIC_CLASS(klass);
2147  }
2148  if (vm_redefinition_check_method_type(me)) {
2149  if (st_lookup(vm_opt_method_def_table, (st_data_t)me->def, &bop)) {
2150  int flag = vm_redefinition_check_flag(klass);
2151  if (flag != 0) {
2154  "Redefining '%s#%s' disables interpreter and JIT optimizations",
2155  rb_class2name(me->owner),
2156  rb_id2name(me->called_id)
2157  );
2158  rb_yjit_bop_redefined(flag, (enum ruby_basic_operators)bop);
2159  rb_rjit_bop_redefined(flag, (enum ruby_basic_operators)bop);
2160  ruby_vm_redefined_flag[bop] |= flag;
2161  }
2162  }
2163  }
2164 }
2165 
2166 static enum rb_id_table_iterator_result
2167 check_redefined_method(ID mid, VALUE value, void *data)
2168 {
2169  VALUE klass = (VALUE)data;
2170  const rb_method_entry_t *me = (rb_method_entry_t *)value;
2171  const rb_method_entry_t *newme = rb_method_entry(klass, mid);
2172 
2173  if (newme != me) rb_vm_check_redefinition_opt_method(me, me->owner);
2174 
2175  return ID_TABLE_CONTINUE;
2176 }
2177 
2178 void
2179 rb_vm_check_redefinition_by_prepend(VALUE klass)
2180 {
2181  if (!vm_redefinition_check_flag(klass)) return;
2182  rb_id_table_foreach(RCLASS_M_TBL(RCLASS_ORIGIN(klass)), check_redefined_method, (void *)klass);
2183 }
2184 
2185 static void
2186 add_opt_method_entry_bop(const rb_method_entry_t *me, ID mid, enum ruby_basic_operators bop)
2187 {
2188  st_insert(vm_opt_method_def_table, (st_data_t)me->def, (st_data_t)bop);
2189  st_insert(vm_opt_mid_table, (st_data_t)mid, (st_data_t)Qtrue);
2190 }
2191 
2192 static void
2193 add_opt_method(VALUE klass, ID mid, enum ruby_basic_operators bop)
2194 {
2195  const rb_method_entry_t *me = rb_method_entry_at(klass, mid);
2196 
2197  if (me && vm_redefinition_check_method_type(me)) {
2198  add_opt_method_entry_bop(me, mid, bop);
2199  }
2200  else {
2201  rb_bug("undefined optimized method: %s", rb_id2name(mid));
2202  }
2203 }
2204 
2205 static enum ruby_basic_operators vm_redefinition_bop_for_id(ID mid);
2206 
2207 static void
2208 add_opt_method_entry(const rb_method_entry_t *me)
2209 {
2210  if (me && vm_redefinition_check_method_type(me)) {
2211  ID mid = me->called_id;
2212  enum ruby_basic_operators bop = vm_redefinition_bop_for_id(mid);
2213  if ((int)bop >= 0) {
2214  add_opt_method_entry_bop(me, mid, bop);
2215  }
2216  }
2217 }
2218 
2219 static void
2220 vm_init_redefined_flag(void)
2221 {
2222  ID mid;
2223  enum ruby_basic_operators bop;
2224 
2225 #define OP(mid_, bop_) (mid = id##mid_, bop = BOP_##bop_, ruby_vm_redefined_flag[bop] = 0)
2226 #define C(k) add_opt_method(rb_c##k, mid, bop)
2227  OP(PLUS, PLUS), (C(Integer), C(Float), C(String), C(Array));
2228  OP(MINUS, MINUS), (C(Integer), C(Float));
2229  OP(MULT, MULT), (C(Integer), C(Float));
2230  OP(DIV, DIV), (C(Integer), C(Float));
2231  OP(MOD, MOD), (C(Integer), C(Float));
2232  OP(Eq, EQ), (C(Integer), C(Float), C(String), C(Symbol));
2233  OP(Eqq, EQQ), (C(Integer), C(Float), C(Symbol), C(String),
2234  C(NilClass), C(TrueClass), C(FalseClass));
2235  OP(LT, LT), (C(Integer), C(Float));
2236  OP(LE, LE), (C(Integer), C(Float));
2237  OP(GT, GT), (C(Integer), C(Float));
2238  OP(GE, GE), (C(Integer), C(Float));
2239  OP(LTLT, LTLT), (C(String), C(Array));
2240  OP(AREF, AREF), (C(Array), C(Hash), C(Integer));
2241  OP(ASET, ASET), (C(Array), C(Hash));
2242  OP(Length, LENGTH), (C(Array), C(String), C(Hash));
2243  OP(Size, SIZE), (C(Array), C(String), C(Hash));
2244  OP(EmptyP, EMPTY_P), (C(Array), C(String), C(Hash));
2245  OP(Succ, SUCC), (C(Integer), C(String));
2246  OP(EqTilde, MATCH), (C(Regexp), C(String));
2247  OP(Freeze, FREEZE), (C(String), C(Array), C(Hash));
2248  OP(UMinus, UMINUS), (C(String));
2249  OP(Max, MAX), (C(Array));
2250  OP(Min, MIN), (C(Array));
2251  OP(Hash, HASH), (C(Array));
2252  OP(Call, CALL), (C(Proc));
2253  OP(And, AND), (C(Integer));
2254  OP(Or, OR), (C(Integer));
2255  OP(NilP, NIL_P), (C(NilClass));
2256  OP(Cmp, CMP), (C(Integer), C(Float), C(String));
2257  OP(Default, DEFAULT), (C(Hash));
2258 #undef C
2259 #undef OP
2260 }
2261 
2262 static enum ruby_basic_operators
2263 vm_redefinition_bop_for_id(ID mid)
2264 {
2265  switch (mid) {
2266 #define OP(mid_, bop_) case id##mid_: return BOP_##bop_
2267  OP(PLUS, PLUS);
2268  OP(MINUS, MINUS);
2269  OP(MULT, MULT);
2270  OP(DIV, DIV);
2271  OP(MOD, MOD);
2272  OP(Eq, EQ);
2273  OP(Eqq, EQQ);
2274  OP(LT, LT);
2275  OP(LE, LE);
2276  OP(GT, GT);
2277  OP(GE, GE);
2278  OP(LTLT, LTLT);
2279  OP(AREF, AREF);
2280  OP(ASET, ASET);
2281  OP(Length, LENGTH);
2282  OP(Size, SIZE);
2283  OP(EmptyP, EMPTY_P);
2284  OP(Succ, SUCC);
2285  OP(EqTilde, MATCH);
2286  OP(Freeze, FREEZE);
2287  OP(UMinus, UMINUS);
2288  OP(Max, MAX);
2289  OP(Min, MIN);
2290  OP(Hash, HASH);
2291  OP(Call, CALL);
2292  OP(And, AND);
2293  OP(Or, OR);
2294  OP(NilP, NIL_P);
2295  OP(Cmp, CMP);
2296  OP(Default, DEFAULT);
2297  OP(Pack, PACK);
2298 #undef OP
2299  }
2300  return -1;
2301 }
2302 
2303 /* for vm development */
2304 
2305 #if VMDEBUG
2306 static const char *
2307 vm_frametype_name(const rb_control_frame_t *cfp)
2308 {
2309  switch (VM_FRAME_TYPE(cfp)) {
2310  case VM_FRAME_MAGIC_METHOD: return "method";
2311  case VM_FRAME_MAGIC_BLOCK: return "block";
2312  case VM_FRAME_MAGIC_CLASS: return "class";
2313  case VM_FRAME_MAGIC_TOP: return "top";
2314  case VM_FRAME_MAGIC_CFUNC: return "cfunc";
2315  case VM_FRAME_MAGIC_IFUNC: return "ifunc";
2316  case VM_FRAME_MAGIC_EVAL: return "eval";
2317  case VM_FRAME_MAGIC_RESCUE: return "rescue";
2318  default:
2319  rb_bug("unknown frame");
2320  }
2321 }
2322 #endif
2323 
2324 static VALUE
2325 frame_return_value(const struct vm_throw_data *err)
2326 {
2327  if (THROW_DATA_P(err) &&
2328  THROW_DATA_STATE(err) == TAG_BREAK &&
2329  THROW_DATA_CONSUMED_P(err) == FALSE) {
2330  return THROW_DATA_VAL(err);
2331  }
2332  else {
2333  return Qnil;
2334  }
2335 }
2336 
2337 #if 0
2338 /* for debug */
2339 static const char *
2340 frame_name(const rb_control_frame_t *cfp)
2341 {
2342  unsigned long type = VM_FRAME_TYPE(cfp);
2343 #define C(t) if (type == VM_FRAME_MAGIC_##t) return #t
2344  C(METHOD);
2345  C(BLOCK);
2346  C(CLASS);
2347  C(TOP);
2348  C(CFUNC);
2349  C(PROC);
2350  C(IFUNC);
2351  C(EVAL);
2352  C(LAMBDA);
2353  C(RESCUE);
2354  C(DUMMY);
2355 #undef C
2356  return "unknown";
2357 }
2358 #endif
2359 
2360 // cfp_returning_with_value:
2361 // Whether cfp is the last frame in the unwinding process for a non-local return.
2362 static void
2363 hook_before_rewind(rb_execution_context_t *ec, bool cfp_returning_with_value, int state, struct vm_throw_data *err)
2364 {
2365  if (state == TAG_RAISE && RBASIC(err)->klass == rb_eSysStackError) {
2366  return;
2367  }
2368  else {
2369  const rb_iseq_t *iseq = ec->cfp->iseq;
2370  rb_hook_list_t *local_hooks = iseq->aux.exec.local_hooks;
2371 
2372  switch (VM_FRAME_TYPE(ec->cfp)) {
2373  case VM_FRAME_MAGIC_METHOD:
2374  RUBY_DTRACE_METHOD_RETURN_HOOK(ec, 0, 0);
2375  EXEC_EVENT_HOOK_AND_POP_FRAME(ec, RUBY_EVENT_RETURN, ec->cfp->self, 0, 0, 0, frame_return_value(err));
2376 
2377  if (UNLIKELY(local_hooks && local_hooks->events & RUBY_EVENT_RETURN)) {
2378  rb_exec_event_hook_orig(ec, local_hooks, RUBY_EVENT_RETURN,
2379  ec->cfp->self, 0, 0, 0, frame_return_value(err), TRUE);
2380  }
2381 
2382  THROW_DATA_CONSUMED_SET(err);
2383  break;
2384  case VM_FRAME_MAGIC_BLOCK:
2385  if (VM_FRAME_BMETHOD_P(ec->cfp)) {
2386  VALUE bmethod_return_value = frame_return_value(err);
2387  if (cfp_returning_with_value) {
2388  // Non-local return terminating at a BMETHOD control frame.
2389  bmethod_return_value = THROW_DATA_VAL(err);
2390  }
2391 
2392 
2393  EXEC_EVENT_HOOK_AND_POP_FRAME(ec, RUBY_EVENT_B_RETURN, ec->cfp->self, 0, 0, 0, bmethod_return_value);
2394  if (UNLIKELY(local_hooks && local_hooks->events & RUBY_EVENT_B_RETURN)) {
2395  rb_exec_event_hook_orig(ec, local_hooks, RUBY_EVENT_B_RETURN,
2396  ec->cfp->self, 0, 0, 0, bmethod_return_value, TRUE);
2397  }
2398 
2399  const rb_callable_method_entry_t *me = rb_vm_frame_method_entry(ec->cfp);
2400 
2401  EXEC_EVENT_HOOK_AND_POP_FRAME(ec, RUBY_EVENT_RETURN, ec->cfp->self,
2402  rb_vm_frame_method_entry(ec->cfp)->def->original_id,
2403  rb_vm_frame_method_entry(ec->cfp)->called_id,
2404  rb_vm_frame_method_entry(ec->cfp)->owner,
2405  bmethod_return_value);
2406 
2407  VM_ASSERT(me->def->type == VM_METHOD_TYPE_BMETHOD);
2408  local_hooks = me->def->body.bmethod.hooks;
2409 
2410  if (UNLIKELY(local_hooks && local_hooks->events & RUBY_EVENT_RETURN)) {
2411  rb_exec_event_hook_orig(ec, local_hooks, RUBY_EVENT_RETURN, ec->cfp->self,
2412  rb_vm_frame_method_entry(ec->cfp)->def->original_id,
2413  rb_vm_frame_method_entry(ec->cfp)->called_id,
2414  rb_vm_frame_method_entry(ec->cfp)->owner,
2415  bmethod_return_value, TRUE);
2416  }
2417  THROW_DATA_CONSUMED_SET(err);
2418  }
2419  else {
2420  EXEC_EVENT_HOOK_AND_POP_FRAME(ec, RUBY_EVENT_B_RETURN, ec->cfp->self, 0, 0, 0, frame_return_value(err));
2421  if (UNLIKELY(local_hooks && local_hooks->events & RUBY_EVENT_B_RETURN)) {
2422  rb_exec_event_hook_orig(ec, local_hooks, RUBY_EVENT_B_RETURN,
2423  ec->cfp->self, 0, 0, 0, frame_return_value(err), TRUE);
2424  }
2425  THROW_DATA_CONSUMED_SET(err);
2426  }
2427  break;
2428  case VM_FRAME_MAGIC_CLASS:
2429  EXEC_EVENT_HOOK_AND_POP_FRAME(ec, RUBY_EVENT_END, ec->cfp->self, 0, 0, 0, Qnil);
2430  break;
2431  }
2432  }
2433 }
2434 
2435 /* evaluator body */
2436 
2437 /* finish
2438  VMe (h1) finish
2439  VM finish F1 F2
2440  cfunc finish F1 F2 C1
2441  rb_funcall finish F1 F2 C1
2442  VMe finish F1 F2 C1
2443  VM finish F1 F2 C1 F3
2444 
2445  F1 - F3 : pushed by VM
2446  C1 : pushed by send insn (CFUNC)
2447 
2448  struct CONTROL_FRAME {
2449  VALUE *pc; // cfp[0], program counter
2450  VALUE *sp; // cfp[1], stack pointer
2451  rb_iseq_t *iseq; // cfp[2], iseq
2452  VALUE self; // cfp[3], self
2453  const VALUE *ep; // cfp[4], env pointer
2454  const void *block_code; // cfp[5], block code
2455  };
2456 
2457  struct rb_captured_block {
2458  VALUE self;
2459  VALUE *ep;
2460  union code;
2461  };
2462 
2463  struct METHOD_ENV {
2464  VALUE param0;
2465  ...
2466  VALUE paramN;
2467  VALUE lvar1;
2468  ...
2469  VALUE lvarM;
2470  VALUE cref; // ep[-2]
2471  VALUE special; // ep[-1]
2472  VALUE flags; // ep[ 0] == lep[0]
2473  };
2474 
2475  struct BLOCK_ENV {
2476  VALUE block_param0;
2477  ...
2478  VALUE block_paramN;
2479  VALUE block_lvar1;
2480  ...
2481  VALUE block_lvarM;
2482  VALUE cref; // ep[-2]
2483  VALUE special; // ep[-1]
2484  VALUE flags; // ep[ 0]
2485  };
2486 
2487  struct CLASS_ENV {
2488  VALUE class_lvar0;
2489  ...
2490  VALUE class_lvarN;
2491  VALUE cref;
2492  VALUE prev_ep; // for frame jump
2493  VALUE flags;
2494  };
2495 
2496  struct C_METHOD_CONTROL_FRAME {
2497  VALUE *pc; // 0
2498  VALUE *sp; // stack pointer
2499  rb_iseq_t *iseq; // cmi
2500  VALUE self; // ?
2501  VALUE *ep; // ep == lep
2502  void *code; //
2503  };
2504 
2505  struct C_BLOCK_CONTROL_FRAME {
2506  VALUE *pc; // point only "finish" insn
2507  VALUE *sp; // sp
2508  rb_iseq_t *iseq; // ?
2509  VALUE self; //
2510  VALUE *ep; // ep
2511  void *code; //
2512  };
2513  */
2514 
2515 static inline VALUE
2516 vm_exec_handle_exception(rb_execution_context_t *ec, enum ruby_tag_type state, VALUE errinfo);
2517 static inline VALUE
2518 vm_exec_loop(rb_execution_context_t *ec, enum ruby_tag_type state, struct rb_vm_tag *tag, VALUE result);
2519 
2520 // for non-Emscripten Wasm build, use vm_exec with optimized setjmp for runtime performance
2521 #if defined(__wasm__) && !defined(__EMSCRIPTEN__)
2522 
2523 struct rb_vm_exec_context {
2524  rb_execution_context_t *const ec;
2525  struct rb_vm_tag *const tag;
2526 
2527  VALUE result;
2528 };
2529 
2530 static void
2531 vm_exec_bottom_main(void *context)
2532 {
2533  struct rb_vm_exec_context *ctx = context;
2534  rb_execution_context_t *ec = ctx->ec;
2535 
2536  ctx->result = vm_exec_loop(ec, TAG_NONE, ctx->tag, vm_exec_core(ec));
2537 }
2538 
2539 static void
2540 vm_exec_bottom_rescue(void *context)
2541 {
2542  struct rb_vm_exec_context *ctx = context;
2543  rb_execution_context_t *ec = ctx->ec;
2544 
2545  ctx->result = vm_exec_loop(ec, rb_ec_tag_state(ec), ctx->tag, ec->errinfo);
2546 }
2547 #endif
2548 
2549 VALUE
2550 vm_exec(rb_execution_context_t *ec)
2551 {
2552  VALUE result = Qundef;
2553 
2554  EC_PUSH_TAG(ec);
2555 
2556  _tag.retval = Qnil;
2557 
2558 #if defined(__wasm__) && !defined(__EMSCRIPTEN__)
2559  struct rb_vm_exec_context ctx = {
2560  .ec = ec,
2561  .tag = &_tag,
2562  };
2563  struct rb_wasm_try_catch try_catch;
2564 
2565  EC_REPUSH_TAG();
2566 
2567  rb_wasm_try_catch_init(&try_catch, vm_exec_bottom_main, vm_exec_bottom_rescue, &ctx);
2568 
2569  rb_wasm_try_catch_loop_run(&try_catch, &RB_VM_TAG_JMPBUF_GET(_tag.buf));
2570 
2571  result = ctx.result;
2572 #else
2573  enum ruby_tag_type state;
2574  if ((state = EC_EXEC_TAG()) == TAG_NONE) {
2575  if (UNDEF_P(result = jit_exec(ec))) {
2576  result = vm_exec_core(ec);
2577  }
2578  /* fallback to the VM */
2579  result = vm_exec_loop(ec, TAG_NONE, &_tag, result);
2580  }
2581  else {
2582  result = vm_exec_loop(ec, state, &_tag, ec->errinfo);
2583  }
2584 #endif
2585 
2586  EC_POP_TAG();
2587  return result;
2588 }
2589 
2590 static inline VALUE
2591 vm_exec_loop(rb_execution_context_t *ec, enum ruby_tag_type state,
2592  struct rb_vm_tag *tag, VALUE result)
2593 {
2594  if (state == TAG_NONE) { /* no jumps, result is discarded */
2595  goto vm_loop_start;
2596  }
2597 
2598  rb_ec_raised_reset(ec, RAISED_STACKOVERFLOW | RAISED_NOMEMORY);
2599  while (UNDEF_P(result = vm_exec_handle_exception(ec, state, result))) {
2600  // caught a jump, exec the handler. JIT code in jit_exec_exception()
2601  // may return Qundef to run remaining frames with vm_exec_core().
2602  if (UNDEF_P(result = jit_exec_exception(ec))) {
2603  result = vm_exec_core(ec);
2604  }
2605  vm_loop_start:
2606  VM_ASSERT(ec->tag == tag);
2607  /* when caught `throw`, `tag.state` is set. */
2608  if ((state = tag->state) == TAG_NONE) break;
2609  tag->state = TAG_NONE;
2610  }
2611 
2612  return result;
2613 }
2614 
2615 static inline VALUE
2616 vm_exec_handle_exception(rb_execution_context_t *ec, enum ruby_tag_type state, VALUE errinfo)
2617 {
2618  struct vm_throw_data *err = (struct vm_throw_data *)errinfo;
2619 
2620  for (;;) {
2621  unsigned int i;
2622  const struct iseq_catch_table_entry *entry;
2623  const struct iseq_catch_table *ct;
2624  unsigned long epc, cont_pc, cont_sp;
2625  const rb_iseq_t *catch_iseq;
2626  VALUE type;
2627  const rb_control_frame_t *escape_cfp;
2628 
2629  cont_pc = cont_sp = 0;
2630  catch_iseq = NULL;
2631 
2632  while (ec->cfp->pc == 0 || ec->cfp->iseq == 0) {
2633  if (UNLIKELY(VM_FRAME_TYPE(ec->cfp) == VM_FRAME_MAGIC_CFUNC)) {
2634  EXEC_EVENT_HOOK_AND_POP_FRAME(ec, RUBY_EVENT_C_RETURN, ec->cfp->self,
2635  rb_vm_frame_method_entry(ec->cfp)->def->original_id,
2636  rb_vm_frame_method_entry(ec->cfp)->called_id,
2637  rb_vm_frame_method_entry(ec->cfp)->owner, Qnil);
2638  RUBY_DTRACE_CMETHOD_RETURN_HOOK(ec,
2639  rb_vm_frame_method_entry(ec->cfp)->owner,
2640  rb_vm_frame_method_entry(ec->cfp)->def->original_id);
2641  }
2642  rb_vm_pop_frame(ec);
2643  }
2644 
2645  rb_control_frame_t *const cfp = ec->cfp;
2646  epc = cfp->pc - ISEQ_BODY(cfp->iseq)->iseq_encoded;
2647 
2648  escape_cfp = NULL;
2649  if (state == TAG_BREAK || state == TAG_RETURN) {
2650  escape_cfp = THROW_DATA_CATCH_FRAME(err);
2651 
2652  if (cfp == escape_cfp) {
2653  if (state == TAG_RETURN) {
2654  if (!VM_FRAME_FINISHED_P(cfp)) {
2655  THROW_DATA_CATCH_FRAME_SET(err, cfp + 1);
2656  THROW_DATA_STATE_SET(err, state = TAG_BREAK);
2657  }
2658  else {
2659  ct = ISEQ_BODY(cfp->iseq)->catch_table;
2660  if (ct) for (i = 0; i < ct->size; i++) {
2661  entry = UNALIGNED_MEMBER_PTR(ct, entries[i]);
2662  if (entry->start < epc && entry->end >= epc) {
2663  if (entry->type == CATCH_TYPE_ENSURE) {
2664  catch_iseq = entry->iseq;
2665  cont_pc = entry->cont;
2666  cont_sp = entry->sp;
2667  break;
2668  }
2669  }
2670  }
2671  if (catch_iseq == NULL) {
2672  ec->errinfo = Qnil;
2673  THROW_DATA_CATCH_FRAME_SET(err, cfp + 1);
2674  // cfp == escape_cfp here so calling with cfp_returning_with_value = true
2675  hook_before_rewind(ec, true, state, err);
2676  rb_vm_pop_frame(ec);
2677  return THROW_DATA_VAL(err);
2678  }
2679  }
2680  /* through */
2681  }
2682  else {
2683  /* TAG_BREAK */
2684  *cfp->sp++ = THROW_DATA_VAL(err);
2685  ec->errinfo = Qnil;
2686  return Qundef;
2687  }
2688  }
2689  }
2690 
2691  if (state == TAG_RAISE) {
2692  ct = ISEQ_BODY(cfp->iseq)->catch_table;
2693  if (ct) for (i = 0; i < ct->size; i++) {
2694  entry = UNALIGNED_MEMBER_PTR(ct, entries[i]);
2695  if (entry->start < epc && entry->end >= epc) {
2696 
2697  if (entry->type == CATCH_TYPE_RESCUE ||
2698  entry->type == CATCH_TYPE_ENSURE) {
2699  catch_iseq = entry->iseq;
2700  cont_pc = entry->cont;
2701  cont_sp = entry->sp;
2702  break;
2703  }
2704  }
2705  }
2706  }
2707  else if (state == TAG_RETRY) {
2708  ct = ISEQ_BODY(cfp->iseq)->catch_table;
2709  if (ct) for (i = 0; i < ct->size; i++) {
2710  entry = UNALIGNED_MEMBER_PTR(ct, entries[i]);
2711  if (entry->start < epc && entry->end >= epc) {
2712 
2713  if (entry->type == CATCH_TYPE_ENSURE) {
2714  catch_iseq = entry->iseq;
2715  cont_pc = entry->cont;
2716  cont_sp = entry->sp;
2717  break;
2718  }
2719  else if (entry->type == CATCH_TYPE_RETRY) {
2720  const rb_control_frame_t *escape_cfp;
2721  escape_cfp = THROW_DATA_CATCH_FRAME(err);
2722  if (cfp == escape_cfp) {
2723  cfp->pc = ISEQ_BODY(cfp->iseq)->iseq_encoded + entry->cont;
2724  ec->errinfo = Qnil;
2725  return Qundef;
2726  }
2727  }
2728  }
2729  }
2730  }
2731  else if ((state == TAG_BREAK && !escape_cfp) ||
2732  (state == TAG_REDO) ||
2733  (state == TAG_NEXT)) {
2734  type = (const enum rb_catch_type[TAG_MASK]) {
2735  [TAG_BREAK] = CATCH_TYPE_BREAK,
2736  [TAG_NEXT] = CATCH_TYPE_NEXT,
2737  [TAG_REDO] = CATCH_TYPE_REDO,
2738  /* otherwise = dontcare */
2739  }[state];
2740 
2741  ct = ISEQ_BODY(cfp->iseq)->catch_table;
2742  if (ct) for (i = 0; i < ct->size; i++) {
2743  entry = UNALIGNED_MEMBER_PTR(ct, entries[i]);
2744 
2745  if (entry->start < epc && entry->end >= epc) {
2746  if (entry->type == CATCH_TYPE_ENSURE) {
2747  catch_iseq = entry->iseq;
2748  cont_pc = entry->cont;
2749  cont_sp = entry->sp;
2750  break;
2751  }
2752  else if (entry->type == type) {
2753  cfp->pc = ISEQ_BODY(cfp->iseq)->iseq_encoded + entry->cont;
2754  cfp->sp = vm_base_ptr(cfp) + entry->sp;
2755 
2756  if (state != TAG_REDO) {
2757  *cfp->sp++ = THROW_DATA_VAL(err);
2758  }
2759  ec->errinfo = Qnil;
2760  VM_ASSERT(ec->tag->state == TAG_NONE);
2761  return Qundef;
2762  }
2763  }
2764  }
2765  }
2766  else {
2767  ct = ISEQ_BODY(cfp->iseq)->catch_table;
2768  if (ct) for (i = 0; i < ct->size; i++) {
2769  entry = UNALIGNED_MEMBER_PTR(ct, entries[i]);
2770  if (entry->start < epc && entry->end >= epc) {
2771 
2772  if (entry->type == CATCH_TYPE_ENSURE) {
2773  catch_iseq = entry->iseq;
2774  cont_pc = entry->cont;
2775  cont_sp = entry->sp;
2776  break;
2777  }
2778  }
2779  }
2780  }
2781 
2782  if (catch_iseq != NULL) { /* found catch table */
2783  /* enter catch scope */
2784  const int arg_size = 1;
2785 
2786  rb_iseq_check(catch_iseq);
2787  cfp->sp = vm_base_ptr(cfp) + cont_sp;
2788  cfp->pc = ISEQ_BODY(cfp->iseq)->iseq_encoded + cont_pc;
2789 
2790  /* push block frame */
2791  cfp->sp[0] = (VALUE)err;
2792  vm_push_frame(ec, catch_iseq, VM_FRAME_MAGIC_RESCUE,
2793  cfp->self,
2794  VM_GUARDED_PREV_EP(cfp->ep),
2795  0, /* cref or me */
2796  ISEQ_BODY(catch_iseq)->iseq_encoded,
2797  cfp->sp + arg_size /* push value */,
2798  ISEQ_BODY(catch_iseq)->local_table_size - arg_size,
2799  ISEQ_BODY(catch_iseq)->stack_max);
2800 
2801  state = 0;
2802  ec->tag->state = TAG_NONE;
2803  ec->errinfo = Qnil;
2804 
2805  return Qundef;
2806  }
2807  else {
2808  hook_before_rewind(ec, (cfp == escape_cfp), state, err);
2809 
2810  if (VM_FRAME_FINISHED_P(ec->cfp)) {
2811  rb_vm_pop_frame(ec);
2812  ec->errinfo = (VALUE)err;
2813  ec->tag = ec->tag->prev;
2814  EC_JUMP_TAG(ec, state);
2815  }
2816  else {
2817  rb_vm_pop_frame(ec);
2818  }
2819  }
2820  }
2821 }
2822 
2823 /* misc */
2824 
2825 VALUE
2826 rb_iseq_eval(const rb_iseq_t *iseq)
2827 {
2828  rb_execution_context_t *ec = GET_EC();
2829  VALUE val;
2830  vm_set_top_stack(ec, iseq);
2831  val = vm_exec(ec);
2832  return val;
2833 }
2834 
2835 VALUE
2836 rb_iseq_eval_main(const rb_iseq_t *iseq)
2837 {
2838  rb_execution_context_t *ec = GET_EC();
2839  VALUE val;
2840 
2841  vm_set_main_stack(ec, iseq);
2842  val = vm_exec(ec);
2843  return val;
2844 }
2845 
2846 int
2847 rb_vm_control_frame_id_and_class(const rb_control_frame_t *cfp, ID *idp, ID *called_idp, VALUE *klassp)
2848 {
2849  const rb_callable_method_entry_t *me = rb_vm_frame_method_entry(cfp);
2850 
2851  if (me) {
2852  if (idp) *idp = me->def->original_id;
2853  if (called_idp) *called_idp = me->called_id;
2854  if (klassp) *klassp = me->owner;
2855  return TRUE;
2856  }
2857  else {
2858  return FALSE;
2859  }
2860 }
2861 
2862 int
2863 rb_ec_frame_method_id_and_class(const rb_execution_context_t *ec, ID *idp, ID *called_idp, VALUE *klassp)
2864 {
2865  return rb_vm_control_frame_id_and_class(ec->cfp, idp, called_idp, klassp);
2866 }
2867 
2868 int
2870 {
2871  return rb_ec_frame_method_id_and_class(GET_EC(), idp, 0, klassp);
2872 }
2873 
2874 VALUE
2875 rb_vm_call_cfunc(VALUE recv, VALUE (*func)(VALUE), VALUE arg,
2876  VALUE block_handler, VALUE filename)
2877 {
2878  rb_execution_context_t *ec = GET_EC();
2879  const rb_control_frame_t *reg_cfp = ec->cfp;
2880  const rb_iseq_t *iseq = rb_iseq_new(Qnil, filename, filename, Qnil, 0, ISEQ_TYPE_TOP);
2881  VALUE val;
2882 
2883  vm_push_frame(ec, iseq, VM_FRAME_MAGIC_TOP | VM_ENV_FLAG_LOCAL | VM_FRAME_FLAG_FINISH,
2884  recv, block_handler,
2885  (VALUE)vm_cref_new_toplevel(ec), /* cref or me */
2886  0, reg_cfp->sp, 0, 0);
2887 
2888  val = (*func)(arg);
2889 
2890  rb_vm_pop_frame(ec);
2891  return val;
2892 }
2893 
2894 /* vm */
2895 
2896 void
2897 rb_vm_update_references(void *ptr)
2898 {
2899  if (ptr) {
2900  rb_vm_t *vm = ptr;
2901 
2902  rb_gc_update_tbl_refs(vm->ci_table);
2903  rb_gc_update_tbl_refs(vm->frozen_strings);
2904  vm->mark_object_ary = rb_gc_location(vm->mark_object_ary);
2905  vm->load_path = rb_gc_location(vm->load_path);
2906  vm->load_path_snapshot = rb_gc_location(vm->load_path_snapshot);
2907 
2908  if (vm->load_path_check_cache) {
2909  vm->load_path_check_cache = rb_gc_location(vm->load_path_check_cache);
2910  }
2911 
2912  vm->expanded_load_path = rb_gc_location(vm->expanded_load_path);
2913  vm->loaded_features = rb_gc_location(vm->loaded_features);
2914  vm->loaded_features_snapshot = rb_gc_location(vm->loaded_features_snapshot);
2915  vm->loaded_features_realpaths = rb_gc_location(vm->loaded_features_realpaths);
2916  vm->loaded_features_realpath_map = rb_gc_location(vm->loaded_features_realpath_map);
2917  vm->top_self = rb_gc_location(vm->top_self);
2918  vm->orig_progname = rb_gc_location(vm->orig_progname);
2919 
2920  rb_gc_update_tbl_refs(vm->overloaded_cme_table);
2921 
2922  rb_gc_update_values(RUBY_NSIG, vm->trap_list.cmd);
2923 
2924  if (vm->coverages) {
2925  vm->coverages = rb_gc_location(vm->coverages);
2926  vm->me2counter = rb_gc_location(vm->me2counter);
2927  }
2928  }
2929 }
2930 
2931 void
2932 rb_vm_each_stack_value(void *ptr, void (*cb)(VALUE, void*), void *ctx)
2933 {
2934  if (ptr) {
2935  rb_vm_t *vm = ptr;
2936  rb_ractor_t *r = 0;
2937  ccan_list_for_each(&vm->ractor.set, r, vmlr_node) {
2938  VM_ASSERT(rb_ractor_status_p(r, ractor_blocking) ||
2939  rb_ractor_status_p(r, ractor_running));
2940  if (r->threads.cnt > 0) {
2941  rb_thread_t *th = 0;
2942  ccan_list_for_each(&r->threads.set, th, lt_node) {
2943  VM_ASSERT(th != NULL);
2944  rb_execution_context_t * ec = th->ec;
2945  if (ec->vm_stack) {
2946  VALUE *p = ec->vm_stack;
2947  VALUE *sp = ec->cfp->sp;
2948  while (p < sp) {
2949  if (!RB_SPECIAL_CONST_P(*p)) {
2950  cb(*p, ctx);
2951  }
2952  p++;
2953  }
2954  }
2955  }
2956  }
2957  }
2958  }
2959 }
2960 
2961 static enum rb_id_table_iterator_result
2962 vm_mark_negative_cme(VALUE val, void *dmy)
2963 {
2964  rb_gc_mark(val);
2965  return ID_TABLE_CONTINUE;
2966 }
2967 
2968 void rb_thread_sched_mark_zombies(rb_vm_t *vm);
2969 
2970 void
2971 rb_vm_mark(void *ptr)
2972 {
2973  RUBY_MARK_ENTER("vm");
2974  RUBY_GC_INFO("-------------------------------------------------\n");
2975  if (ptr) {
2976  rb_vm_t *vm = ptr;
2977  rb_ractor_t *r = 0;
2978  long i;
2979 
2980  ccan_list_for_each(&vm->ractor.set, r, vmlr_node) {
2981  // ractor.set only contains blocking or running ractors
2982  VM_ASSERT(rb_ractor_status_p(r, ractor_blocking) ||
2983  rb_ractor_status_p(r, ractor_running));
2984  rb_gc_mark(rb_ractor_self(r));
2985  }
2986 
2987  for (struct global_object_list *list = vm->global_object_list; list; list = list->next) {
2988  rb_gc_mark_maybe(*list->varptr);
2989  }
2990 
2991  rb_gc_mark_movable(vm->mark_object_ary);
2992  rb_gc_mark_movable(vm->load_path);
2993  rb_gc_mark_movable(vm->load_path_snapshot);
2994  rb_gc_mark_movable(vm->load_path_check_cache);
2995  rb_gc_mark_movable(vm->expanded_load_path);
2996  rb_gc_mark_movable(vm->loaded_features);
2997  rb_gc_mark_movable(vm->loaded_features_snapshot);
2998  rb_gc_mark_movable(vm->loaded_features_realpaths);
2999  rb_gc_mark_movable(vm->loaded_features_realpath_map);
3000  rb_gc_mark_movable(vm->top_self);
3001  rb_gc_mark_movable(vm->orig_progname);
3002  rb_gc_mark_movable(vm->coverages);
3003  rb_gc_mark_movable(vm->me2counter);
3004 
3005  if (vm->loading_table) {
3006  rb_mark_tbl(vm->loading_table);
3007  }
3008 
3009  rb_gc_mark_values(RUBY_NSIG, vm->trap_list.cmd);
3010 
3011  rb_id_table_foreach_values(vm->negative_cme_table, vm_mark_negative_cme, NULL);
3012  rb_mark_tbl_no_pin(vm->overloaded_cme_table);
3013  for (i=0; i<VM_GLOBAL_CC_CACHE_TABLE_SIZE; i++) {
3014  const struct rb_callcache *cc = vm->global_cc_cache_table[i];
3015 
3016  if (cc != NULL) {
3017  if (!vm_cc_invalidated_p(cc)) {
3018  rb_gc_mark((VALUE)cc);
3019  }
3020  else {
3021  vm->global_cc_cache_table[i] = NULL;
3022  }
3023  }
3024  }
3025 
3026  rb_thread_sched_mark_zombies(vm);
3027  rb_rjit_mark();
3028  }
3029 
3030  RUBY_MARK_LEAVE("vm");
3031 }
3032 
3033 #undef rb_vm_register_special_exception
3034 void
3035 rb_vm_register_special_exception_str(enum ruby_special_exceptions sp, VALUE cls, VALUE mesg)
3036 {
3037  rb_vm_t *vm = GET_VM();
3038  VALUE exc = rb_exc_new3(cls, rb_obj_freeze(mesg));
3039  OBJ_FREEZE(exc);
3040  ((VALUE *)vm->special_exceptions)[sp] = exc;
3041  rb_vm_register_global_object(exc);
3042 }
3043 
3044 static int
3045 free_loading_table_entry(st_data_t key, st_data_t value, st_data_t arg)
3046 {
3047  xfree((char *)key);
3048  return ST_DELETE;
3049 }
3050 
3051 void rb_free_loaded_features_index(rb_vm_t *vm);
3052 void rb_objspace_free_objects(void *objspace);
3053 
3054 int
3056 {
3057  RUBY_FREE_ENTER("vm");
3058 
3059  if (vm) {
3060  rb_thread_t *th = vm->ractor.main_thread;
3061  VALUE *stack = th->ec->vm_stack;
3062  if (rb_free_at_exit) {
3063  rb_free_encoded_insn_data();
3064  rb_free_global_enc_table();
3065  rb_free_loaded_builtin_table();
3066 
3067  rb_free_shared_fiber_pool();
3068  rb_free_static_symid_str();
3069  rb_free_transcoder_table();
3070  rb_free_vm_opt_tables();
3071  rb_free_warning();
3072  rb_free_rb_global_tbl();
3073  rb_free_loaded_features_index(vm);
3074 
3075  rb_id_table_free(vm->negative_cme_table);
3076  st_free_table(vm->overloaded_cme_table);
3077 
3078  rb_id_table_free(RCLASS(rb_mRubyVMFrozenCore)->m_tbl);
3079 
3080  rb_shape_t *cursor = rb_shape_get_root_shape();
3081  rb_shape_t *end = rb_shape_get_shape_by_id(GET_SHAPE_TREE()->next_shape_id);
3082  while (cursor < end) {
3083  // 0x1 == SINGLE_CHILD_P
3084  if (cursor->edges && !(((uintptr_t)cursor->edges) & 0x1))
3085  rb_id_table_free(cursor->edges);
3086  cursor += 1;
3087  }
3088 
3089  xfree(GET_SHAPE_TREE());
3090 
3091  st_free_table(vm->static_ext_inits);
3092 
3093  rb_vm_postponed_job_free();
3094 
3095  rb_id_table_free(vm->constant_cache);
3096  st_free_table(vm->unused_block_warning_table);
3097 
3098  if (th) {
3099  xfree(th->nt);
3100  th->nt = NULL;
3101  }
3102 
3103 #ifndef HAVE_SETPROCTITLE
3104  ruby_free_proctitle();
3105 #endif
3106  }
3107  else {
3108  if (th) {
3109  rb_fiber_reset_root_local_storage(th);
3110  thread_free(th);
3111  }
3112  }
3113 
3114  struct rb_objspace *objspace = vm->gc.objspace;
3115 
3116  rb_vm_living_threads_init(vm);
3117  ruby_vm_run_at_exit_hooks(vm);
3118  if (vm->loading_table) {
3119  st_foreach(vm->loading_table, free_loading_table_entry, 0);
3120  st_free_table(vm->loading_table);
3121  vm->loading_table = 0;
3122  }
3123  if (vm->ci_table) {
3124  st_free_table(vm->ci_table);
3125  vm->ci_table = NULL;
3126  }
3127  if (vm->frozen_strings) {
3128  st_free_table(vm->frozen_strings);
3129  vm->frozen_strings = 0;
3130  }
3131  RB_ALTSTACK_FREE(vm->main_altstack);
3132 
3133  struct global_object_list *next;
3134  for (struct global_object_list *list = vm->global_object_list; list; list = next) {
3135  next = list->next;
3136  xfree(list);
3137  }
3138 
3139  if (objspace) {
3140  if (rb_free_at_exit) {
3141  rb_objspace_free_objects(objspace);
3142  rb_free_generic_iv_tbl_();
3143  rb_free_default_rand_key();
3144  if (th && vm->fork_gen == 0) {
3145  /* If we have forked, main_thread may not be the initial thread */
3146  xfree(stack);
3147  ruby_mimfree(th);
3148  }
3149  }
3150  rb_objspace_free(objspace);
3151  }
3152  rb_native_mutex_destroy(&vm->workqueue_lock);
3153  /* after freeing objspace, you *can't* use ruby_xfree() */
3154  ruby_mimfree(vm);
3155  ruby_current_vm_ptr = NULL;
3156  }
3157  RUBY_FREE_LEAVE("vm");
3158  return 0;
3159 }
3160 
3161 size_t rb_vm_memsize_waiting_fds(struct ccan_list_head *waiting_fds); // thread.c
3162 size_t rb_vm_memsize_workqueue(struct ccan_list_head *workqueue); // vm_trace.c
3163 
3164 // Used for VM memsize reporting. Returns the size of the at_exit list by
3165 // looping through the linked list and adding up the size of the structs.
3166 static enum rb_id_table_iterator_result
3167 vm_memsize_constant_cache_i(ID id, VALUE ics, void *size)
3168 {
3169  *((size_t *) size) += rb_st_memsize((st_table *) ics);
3170  return ID_TABLE_CONTINUE;
3171 }
3172 
3173 // Returns a size_t representing the memory footprint of the VM's constant
3174 // cache, which is the memsize of the table as well as the memsize of all of the
3175 // nested tables.
3176 static size_t
3177 vm_memsize_constant_cache(void)
3178 {
3179  rb_vm_t *vm = GET_VM();
3180  size_t size = rb_id_table_memsize(vm->constant_cache);
3181 
3182  rb_id_table_foreach(vm->constant_cache, vm_memsize_constant_cache_i, &size);
3183  return size;
3184 }
3185 
3186 static size_t
3187 vm_memsize_at_exit_list(rb_at_exit_list *at_exit)
3188 {
3189  size_t size = 0;
3190 
3191  while (at_exit) {
3192  size += sizeof(rb_at_exit_list);
3193  at_exit = at_exit->next;
3194  }
3195 
3196  return size;
3197 }
3198 
3199 // Used for VM memsize reporting. Returns the size of the builtin function
3200 // table if it has been defined.
3201 static size_t
3202 vm_memsize_builtin_function_table(const struct rb_builtin_function *builtin_function_table)
3203 {
3204  return builtin_function_table == NULL ? 0 : sizeof(struct rb_builtin_function);
3205 }
3206 
3207 // Reports the memsize of the VM struct object and the structs that are
3208 // associated with it.
3209 static size_t
3210 vm_memsize(const void *ptr)
3211 {
3212  rb_vm_t *vm = GET_VM();
3213 
3214  return (
3215  sizeof(rb_vm_t) +
3216  rb_vm_memsize_waiting_fds(&vm->waiting_fds) +
3217  rb_st_memsize(vm->loaded_features_index) +
3218  rb_st_memsize(vm->loading_table) +
3219  rb_vm_memsize_postponed_job_queue() +
3220  rb_vm_memsize_workqueue(&vm->workqueue) +
3221  vm_memsize_at_exit_list(vm->at_exit) +
3222  rb_st_memsize(vm->ci_table) +
3223  rb_st_memsize(vm->frozen_strings) +
3224  vm_memsize_builtin_function_table(vm->builtin_function_table) +
3225  rb_id_table_memsize(vm->negative_cme_table) +
3226  rb_st_memsize(vm->overloaded_cme_table) +
3227  vm_memsize_constant_cache() +
3228  GET_SHAPE_TREE()->cache_size * sizeof(redblack_node_t)
3229  );
3230 
3231  // TODO
3232  // struct { struct ccan_list_head set; } ractor;
3233  // void *main_altstack; #ifdef USE_SIGALTSTACK
3234  // struct rb_objspace *objspace;
3235 }
3236 
3237 static const rb_data_type_t vm_data_type = {
3238  "VM",
3239  {0, 0, vm_memsize,},
3240  0, 0, RUBY_TYPED_FREE_IMMEDIATELY
3241 };
3242 
3243 
3244 static VALUE
3245 vm_default_params(void)
3246 {
3247  rb_vm_t *vm = GET_VM();
3248  VALUE result = rb_hash_new_with_size(4);
3249 #define SET(name) rb_hash_aset(result, ID2SYM(rb_intern(#name)), SIZET2NUM(vm->default_params.name));
3250  SET(thread_vm_stack_size);
3251  SET(thread_machine_stack_size);
3252  SET(fiber_vm_stack_size);
3253  SET(fiber_machine_stack_size);
3254 #undef SET
3255  rb_obj_freeze(result);
3256  return result;
3257 }
3258 
3259 static size_t
3260 get_param(const char *name, size_t default_value, size_t min_value)
3261 {
3262  const char *envval;
3263  size_t result = default_value;
3264  if ((envval = getenv(name)) != 0) {
3265  long val = atol(envval);
3266  if (val < (long)min_value) {
3267  val = (long)min_value;
3268  }
3269  result = (size_t)(((val -1 + RUBY_VM_SIZE_ALIGN) / RUBY_VM_SIZE_ALIGN) * RUBY_VM_SIZE_ALIGN);
3270  }
3271  if (0) ruby_debug_printf("%s: %"PRIuSIZE"\n", name, result); /* debug print */
3272 
3273  return result;
3274 }
3275 
3276 static void
3277 check_machine_stack_size(size_t *sizep)
3278 {
3279 #ifdef PTHREAD_STACK_MIN
3280  size_t size = *sizep;
3281 #endif
3282 
3283 #ifdef PTHREAD_STACK_MIN
3284  if (size < (size_t)PTHREAD_STACK_MIN) {
3285  *sizep = (size_t)PTHREAD_STACK_MIN * 2;
3286  }
3287 #endif
3288 }
3289 
3290 static void
3291 vm_default_params_setup(rb_vm_t *vm)
3292 {
3293  vm->default_params.thread_vm_stack_size =
3294  get_param("RUBY_THREAD_VM_STACK_SIZE",
3295  RUBY_VM_THREAD_VM_STACK_SIZE,
3296  RUBY_VM_THREAD_VM_STACK_SIZE_MIN);
3297 
3298  vm->default_params.thread_machine_stack_size =
3299  get_param("RUBY_THREAD_MACHINE_STACK_SIZE",
3300  RUBY_VM_THREAD_MACHINE_STACK_SIZE,
3301  RUBY_VM_THREAD_MACHINE_STACK_SIZE_MIN);
3302 
3303  vm->default_params.fiber_vm_stack_size =
3304  get_param("RUBY_FIBER_VM_STACK_SIZE",
3305  RUBY_VM_FIBER_VM_STACK_SIZE,
3306  RUBY_VM_FIBER_VM_STACK_SIZE_MIN);
3307 
3308  vm->default_params.fiber_machine_stack_size =
3309  get_param("RUBY_FIBER_MACHINE_STACK_SIZE",
3310  RUBY_VM_FIBER_MACHINE_STACK_SIZE,
3311  RUBY_VM_FIBER_MACHINE_STACK_SIZE_MIN);
3312 
3313  /* environment dependent check */
3314  check_machine_stack_size(&vm->default_params.thread_machine_stack_size);
3315  check_machine_stack_size(&vm->default_params.fiber_machine_stack_size);
3316 }
3317 
3318 static void
3319 vm_init2(rb_vm_t *vm)
3320 {
3321  rb_vm_living_threads_init(vm);
3322  vm->thread_report_on_exception = 1;
3323  vm->src_encoding_index = -1;
3324 
3325  vm_default_params_setup(vm);
3326 }
3327 
3328 void
3329 rb_execution_context_update(rb_execution_context_t *ec)
3330 {
3331  /* update VM stack */
3332  if (ec->vm_stack) {
3333  long i;
3334  VM_ASSERT(ec->cfp);
3335  VALUE *p = ec->vm_stack;
3336  VALUE *sp = ec->cfp->sp;
3337  rb_control_frame_t *cfp = ec->cfp;
3338  rb_control_frame_t *limit_cfp = (void *)(ec->vm_stack + ec->vm_stack_size);
3339 
3340  for (i = 0; i < (long)(sp - p); i++) {
3341  VALUE ref = p[i];
3342  VALUE update = rb_gc_location(ref);
3343  if (ref != update) {
3344  p[i] = update;
3345  }
3346  }
3347 
3348  while (cfp != limit_cfp) {
3349  const VALUE *ep = cfp->ep;
3350  cfp->self = rb_gc_location(cfp->self);
3351  cfp->iseq = (rb_iseq_t *)rb_gc_location((VALUE)cfp->iseq);
3352  cfp->block_code = (void *)rb_gc_location((VALUE)cfp->block_code);
3353 
3354  if (!VM_ENV_LOCAL_P(ep)) {
3355  const VALUE *prev_ep = VM_ENV_PREV_EP(ep);
3356  if (VM_ENV_FLAGS(prev_ep, VM_ENV_FLAG_ESCAPED)) {
3357  VM_FORCE_WRITE(&prev_ep[VM_ENV_DATA_INDEX_ENV], rb_gc_location(prev_ep[VM_ENV_DATA_INDEX_ENV]));
3358  }
3359 
3360  if (VM_ENV_FLAGS(ep, VM_ENV_FLAG_ESCAPED)) {
3361  VM_FORCE_WRITE(&ep[VM_ENV_DATA_INDEX_ENV], rb_gc_location(ep[VM_ENV_DATA_INDEX_ENV]));
3362  VM_FORCE_WRITE(&ep[VM_ENV_DATA_INDEX_ME_CREF], rb_gc_location(ep[VM_ENV_DATA_INDEX_ME_CREF]));
3363  }
3364  }
3365 
3366  cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp);
3367  }
3368  }
3369 
3370  ec->storage = rb_gc_location(ec->storage);
3371 }
3372 
3373 static enum rb_id_table_iterator_result
3374 mark_local_storage_i(VALUE local, void *data)
3375 {
3376  rb_gc_mark(local);
3377  return ID_TABLE_CONTINUE;
3378 }
3379 
3380 void
3381 rb_execution_context_mark(const rb_execution_context_t *ec)
3382 {
3383  /* mark VM stack */
3384  if (ec->vm_stack) {
3385  VM_ASSERT(ec->cfp);
3386  VALUE *p = ec->vm_stack;
3387  VALUE *sp = ec->cfp->sp;
3388  rb_control_frame_t *cfp = ec->cfp;
3389  rb_control_frame_t *limit_cfp = (void *)(ec->vm_stack + ec->vm_stack_size);
3390 
3391  VM_ASSERT(sp == ec->cfp->sp);
3392  rb_gc_mark_vm_stack_values((long)(sp - p), p);
3393 
3394  while (cfp != limit_cfp) {
3395  const VALUE *ep = cfp->ep;
3396  VM_ASSERT(!!VM_ENV_FLAGS(ep, VM_ENV_FLAG_ESCAPED) == vm_ep_in_heap_p_(ec, ep));
3397 
3398  if (VM_FRAME_TYPE(cfp) != VM_FRAME_MAGIC_DUMMY) {
3399  rb_gc_mark_movable(cfp->self);
3400  rb_gc_mark_movable((VALUE)cfp->iseq);
3401  rb_gc_mark_movable((VALUE)cfp->block_code);
3402 
3403  if (!VM_ENV_LOCAL_P(ep)) {
3404  const VALUE *prev_ep = VM_ENV_PREV_EP(ep);
3405  if (VM_ENV_FLAGS(prev_ep, VM_ENV_FLAG_ESCAPED)) {
3406  rb_gc_mark_movable(prev_ep[VM_ENV_DATA_INDEX_ENV]);
3407  }
3408 
3409  if (VM_ENV_FLAGS(ep, VM_ENV_FLAG_ESCAPED)) {
3410  rb_gc_mark_movable(ep[VM_ENV_DATA_INDEX_ENV]);
3411  rb_gc_mark(ep[VM_ENV_DATA_INDEX_ME_CREF]);
3412  }
3413  }
3414  }
3415 
3416  cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp);
3417  }
3418  }
3419 
3420  /* mark machine stack */
3421  if (ec->machine.stack_start && ec->machine.stack_end &&
3422  ec != GET_EC() /* marked for current ec at the first stage of marking */
3423  ) {
3424  rb_gc_mark_machine_context(ec);
3425  }
3426 
3427  rb_gc_mark(ec->errinfo);
3428  rb_gc_mark(ec->root_svar);
3429  if (ec->local_storage) {
3430  rb_id_table_foreach_values(ec->local_storage, mark_local_storage_i, NULL);
3431  }
3432  rb_gc_mark(ec->local_storage_recursive_hash);
3433  rb_gc_mark(ec->local_storage_recursive_hash_for_trace);
3434  rb_gc_mark(ec->private_const_reference);
3435 
3436  rb_gc_mark_movable(ec->storage);
3437 }
3438 
3439 void rb_fiber_mark_self(rb_fiber_t *fib);
3440 void rb_fiber_update_self(rb_fiber_t *fib);
3441 void rb_threadptr_root_fiber_setup(rb_thread_t *th);
3442 void rb_threadptr_root_fiber_release(rb_thread_t *th);
3443 
3444 static void
3445 thread_compact(void *ptr)
3446 {
3447  rb_thread_t *th = ptr;
3448 
3449  th->self = rb_gc_location(th->self);
3450 
3451  if (!th->root_fiber) {
3452  rb_execution_context_update(th->ec);
3453  }
3454 }
3455 
3456 static void
3457 thread_mark(void *ptr)
3458 {
3459  rb_thread_t *th = ptr;
3460  RUBY_MARK_ENTER("thread");
3461  rb_fiber_mark_self(th->ec->fiber_ptr);
3462 
3463  /* mark ruby objects */
3464  switch (th->invoke_type) {
3465  case thread_invoke_type_proc:
3466  case thread_invoke_type_ractor_proc:
3467  rb_gc_mark(th->invoke_arg.proc.proc);
3468  rb_gc_mark(th->invoke_arg.proc.args);
3469  break;
3470  case thread_invoke_type_func:
3471  rb_gc_mark_maybe((VALUE)th->invoke_arg.func.arg);
3472  break;
3473  default:
3474  break;
3475  }
3476 
3477  rb_gc_mark(rb_ractor_self(th->ractor));
3478  rb_gc_mark(th->thgroup);
3479  rb_gc_mark(th->value);
3480  rb_gc_mark(th->pending_interrupt_queue);
3481  rb_gc_mark(th->pending_interrupt_mask_stack);
3482  rb_gc_mark(th->top_self);
3483  rb_gc_mark(th->top_wrapper);
3484  if (th->root_fiber) rb_fiber_mark_self(th->root_fiber);
3485 
3486  RUBY_ASSERT(th->ec == rb_fiberptr_get_ec(th->ec->fiber_ptr));
3487  rb_gc_mark(th->stat_insn_usage);
3488  rb_gc_mark(th->last_status);
3489  rb_gc_mark(th->locking_mutex);
3490  rb_gc_mark(th->name);
3491 
3492  rb_gc_mark(th->scheduler);
3493 
3494  RUBY_MARK_LEAVE("thread");
3495 }
3496 
3497 void rb_threadptr_sched_free(rb_thread_t *th); // thread_*.c
3498 
3499 static void
3500 thread_free(void *ptr)
3501 {
3502  rb_thread_t *th = ptr;
3503  RUBY_FREE_ENTER("thread");
3504 
3505  rb_threadptr_sched_free(th);
3506 
3507  if (th->locking_mutex != Qfalse) {
3508  rb_bug("thread_free: locking_mutex must be NULL (%p:%p)", (void *)th, (void *)th->locking_mutex);
3509  }
3510  if (th->keeping_mutexes != NULL) {
3511  rb_bug("thread_free: keeping_mutexes must be NULL (%p:%p)", (void *)th, (void *)th->keeping_mutexes);
3512  }
3513 
3514  ruby_xfree(th->specific_storage);
3515 
3516  rb_threadptr_root_fiber_release(th);
3517 
3518  if (th->vm && th->vm->ractor.main_thread == th) {
3519  RUBY_GC_INFO("MRI main thread\n");
3520  }
3521  else {
3522  // ruby_xfree(th->nt);
3523  // TODO: MN system collect nt, but without MN system it should be freed here.
3524  ruby_xfree(th);
3525  }
3526 
3527  RUBY_FREE_LEAVE("thread");
3528 }
3529 
3530 static size_t
3531 thread_memsize(const void *ptr)
3532 {
3533  const rb_thread_t *th = ptr;
3534  size_t size = sizeof(rb_thread_t);
3535 
3536  if (!th->root_fiber) {
3537  size += th->ec->vm_stack_size * sizeof(VALUE);
3538  }
3539  if (th->ec->local_storage) {
3540  size += rb_id_table_memsize(th->ec->local_storage);
3541  }
3542  return size;
3543 }
3544 
3545 #define thread_data_type ruby_threadptr_data_type
3546 const rb_data_type_t ruby_threadptr_data_type = {
3547  "VM/thread",
3548  {
3549  thread_mark,
3550  thread_free,
3551  thread_memsize,
3552  thread_compact,
3553  },
3554  0, 0, RUBY_TYPED_FREE_IMMEDIATELY
3555 };
3556 
3557 VALUE
3558 rb_obj_is_thread(VALUE obj)
3559 {
3560  return RBOOL(rb_typeddata_is_kind_of(obj, &thread_data_type));
3561 }
3562 
3563 static VALUE
3564 thread_alloc(VALUE klass)
3565 {
3566  rb_thread_t *th;
3567  return TypedData_Make_Struct(klass, rb_thread_t, &thread_data_type, th);
3568 }
3569 
3570 inline void
3571 rb_ec_set_vm_stack(rb_execution_context_t *ec, VALUE *stack, size_t size)
3572 {
3573  ec->vm_stack = stack;
3574  ec->vm_stack_size = size;
3575 }
3576 
3577 void
3578 rb_ec_initialize_vm_stack(rb_execution_context_t *ec, VALUE *stack, size_t size)
3579 {
3580  rb_ec_set_vm_stack(ec, stack, size);
3581 
3582 #if VM_CHECK_MODE > 0
3583  MEMZERO(stack, VALUE, size); // malloc memory could have the VM canary in it
3584 #endif
3585 
3586  ec->cfp = (void *)(ec->vm_stack + ec->vm_stack_size);
3587 
3588  vm_push_frame(ec,
3589  NULL /* dummy iseq */,
3590  VM_FRAME_MAGIC_DUMMY | VM_ENV_FLAG_LOCAL | VM_FRAME_FLAG_FINISH | VM_FRAME_FLAG_CFRAME /* dummy frame */,
3591  Qnil /* dummy self */, VM_BLOCK_HANDLER_NONE /* dummy block ptr */,
3592  0 /* dummy cref/me */,
3593  0 /* dummy pc */, ec->vm_stack, 0, 0
3594  );
3595 }
3596 
3597 void
3598 rb_ec_clear_vm_stack(rb_execution_context_t *ec)
3599 {
3600  rb_ec_set_vm_stack(ec, NULL, 0);
3601 
3602  // Avoid dangling pointers:
3603  ec->cfp = NULL;
3604 }
3605 
3606 static void
3607 th_init(rb_thread_t *th, VALUE self, rb_vm_t *vm)
3608 {
3609  th->self = self;
3610 
3611  rb_threadptr_root_fiber_setup(th);
3612 
3613  /* All threads are blocking until a non-blocking fiber is scheduled */
3614  th->blocking = 1;
3615  th->scheduler = Qnil;
3616 
3617  if (self == 0) {
3618  size_t size = vm->default_params.thread_vm_stack_size / sizeof(VALUE);
3619  rb_ec_initialize_vm_stack(th->ec, ALLOC_N(VALUE, size), size);
3620  }
3621  else {
3622  VM_ASSERT(th->ec->cfp == NULL);
3623  VM_ASSERT(th->ec->vm_stack == NULL);
3624  VM_ASSERT(th->ec->vm_stack_size == 0);
3625  }
3626 
3627  th->status = THREAD_RUNNABLE;
3628  th->last_status = Qnil;
3629  th->top_wrapper = 0;
3630  th->top_self = vm->top_self; // 0 while self == 0
3631  th->value = Qundef;
3632 
3633  th->ec->errinfo = Qnil;
3634  th->ec->root_svar = Qfalse;
3635  th->ec->local_storage_recursive_hash = Qnil;
3636  th->ec->local_storage_recursive_hash_for_trace = Qnil;
3637 
3638  th->ec->storage = Qnil;
3639 
3640 #if OPT_CALL_THREADED_CODE
3641  th->retval = Qundef;
3642 #endif
3643  th->name = Qnil;
3644  th->report_on_exception = vm->thread_report_on_exception;
3645  th->ext_config.ractor_safe = true;
3646 
3647 #if USE_RUBY_DEBUG_LOG
3648  static rb_atomic_t thread_serial = 1;
3649  th->serial = RUBY_ATOMIC_FETCH_ADD(thread_serial, 1);
3650 
3651  RUBY_DEBUG_LOG("th:%u", th->serial);
3652 #endif
3653 }
3654 
3655 VALUE
3656 rb_thread_alloc(VALUE klass)
3657 {
3658  VALUE self = thread_alloc(klass);
3659  rb_thread_t *target_th = rb_thread_ptr(self);
3660  target_th->ractor = GET_RACTOR();
3661  th_init(target_th, self, target_th->vm = GET_VM());
3662  return self;
3663 }
3664 
3665 #define REWIND_CFP(expr) do { \
3666  rb_execution_context_t *ec__ = GET_EC(); \
3667  VALUE *const curr_sp = (ec__->cfp++)->sp; \
3668  VALUE *const saved_sp = ec__->cfp->sp; \
3669  ec__->cfp->sp = curr_sp; \
3670  expr; \
3671  (ec__->cfp--)->sp = saved_sp; \
3672 } while (0)
3673 
3674 static VALUE
3675 m_core_set_method_alias(VALUE self, VALUE cbase, VALUE sym1, VALUE sym2)
3676 {
3677  REWIND_CFP({
3678  rb_alias(cbase, SYM2ID(sym1), SYM2ID(sym2));
3679  });
3680  return Qnil;
3681 }
3682 
3683 static VALUE
3684 m_core_set_variable_alias(VALUE self, VALUE sym1, VALUE sym2)
3685 {
3686  REWIND_CFP({
3687  rb_alias_variable(SYM2ID(sym1), SYM2ID(sym2));
3688  });
3689  return Qnil;
3690 }
3691 
3692 static VALUE
3693 m_core_undef_method(VALUE self, VALUE cbase, VALUE sym)
3694 {
3695  REWIND_CFP({
3696  ID mid = SYM2ID(sym);
3697  rb_undef(cbase, mid);
3698  rb_clear_method_cache(self, mid);
3699  });
3700  return Qnil;
3701 }
3702 
3703 static VALUE
3704 m_core_set_postexe(VALUE self)
3705 {
3706  rb_set_end_proc(rb_call_end_proc, rb_block_proc());
3707  return Qnil;
3708 }
3709 
3710 static VALUE core_hash_merge_kwd(VALUE hash, VALUE kw);
3711 
3712 static VALUE
3713 core_hash_merge(VALUE hash, long argc, const VALUE *argv)
3714 {
3715  Check_Type(hash, T_HASH);
3716  VM_ASSERT(argc % 2 == 0);
3717  rb_hash_bulk_insert(argc, argv, hash);
3718  return hash;
3719 }
3720 
3721 static VALUE
3722 m_core_hash_merge_ptr(int argc, VALUE *argv, VALUE recv)
3723 {
3724  VALUE hash = argv[0];
3725 
3726  REWIND_CFP(hash = core_hash_merge(hash, argc-1, argv+1));
3727 
3728  return hash;
3729 }
3730 
3731 static int
3732 kwmerge_i(VALUE key, VALUE value, VALUE hash)
3733 {
3734  rb_hash_aset(hash, key, value);
3735  return ST_CONTINUE;
3736 }
3737 
3738 static VALUE
3739 m_core_hash_merge_kwd(VALUE recv, VALUE hash, VALUE kw)
3740 {
3741  if (!NIL_P(kw)) {
3742  REWIND_CFP(hash = core_hash_merge_kwd(hash, kw));
3743  }
3744  return hash;
3745 }
3746 
3747 static VALUE
3748 m_core_make_shareable(VALUE recv, VALUE obj)
3749 {
3750  return rb_ractor_make_shareable(obj);
3751 }
3752 
3753 static VALUE
3754 m_core_make_shareable_copy(VALUE recv, VALUE obj)
3755 {
3756  return rb_ractor_make_shareable_copy(obj);
3757 }
3758 
3759 static VALUE
3760 m_core_ensure_shareable(VALUE recv, VALUE obj, VALUE name)
3761 {
3762  return rb_ractor_ensure_shareable(obj, name);
3763 }
3764 
3765 static VALUE
3766 core_hash_merge_kwd(VALUE hash, VALUE kw)
3767 {
3768  rb_hash_foreach(rb_to_hash_type(kw), kwmerge_i, hash);
3769  return hash;
3770 }
3771 
3772 extern VALUE *rb_gc_stack_start;
3773 extern size_t rb_gc_stack_maxsize;
3774 
3775 /* debug functions */
3776 
3777 /* :nodoc: */
3778 static VALUE
3779 sdr(VALUE self)
3780 {
3781  rb_vm_bugreport(NULL, stderr);
3782  return Qnil;
3783 }
3784 
3785 /* :nodoc: */
3786 static VALUE
3787 nsdr(VALUE self)
3788 {
3789  VALUE ary = rb_ary_new();
3790 #ifdef HAVE_BACKTRACE
3791 #include <execinfo.h>
3792 #define MAX_NATIVE_TRACE 1024
3793  static void *trace[MAX_NATIVE_TRACE];
3794  int n = (int)backtrace(trace, MAX_NATIVE_TRACE);
3795  char **syms = backtrace_symbols(trace, n);
3796  int i;
3797 
3798  if (syms == 0) {
3799  rb_memerror();
3800  }
3801 
3802  for (i=0; i<n; i++) {
3803  rb_ary_push(ary, rb_str_new2(syms[i]));
3804  }
3805  free(syms); /* OK */
3806 #endif
3807  return ary;
3808 }
3809 
3810 #if VM_COLLECT_USAGE_DETAILS
3811 static VALUE usage_analysis_insn_start(VALUE self);
3812 static VALUE usage_analysis_operand_start(VALUE self);
3813 static VALUE usage_analysis_register_start(VALUE self);
3814 static VALUE usage_analysis_insn_stop(VALUE self);
3815 static VALUE usage_analysis_operand_stop(VALUE self);
3816 static VALUE usage_analysis_register_stop(VALUE self);
3817 static VALUE usage_analysis_insn_running(VALUE self);
3818 static VALUE usage_analysis_operand_running(VALUE self);
3819 static VALUE usage_analysis_register_running(VALUE self);
3820 static VALUE usage_analysis_insn_clear(VALUE self);
3821 static VALUE usage_analysis_operand_clear(VALUE self);
3822 static VALUE usage_analysis_register_clear(VALUE self);
3823 #endif
3824 
3825 static VALUE
3826 f_raise(int c, VALUE *v, VALUE _)
3827 {
3828  return rb_f_raise(c, v);
3829 }
3830 
3831 static VALUE
3832 f_proc(VALUE _)
3833 {
3834  return rb_block_proc();
3835 }
3836 
3837 static VALUE
3838 f_lambda(VALUE _)
3839 {
3840  return rb_block_lambda();
3841 }
3842 
3843 static VALUE
3844 f_sprintf(int c, const VALUE *v, VALUE _)
3845 {
3846  return rb_f_sprintf(c, v);
3847 }
3848 
3849 /* :nodoc: */
3850 static VALUE
3851 vm_mtbl(VALUE self, VALUE obj, VALUE sym)
3852 {
3853  vm_mtbl_dump(CLASS_OF(obj), RTEST(sym) ? SYM2ID(sym) : 0);
3854  return Qnil;
3855 }
3856 
3857 /* :nodoc: */
3858 static VALUE
3859 vm_mtbl2(VALUE self, VALUE obj, VALUE sym)
3860 {
3861  vm_mtbl_dump(obj, RTEST(sym) ? SYM2ID(sym) : 0);
3862  return Qnil;
3863 }
3864 
3865 /*
3866  * call-seq:
3867  * RubyVM.keep_script_lines -> true or false
3868  *
3869  * Return current +keep_script_lines+ status. Now it only returns
3870  * +true+ of +false+, but it can return other objects in future.
3871  *
3872  * Note that this is an API for ruby internal use, debugging,
3873  * and research. Do not use this for any other purpose.
3874  * The compatibility is not guaranteed.
3875  */
3876 static VALUE
3877 vm_keep_script_lines(VALUE self)
3878 {
3879  return RBOOL(ruby_vm_keep_script_lines);
3880 }
3881 
3882 /*
3883  * call-seq:
3884  * RubyVM.keep_script_lines = true / false
3885  *
3886  * It set +keep_script_lines+ flag. If the flag is set, all
3887  * loaded scripts are recorded in a interpreter process.
3888  *
3889  * Note that this is an API for ruby internal use, debugging,
3890  * and research. Do not use this for any other purpose.
3891  * The compatibility is not guaranteed.
3892  */
3893 static VALUE
3894 vm_keep_script_lines_set(VALUE self, VALUE flags)
3895 {
3896  ruby_vm_keep_script_lines = RTEST(flags);
3897  return flags;
3898 }
3899 
3900 void
3901 Init_VM(void)
3902 {
3903  VALUE opts;
3904  VALUE klass;
3905  VALUE fcore;
3906 
3907  /*
3908  * Document-class: RubyVM
3909  *
3910  * The RubyVM module only exists on MRI. +RubyVM+ is not defined in
3911  * other Ruby implementations such as JRuby and TruffleRuby.
3912  *
3913  * The RubyVM module provides some access to MRI internals.
3914  * This module is for very limited purposes, such as debugging,
3915  * prototyping, and research. Normal users must not use it.
3916  * This module is not portable between Ruby implementations.
3917  */
3918  rb_cRubyVM = rb_define_class("RubyVM", rb_cObject);
3919  rb_undef_alloc_func(rb_cRubyVM);
3920  rb_undef_method(CLASS_OF(rb_cRubyVM), "new");
3921  rb_define_singleton_method(rb_cRubyVM, "stat", vm_stat, -1);
3922  rb_define_singleton_method(rb_cRubyVM, "keep_script_lines", vm_keep_script_lines, 0);
3923  rb_define_singleton_method(rb_cRubyVM, "keep_script_lines=", vm_keep_script_lines_set, 1);
3924 
3925 #if USE_DEBUG_COUNTER
3926  rb_define_singleton_method(rb_cRubyVM, "reset_debug_counters", rb_debug_counter_reset, 0);
3927  rb_define_singleton_method(rb_cRubyVM, "show_debug_counters", rb_debug_counter_show, 0);
3928 #endif
3929 
3930  /* FrozenCore (hidden) */
3931  fcore = rb_class_new(rb_cBasicObject);
3932  rb_set_class_path(fcore, rb_cRubyVM, "FrozenCore");
3933  rb_vm_register_global_object(rb_class_path_cached(fcore));
3934  RBASIC(fcore)->flags = T_ICLASS;
3935  klass = rb_singleton_class(fcore);
3936  rb_define_method_id(klass, id_core_set_method_alias, m_core_set_method_alias, 3);
3937  rb_define_method_id(klass, id_core_set_variable_alias, m_core_set_variable_alias, 2);
3938  rb_define_method_id(klass, id_core_undef_method, m_core_undef_method, 2);
3939  rb_define_method_id(klass, id_core_set_postexe, m_core_set_postexe, 0);
3940  rb_define_method_id(klass, id_core_hash_merge_ptr, m_core_hash_merge_ptr, -1);
3941  rb_define_method_id(klass, id_core_hash_merge_kwd, m_core_hash_merge_kwd, 2);
3942  rb_define_method_id(klass, id_core_raise, f_raise, -1);
3943  rb_define_method_id(klass, id_core_sprintf, f_sprintf, -1);
3944  rb_define_method_id(klass, idProc, f_proc, 0);
3945  rb_define_method_id(klass, idLambda, f_lambda, 0);
3946  rb_define_method(klass, "make_shareable", m_core_make_shareable, 1);
3947  rb_define_method(klass, "make_shareable_copy", m_core_make_shareable_copy, 1);
3948  rb_define_method(klass, "ensure_shareable", m_core_ensure_shareable, 2);
3949  rb_obj_freeze(fcore);
3950  RBASIC_CLEAR_CLASS(klass);
3951  rb_obj_freeze(klass);
3952  rb_vm_register_global_object(fcore);
3953  rb_mRubyVMFrozenCore = fcore;
3954 
3955  /*
3956  * Document-class: Thread
3957  *
3958  * Threads are the Ruby implementation for a concurrent programming model.
3959  *
3960  * Programs that require multiple threads of execution are a perfect
3961  * candidate for Ruby's Thread class.
3962  *
3963  * For example, we can create a new thread separate from the main thread's
3964  * execution using ::new.
3965  *
3966  * thr = Thread.new { puts "What's the big deal" }
3967  *
3968  * Then we are able to pause the execution of the main thread and allow
3969  * our new thread to finish, using #join:
3970  *
3971  * thr.join #=> "What's the big deal"
3972  *
3973  * If we don't call +thr.join+ before the main thread terminates, then all
3974  * other threads including +thr+ will be killed.
3975  *
3976  * Alternatively, you can use an array for handling multiple threads at
3977  * once, like in the following example:
3978  *
3979  * threads = []
3980  * threads << Thread.new { puts "What's the big deal" }
3981  * threads << Thread.new { 3.times { puts "Threads are fun!" } }
3982  *
3983  * After creating a few threads we wait for them all to finish
3984  * consecutively.
3985  *
3986  * threads.each { |thr| thr.join }
3987  *
3988  * To retrieve the last value of a thread, use #value
3989  *
3990  * thr = Thread.new { sleep 1; "Useful value" }
3991  * thr.value #=> "Useful value"
3992  *
3993  * === Thread initialization
3994  *
3995  * In order to create new threads, Ruby provides ::new, ::start, and
3996  * ::fork. A block must be provided with each of these methods, otherwise
3997  * a ThreadError will be raised.
3998  *
3999  * When subclassing the Thread class, the +initialize+ method of your
4000  * subclass will be ignored by ::start and ::fork. Otherwise, be sure to
4001  * call super in your +initialize+ method.
4002  *
4003  * === Thread termination
4004  *
4005  * For terminating threads, Ruby provides a variety of ways to do this.
4006  *
4007  * The class method ::kill, is meant to exit a given thread:
4008  *
4009  * thr = Thread.new { sleep }
4010  * Thread.kill(thr) # sends exit() to thr
4011  *
4012  * Alternatively, you can use the instance method #exit, or any of its
4013  * aliases #kill or #terminate.
4014  *
4015  * thr.exit
4016  *
4017  * === Thread status
4018  *
4019  * Ruby provides a few instance methods for querying the state of a given
4020  * thread. To get a string with the current thread's state use #status
4021  *
4022  * thr = Thread.new { sleep }
4023  * thr.status # => "sleep"
4024  * thr.exit
4025  * thr.status # => false
4026  *
4027  * You can also use #alive? to tell if the thread is running or sleeping,
4028  * and #stop? if the thread is dead or sleeping.
4029  *
4030  * === Thread variables and scope
4031  *
4032  * Since threads are created with blocks, the same rules apply to other
4033  * Ruby blocks for variable scope. Any local variables created within this
4034  * block are accessible to only this thread.
4035  *
4036  * ==== Fiber-local vs. Thread-local
4037  *
4038  * Each fiber has its own bucket for Thread#[] storage. When you set a
4039  * new fiber-local it is only accessible within this Fiber. To illustrate:
4040  *
4041  * Thread.new {
4042  * Thread.current[:foo] = "bar"
4043  * Fiber.new {
4044  * p Thread.current[:foo] # => nil
4045  * }.resume
4046  * }.join
4047  *
4048  * This example uses #[] for getting and #[]= for setting fiber-locals,
4049  * you can also use #keys to list the fiber-locals for a given
4050  * thread and #key? to check if a fiber-local exists.
4051  *
4052  * When it comes to thread-locals, they are accessible within the entire
4053  * scope of the thread. Given the following example:
4054  *
4055  * Thread.new{
4056  * Thread.current.thread_variable_set(:foo, 1)
4057  * p Thread.current.thread_variable_get(:foo) # => 1
4058  * Fiber.new{
4059  * Thread.current.thread_variable_set(:foo, 2)
4060  * p Thread.current.thread_variable_get(:foo) # => 2
4061  * }.resume
4062  * p Thread.current.thread_variable_get(:foo) # => 2
4063  * }.join
4064  *
4065  * You can see that the thread-local +:foo+ carried over into the fiber
4066  * and was changed to +2+ by the end of the thread.
4067  *
4068  * This example makes use of #thread_variable_set to create new
4069  * thread-locals, and #thread_variable_get to reference them.
4070  *
4071  * There is also #thread_variables to list all thread-locals, and
4072  * #thread_variable? to check if a given thread-local exists.
4073  *
4074  * === Exception handling
4075  *
4076  * When an unhandled exception is raised inside a thread, it will
4077  * terminate. By default, this exception will not propagate to other
4078  * threads. The exception is stored and when another thread calls #value
4079  * or #join, the exception will be re-raised in that thread.
4080  *
4081  * t = Thread.new{ raise 'something went wrong' }
4082  * t.value #=> RuntimeError: something went wrong
4083  *
4084  * An exception can be raised from outside the thread using the
4085  * Thread#raise instance method, which takes the same parameters as
4086  * Kernel#raise.
4087  *
4088  * Setting Thread.abort_on_exception = true, Thread#abort_on_exception =
4089  * true, or $DEBUG = true will cause a subsequent unhandled exception
4090  * raised in a thread to be automatically re-raised in the main thread.
4091  *
4092  * With the addition of the class method ::handle_interrupt, you can now
4093  * handle exceptions asynchronously with threads.
4094  *
4095  * === Scheduling
4096  *
4097  * Ruby provides a few ways to support scheduling threads in your program.
4098  *
4099  * The first way is by using the class method ::stop, to put the current
4100  * running thread to sleep and schedule the execution of another thread.
4101  *
4102  * Once a thread is asleep, you can use the instance method #wakeup to
4103  * mark your thread as eligible for scheduling.
4104  *
4105  * You can also try ::pass, which attempts to pass execution to another
4106  * thread but is dependent on the OS whether a running thread will switch
4107  * or not. The same goes for #priority, which lets you hint to the thread
4108  * scheduler which threads you want to take precedence when passing
4109  * execution. This method is also dependent on the OS and may be ignored
4110  * on some platforms.
4111  *
4112  */
4113  rb_cThread = rb_define_class("Thread", rb_cObject);
4115 
4116 #if VM_COLLECT_USAGE_DETAILS
4117  /* ::RubyVM::USAGE_ANALYSIS_* */
4118 #define define_usage_analysis_hash(name) /* shut up rdoc -C */ \
4119  rb_define_const(rb_cRubyVM, "USAGE_ANALYSIS_" #name, rb_hash_new())
4120  define_usage_analysis_hash(INSN);
4121  define_usage_analysis_hash(REGS);
4122  define_usage_analysis_hash(INSN_BIGRAM);
4123 
4124  rb_define_singleton_method(rb_cRubyVM, "USAGE_ANALYSIS_INSN_START", usage_analysis_insn_start, 0);
4125  rb_define_singleton_method(rb_cRubyVM, "USAGE_ANALYSIS_OPERAND_START", usage_analysis_operand_start, 0);
4126  rb_define_singleton_method(rb_cRubyVM, "USAGE_ANALYSIS_REGISTER_START", usage_analysis_register_start, 0);
4127  rb_define_singleton_method(rb_cRubyVM, "USAGE_ANALYSIS_INSN_STOP", usage_analysis_insn_stop, 0);
4128  rb_define_singleton_method(rb_cRubyVM, "USAGE_ANALYSIS_OPERAND_STOP", usage_analysis_operand_stop, 0);
4129  rb_define_singleton_method(rb_cRubyVM, "USAGE_ANALYSIS_REGISTER_STOP", usage_analysis_register_stop, 0);
4130  rb_define_singleton_method(rb_cRubyVM, "USAGE_ANALYSIS_INSN_RUNNING", usage_analysis_insn_running, 0);
4131  rb_define_singleton_method(rb_cRubyVM, "USAGE_ANALYSIS_OPERAND_RUNNING", usage_analysis_operand_running, 0);
4132  rb_define_singleton_method(rb_cRubyVM, "USAGE_ANALYSIS_REGISTER_RUNNING", usage_analysis_register_running, 0);
4133  rb_define_singleton_method(rb_cRubyVM, "USAGE_ANALYSIS_INSN_CLEAR", usage_analysis_insn_clear, 0);
4134  rb_define_singleton_method(rb_cRubyVM, "USAGE_ANALYSIS_OPERAND_CLEAR", usage_analysis_operand_clear, 0);
4135  rb_define_singleton_method(rb_cRubyVM, "USAGE_ANALYSIS_REGISTER_CLEAR", usage_analysis_register_clear, 0);
4136 #endif
4137 
4138  /* ::RubyVM::OPTS
4139  * An Array of VM build options.
4140  * This constant is MRI specific.
4141  */
4142  rb_define_const(rb_cRubyVM, "OPTS", opts = rb_ary_new());
4143 
4144 #if OPT_DIRECT_THREADED_CODE
4145  rb_ary_push(opts, rb_str_new2("direct threaded code"));
4146 #elif OPT_TOKEN_THREADED_CODE
4147  rb_ary_push(opts, rb_str_new2("token threaded code"));
4148 #elif OPT_CALL_THREADED_CODE
4149  rb_ary_push(opts, rb_str_new2("call threaded code"));
4150 #endif
4151 
4152 #if OPT_OPERANDS_UNIFICATION
4153  rb_ary_push(opts, rb_str_new2("operands unification"));
4154 #endif
4155 #if OPT_INSTRUCTIONS_UNIFICATION
4156  rb_ary_push(opts, rb_str_new2("instructions unification"));
4157 #endif
4158 #if OPT_INLINE_METHOD_CACHE
4159  rb_ary_push(opts, rb_str_new2("inline method cache"));
4160 #endif
4161 
4162  /* ::RubyVM::INSTRUCTION_NAMES
4163  * A list of bytecode instruction names in MRI.
4164  * This constant is MRI specific.
4165  */
4166  rb_define_const(rb_cRubyVM, "INSTRUCTION_NAMES", rb_insns_name_array());
4167 
4168  /* ::RubyVM::DEFAULT_PARAMS
4169  * This constant exposes the VM's default parameters.
4170  * Note that changing these values does not affect VM execution.
4171  * Specification is not stable and you should not depend on this value.
4172  * Of course, this constant is MRI specific.
4173  */
4174  rb_define_const(rb_cRubyVM, "DEFAULT_PARAMS", vm_default_params());
4175 
4176  /* debug functions ::RubyVM::SDR(), ::RubyVM::NSDR() */
4177 #if VMDEBUG
4178  rb_define_singleton_method(rb_cRubyVM, "SDR", sdr, 0);
4179  rb_define_singleton_method(rb_cRubyVM, "NSDR", nsdr, 0);
4180  rb_define_singleton_method(rb_cRubyVM, "mtbl", vm_mtbl, 2);
4181  rb_define_singleton_method(rb_cRubyVM, "mtbl2", vm_mtbl2, 2);
4182 #else
4183  (void)sdr;
4184  (void)nsdr;
4185  (void)vm_mtbl;
4186  (void)vm_mtbl2;
4187 #endif
4188 
4189  /* VM bootstrap: phase 2 */
4190  {
4191  rb_vm_t *vm = ruby_current_vm_ptr;
4192  rb_thread_t *th = GET_THREAD();
4193  VALUE filename = rb_fstring_lit("<main>");
4194  const rb_iseq_t *iseq = rb_iseq_new(Qnil, filename, filename, Qnil, 0, ISEQ_TYPE_TOP);
4195 
4196  // Ractor setup
4197  rb_ractor_main_setup(vm, th->ractor, th);
4198 
4199  /* create vm object */
4200  vm->self = TypedData_Wrap_Struct(rb_cRubyVM, &vm_data_type, vm);
4201 
4202  /* create main thread */
4203  th->self = TypedData_Wrap_Struct(rb_cThread, &thread_data_type, th);
4204  vm->ractor.main_thread = th;
4205  vm->ractor.main_ractor = th->ractor;
4206  th->vm = vm;
4207  th->top_wrapper = 0;
4208  th->top_self = rb_vm_top_self();
4209 
4210  rb_vm_register_global_object((VALUE)iseq);
4211  th->ec->cfp->iseq = iseq;
4212  th->ec->cfp->pc = ISEQ_BODY(iseq)->iseq_encoded;
4213  th->ec->cfp->self = th->top_self;
4214 
4215  VM_ENV_FLAGS_UNSET(th->ec->cfp->ep, VM_FRAME_FLAG_CFRAME);
4216  VM_STACK_ENV_WRITE(th->ec->cfp->ep, VM_ENV_DATA_INDEX_ME_CREF, (VALUE)vm_cref_new(rb_cObject, METHOD_VISI_PRIVATE, FALSE, NULL, FALSE, FALSE));
4217 
4218  /*
4219  * The Binding of the top level scope
4220  */
4221  rb_define_global_const("TOPLEVEL_BINDING", rb_binding_new());
4222 
4223 #ifdef _WIN32
4224  rb_objspace_gc_enable(vm->gc.objspace);
4225 #endif
4226  }
4227  vm_init_redefined_flag();
4228 
4229  rb_block_param_proxy = rb_obj_alloc(rb_cObject);
4230  rb_add_method_optimized(rb_singleton_class(rb_block_param_proxy), idCall,
4231  OPTIMIZED_METHOD_TYPE_BLOCK_CALL, 0, METHOD_VISI_PUBLIC);
4232  rb_obj_freeze(rb_block_param_proxy);
4233  rb_vm_register_global_object(rb_block_param_proxy);
4234 
4235  /* vm_backtrace.c */
4236  Init_vm_backtrace();
4237 }
4238 
4239 void
4240 rb_vm_set_progname(VALUE filename)
4241 {
4242  rb_thread_t *th = GET_VM()->ractor.main_thread;
4243  rb_control_frame_t *cfp = (void *)(th->ec->vm_stack + th->ec->vm_stack_size);
4244  --cfp;
4245 
4246  filename = rb_str_new_frozen(filename);
4247  rb_iseq_pathobj_set(cfp->iseq, filename, rb_iseq_realpath(cfp->iseq));
4248 }
4249 
4250 extern const struct st_hash_type rb_fstring_hash_type;
4251 
4252 void
4253 Init_BareVM(void)
4254 {
4255  /* VM bootstrap: phase 1 */
4256  rb_vm_t *vm = ruby_mimcalloc(1, sizeof(*vm));
4257  rb_thread_t *th = ruby_mimcalloc(1, sizeof(*th));
4258  if (!vm || !th) {
4259  fputs("[FATAL] failed to allocate memory\n", stderr);
4260  exit(EXIT_FAILURE);
4261  }
4262 
4263  // setup the VM
4264  vm_init2(vm);
4265 
4266  rb_vm_postponed_job_queue_init(vm);
4267  ruby_current_vm_ptr = vm;
4268  rb_objspace_alloc();
4269  vm->negative_cme_table = rb_id_table_create(16);
4270  vm->overloaded_cme_table = st_init_numtable();
4271  vm->constant_cache = rb_id_table_create(0);
4272  vm->unused_block_warning_table = st_init_numtable();
4273 
4274  // TODO: remove before Ruby 3.4.0 release
4275  const char *s = getenv("RUBY_TRY_UNUSED_BLOCK_WARNING_STRICT");
4276  if (s && strcmp(s, "1") == 0) {
4277  vm->unused_block_warning_strict = true;
4278  }
4279 
4280  // setup main thread
4281  th->nt = ZALLOC(struct rb_native_thread);
4282  th->vm = vm;
4283  th->ractor = vm->ractor.main_ractor = rb_ractor_main_alloc();
4284  Init_native_thread(th);
4285  rb_jit_cont_init();
4286  th_init(th, 0, vm);
4287 
4288  rb_ractor_set_current_ec(th->ractor, th->ec);
4289  /* n.b. native_main_thread_stack_top is set by the INIT_STACK macro */
4290  ruby_thread_init_stack(th, native_main_thread_stack_top);
4291 
4292  // setup ractor system
4293  rb_native_mutex_initialize(&vm->ractor.sync.lock);
4294  rb_native_cond_initialize(&vm->ractor.sync.terminate_cond);
4295 
4296  vm_opt_method_def_table = st_init_numtable();
4297  vm_opt_mid_table = st_init_numtable();
4298 
4299 #ifdef RUBY_THREAD_WIN32_H
4300  rb_native_cond_initialize(&vm->ractor.sync.barrier_cond);
4301 #endif
4302 }
4303 
4304 void
4305 ruby_init_stack(void *addr)
4306 {
4307  native_main_thread_stack_top = addr;
4308 }
4309 
4310 #ifndef _WIN32
4311 #include <unistd.h>
4312 #include <sys/mman.h>
4313 #endif
4314 
4315 
4316 #ifndef MARK_OBJECT_ARY_BUCKET_SIZE
4317 #define MARK_OBJECT_ARY_BUCKET_SIZE 1024
4318 #endif
4319 
4321  VALUE next;
4322  long len;
4323  VALUE *array;
4324 };
4325 
4326 static void
4327 pin_array_list_mark(void *data)
4328 {
4329  struct pin_array_list *array = (struct pin_array_list *)data;
4330  rb_gc_mark_movable(array->next);
4331 
4332  rb_gc_mark_vm_stack_values(array->len, array->array);
4333 }
4334 
4335 static void
4336 pin_array_list_free(void *data)
4337 {
4338  struct pin_array_list *array = (struct pin_array_list *)data;
4339  xfree(array->array);
4340 }
4341 
4342 static size_t
4343 pin_array_list_memsize(const void *data)
4344 {
4345  return sizeof(struct pin_array_list) + (MARK_OBJECT_ARY_BUCKET_SIZE * sizeof(VALUE));
4346 }
4347 
4348 static void
4349 pin_array_list_update_references(void *data)
4350 {
4351  struct pin_array_list *array = (struct pin_array_list *)data;
4352  array->next = rb_gc_location(array->next);
4353 }
4354 
4355 static const rb_data_type_t pin_array_list_type = {
4356  .wrap_struct_name = "VM/pin_array_list",
4357  .function = {
4358  .dmark = pin_array_list_mark,
4359  .dfree = pin_array_list_free,
4360  .dsize = pin_array_list_memsize,
4361  .dcompact = pin_array_list_update_references,
4362  },
4363  .flags = RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_EMBEDDABLE,
4364 };
4365 
4366 static VALUE
4367 pin_array_list_new(VALUE next)
4368 {
4369  struct pin_array_list *array_list;
4370  VALUE obj = TypedData_Make_Struct(0, struct pin_array_list, &pin_array_list_type, array_list);
4371  RB_OBJ_WRITE(obj, &array_list->next, next);
4372  array_list->array = ALLOC_N(VALUE, MARK_OBJECT_ARY_BUCKET_SIZE);
4373  return obj;
4374 }
4375 
4376 static VALUE
4377 pin_array_list_append(VALUE obj, VALUE item)
4378 {
4379  struct pin_array_list *array_list;
4380  TypedData_Get_Struct(obj, struct pin_array_list, &pin_array_list_type, array_list);
4381 
4382  if (array_list->len >= MARK_OBJECT_ARY_BUCKET_SIZE) {
4383  obj = pin_array_list_new(obj);
4384  TypedData_Get_Struct(obj, struct pin_array_list, &pin_array_list_type, array_list);
4385  }
4386 
4387  RB_OBJ_WRITE(obj, &array_list->array[array_list->len], item);
4388  array_list->len++;
4389  return obj;
4390 }
4391 
4392 void
4393 rb_vm_register_global_object(VALUE obj)
4394 {
4396  if (RB_SPECIAL_CONST_P(obj)) {
4397  return;
4398  }
4399 
4400  switch (RB_BUILTIN_TYPE(obj)) {
4401  case T_CLASS:
4402  case T_MODULE:
4403  if (FL_TEST(obj, RCLASS_IS_ROOT)) {
4404  return;
4405  }
4406  FL_SET(obj, RCLASS_IS_ROOT);
4407  break;
4408  default:
4409  break;
4410  }
4411  RB_VM_LOCK_ENTER();
4412  {
4413  VALUE list = GET_VM()->mark_object_ary;
4414  VALUE head = pin_array_list_append(list, obj);
4415  if (head != list) {
4416  GET_VM()->mark_object_ary = head;
4417  }
4418  RB_GC_GUARD(obj);
4419  }
4420  RB_VM_LOCK_LEAVE();
4421 }
4422 
4423 void
4424 Init_vm_objects(void)
4425 {
4426  rb_vm_t *vm = GET_VM();
4427 
4428  /* initialize mark object array, hash */
4429  vm->mark_object_ary = pin_array_list_new(Qnil);
4430  vm->loading_table = st_init_strtable();
4431  vm->ci_table = st_init_table(&vm_ci_hashtype);
4432  vm->frozen_strings = st_init_table_with_size(&rb_fstring_hash_type, 10000);
4433 }
4434 
4435 // Stub for builtin function when not building YJIT units
4436 #if !USE_YJIT
4437 void Init_builtin_yjit(void) {}
4438 #endif
4439 
4440 // Whether YJIT is enabled or not, we load yjit_hook.rb to remove Kernel#with_yjit.
4441 #include "yjit_hook.rbinc"
4442 
4443 // Stub for builtin function when not building RJIT units
4444 #if !USE_RJIT
4445 void Init_builtin_rjit(void) {}
4446 void Init_builtin_rjit_c(void) {}
4447 #endif
4448 
4449 /* top self */
4450 
4451 static VALUE
4452 main_to_s(VALUE obj)
4453 {
4454  return rb_str_new2("main");
4455 }
4456 
4457 VALUE
4458 rb_vm_top_self(void)
4459 {
4460  return GET_VM()->top_self;
4461 }
4462 
4463 void
4464 Init_top_self(void)
4465 {
4466  rb_vm_t *vm = GET_VM();
4467 
4468  vm->top_self = rb_obj_alloc(rb_cObject);
4469  rb_define_singleton_method(rb_vm_top_self(), "to_s", main_to_s, 0);
4470  rb_define_alias(rb_singleton_class(rb_vm_top_self()), "inspect", "to_s");
4471 }
4472 
4473 VALUE *
4475 {
4476  rb_ractor_t *cr = GET_RACTOR();
4477  return &cr->verbose;
4478 }
4479 
4480 VALUE *
4482 {
4483  rb_ractor_t *cr = GET_RACTOR();
4484  return &cr->debug;
4485 }
4486 
4487 bool rb_free_at_exit = false;
4488 
4489 bool
4491 {
4492  return rb_free_at_exit;
4493 }
4494 
4495 /* iseq.c */
4496 VALUE rb_insn_operand_intern(const rb_iseq_t *iseq,
4497  VALUE insn, int op_no, VALUE op,
4498  int len, size_t pos, VALUE *pnop, VALUE child);
4499 
4500 st_table *
4501 rb_vm_fstring_table(void)
4502 {
4503  return GET_VM()->frozen_strings;
4504 }
4505 
4506 #if VM_COLLECT_USAGE_DETAILS
4507 
4508 #define HASH_ASET(h, k, v) rb_hash_aset((h), (st_data_t)(k), (st_data_t)(v))
4509 
4510 /* uh = {
4511  * insn(Fixnum) => ihash(Hash)
4512  * }
4513  * ihash = {
4514  * -1(Fixnum) => count, # insn usage
4515  * 0(Fixnum) => ophash, # operand usage
4516  * }
4517  * ophash = {
4518  * val(interned string) => count(Fixnum)
4519  * }
4520  */
4521 static void
4522 vm_analysis_insn(int insn)
4523 {
4524  ID usage_hash;
4525  ID bigram_hash;
4526  static int prev_insn = -1;
4527 
4528  VALUE uh;
4529  VALUE ihash;
4530  VALUE cv;
4531 
4532  CONST_ID(usage_hash, "USAGE_ANALYSIS_INSN");
4533  CONST_ID(bigram_hash, "USAGE_ANALYSIS_INSN_BIGRAM");
4534  uh = rb_const_get(rb_cRubyVM, usage_hash);
4535  if (NIL_P(ihash = rb_hash_aref(uh, INT2FIX(insn)))) {
4536  ihash = rb_hash_new();
4537  HASH_ASET(uh, INT2FIX(insn), ihash);
4538  }
4539  if (NIL_P(cv = rb_hash_aref(ihash, INT2FIX(-1)))) {
4540  cv = INT2FIX(0);
4541  }
4542  HASH_ASET(ihash, INT2FIX(-1), INT2FIX(FIX2INT(cv) + 1));
4543 
4544  /* calc bigram */
4545  if (prev_insn != -1) {
4546  VALUE bi;
4547  VALUE ary[2];
4548  VALUE cv;
4549 
4550  ary[0] = INT2FIX(prev_insn);
4551  ary[1] = INT2FIX(insn);
4552  bi = rb_ary_new4(2, &ary[0]);
4553 
4554  uh = rb_const_get(rb_cRubyVM, bigram_hash);
4555  if (NIL_P(cv = rb_hash_aref(uh, bi))) {
4556  cv = INT2FIX(0);
4557  }
4558  HASH_ASET(uh, bi, INT2FIX(FIX2INT(cv) + 1));
4559  }
4560  prev_insn = insn;
4561 }
4562 
4563 static void
4564 vm_analysis_operand(int insn, int n, VALUE op)
4565 {
4566  ID usage_hash;
4567 
4568  VALUE uh;
4569  VALUE ihash;
4570  VALUE ophash;
4571  VALUE valstr;
4572  VALUE cv;
4573 
4574  CONST_ID(usage_hash, "USAGE_ANALYSIS_INSN");
4575 
4576  uh = rb_const_get(rb_cRubyVM, usage_hash);
4577  if (NIL_P(ihash = rb_hash_aref(uh, INT2FIX(insn)))) {
4578  ihash = rb_hash_new();
4579  HASH_ASET(uh, INT2FIX(insn), ihash);
4580  }
4581  if (NIL_P(ophash = rb_hash_aref(ihash, INT2FIX(n)))) {
4582  ophash = rb_hash_new();
4583  HASH_ASET(ihash, INT2FIX(n), ophash);
4584  }
4585  /* intern */
4586  valstr = rb_insn_operand_intern(GET_EC()->cfp->iseq, insn, n, op, 0, 0, 0, 0);
4587 
4588  /* set count */
4589  if (NIL_P(cv = rb_hash_aref(ophash, valstr))) {
4590  cv = INT2FIX(0);
4591  }
4592  HASH_ASET(ophash, valstr, INT2FIX(FIX2INT(cv) + 1));
4593 }
4594 
4595 static void
4596 vm_analysis_register(int reg, int isset)
4597 {
4598  ID usage_hash;
4599  VALUE uh;
4600  VALUE valstr;
4601  static const char regstrs[][5] = {
4602  "pc", /* 0 */
4603  "sp", /* 1 */
4604  "ep", /* 2 */
4605  "cfp", /* 3 */
4606  "self", /* 4 */
4607  "iseq", /* 5 */
4608  };
4609  static const char getsetstr[][4] = {
4610  "get",
4611  "set",
4612  };
4613  static VALUE syms[sizeof(regstrs) / sizeof(regstrs[0])][2];
4614 
4615  VALUE cv;
4616 
4617  CONST_ID(usage_hash, "USAGE_ANALYSIS_REGS");
4618  if (syms[0] == 0) {
4619  char buff[0x10];
4620  int i;
4621 
4622  for (i = 0; i < (int)(sizeof(regstrs) / sizeof(regstrs[0])); i++) {
4623  int j;
4624  for (j = 0; j < 2; j++) {
4625  snprintf(buff, 0x10, "%d %s %-4s", i, getsetstr[j], regstrs[i]);
4626  syms[i][j] = ID2SYM(rb_intern(buff));
4627  }
4628  }
4629  }
4630  valstr = syms[reg][isset];
4631 
4632  uh = rb_const_get(rb_cRubyVM, usage_hash);
4633  if (NIL_P(cv = rb_hash_aref(uh, valstr))) {
4634  cv = INT2FIX(0);
4635  }
4636  HASH_ASET(uh, valstr, INT2FIX(FIX2INT(cv) + 1));
4637 }
4638 
4639 #undef HASH_ASET
4640 
4641 static void (*ruby_vm_collect_usage_func_insn)(int insn) = NULL;
4642 static void (*ruby_vm_collect_usage_func_operand)(int insn, int n, VALUE op) = NULL;
4643 static void (*ruby_vm_collect_usage_func_register)(int reg, int isset) = NULL;
4644 
4645 /* :nodoc: */
4646 static VALUE
4647 usage_analysis_insn_start(VALUE self)
4648 {
4649  ruby_vm_collect_usage_func_insn = vm_analysis_insn;
4650  return Qnil;
4651 }
4652 
4653 /* :nodoc: */
4654 static VALUE
4655 usage_analysis_operand_start(VALUE self)
4656 {
4657  ruby_vm_collect_usage_func_operand = vm_analysis_operand;
4658  return Qnil;
4659 }
4660 
4661 /* :nodoc: */
4662 static VALUE
4663 usage_analysis_register_start(VALUE self)
4664 {
4665  ruby_vm_collect_usage_func_register = vm_analysis_register;
4666  return Qnil;
4667 }
4668 
4669 /* :nodoc: */
4670 static VALUE
4671 usage_analysis_insn_stop(VALUE self)
4672 {
4673  ruby_vm_collect_usage_func_insn = 0;
4674  return Qnil;
4675 }
4676 
4677 /* :nodoc: */
4678 static VALUE
4679 usage_analysis_operand_stop(VALUE self)
4680 {
4681  ruby_vm_collect_usage_func_operand = 0;
4682  return Qnil;
4683 }
4684 
4685 /* :nodoc: */
4686 static VALUE
4687 usage_analysis_register_stop(VALUE self)
4688 {
4689  ruby_vm_collect_usage_func_register = 0;
4690  return Qnil;
4691 }
4692 
4693 /* :nodoc: */
4694 static VALUE
4695 usage_analysis_insn_running(VALUE self)
4696 {
4697  return RBOOL(ruby_vm_collect_usage_func_insn != 0);
4698 }
4699 
4700 /* :nodoc: */
4701 static VALUE
4702 usage_analysis_operand_running(VALUE self)
4703 {
4704  return RBOOL(ruby_vm_collect_usage_func_operand != 0);
4705 }
4706 
4707 /* :nodoc: */
4708 static VALUE
4709 usage_analysis_register_running(VALUE self)
4710 {
4711  return RBOOL(ruby_vm_collect_usage_func_register != 0);
4712 }
4713 
4714 static VALUE
4715 usage_analysis_clear(VALUE self, ID usage_hash)
4716 {
4717  VALUE uh;
4718  uh = rb_const_get(self, usage_hash);
4719  rb_hash_clear(uh);
4720 
4721  return Qtrue;
4722 }
4723 
4724 
4725 /* :nodoc: */
4726 static VALUE
4727 usage_analysis_insn_clear(VALUE self)
4728 {
4729  ID usage_hash;
4730  ID bigram_hash;
4731 
4732  CONST_ID(usage_hash, "USAGE_ANALYSIS_INSN");
4733  CONST_ID(bigram_hash, "USAGE_ANALYSIS_INSN_BIGRAM");
4734  usage_analysis_clear(rb_cRubyVM, usage_hash);
4735  return usage_analysis_clear(rb_cRubyVM, bigram_hash);
4736 }
4737 
4738 /* :nodoc: */
4739 static VALUE
4740 usage_analysis_operand_clear(VALUE self)
4741 {
4742  ID usage_hash;
4743 
4744  CONST_ID(usage_hash, "USAGE_ANALYSIS_INSN");
4745  return usage_analysis_clear(self, usage_hash);
4746 }
4747 
4748 /* :nodoc: */
4749 static VALUE
4750 usage_analysis_register_clear(VALUE self)
4751 {
4752  ID usage_hash;
4753 
4754  CONST_ID(usage_hash, "USAGE_ANALYSIS_REGS");
4755  return usage_analysis_clear(self, usage_hash);
4756 }
4757 
4758 #else
4759 
4760 MAYBE_UNUSED(static void (*ruby_vm_collect_usage_func_insn)(int insn)) = 0;
4761 MAYBE_UNUSED(static void (*ruby_vm_collect_usage_func_operand)(int insn, int n, VALUE op)) = 0;
4762 MAYBE_UNUSED(static void (*ruby_vm_collect_usage_func_register)(int reg, int isset)) = 0;
4763 
4764 #endif
4765 
4766 #if VM_COLLECT_USAGE_DETAILS
4767 /* @param insn instruction number */
4768 static void
4769 vm_collect_usage_insn(int insn)
4770 {
4771  if (RUBY_DTRACE_INSN_ENABLED()) {
4772  RUBY_DTRACE_INSN(rb_insns_name(insn));
4773  }
4774  if (ruby_vm_collect_usage_func_insn)
4775  (*ruby_vm_collect_usage_func_insn)(insn);
4776 }
4777 
4778 /* @param insn instruction number
4779  * @param n n-th operand
4780  * @param op operand value
4781  */
4782 static void
4783 vm_collect_usage_operand(int insn, int n, VALUE op)
4784 {
4785  if (RUBY_DTRACE_INSN_OPERAND_ENABLED()) {
4786  VALUE valstr;
4787 
4788  valstr = rb_insn_operand_intern(GET_EC()->cfp->iseq, insn, n, op, 0, 0, 0, 0);
4789 
4790  RUBY_DTRACE_INSN_OPERAND(RSTRING_PTR(valstr), rb_insns_name(insn));
4791  RB_GC_GUARD(valstr);
4792  }
4793  if (ruby_vm_collect_usage_func_operand)
4794  (*ruby_vm_collect_usage_func_operand)(insn, n, op);
4795 }
4796 
4797 /* @param reg register id. see code of vm_analysis_register() */
4798 /* @param isset 0: read, 1: write */
4799 static void
4800 vm_collect_usage_register(int reg, int isset)
4801 {
4802  if (ruby_vm_collect_usage_func_register)
4803  (*ruby_vm_collect_usage_func_register)(reg, isset);
4804 }
4805 #endif
4806 
4807 const struct rb_callcache *
4808 rb_vm_empty_cc(void)
4809 {
4810  return &vm_empty_cc;
4811 }
4812 
4813 const struct rb_callcache *
4814 rb_vm_empty_cc_for_super(void)
4815 {
4816  return &vm_empty_cc_for_super;
4817 }
4818 
4819 #include "vm_call_iseq_optimized.inc" /* required from vm_insnhelper.c */
#define RUBY_ASSERT_MESG(expr,...)
Asserts that the expression is truthy.
Definition: assert.h:186
#define RUBY_ASSERT(...)
Asserts that the given expression is truthy if and only if RUBY_DEBUG is truthy.
Definition: assert.h:219
std::atomic< unsigned > rb_atomic_t
Type that is eligible for atomic operations.
Definition: atomic.h:69
#define RUBY_ATOMIC_FETCH_ADD(var, val)
Atomically replaces the value pointed by var with the result of addition of val to the old value of v...
Definition: atomic.h:93
#define rb_define_method_id(klass, mid, func, arity)
Defines klass#mid.
Definition: cxxanyargs.hpp:673
#define rb_define_singleton_method(klass, mid, func, arity)
Defines klass.mid.
Definition: cxxanyargs.hpp:685
#define RUBY_EVENT_END
Encountered an end of a class clause.
Definition: event.h:40
#define RUBY_EVENT_B_RETURN
Encountered a next statement.
Definition: event.h:56
#define RUBY_EVENT_RETURN
Encountered a return statement.
Definition: event.h:42
#define RUBY_EVENT_C_RETURN
Return from a method, written in C.
Definition: event.h:44
uint32_t rb_event_flag_t
Represents event(s).
Definition: event.h:108
@ RUBY_FL_SHAREABLE
This flag has something to do with Ractor.
Definition: fl_type.h:266
VALUE rb_define_class(const char *name, VALUE super)
Defines a top-level class.
Definition: class.c:980
VALUE rb_class_new(VALUE super)
Creates a new, anonymous class.
Definition: class.c:359
VALUE rb_singleton_class(VALUE obj)
Finds or creates the singleton class of the passed object.
Definition: class.c:2297
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
void rb_define_method(VALUE klass, const char *name, VALUE(*func)(ANYARGS), int argc)
Defines a method.
Definition: class.c:2142
#define rb_str_new2
Old name of rb_str_new_cstr.
Definition: string.h:1675
#define NUM2ULONG
Old name of RB_NUM2ULONG.
Definition: long.h:52
#define ALLOCV
Old name of RB_ALLOCV.
Definition: memory.h:399
#define ALLOC
Old name of RB_ALLOC.
Definition: memory.h:395
#define xfree
Old name of ruby_xfree.
Definition: xmalloc.h:58
#define Qundef
Old name of RUBY_Qundef.
#define INT2FIX
Old name of RB_INT2FIX.
Definition: long.h:48
#define T_IMEMO
Old name of RUBY_T_IMEMO.
Definition: value_type.h:67
#define ID2SYM
Old name of RB_ID2SYM.
Definition: symbol.h:44
#define OBJ_FREEZE
Old name of RB_OBJ_FREEZE.
Definition: fl_type.h:135
#define ULONG2NUM
Old name of RB_ULONG2NUM.
Definition: long.h:60
#define SYM2ID
Old name of RB_SYM2ID.
Definition: symbol.h:45
#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 FIX2INT
Old name of RB_FIX2INT.
Definition: int.h:41
#define T_MODULE
Old name of RUBY_T_MODULE.
Definition: value_type.h:70
#define ZALLOC_N
Old name of RB_ZALLOC_N.
Definition: memory.h:396
#define ASSUME
Old name of RBIMPL_ASSUME.
Definition: assume.h:27
#define T_ICLASS
Old name of RUBY_T_ICLASS.
Definition: value_type.h:66
#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 FL_SET
Old name of RB_FL_SET.
Definition: fl_type.h:129
#define rb_exc_new3
Old name of rb_exc_new_str.
Definition: error.h:38
#define ULL2NUM
Old name of RB_ULL2NUM.
Definition: long_long.h:31
#define Qtrue
Old name of RUBY_Qtrue.
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#define NIL_P
Old name of RB_NIL_P.
#define NUM2ULL
Old name of RB_NUM2ULL.
Definition: long_long.h:35
#define T_CLASS
Old name of RUBY_T_CLASS.
Definition: value_type.h:58
#define BUILTIN_TYPE
Old name of RB_BUILTIN_TYPE.
Definition: value_type.h:85
#define FL_TEST
Old name of RB_FL_TEST.
Definition: fl_type.h:131
#define FIXNUM_P
Old name of RB_FIXNUM_P.
#define FL_USHIFT
Old name of RUBY_FL_USHIFT.
Definition: fl_type.h:69
#define CONST_ID
Old name of RUBY_CONST_ID.
Definition: symbol.h:47
#define FL_SET_RAW
Old name of RB_FL_SET_RAW.
Definition: fl_type.h:130
#define ALLOCV_END
Old name of RB_ALLOCV_END.
Definition: memory.h:401
#define SYMBOL_P
Old name of RB_SYMBOL_P.
Definition: value_type.h:88
void ruby_init_stack(void *addr)
Set stack bottom of Ruby implementation.
Definition: vm.c:4305
VALUE rb_eLocalJumpError
LocalJumpError exception.
Definition: eval.c:49
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_bug(const char *fmt,...)
Interpreter panic switch.
Definition: error.c:1088
void rb_iter_break(void)
Breaks from a block.
Definition: vm.c:2067
VALUE rb_eTypeError
TypeError exception.
Definition: error.c:1403
void rb_iter_break_value(VALUE val)
Identical to rb_iter_break(), except it additionally takes the "value" of this breakage.
Definition: vm.c:2073
VALUE rb_eRuntimeError
RuntimeError exception.
Definition: error.c:1401
VALUE rb_exc_new_str(VALUE etype, VALUE str)
Identical to rb_exc_new_cstr(), except it takes a Ruby's string instead of C's.
Definition: error.c:1454
VALUE rb_eArgError
ArgumentError exception.
Definition: error.c:1404
VALUE * rb_ruby_debug_ptr(void)
This is an implementation detail of ruby_debug.
Definition: vm.c:4481
VALUE rb_eSysStackError
SystemStackError exception.
Definition: eval.c:50
VALUE * rb_ruby_verbose_ptr(void)
This is an implementation detail of ruby_verbose.
Definition: vm.c:4474
@ RB_WARN_CATEGORY_PERFORMANCE
Warning is for performance issues (not enabled by -w).
Definition: error.h:54
VALUE rb_cTime
Time class.
Definition: time.c:672
VALUE rb_cArray
Array class.
Definition: array.c:40
VALUE rb_obj_alloc(VALUE klass)
Allocates an instance of the given class.
Definition: object.c:2091
VALUE rb_cInteger
Module class.
Definition: numeric.c:198
VALUE rb_cNilClass
NilClass class.
Definition: object.c:71
VALUE rb_cBinding
Binding class.
Definition: proc.c:43
VALUE rb_cRegexp
Regexp class.
Definition: re.c:2640
VALUE rb_cHash
Hash class.
Definition: hash.c:113
VALUE rb_cFalseClass
FalseClass class.
Definition: object.c:73
VALUE rb_obj_class(VALUE obj)
Queries the class of an object.
Definition: object.c:247
VALUE rb_cSymbol
Symbol class.
Definition: string.c:79
VALUE rb_cBasicObject
BasicObject class.
Definition: object.c:64
VALUE rb_cThread
Thread class.
Definition: vm.c:543
VALUE rb_obj_freeze(VALUE obj)
Just calls rb_obj_freeze_inline() inside.
Definition: object.c:1258
VALUE rb_cFloat
Float class.
Definition: numeric.c:197
VALUE rb_cProc
Proc class.
Definition: proc.c:44
VALUE rb_cTrueClass
TrueClass class.
Definition: object.c:72
VALUE rb_cString
String class.
Definition: string.c:78
#define RB_OBJ_WRITTEN(old, oldv, young)
Identical to RB_OBJ_WRITE(), except it doesn't write any values, but only a WB declaration.
Definition: gc.h:615
#define RB_OBJ_WRITE(old, slot, young)
Declaration of a "back" pointer.
Definition: gc.h:603
void rb_gc_mark(VALUE obj)
Marks an object.
Definition: gc.c:2094
void rb_mark_tbl_no_pin(struct st_table *tbl)
Identical to rb_mark_tbl(), except it marks objects using rb_gc_mark_movable().
Definition: gc.c:2410
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
void rb_mark_tbl(struct st_table *tbl)
Identical to rb_mark_hash(), except it marks only values of the table and leave their associated keys...
Definition: gc.c:2394
void rb_gc_mark_maybe(VALUE obj)
Identical to rb_gc_mark(), except it allows the passed value be a non-object.
Definition: gc.c:2106
VALUE rb_gc_location(VALUE obj)
Finds a new "location" of an object.
Definition: gc.c:3004
void rb_gc_update_tbl_refs(st_table *ptr)
Updates references inside of tables.
Definition: gc.c:2966
Defines RBIMPL_HAS_BUILTIN.
VALUE rb_ary_delete_at(VALUE ary, long pos)
Destructively removes an element which resides at the specific index of the passed array.
Definition: array.c:4045
VALUE rb_ary_new(void)
Allocates a new, empty array.
Definition: array.c:747
VALUE rb_ary_push(VALUE ary, VALUE elem)
Special case of rb_ary_cat() that it adds only one element.
Definition: array.c:1384
void rb_undef(VALUE mod, ID mid)
Inserts a method entry that hides previous method definition of the given name.
Definition: vm_method.c:1901
static int rb_check_arity(int argc, int min, int max)
Ensures that the passed integer is in the passed range.
Definition: error.h:284
void rb_set_end_proc(void(*func)(VALUE arg), VALUE arg)
Registers a function that shall run on process exit.
void rb_hash_bulk_insert(long argc, const VALUE *argv, VALUE hash)
Inserts a list of key-value pairs into a hash table at once.
Definition: hash.c:4766
void rb_hash_foreach(VALUE hash, int(*func)(VALUE key, VALUE val, VALUE arg), VALUE arg)
Iterates over a hash.
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_dup(VALUE hash)
Duplicates a hash.
Definition: hash.c:1563
VALUE rb_hash_clear(VALUE hash)
Swipes everything out of the passed hash table.
Definition: hash.c:2820
VALUE rb_hash_new(void)
Creates a new, empty hash object.
Definition: hash.c:1475
VALUE rb_backref_get(void)
Queries the last match, or Regexp.last_match, or the $~.
Definition: vm.c:1817
void rb_lastline_set(VALUE str)
Updates $_.
Definition: vm.c:1835
VALUE rb_lastline_get(void)
Queries the last line, or the $_.
Definition: vm.c:1829
void rb_backref_set(VALUE md)
Updates $~.
Definition: vm.c:1823
VALUE rb_block_proc(void)
Constructs a Proc object from implicitly passed components.
Definition: proc.c:813
VALUE rb_block_lambda(void)
Identical to rb_proc_new(), except it returns a lambda.
Definition: proc.c:832
VALUE rb_binding_new(void)
Snapshots the current execution context and turn it into an instance of rb_cBinding.
Definition: proc.c:324
VALUE rb_str_append(VALUE dst, VALUE src)
Identical to rb_str_buf_append(), except it converts the right hand side before concatenating.
Definition: string.c:3662
VALUE rb_str_new_frozen(VALUE str)
Creates a frozen copy of the string, if necessary.
Definition: string.c:1446
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
VALUE rb_const_get(VALUE space, ID name)
Identical to rb_const_defined(), except it returns the actual defined value.
Definition: variable.c:3151
void rb_set_class_path(VALUE klass, VALUE space, const char *name)
Names a class.
Definition: variable.c:353
VALUE rb_class_path_cached(VALUE mod)
Just another name of rb_mod_name.
Definition: variable.c:302
void rb_alias_variable(ID dst, ID src)
Aliases a global variable.
Definition: variable.c:987
VALUE rb_class_path(VALUE mod)
Identical to rb_mod_name(), except it returns #<Class: ...> style inspection for anonymous modules.
Definition: variable.c:293
void rb_undef_alloc_func(VALUE klass)
Deletes the allocator function of a class.
Definition: vm_method.c:1286
void rb_alias(VALUE klass, ID dst, ID src)
Resembles alias.
Definition: vm_method.c:2284
const char * rb_sourcefile(void)
Resembles __FILE__.
Definition: vm.c:1854
int rb_frame_method_id_and_class(ID *idp, VALUE *klassp)
Resembles __method__.
Definition: vm.c:2869
int rb_sourceline(void)
Resembles __LINE__.
Definition: vm.c:1868
const char * rb_id2name(ID id)
Retrieves the name mapped to the given id.
Definition: symbol.c:992
ID rb_intern(const char *name)
Finds or creates a symbol of the given name.
Definition: symbol.c:823
VALUE rb_sym2str(VALUE id)
Identical to rb_id2str(), except it takes an instance of rb_cSymbol rather than an ID.
Definition: symbol.c:970
VALUE rb_id2str(ID id)
Identical to rb_id2name(), except it returns a Ruby's String instead of C's.
Definition: symbol.c:986
void rb_define_global_const(const char *name, VALUE val)
Identical to rb_define_const(), except it defines that of "global", i.e.
Definition: variable.c:3727
void rb_define_const(VALUE klass, const char *name, VALUE val)
Defines a Ruby level constant under a namespace.
Definition: variable.c:3713
VALUE rb_iv_set(VALUE obj, const char *name, VALUE val)
Assigns to an instance variable.
Definition: variable.c:4211
char * ptr
Pointer to the underlying memory region, of at least capa bytes.
Definition: io.h:2
int len
Length of the buffer.
Definition: io.h:8
VALUE rb_ractor_make_shareable_copy(VALUE obj)
Identical to rb_ractor_make_shareable(), except it returns a (deep) copy of the passed one instead of...
Definition: ractor.c:3074
static bool rb_ractor_shareable_p(VALUE obj)
Queries if multiple Ractors can share the passed object or not.
Definition: ractor.h:249
#define RB_OBJ_SHAREABLE_P(obj)
Queries if the passed object has previously classified as shareable or not.
Definition: ractor.h:235
VALUE rb_ractor_make_shareable(VALUE obj)
Destructively transforms the passed object so that multiple Ractors can share it.
Definition: ractor.c:3065
void ruby_vm_at_exit(void(*func)(ruby_vm_t *))
ruby_vm_at_exit registers a function func to be invoked when a VM passed away.
Definition: vm.c:869
bool ruby_free_at_exit_p(void)
Returns whether the Ruby VM will free all memory at shutdown.
Definition: vm.c:4490
int ruby_vm_destruct(ruby_vm_t *vm)
Destructs the passed VM.
Definition: vm.c:3055
VALUE rb_f_sprintf(int argc, const VALUE *argv)
Identical to rb_str_format(), except how the arguments are arranged.
Definition: sprintf.c:208
VALUE rb_sprintf(const char *fmt,...)
Ruby's extended sprintf(3).
Definition: sprintf.c:1217
VALUE rb_str_catf(VALUE dst, const char *fmt,...)
Identical to rb_sprintf(), except it renders the output to the specified object rather than creating ...
Definition: sprintf.c:1240
#define MEMCPY(p1, p2, type, n)
Handy macro to call memcpy.
Definition: memory.h:367
#define MEMZERO(p, type, n)
Handy macro to erase a region of memory.
Definition: memory.h:355
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
Definition: memory.h:162
VALUE type(ANYARGS)
ANYARGS-ed function type.
Definition: cxxanyargs.hpp:56
int st_foreach(st_table *q, int_type *w, st_data_t e)
Iteration over the given table.
Definition: cxxanyargs.hpp:432
#define RARRAY_LEN
Just another name of rb_array_len.
Definition: rarray.h:51
static int RARRAY_LENINT(VALUE ary)
Identical to rb_array_len(), except it differs for the return type.
Definition: rarray.h:281
#define RARRAY_AREF(a, i)
Definition: rarray.h:403
static VALUE RBASIC_CLASS(VALUE obj)
Queries the class of an object.
Definition: rbasic.h:150
#define RBASIC(obj)
Convenient casting macro.
Definition: rbasic.h:40
#define RCLASS(obj)
Convenient casting macro.
Definition: rclass.h:38
#define RHASH_EMPTY_P(h)
Checks if the hash is empty.
Definition: rhash.h:79
#define StringValuePtr(v)
Identical to StringValue, except it returns a char*.
Definition: rstring.h:76
static char * RSTRING_PTR(VALUE str)
Queries the contents pointer of the string.
Definition: rstring.h:416
#define RTYPEDDATA_DATA(v)
Convenient getter macro.
Definition: rtypeddata.h:102
#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
const char * rb_class2name(VALUE klass)
Queries the name of the passed class.
Definition: variable.c:418
#define RB_NO_KEYWORDS
Do not pass keywords.
Definition: scan_args.h:69
static bool RB_SPECIAL_CONST_P(VALUE obj)
Checks if the given object is of enum ruby_special_consts.
#define RTEST
This is an old name of RB_TEST.
#define _(args)
This was a transition path from K&R to ANSI.
Definition: stdarg.h:35
Definition: proc.c:29
Definition: iseq.h:269
Definition: method.h:62
CREF (Class REFerence)
Definition: method.h:44
This is the struct that holds necessary info for a struct.
Definition: rtypeddata.h:200
const char * wrap_struct_name
Name of structs of this kind.
Definition: rtypeddata.h:207
Definition: method.h:54
Definition: shape.h:44
Definition: st.h:79
IFUNC (Internal FUNCtion)
Definition: imemo.h:88
THROW_DATA.
Definition: imemo.h:61
void rb_native_cond_initialize(rb_nativethread_cond_t *cond)
Fills the passed condition variable with an initial value.
void rb_native_mutex_initialize(rb_nativethread_lock_t *lock)
Just another name of rb_nativethread_lock_initialize.
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 enum ruby_value_type RB_BUILTIN_TYPE(VALUE obj)
Queries the type of the object.
Definition: value_type.h:182
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
ruby_value_type
C-level type of an object.
Definition: value_type.h:113
void ruby_xfree(void *ptr)
Deallocates a storage instance.
Definition: gc.c:4264