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