Ruby: vm.c Source File

Ruby 3.3.6p108 (2024-11-05 revision 75015d4c1f6965b5e85e96fb309f1f2129f933c0)

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