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