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