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