Ruby 4.1.0dev (2026-09-07 revision b57404b461ba8bf34e802d86b0db78388216e182)
jit.c (b57404b461ba8bf34e802d86b0db78388216e182)
1// Glue code shared between YJIT and ZJIT for use from Rust.
2// For FFI safety and bindgen compatibility reasons, certain types of C
3// functions require wrapping before they can be called from Rust. Those show
4// up here.
5//
6// Code specific to YJIT and ZJIT should go to yjit.c and zjit.c respectively.
7
8#include "internal.h"
9#include "vm_core.h"
10#include "vm_callinfo.h"
11#include "builtin.h"
12#include "insns.inc"
13#include "insns_info.inc"
14#include "iseq.h"
15#include "internal/compile.h"
16#include "internal/gc.h"
17#include "vm_sync.h"
18#include "internal/fixnum.h"
19#include "internal/hash.h"
20#include "internal/string.h"
21#include "internal/class.h"
22#include "internal/imemo.h"
24#include "zjit.h"
25
26#ifndef _WIN32
27#include <sys/mman.h>
28#endif
29
30enum jit_bindgen_constants {
31 // Field offsets for the RObject struct
32 ROBJECT_OFFSET_AS_HEAP_FIELDS = offsetof(struct RObject, as.extended),
33 ROBJECT_OFFSET_AS_ARY = offsetof(struct RObject, as.ary),
34
35 // Field offset for prime classext's fields_obj from a class pointer
36 RCLASS_OFFSET_PRIME_FIELDS_OBJ = offsetof(struct RClass_and_rb_classext_t, classext.fields_obj),
37
38 // Field offset for fields_obj in T_DATA
39 TDATA_OFFSET_FIELDS_OBJ = offsetof(struct RTypedData, fields_obj),
40
41 // Field offset for the RHash struct
42 RUBY_OFFSET_RHASH_IFNONE = offsetof(struct RHash, ifnone),
43
44 // Field offsets for the embedded ar_table in a hash
45 RUBY_OFFSET_RHASH_AR_HINT = sizeof(struct RHash) + offsetof(ar_table, ar_hint),
46 RUBY_OFFSET_RHASH_AR_PAIRS = sizeof(struct RHash) + offsetof(ar_table, pairs),
47
48 // Max pairs an embedded ar_table hash holds before it converts to an st_table
49 RUBY_RHASH_AR_TABLE_MAX_SIZE = RHASH_AR_TABLE_MAX_SIZE,
50
51 // Field offsets for the RString struct
52 RUBY_OFFSET_RSTRING_LEN = offsetof(struct RString, len),
53
54 // Shape constant related to RBasic::flags. (See RBASIC_SET_SHAPE_ID())
55 RB_SHAPE_FLAG_SHIFT = SHAPE_FLAG_SHIFT,
56
57 // Field offsets for rb_execution_context_t
58 RUBY_OFFSET_EC_CFP = offsetof(rb_execution_context_t, cfp),
59 RUBY_OFFSET_EC_INTERRUPT_FLAG = offsetof(rb_execution_context_t, interrupt_flag),
60 RUBY_OFFSET_EC_INTERRUPT_MASK = offsetof(rb_execution_context_t, interrupt_mask),
61 RUBY_OFFSET_EC_THREAD_PTR = offsetof(rb_execution_context_t, thread_ptr),
62 RUBY_OFFSET_EC_RACTOR_ID = offsetof(rb_execution_context_t, ractor_id),
63};
64
65// Manually bound in rust since this is out-of-range of `int`,
66// so this can't be in a `enum`, and we avoid `static const`
67// to avoid allocating storage for the constant.
68const shape_id_t rb_invalid_shape_id = INVALID_SHAPE_ID;
69
70unsigned int
71rb_iseq_encoded_size(const rb_iseq_t *iseq)
72{
73 return ISEQ_BODY(iseq)->iseq_size;
74}
75
76// Get the PC for a given index in an iseq
77VALUE *
78rb_iseq_pc_at_idx(const rb_iseq_t *iseq, uint32_t insn_idx)
79{
80 RUBY_ASSERT_ALWAYS(IMEMO_TYPE_P(iseq, imemo_iseq));
81 RUBY_ASSERT_ALWAYS(insn_idx < ISEQ_BODY(iseq)->iseq_size);
82 VALUE *encoded = ISEQ_BODY(iseq)->iseq_encoded;
83 VALUE *pc = &encoded[insn_idx];
84 return pc;
85}
86
87// Get the opcode given a program counter. Can return trace opcode variants.
88int
89rb_iseq_opcode_at_pc(const rb_iseq_t *iseq, const VALUE *pc)
90{
91 // YJIT should only use iseqs after AST to bytecode compilation.
92 // (Certain non-default interpreter configurations never set ISEQ_TRANSLATED)
93 if (OPT_DIRECT_THREADED_CODE || OPT_CALL_THREADED_CODE) {
94 RUBY_ASSERT_ALWAYS(FL_TEST_RAW((VALUE)iseq, ISEQ_TRANSLATED));
95 }
96
97 const VALUE at_pc = *pc;
98 return rb_vm_insn_addr2opcode((const void *)at_pc);
99}
100
101// Get the bare opcode given a program counter. Always returns the base
102// instruction, stripping trace/zjit variants.
103int
104rb_iseq_bare_opcode_at_pc(const rb_iseq_t *iseq, const VALUE *pc)
105{
106 if (OPT_DIRECT_THREADED_CODE || OPT_CALL_THREADED_CODE) {
107 RUBY_ASSERT_ALWAYS(FL_TEST_RAW((VALUE)iseq, ISEQ_TRANSLATED));
108 }
109
110 const VALUE at_pc = *pc;
111 return rb_vm_insn_addr2insn((const void *)at_pc);
112}
113
114unsigned long
115rb_RSTRING_LEN(VALUE str)
116{
117 return RSTRING_LEN(str);
118}
119
120char *
121rb_RSTRING_PTR(VALUE str)
122{
123 return RSTRING_PTR(str);
124}
125
126const char *
127rb_insn_name(VALUE insn)
128{
129 return insn_name(insn);
130}
131
132unsigned int
133rb_vm_ci_argc(const struct rb_callinfo *ci)
134{
135 return vm_ci_argc(ci);
136}
137
138ID
139rb_vm_ci_mid(const struct rb_callinfo *ci)
140{
141 return vm_ci_mid(ci);
142}
143
144unsigned int
145rb_vm_ci_flag(const struct rb_callinfo *ci)
146{
147 return vm_ci_flag(ci);
148}
149
150const struct rb_callinfo_kwarg *
151rb_vm_ci_kwarg(const struct rb_callinfo *ci)
152{
153 return vm_ci_kwarg(ci);
154}
155
156int
157rb_get_cikw_keyword_len(const struct rb_callinfo_kwarg *cikw)
158{
159 return cikw->keyword_len;
160}
161
162VALUE
163rb_get_cikw_keywords_idx(const struct rb_callinfo_kwarg *cikw, int idx)
164{
165 return cikw->keywords[idx];
166}
167
168rb_method_visibility_t
169rb_METHOD_ENTRY_VISI(const rb_callable_method_entry_t *me)
170{
171 return METHOD_ENTRY_VISI(me);
172}
173
174rb_method_type_t
175rb_get_cme_def_type(const rb_callable_method_entry_t *cme)
176{
177 if (UNDEFINED_METHOD_ENTRY_P(cme)) {
178 return VM_METHOD_TYPE_UNDEF;
179 }
180 else {
181 return cme->def->type;
182 }
183}
184
185ID
186rb_get_cme_def_body_attr_id(const rb_callable_method_entry_t *cme)
187{
188 return cme->def->body.attr.id;
189}
190
191enum method_optimized_type
192rb_get_cme_def_body_optimized_type(const rb_callable_method_entry_t *cme)
193{
194 return cme->def->body.optimized.type;
195}
196
197unsigned int
198rb_get_cme_def_body_optimized_index(const rb_callable_method_entry_t *cme)
199{
200 return cme->def->body.optimized.index;
201}
202
204rb_get_cme_def_body_cfunc(const rb_callable_method_entry_t *cme)
205{
206 return UNALIGNED_MEMBER_PTR(cme->def, body.cfunc);
207}
208
209uintptr_t
210rb_get_def_method_serial(const rb_method_definition_t *def)
211{
212 return def->method_serial;
213}
214
215ID
216rb_get_def_original_id(const rb_method_definition_t *def)
217{
218 return def->original_id;
219}
220
221VALUE
222rb_get_def_bmethod_proc(rb_method_definition_t *def)
223{
224 RUBY_ASSERT(def->type == VM_METHOD_TYPE_BMETHOD);
225 return def->body.bmethod.proc;
226}
227
228rb_proc_t *
229rb_jit_get_proc_ptr(VALUE procv)
230{
231 rb_proc_t *proc;
232 GetProcPtr(procv, proc);
233 return proc;
234}
235
236VALUE
237rb_optimized_call(VALUE recv, rb_execution_context_t *ec, int argc, VALUE *argv, int kw_splat, VALUE block_handler)
238{
239 rb_proc_t *proc;
240 GetProcPtr(recv, proc);
241 return rb_vm_invoke_proc(ec, proc, argc, argv, kw_splat, block_handler,
242 rb_proc_refinements_cref_for_call(recv));
243}
244
245unsigned int
246rb_jit_iseq_builtin_attrs(const rb_iseq_t *iseq)
247{
248 return ISEQ_BODY(iseq)->builtin_attrs;
249}
250
251// Relaxed memory ordering, but called by the JIT with VM lock and barrier.
252void
253rb_jit_iseq_mark_ep_escape_recorded(const rb_iseq_t *iseq)
254{
255 rbimpl_atomic_store(&ISEQ_BODY(iseq)->jit_ep_escape_recorded, 1, RBIMPL_ATOMIC_RELAXED);
256}
257
258// Whether an EP escape of this iseq has been reported to the enabled JIT.
259bool
260rb_jit_iseq_ep_escape_recorded_p(const rb_iseq_t *iseq)
261{
262 return rbimpl_atomic_load(&ISEQ_BODY(iseq)->jit_ep_escape_recorded, RBIMPL_ATOMIC_RELAXED) != 0;
263}
264
265int
266rb_get_mct_argc(const rb_method_cfunc_t *mct)
267{
268 return mct->argc;
269}
270
271void *
272rb_get_mct_func(const rb_method_cfunc_t *mct)
273{
274 return (void*)(uintptr_t)mct->func; // this field is defined as type VALUE (*func)(ANYARGS)
275}
276
277const rb_iseq_t *
278rb_get_def_iseq_ptr(rb_method_definition_t *def)
279{
280 return def_iseq_ptr(def);
281}
282
283const rb_iseq_t *
284rb_get_iseq_body_local_iseq(const rb_iseq_t *iseq)
285{
286 return ISEQ_BODY(iseq)->local_iseq;
287}
288
289const rb_iseq_t *
290rb_get_iseq_body_parent_iseq(const rb_iseq_t *iseq)
291{
292 return ISEQ_BODY(iseq)->parent_iseq;
293}
294
295unsigned int
296rb_get_iseq_body_local_table_size(const rb_iseq_t *iseq)
297{
298 return ISEQ_BODY(iseq)->local_table_size;
299}
300
301VALUE *
302rb_get_iseq_body_iseq_encoded(const rb_iseq_t *iseq)
303{
304 return ISEQ_BODY(iseq)->iseq_encoded;
305}
306
307unsigned
308rb_get_iseq_body_stack_max(const rb_iseq_t *iseq)
309{
310 return ISEQ_BODY(iseq)->stack_max;
311}
312
313enum rb_iseq_type
314rb_get_iseq_body_type(const rb_iseq_t *iseq)
315{
316 return ISEQ_BODY(iseq)->type;
317}
318
319bool
320rb_get_iseq_flags_has_lead(const rb_iseq_t *iseq)
321{
322 return ISEQ_BODY(iseq)->param.flags.has_lead;
323}
324
325bool
326rb_get_iseq_flags_has_opt(const rb_iseq_t *iseq)
327{
328 return ISEQ_BODY(iseq)->param.flags.has_opt;
329}
330
331bool
332rb_get_iseq_flags_has_kw(const rb_iseq_t *iseq)
333{
334 return ISEQ_BODY(iseq)->param.flags.has_kw;
335}
336
337bool
338rb_get_iseq_flags_has_post(const rb_iseq_t *iseq)
339{
340 return ISEQ_BODY(iseq)->param.flags.has_post;
341}
342
343bool
344rb_get_iseq_flags_has_kwrest(const rb_iseq_t *iseq)
345{
346 return ISEQ_BODY(iseq)->param.flags.has_kwrest;
347}
348
349bool
350rb_get_iseq_flags_anon_kwrest(const rb_iseq_t *iseq)
351{
352 return ISEQ_BODY(iseq)->param.flags.anon_kwrest;
353}
354
355bool
356rb_get_iseq_flags_has_rest(const rb_iseq_t *iseq)
357{
358 return ISEQ_BODY(iseq)->param.flags.has_rest;
359}
360
361bool
362rb_get_iseq_flags_ruby2_keywords(const rb_iseq_t *iseq)
363{
364 return ISEQ_BODY(iseq)->param.flags.ruby2_keywords;
365}
366
367bool
368rb_get_iseq_flags_has_block(const rb_iseq_t *iseq)
369{
370 return ISEQ_BODY(iseq)->param.flags.has_block;
371}
372
373bool
374rb_get_iseq_flags_ambiguous_param0(const rb_iseq_t *iseq)
375{
376 return ISEQ_BODY(iseq)->param.flags.ambiguous_param0;
377}
378
379bool
380rb_get_iseq_flags_accepts_no_kwarg(const rb_iseq_t *iseq)
381{
382 return ISEQ_BODY(iseq)->param.flags.accepts_no_kwarg;
383}
384
385bool
386rb_get_iseq_flags_forwardable(const rb_iseq_t *iseq)
387{
388 return ISEQ_BODY(iseq)->param.flags.forwardable;
389}
390
391// This is defined only as a named struct inside rb_iseq_constant_body.
392// By giving it a separate typedef, we make it nameable by rust-bindgen.
393// Bindgen's temp/anon name isn't guaranteed stable.
394typedef struct rb_iseq_param_keyword rb_iseq_param_keyword_struct;
395
396const rb_iseq_param_keyword_struct *
397rb_get_iseq_body_param_keyword(const rb_iseq_t *iseq)
398{
399 return ISEQ_BODY(iseq)->param.keyword;
400}
401
402unsigned
403rb_get_iseq_body_param_size(const rb_iseq_t *iseq)
404{
405 return ISEQ_BODY(iseq)->param.size;
406}
407
408int
409rb_get_iseq_body_param_lead_num(const rb_iseq_t *iseq)
410{
411 return ISEQ_BODY(iseq)->param.lead_num;
412}
413
414int
415rb_get_iseq_body_param_opt_num(const rb_iseq_t *iseq)
416{
417 return ISEQ_BODY(iseq)->param.opt_num;
418}
419
420const VALUE *
421rb_get_iseq_body_param_opt_table(const rb_iseq_t *iseq)
422{
423 return ISEQ_BODY(iseq)->param.opt_table;
424}
425
427rb_get_ec_cfp(const rb_execution_context_t *ec)
428{
429 return ec->cfp;
430}
431
432const rb_iseq_t *
433rb_get_cfp_iseq(struct rb_control_frame_struct *cfp)
434{
435 return CFP_ISEQ(cfp);
436}
437
438VALUE *
439rb_get_cfp_pc(struct rb_control_frame_struct *cfp)
440{
441 return (VALUE*)cfp->pc;
442}
443
444VALUE *
445rb_get_cfp_sp(struct rb_control_frame_struct *cfp)
446{
447 return cfp->sp;
448}
449
450VALUE
451rb_get_cfp_self(struct rb_control_frame_struct *cfp)
452{
453 return cfp->self;
454}
455
456VALUE *
457rb_get_cfp_ep(struct rb_control_frame_struct *cfp)
458{
459 return (VALUE*)cfp->ep;
460}
461
462const VALUE *
463rb_get_cfp_ep_level(struct rb_control_frame_struct *cfp, uint32_t lv)
464{
465 uint32_t i;
466 const VALUE *ep = (VALUE*)cfp->ep;
467 for (i = 0; i < lv; i++) {
468 ep = VM_ENV_PREV_EP(ep);
469 }
470 return ep;
471}
472
473VALUE
474rb_yarv_class_of(VALUE obj)
475{
476 return rb_class_of(obj);
477}
478
479// The FL_TEST() macro
480VALUE
481rb_FL_TEST(VALUE obj, VALUE flags)
482{
483 return RB_FL_TEST(obj, flags);
484}
485
486// The FL_TEST_RAW() macro, normally an internal implementation detail
487VALUE
488rb_FL_TEST_RAW(VALUE obj, VALUE flags)
489{
490 return FL_TEST_RAW(obj, flags);
491}
492
493// The RB_TYPE_P macro
494bool
495rb_RB_TYPE_P(VALUE obj, enum ruby_value_type t)
496{
497 return RB_TYPE_P(obj, t);
498}
499
500long
501rb_RSTRUCT_LEN(VALUE st)
502{
503 return RSTRUCT_LEN(st);
504}
505
506const struct rb_callinfo *
507rb_get_call_data_ci(const struct rb_call_data *cd)
508{
509 return cd->ci;
510}
511
512bool
513rb_BASIC_OP_UNREDEFINED_P(enum ruby_basic_operators bop, uint32_t klass)
514{
515 return BASIC_OP_UNREDEFINED_P(bop, klass);
516}
517
518VALUE
519rb_RCLASS_ORIGIN(VALUE c)
520{
521 return RCLASS_ORIGIN(c);
522}
523
524// For debug builds
525void
526rb_assert_iseq_handle(VALUE handle)
527{
528 RUBY_ASSERT_ALWAYS(IMEMO_TYPE_P(handle, imemo_iseq));
529}
530
531// Assert that we have the VM lock. Relevant mostly for multi ractor situations.
532// The GC takes the lock before calling us, and this asserts that it indeed happens.
533void
534rb_assert_holding_vm_lock(void)
535{
536 ASSERT_vm_locking();
537}
538
539int
540rb_IMEMO_TYPE_P(VALUE imemo, enum imemo_type imemo_type)
541{
542 return IMEMO_TYPE_P(imemo, imemo_type);
543}
544
545void
546rb_assert_cme_handle(VALUE handle)
547{
548 RUBY_ASSERT_ALWAYS(!rb_objspace_garbage_object_p(handle));
549 RUBY_ASSERT_ALWAYS(IMEMO_TYPE_P(handle, imemo_ment));
550}
551
552// YJIT and ZJIT need this function to never allocate and never raise
553VALUE
554rb_yarv_ary_entry_internal(VALUE ary, long offset)
555{
556 return rb_ary_entry_internal(ary, offset);
557}
558
559long
560rb_jit_array_len(VALUE a)
561{
562 return rb_array_len(a);
563}
564
565// Return non-zero when `obj` is an array and its last item is a
566// `ruby2_keywords` hash. The JITs don't support this kind of splat.
567size_t
568rb_jit_ruby2_keywords_splat_p(VALUE obj)
569{
570 if (!RB_TYPE_P(obj, T_ARRAY)) return 0;
571 long len = RARRAY_LEN(obj);
572 if (len == 0) return 0;
573 VALUE last = RARRAY_AREF(obj, len - 1);
574 if (!RB_TYPE_P(last, T_HASH)) return 0;
575 return FL_TEST_RAW(last, RHASH_PASS_AS_KEYWORDS);
576}
577
578void
579rb_set_cfp_pc(struct rb_control_frame_struct *cfp, const VALUE *pc)
580{
581 cfp->pc = pc;
582}
583
584void
585rb_set_cfp_sp(struct rb_control_frame_struct *cfp, VALUE *sp)
586{
587 cfp->sp = sp;
588}
589
590bool
591rb_jit_shape_complex_p(shape_id_t shape_id)
592{
593 return rb_shape_complex_p(shape_id);
594}
595
596bool
597rb_jit_multi_ractor_p(void)
598{
599 return rb_multi_ractor_p();
600}
601
602bool
603rb_jit_constcache_shareable(const struct iseq_inline_constant_cache_entry *ice)
604{
605 return (ice->flags & IMEMO_CONST_CACHE_SHAREABLE) != 0;
606}
607
608// Acquire the VM lock and then signal all other Ruby threads (ractors) to
609// contend for the VM lock, putting them to sleep. ZJIT and YJIT use this to
610// evict threads running inside generated code so among other things, it can
611// safely change memory protection of regions housing generated code.
612void
613rb_jit_vm_lock_then_barrier(unsigned int *recursive_lock_level, const char *file, int line)
614{
615 rb_vm_lock_enter(recursive_lock_level, file, line);
616 rb_vm_barrier();
617}
618
619// Release the VM lock. The lock level must point to the same integer used to
620// acquire the lock.
621void
622rb_jit_vm_unlock(unsigned int *recursive_lock_level, const char *file, int line)
623{
624 rb_vm_lock_leave(recursive_lock_level, file, line);
625}
626
627void *
628rb_iseq_get_jit_payload(const rb_iseq_t *iseq)
629{
630 RUBY_ASSERT_ALWAYS(IMEMO_TYPE_P(iseq, imemo_iseq));
631 if (ISEQ_BODY(iseq)) {
632 return ISEQ_BODY(iseq)->jit_payload;
633 }
634 else {
635 return NULL;
636 }
637}
638
639void
640rb_iseq_set_jit_payload(const rb_iseq_t *iseq, void *payload)
641{
642 RUBY_ASSERT_ALWAYS(IMEMO_TYPE_P(iseq, imemo_iseq));
643 RUBY_ASSERT_ALWAYS(ISEQ_BODY(iseq));
644 RUBY_ASSERT_ALWAYS(NULL == ISEQ_BODY(iseq)->jit_payload);
645 ISEQ_BODY(iseq)->jit_payload = payload;
646}
647
648void
649rb_iseq_reset_jit_func(const rb_iseq_t *iseq)
650{
651 RUBY_ASSERT_ALWAYS(IMEMO_TYPE_P(iseq, imemo_iseq));
652 ISEQ_BODY(iseq)->jit_entry = NULL;
653 ISEQ_BODY(iseq)->jit_exception = NULL;
654 // Enable re-compiling this ISEQ. Event when it's invalidated for TracePoint,
655 // we'd like to re-compile ISEQs that haven't been converted to trace_* insns.
656 ISEQ_BODY(iseq)->jit_entry_calls = 0;
657 ISEQ_BODY(iseq)->jit_exception_calls = 0;
658}
659
660// Callback data for rb_jit_for_each_iseq
662 rb_iseq_callback callback;
663 void *data;
664};
665
666// Heap-walking callback for rb_jit_for_each_iseq
667static int
668for_each_iseq_i(void *vstart, void *vend, size_t stride, void *data)
669{
670 const struct iseq_callback_data *callback_data = (struct iseq_callback_data *)data;
671 VALUE v = (VALUE)vstart;
672 for (; v != (VALUE)vend; v += stride) {
673 void *ptr = rb_asan_poisoned_object_p(v);
674 rb_asan_unpoison_object(v, false);
675
676 if (rb_obj_is_iseq(v)) {
677 rb_iseq_t *iseq = (rb_iseq_t *)v;
678 callback_data->callback(iseq, callback_data->data);
679 }
680
681 if (ptr) {
682 rb_asan_poison_object(v);
683 }
684 }
685 return 0;
686}
687
688uint32_t
689rb_jit_get_page_size(void)
690{
691#if defined(_SC_PAGESIZE)
692 long page_size = sysconf(_SC_PAGESIZE);
693 if (page_size <= 0) rb_bug("jit: failed to get page size");
694
695 // 1 GiB limit. x86 CPUs with PDPE1GB can do this and anything larger is unexpected.
696 // Though our design sort of assume we have fine grained control over memory protection
697 // which require small page sizes.
698 if (page_size > 0x40000000l) rb_bug("jit page size too large");
699
700 return (uint32_t)page_size;
701#else
702#error "JIT supports POSIX only for now"
703#endif
704}
705
706#if defined(MAP_FIXED_NOREPLACE) && defined(_SC_PAGESIZE)
707// Round `ptr` up to the next multiple of `multiple` bytes. Shared with zjit.c.
708uint8_t *
709rb_jit_align_ptr(uint8_t *ptr, uint32_t multiple)
710{
711 // Compute the pointer modulo the given alignment boundary
712 uint32_t rem = ((uint32_t)(uintptr_t)ptr) % multiple;
713
714 // If the pointer is already aligned, stop
715 if (rem == 0)
716 return ptr;
717
718 // Pad the pointer by the necessary amount to align it
719 uint32_t pad = multiple - rem;
720
721 return ptr + pad;
722}
723#endif
724
725// Address space reservation. Memory pages are mapped on an as needed basis.
726// See the Rust mm module for details.
727uint8_t *
728rb_jit_reserve_addr_space(uint32_t mem_size)
729{
730#ifndef _WIN32
731 uint8_t *mem_block;
732
733 // On Linux
734 #if defined(MAP_FIXED_NOREPLACE) && defined(_SC_PAGESIZE)
735 uint32_t const page_size = (uint32_t)sysconf(_SC_PAGESIZE);
736 uint8_t *const cfunc_sample_addr = (void *)(uintptr_t)&rb_jit_reserve_addr_space;
737 uint8_t *const probe_region_end = cfunc_sample_addr + INT32_MAX;
738 // Align the requested address to page size
739 uint8_t *req_addr = rb_jit_align_ptr(cfunc_sample_addr, page_size);
740
741 // Probe for addresses close to this function using MAP_FIXED_NOREPLACE
742 // to improve odds of being in range for 32-bit relative call instructions.
743 do {
744 mem_block = mmap(
745 req_addr,
746 mem_size,
747 PROT_NONE,
748 MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED_NOREPLACE,
749 -1,
750 0
751 );
752
753 // If we succeeded, stop
754 if (mem_block != MAP_FAILED) {
755 ruby_annotate_mmap(mem_block, mem_size, "Ruby:rb_jit_reserve_addr_space");
756 break;
757 }
758
759 // -4MiB. Downwards to probe away from the heap. (On x86/A64 Linux
760 // main_code_addr < heap_addr, and in case we are in a shared
761 // library mapped higher than the heap, downwards is still better
762 // since it's towards the end of the heap rather than the stack.)
763 req_addr -= 4 * 1024 * 1024;
764 } while (req_addr < probe_region_end);
765
766 // On MacOS and other platforms
767 #else
768 // Try to map a chunk of memory as executable
769 mem_block = mmap(
770 (void *)rb_jit_reserve_addr_space,
771 mem_size,
772 PROT_NONE,
773 MAP_PRIVATE | MAP_ANONYMOUS,
774 -1,
775 0
776 );
777 #endif
778
779 // Fallback
780 if (mem_block == MAP_FAILED) {
781 // Try again without the address hint (e.g., valgrind)
782 mem_block = mmap(
783 NULL,
784 mem_size,
785 PROT_NONE,
786 MAP_PRIVATE | MAP_ANONYMOUS,
787 -1,
788 0
789 );
790
791 if (mem_block != MAP_FAILED) {
792 ruby_annotate_mmap(mem_block, mem_size, "Ruby:rb_jit_reserve_addr_space:fallback");
793 }
794 }
795
796 // Check that the memory mapping was successful
797 if (mem_block == MAP_FAILED) {
798 perror("ruby: jit: mmap:");
799 if(errno == ENOMEM) {
800 // No crash report if it's only insufficient memory
801 exit(EXIT_FAILURE);
802 }
803 rb_bug("mmap failed");
804 }
805
806 return mem_block;
807#else
808 // Windows not supported for now
809 return NULL;
810#endif
811}
812
813// Walk all ISEQs in the heap and invoke the callback - shared between YJIT and ZJIT
814void
815rb_jit_for_each_iseq(rb_iseq_callback callback, void *data)
816{
817 struct iseq_callback_data callback_data = { .callback = callback, .data = data };
818 rb_objspace_each_objects(for_each_iseq_i, (void *)&callback_data);
819}
820
821bool
822rb_jit_mark_writable(void *mem_block, uint32_t mem_size)
823{
824 return mprotect(mem_block, mem_size, PROT_READ | PROT_WRITE) == 0;
825}
826
827void
828rb_jit_mark_executable(void *mem_block, uint32_t mem_size)
829{
830 // Do not call mprotect when mem_size is zero. Some platforms may return
831 // an error for it. https://github.com/Shopify/ruby/issues/450
832 if (mem_size == 0) {
833 return;
834 }
835 if (mprotect(mem_block, mem_size, PROT_READ | PROT_EXEC)) {
836 rb_bug("Couldn't make JIT page (%p, %lu bytes) executable, errno: %s",
837 mem_block, (unsigned long)mem_size, strerror(errno));
838 }
839}
840
841// Free the specified memory block.
842bool
843rb_jit_mark_unused(void *mem_block, uint32_t mem_size)
844{
845 // On Linux, you need to use madvise MADV_DONTNEED to free memory.
846 // We might not need to call this on macOS, but it's not really documented.
847 // We generally prefer to do the same thing on both to ease testing too.
848 madvise(mem_block, mem_size, MADV_DONTNEED);
849
850 // On macOS, mprotect PROT_NONE seems to reduce RSS.
851 // We also call this on Linux to avoid executing unused pages.
852 return mprotect(mem_block, mem_size, PROT_NONE) == 0;
853}
854
855// Invalidate icache for arm64.
856// `start` is inclusive and `end` is exclusive.
857void
858rb_jit_icache_invalidate(void *start, void *end)
859{
860 // Clear/invalidate the instruction cache. Compiles to nothing on x86_64
861 // but required on ARM before running freshly written code.
862 // On Darwin it's the same as calling sys_icache_invalidate().
863#ifdef __GNUC__
864 __builtin___clear_cache(start, end);
865#elif defined(__aarch64__)
866#error No instruction cache clear available with this compiler on Aarch64!
867#endif
868}
869
870VALUE
871rb_jit_fix_mod_fix(VALUE recv, VALUE obj)
872{
873 return rb_fix_mod_fix(recv, obj);
874}
875
876VALUE
877rb_jit_fix_div_fix(VALUE recv, VALUE obj)
878{
879 return rb_fix_div_fix(recv, obj);
880}
881
882// YJIT/ZJIT need this function to never allocate and never raise
883VALUE
884rb_yarv_str_eql_internal(VALUE str1, VALUE str2)
885{
886 // We wrap this since it's static inline
887 return rb_str_eql_internal(str1, str2);
888}
889
890VALUE
891rb_jit_str_simple_append(VALUE str1, VALUE str2)
892{
893 return rb_str_cat(str1, RSTRING_PTR(str2), RSTRING_LEN(str2));
894}
895
896void rb_jit_str_concat_codepoint(VALUE str, VALUE codepoint);
897
898attr_index_t
899rb_jit_shape_capacity(shape_id_t shape_id)
900{
901 return RSHAPE_CAPACITY(shape_id);
902}
#define RUBY_ASSERT_ALWAYS(expr,...)
A variant of RUBY_ASSERT that does not interface with RUBY_DEBUG.
Definition assert.h:199
#define RUBY_ASSERT(...)
Asserts that the given expression is truthy if and only if RUBY_DEBUG is truthy.
Definition assert.h:219
static VALUE RB_FL_TEST(VALUE obj, VALUE flags)
Tests if the given flag(s) are set or not.
Definition fl_type.h:430
#define T_HASH
Old name of RUBY_T_HASH.
Definition value_type.h:65
#define FL_TEST_RAW
Old name of RB_FL_TEST_RAW.
Definition fl_type.h:128
#define T_ARRAY
Old name of RUBY_T_ARRAY.
Definition value_type.h:56
static VALUE rb_class_of(VALUE obj)
Object to class mapping function.
Definition globals.h:174
Defines RBIMPL_HAS_BUILTIN.
VALUE rb_str_cat(VALUE dst, const char *src, long srclen)
Destructively appends the passed contents to the string.
Definition string.c:3666
int len
Length of the buffer.
Definition io.h:8
#define RARRAY_LEN
Just another name of rb_array_len.
Definition rarray.h:50
static long rb_array_len(VALUE a)
Queries the length of the array.
Definition rarray.h:254
#define RARRAY_AREF(a, i)
Definition rarray.h:402
static long RSTRUCT_LEN(VALUE st)
Returns the number of struct members.
Definition rstruct.h:82
Defines struct RTypedData.
#define errno
Ractor-aware version of errno.
Definition ruby.h:388
Definition hash.h:54
Ruby's ordinal objects.
Definition robject.h:56
VALUE extended
When an object slot is too small or too complex to store instance variables inline,...
Definition robject.h:78
Ruby's String.
Definition rstring.h:196
"Typed" user data.
Definition rtypeddata.h:393
Definition vm_core.h:261
Definition method.h:63
uintptr_t ID
Type that represents a Ruby identifier such as a variable name.
Definition value.h:52
uintptr_t VALUE
Type that represents a Ruby object.
Definition value.h:40
static 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