Ruby 4.1.0dev (2026-09-21 revision 61de3dd727146cfcf24e8051595bb2fb842f37aa)
iseq.c (61de3dd727146cfcf24e8051595bb2fb842f37aa)
1/**********************************************************************
2
3 iseq.c -
4
5 $Author$
6 created at: 2006-07-11(Tue) 09:00:03 +0900
7
8 Copyright (C) 2006 Koichi Sasada
9
10**********************************************************************/
11
12#define RUBY_VM_INSNS_INFO 1
13/* #define RUBY_MARK_FREE_DEBUG 1 */
14
15#include "ruby/internal/config.h"
16
17#ifdef HAVE_DLADDR
18# include <dlfcn.h>
19#endif
20
21#include "eval_intern.h"
22#include "id.h"
23#include "id_table.h"
24#include "internal.h"
25#include "internal/bits.h"
26#include "internal/class.h"
27#include "internal/compile.h"
28#include "internal/coverage.h"
29#include "internal/error.h"
30#include "internal/file.h"
31#include "internal/gc.h"
32#include "internal/hash.h"
33#include "internal/io.h"
34#include "internal/ruby_parser.h"
35#include "internal/sanitizers.h"
36#include "internal/set_table.h"
37#include "internal/symbol.h"
38#include "internal/thread.h"
39#include "internal/variable.h"
40#include "iseq.h"
41#include "ruby/util.h"
42#include "vm_core.h"
43#include "vm_sync.h"
44#include "ractor_core.h"
45#include "vm_callinfo.h"
46#include "yjit.h"
47#include "ruby/ractor.h"
48#include "builtin.h"
49#include "insns.inc"
50#include "insns_info.inc"
51#include "zjit.h"
52
53VALUE rb_cISeq;
54static VALUE iseqw_new(const rb_iseq_t *iseq);
55static const rb_iseq_t *iseqw_check(VALUE iseqw);
56
57#if VM_INSN_INFO_TABLE_IMPL == 2
58static struct succ_index_table *succ_index_table_create(int max_pos, int *data, int size);
59static unsigned int *succ_index_table_invert(int max_pos, struct succ_index_table *sd, int size);
60static int succ_index_lookup(const struct succ_index_table *sd, int x);
61#endif
62
63#define hidden_obj_p(obj) (!SPECIAL_CONST_P(obj) && !RBASIC(obj)->klass)
64
65static inline VALUE
66obj_resurrect(VALUE obj)
67{
68 if (hidden_obj_p(obj)) {
69 switch (BUILTIN_TYPE(obj)) {
70 case T_STRING:
71 obj = rb_str_resurrect(obj);
72 break;
73 case T_ARRAY:
74 obj = rb_ary_resurrect(obj);
75 break;
76 case T_HASH:
77 obj = rb_hash_resurrect(obj);
78 break;
79 default:
80 break;
81 }
82 }
83 return obj;
84}
85
86static void
87free_arena(struct iseq_compile_data_storage *cur)
88{
89 struct iseq_compile_data_storage *next;
90
91 while (cur) {
92 next = cur->next;
93 ruby_xfree_sized(cur, offsetof(struct iseq_compile_data_storage, buff) + cur->size * sizeof(char));
94 cur = next;
95 }
96}
97
98static void
99compile_data_free(struct iseq_compile_data *compile_data)
100{
101 if (compile_data) {
102 free_arena(compile_data->node.storage_head);
103 free_arena(compile_data->insn.storage_head);
104 if (compile_data->ivar_cache_table) {
105 rb_id_table_free(compile_data->ivar_cache_table);
106 }
107 SIZED_FREE(compile_data);
108 }
109}
110
111static void
112remove_from_constant_cache(ID id, IC ic)
113{
114 rb_vm_t *vm = GET_VM();
115 VALUE lookup_result;
116 st_data_t ic_data = (st_data_t)ic;
117
118 if (rb_id_table_lookup(&vm->constant_cache, id, &lookup_result)) {
119 set_table *ics = (set_table *)lookup_result;
120 set_table_delete(ics, &ic_data);
121
122 if (ics->num_entries == 0 &&
123 // See comment in vm_track_constant_cache on why we need this check
124 id != vm->inserting_constant_cache_id) {
125 rb_id_table_delete(&vm->constant_cache, id);
126 set_free_table(ics);
127 }
128 }
129}
130
131// When an ISEQ is being freed, all of its associated ICs are going to go away
132// as well. Because of this, we need to iterate over the ICs, and clear them
133// from the VM's constant cache.
134static void
135iseq_clear_ic_references(const rb_iseq_t *iseq)
136{
137 // In some cases (when there is a compilation error), we end up with
138 // ic_size greater than 0, but no allocated is_entries buffer.
139 // If there's no is_entries buffer to loop through, return early.
140 // [Bug #19173]
141 if (!ISEQ_BODY(iseq)->is_entries) {
142 return;
143 }
144
145 for (unsigned int ic_idx = 0; ic_idx < ISEQ_BODY(iseq)->ic_size; ic_idx++) {
146 IC ic = &ISEQ_IS_IC_ENTRY(ISEQ_BODY(iseq), ic_idx);
147
148 // Iterate over the IC's constant path's segments and clean any references to
149 // the ICs out of the VM's constant cache table.
150 const ID *segments = ic->segments;
151
152 // It's possible that segments is NULL if we overallocated an IC but
153 // optimizations removed the instruction using it
154 if (segments == NULL)
155 continue;
156
157 int i;
158 for (i = 0; segments[i]; i++) {
159 ID id = segments[i];
160 if (id == idNULL) continue;
161 remove_from_constant_cache(id, ic);
162 }
163
164 SIZED_FREE_N(segments, i + 1);
165 }
166}
167
168
170rb_iseq_local_hooks(const rb_iseq_t *iseq, rb_ractor_t *r, bool create)
171{
172 rb_hook_list_t *hook_list = NULL;
173 st_data_t val;
174 if (st_lookup(rb_ractor_targeted_hooks(r), (st_data_t)iseq, &val)) {
175 hook_list = (rb_hook_list_t*)val;
176 RUBY_ASSERT(hook_list->type == hook_list_type_targeted_iseq);
177 }
178 else if (create) {
179 hook_list = RB_ZALLOC(rb_hook_list_t);
180 hook_list->type = hook_list_type_targeted_iseq;
181 st_insert(rb_ractor_targeted_hooks(r), (st_data_t)iseq, (st_data_t)hook_list);
182 }
183 return hook_list;
184}
185
186void
187rb_iseq_free(const rb_iseq_t *iseq)
188{
189 RUBY_FREE_ENTER("iseq");
190
191 if (iseq && ISEQ_BODY(iseq)) {
192 iseq_clear_ic_references(iseq);
193 struct rb_iseq_constant_body *const body = ISEQ_BODY(iseq);
194#if USE_YJIT
195 if (rb_yjit_enabled_p) rb_yjit_iseq_free(iseq);
196 if (FL_TEST_RAW((VALUE)iseq, ISEQ_TRANSLATED)) {
197 RUBY_ASSERT(rb_yjit_live_iseq_count > 0);
198 rb_yjit_live_iseq_count--;
199 }
200#endif
201#if USE_ZJIT
202 if (rb_zjit_enabled_p) rb_zjit_iseq_free(iseq);
203#endif
204 SIZED_FREE_N(body->iseq_encoded, body->iseq_size);
205 SIZED_FREE_N(body->insns_info.body, body->insns_info.size);
206#if VM_INSN_INFO_TABLE_IMPL == 2
207 ruby_xfree(body->insns_info.positions_or_succ_index_table.succ_index_table);
208#else
209 SIZED_FREE_N(body->insns_info.positions_or_succ_index_table.positions, body->insns_info.size);
210#endif
211 SIZED_FREE_N(body->is_entries, ISEQ_IS_SIZE(body));
212 SIZED_FREE_N(body->call_data, body->ci_size);
213 if (body->catch_table) {
214 ruby_xfree_sized(body->catch_table, iseq_catch_table_bytes(body->catch_table->size));
215 }
216 SIZED_FREE_N(body->param.opt_table, body->param.opt_num + 1);
217 if (ISEQ_MBITS_BUFLEN(body->iseq_size) > 1 && body->mark_bits.list) {
218 SIZED_FREE_N(body->mark_bits.list, ISEQ_MBITS_BUFLEN(body->iseq_size));
219 }
220
221 ISEQ_ORIGINAL_ISEQ_CLEAR(iseq);
222 if (body->variable) xfree(body->variable);
223
224 struct rb_iseq_param_keyword *pkw = (struct rb_iseq_param_keyword *)body->param.keyword;
225 if (pkw != NULL) {
226 if (pkw->table != &body->local_table[pkw->bits_start - pkw->num])
227 SIZED_FREE_N(pkw->table, pkw->required_num);
228 if (pkw->default_values) {
229 SIZED_FREE_N(pkw->default_values, pkw->num - pkw->required_num);
230 }
231 SIZED_FREE(pkw);
232 }
233 if (LIKELY(body->local_table != rb_iseq_shared_exc_local_tbl)) {
234 SIZED_FREE_N(body->local_table, body->local_table_size);
235 }
236 if (!ISEQ_LVAR_STATES_EMBED_P(body->local_table_size)) {
237 SIZED_FREE_N(body->lvar_states.list, ISEQ_LVAR_STATES_BUFLEN(body->local_table_size));
238 }
239
240 compile_data_free(ISEQ_COMPILE_DATA(iseq));
241 if (body->outer_variables) rb_id_table_free(body->outer_variables);
242 SIZED_FREE(body);
243 }
244
245 RUBY_FREE_LEAVE("iseq");
246}
247
248/* CAS-publish the out-of-lined variable struct: concurrent callers (e.g. two
249 * dumpers hitting rb_iseq_original_iseq on a shared iseq) can each build a
250 * copy, mirroring the original_iseq CAS in compile.c. */
251struct rb_iseq_variable *
252rb_iseq_variable_ensure(rb_iseq_t *iseq)
253{
254 struct rb_iseq_variable *v = ISEQ_VARIABLE(iseq);
255 if (v) return v;
256 v = ALLOC(struct rb_iseq_variable);
257 v->flip_count = 0;
258 v->script_lines = Qnil;
259 v->coverage = Qfalse;
260 v->pc2branchindex = Qfalse;
261 v->original_iseq = NULL;
262 struct rb_iseq_variable *prev = ATOMIC_PTR_CAS(ISEQ_BODY(iseq)->variable, NULL, v);
263 if (prev) {
264 xfree(v);
265 v = prev;
266 }
267 return v;
268}
269
270void
271rb_iseq_coverage_set(rb_iseq_t *iseq, VALUE cov)
272{
273 if (!RTEST(cov) && !ISEQ_VARIABLE(iseq)) return;
274 struct rb_iseq_variable *v = rb_iseq_variable_ensure(iseq);
275 RB_OBJ_WRITE(iseq, &v->coverage, cov);
276}
277
278void
279rb_iseq_pc2branchindex_set(rb_iseq_t *iseq, VALUE h)
280{
281 if (!RTEST(h) && !ISEQ_VARIABLE(iseq)) return;
282 struct rb_iseq_variable *v = rb_iseq_variable_ensure(iseq);
283 RB_OBJ_WRITE(iseq, &v->pc2branchindex, h);
284}
285
286rb_snum_t
287rb_iseq_flip_cnt_increment(const rb_iseq_t *iseq)
288{
289 struct rb_iseq_variable *v = rb_iseq_variable_ensure((rb_iseq_t *)iseq);
290 rb_snum_t cnt = v->flip_count;
291 v->flip_count += 1;
292 return cnt;
293}
294
295typedef VALUE iseq_value_itr_t(void *ctx, VALUE obj);
296
297static inline void
298iseq_scan_bits(unsigned int page, iseq_bits_t bits, VALUE *code, VALUE *original_iseq)
299{
300 unsigned int offset;
301 unsigned int page_offset = (page * ISEQ_MBITS_BITLENGTH);
302
303 while (bits) {
304 offset = ntz_intptr(bits);
305 if (original_iseq) {
306 VALUE op = original_iseq[page_offset + offset];
307 rb_gc_mark_and_move(&code[page_offset + offset]);
308 VALUE newop = code[page_offset + offset];
309 if (op != newop) {
310 original_iseq[page_offset + offset] = newop;
311 }
312 }
313 else {
314 rb_gc_mark_and_move(&code[page_offset + offset]);
315 }
316 bits &= bits - 1; // Reset Lowest Set Bit (BLSR)
317 }
318}
319
320static void
321rb_iseq_mark_and_move_each_compile_data_value(const rb_iseq_t *iseq, VALUE *original_iseq)
322{
323 unsigned int size;
324 VALUE *code;
325 const struct iseq_compile_data *const compile_data = ISEQ_COMPILE_DATA(iseq);
326
327 size = compile_data->iseq_size;
328 code = compile_data->iseq_encoded;
329
330 // Embedded VALUEs
331 if (compile_data->mark_bits.list) {
332 if(compile_data->is_single_mark_bit) {
333 iseq_scan_bits(0, compile_data->mark_bits.single, code, original_iseq);
334 }
335 else {
336 for (unsigned int i = 0; i < ISEQ_MBITS_BUFLEN(size); i++) {
337 iseq_bits_t bits = compile_data->mark_bits.list[i];
338 iseq_scan_bits(i, bits, code, original_iseq);
339 }
340 }
341 }
342}
343static void
344rb_iseq_mark_and_move_each_body_value(const rb_iseq_t *iseq, VALUE *original_iseq)
345{
346 unsigned int size;
347 VALUE *code;
348 const struct rb_iseq_constant_body *const body = ISEQ_BODY(iseq);
349
350 size = body->iseq_size;
351 code = body->iseq_encoded;
352
353 union iseq_inline_storage_entry *is_entries = body->is_entries;
354
355 if (body->is_entries) {
356 // Skip iterating over ivc caches
357 is_entries += body->ivc_size;
358
359 // ICVARC entries
360 for (unsigned int i = 0; i < body->icvarc_size; i++, is_entries++) {
361 ICVARC icvarc = (ICVARC)is_entries;
362 if (icvarc->entry) {
363 rb_gc_mark_and_move((VALUE *)&icvarc->entry);
364 }
365 }
366
367 // ISE entries
368 for (unsigned int i = 0; i < body->ise_size; i++, is_entries++) {
369 union iseq_inline_storage_entry *const is = (union iseq_inline_storage_entry *)is_entries;
370 if (is->once.value) {
371 rb_gc_mark_and_move(&is->once.value);
372 }
373 }
374
375 // IC Entries
376 for (unsigned int i = 0; i < body->ic_size; i++, is_entries++) {
377 IC ic = (IC)is_entries;
378 if (ic->entry) {
379 rb_gc_mark_and_move_ptr(&ic->entry);
380 }
381 }
382 }
383
384 // Embedded VALUEs
385 if (body->mark_bits.list) {
386 if (ISEQ_MBITS_BUFLEN(size) == 1) {
387 iseq_scan_bits(0, body->mark_bits.single, code, original_iseq);
388 }
389 else {
390 for (unsigned int i = 0; i < ISEQ_MBITS_BUFLEN(size); i++) {
391 iseq_bits_t bits = body->mark_bits.list[i];
392 iseq_scan_bits(i, bits, code, original_iseq);
393 }
394 }
395 }
396}
397
398static bool
399cc_is_active(const struct rb_callcache *cc)
400{
401 RUBY_ASSERT(cc);
402 RUBY_ASSERT(vm_cc_markable(cc));
403
404 return vm_cc_valid(cc) && !METHOD_ENTRY_INVALIDATED(vm_cc_cme(cc));
405}
406
407void
408rb_iseq_mark_and_move(rb_iseq_t *iseq, bool reference_updating)
409{
410 RUBY_MARK_ENTER("iseq");
411
412 if (ISEQ_BODY(iseq)) {
413 struct rb_iseq_constant_body *body = ISEQ_BODY(iseq);
414
415 rb_iseq_mark_and_move_each_body_value(iseq, reference_updating ? ISEQ_ORIGINAL_ISEQ(iseq) : NULL);
416
417 struct rb_iseq_variable *v = ISEQ_VARIABLE(iseq);
418 if (v) rb_gc_mark_and_move(&v->script_lines);
419 rb_gc_mark_and_move(&body->location.label);
420 rb_gc_mark_and_move(&body->location.pathobj);
421 if (body->local_iseq) rb_gc_mark_and_move_ptr(&body->local_iseq);
422 if (body->parent_iseq) rb_gc_mark_and_move_ptr(&body->parent_iseq);
423 if (body->mandatory_only_iseq) rb_gc_mark_and_move_ptr(&body->mandatory_only_iseq);
424
425 if (body->call_data) {
426 struct rb_call_data *cds = body->call_data;
427 for (unsigned int i = 0; i < body->ci_size; i++) {
428
429 if (cds[i].ci) rb_gc_mark_and_move_ptr(&cds[i].ci);
430
431 const struct rb_callcache *cc = cds[i].cc;
432 if (!cc || cc == rb_vm_empty_cc() || cc == rb_vm_empty_cc_for_super()) {
433 // No need for marking, reference updating, or clearing
434 // We also want to avoid reassigning to improve CoW
435 continue;
436 }
437
438 if (reference_updating) {
439 rb_gc_update_moved_ptr(&cds[i].cc);
440 }
441 else {
442 if (cc_is_active(cc)) {
443 rb_gc_mark_movable((VALUE)cc);
444 }
445 else {
446 // Either the CC or CME has been invalidated. Replace
447 // it with the empty CC so that it can be GC'd.
448 cds[i].cc = rb_vm_empty_cc();
449 }
450 }
451 }
452 }
453
454 if (body->param.flags.has_kw && body->param.keyword != NULL) {
455 const struct rb_iseq_param_keyword *const keyword = body->param.keyword;
456
457 if (keyword->default_values != NULL) {
458 for (int j = 0, i = keyword->required_num; i < keyword->num; i++, j++) {
459 rb_gc_mark_and_move(&keyword->default_values[j]);
460 }
461 }
462 }
463
464 if (body->catch_table) {
465 struct iseq_catch_table *table = body->catch_table;
466
467 for (unsigned int i = 0; i < table->size; i++) {
468 struct iseq_catch_table_entry *entry;
469 entry = UNALIGNED_MEMBER_PTR(table, entries[i]);
470 if (entry->iseq) {
471 rb_gc_mark_and_move_ptr(&entry->iseq);
472 }
473 }
474 }
475
476#if USE_YJIT || USE_ZJIT
477 /* The JIT payload's critical section is the VM lock (racing other Ractors'
478 * compile/invalidate). Iseqs are born shareable, so a multi-Ractor local GC
479 * never traverses them. */
480 const bool jit_payload_lock_p = rb_gc_multi_objspace_p();
481 bool jit_payload_p = body->jit_payload != NULL;
482#endif
483 if (reference_updating) {
484#if USE_YJIT || USE_ZJIT
485 if (jit_payload_p) {
486 if (jit_payload_lock_p) {
487 RB_VM_LOCKING_NO_BARRIER() {
488# if USE_YJIT
489 if (rb_yjit_enabled_p) rb_yjit_iseq_update_references(iseq);
490# endif
491# if USE_ZJIT
492 if (rb_zjit_enabled_p) rb_zjit_iseq_update_references(body->jit_payload);
493# endif
494 }
495 }
496 else {
497# if USE_YJIT
498 if (rb_yjit_enabled_p) rb_yjit_iseq_update_references(iseq);
499# endif
500# if USE_ZJIT
501 if (rb_zjit_enabled_p) rb_zjit_iseq_update_references(body->jit_payload);
502# endif
503 }
504 }
505#endif
506 }
507 else {
508 // TODO: check jit payload
509 if (!rb_gc_checking_shareable()) {
510#if USE_YJIT || USE_ZJIT
511 if (jit_payload_p) {
512 if (jit_payload_lock_p) {
513 RB_VM_LOCKING_NO_BARRIER() {
514# if USE_YJIT
515 if (rb_yjit_enabled_p) rb_yjit_iseq_mark(body->jit_payload);
516# endif
517# if USE_ZJIT
518 if (rb_zjit_enabled_p) rb_zjit_iseq_mark(body->jit_payload);
519# endif
520 }
521 }
522 else {
523# if USE_YJIT
524 if (rb_yjit_enabled_p) rb_yjit_iseq_mark(body->jit_payload);
525# endif
526# if USE_ZJIT
527 if (rb_zjit_enabled_p) rb_zjit_iseq_mark(body->jit_payload);
528# endif
529 }
530 }
531#endif
532 }
533 }
534
535 // TODO: ractor aware coverage
536 if (!rb_gc_checking_shareable()) {
537 if (v) {
538 rb_gc_mark_and_move(&v->coverage);
539 rb_gc_mark_and_move(&v->pc2branchindex);
540 }
541 }
542 }
543
544 if (FL_TEST_RAW((VALUE)iseq, ISEQ_NOT_LOADED_YET)) {
545 if (!rb_gc_checking_shareable()) {
546 rb_gc_mark_and_move(&iseq->aux.loader.obj);
547 }
548 }
549 else if (FL_TEST_RAW((VALUE)iseq, ISEQ_USE_COMPILE_DATA)) {
550 if (!rb_gc_checking_shareable()) {
551 const struct iseq_compile_data *const compile_data = ISEQ_COMPILE_DATA(iseq);
552
553 rb_iseq_mark_and_move_insn_storage(compile_data->insn.storage_head);
554 rb_iseq_mark_and_move_each_compile_data_value(iseq, reference_updating ? ISEQ_ORIGINAL_ISEQ(iseq) : NULL);
555
556 rb_gc_mark_and_move((VALUE *)&compile_data->err_info);
557 rb_gc_mark_and_move((VALUE *)&compile_data->catch_table_ary);
558 }
559 }
560 else {
561 /* executable */
562 VM_ASSERT(ISEQ_EXECUTABLE_P(iseq));
563 }
564
565 RUBY_MARK_LEAVE("iseq");
566}
567
568static size_t
569param_keyword_size(const struct rb_iseq_param_keyword *pkw)
570{
571 size_t size = 0;
572
573 if (!pkw) return size;
574
575 size += sizeof(struct rb_iseq_param_keyword);
576 size += sizeof(VALUE) * (pkw->num - pkw->required_num);
577
578 return size;
579}
580
581size_t
582rb_iseq_memsize(const rb_iseq_t *iseq)
583{
584 size_t size = 0; /* struct already counted as RVALUE size */
585 const struct rb_iseq_constant_body *body = ISEQ_BODY(iseq);
586 const struct iseq_compile_data *compile_data;
587
588 /* TODO: should we count original_iseq? */
589
590 if (ISEQ_EXECUTABLE_P(iseq) && body) {
591 size += sizeof(struct rb_iseq_constant_body);
592 if (body->variable) size += sizeof(struct rb_iseq_variable);
593 size += body->iseq_size * sizeof(VALUE);
594 size += body->insns_info.size * (sizeof(struct iseq_insn_info_entry) + sizeof(unsigned int));
595 size += body->local_table_size * sizeof(ID); // body->local_table
596 if (!ISEQ_LVAR_STATES_EMBED_P(body->local_table_size) && body->lvar_states.list) {
597 size += ISEQ_LVAR_STATES_BUFLEN(body->local_table_size) * sizeof(uint8_t);
598 }
599 size += ISEQ_MBITS_BUFLEN(body->iseq_size) * ISEQ_MBITS_SIZE;
600 if (body->catch_table) {
601 size += iseq_catch_table_bytes(body->catch_table->size);
602 }
603 size += (body->param.opt_num + 1) * sizeof(VALUE);
604 size += param_keyword_size(body->param.keyword);
605
606 if (body->outer_variables) size += rb_id_table_memsize(body->outer_variables);
607
608 /* body->is_entries */
609 size += ISEQ_IS_SIZE(body) * sizeof(union iseq_inline_storage_entry);
610
611 if (ISEQ_BODY(iseq)->is_entries) {
612 /* IC entries constant segments */
613 for (unsigned int ic_idx = 0; ic_idx < body->ic_size; ic_idx++) {
614 IC ic = &ISEQ_IS_IC_ENTRY(body, ic_idx);
615 const ID *ids = ic->segments;
616 if (!ids) continue;
617 while (*ids++) {
618 size += sizeof(ID);
619 }
620 size += sizeof(ID); // null terminator
621 }
622 }
623
624 /* body->call_data */
625 size += body->ci_size * sizeof(struct rb_call_data);
626 // TODO: should we count imemo_callinfo?
627 }
628
629 compile_data = ISEQ_COMPILE_DATA(iseq);
630 if (compile_data) {
631 struct iseq_compile_data_storage *cur;
632
633 size += sizeof(struct iseq_compile_data);
634
635 cur = compile_data->node.storage_head;
636 while (cur) {
637 size += cur->size + offsetof(struct iseq_compile_data_storage, buff);
638 cur = cur->next;
639 }
640 }
641
642 return size;
643}
644
646rb_iseq_constant_body_alloc(void)
647{
648 struct rb_iseq_constant_body *iseq_body;
649 iseq_body = ZALLOC(struct rb_iseq_constant_body);
650 return iseq_body;
651}
652
653static rb_iseq_t *
654iseq_alloc(void)
655{
656 rb_iseq_t *iseq = iseq_imemo_alloc();
657 ISEQ_BODY(iseq) = rb_iseq_constant_body_alloc();
658 return iseq;
659}
660
661VALUE
662rb_iseq_pathobj_new(VALUE path, VALUE realpath)
663{
664 VALUE pathobj;
665 VM_ASSERT(RB_TYPE_P(path, T_STRING));
666 VM_ASSERT(NIL_P(realpath) || RB_TYPE_P(realpath, T_STRING));
667
668 if (path == realpath ||
669 (!NIL_P(realpath) && rb_str_cmp(path, realpath) == 0)) {
670 pathobj = rb_fstring(path);
671 }
672 else {
673 if (!NIL_P(realpath)) {
674 realpath = rb_fstring(realpath);
675 }
676 VALUE fpath = rb_fstring(path);
677
678 pathobj = rb_ary_new_from_args(2, fpath, realpath);
679 rb_ary_freeze(pathobj);
680 RB_OBJ_SET_SHAREABLE(pathobj);
681 }
682 return pathobj;
683}
684
685void
686rb_iseq_pathobj_set(const rb_iseq_t *iseq, VALUE path, VALUE realpath)
687{
688 RB_OBJ_WRITE(iseq, &ISEQ_BODY(iseq)->location.pathobj,
689 rb_iseq_pathobj_new(path, realpath));
690}
691
692// Make a dummy iseq for a dummy frame that exposes a path for profilers to inspect
693rb_iseq_t *
694rb_iseq_alloc_with_dummy_path(VALUE fname)
695{
696 rb_iseq_t *dummy_iseq = iseq_alloc();
697
698 ISEQ_BODY(dummy_iseq)->type = ISEQ_TYPE_TOP;
699
700 if (!RB_OBJ_SHAREABLE_P(fname)) {
702 }
703
704 RB_OBJ_WRITE(dummy_iseq, &ISEQ_BODY(dummy_iseq)->location.pathobj, fname);
705 RB_OBJ_WRITE(dummy_iseq, &ISEQ_BODY(dummy_iseq)->location.label, fname);
706
707 return dummy_iseq;
708}
709
710static rb_iseq_location_t *
711iseq_location_setup(rb_iseq_t *iseq, VALUE name, VALUE path, VALUE realpath, int first_lineno, const rb_code_location_t *code_location, const int node_id)
712{
713 rb_iseq_location_t *loc = &ISEQ_BODY(iseq)->location;
714
715 rb_iseq_pathobj_set(iseq, path, realpath);
716 RB_OBJ_WRITE(iseq, &loc->label, name);
717 loc->first_lineno = first_lineno;
718
719 if (ISEQ_BODY(iseq)->local_iseq == iseq && rb_streql_lit(name, "initialize")) {
720 ISEQ_BODY(iseq)->param.flags.use_block = 1;
721 }
722
723 if (code_location) {
724 loc->node_id = node_id;
725 loc->code_location = *code_location;
726 }
727 else {
728 loc->code_location.beg_pos.lineno = 0;
729 loc->code_location.beg_pos.column = 0;
730 loc->code_location.end_pos.lineno = -1;
731 loc->code_location.end_pos.column = -1;
732 }
733
734 return loc;
735}
736
737static void
738set_relation(rb_iseq_t *iseq, const rb_iseq_t *piseq)
739{
740 struct rb_iseq_constant_body *const body = ISEQ_BODY(iseq);
741 const VALUE type = body->type;
742
743 /* set class nest stack */
744 if (type == ISEQ_TYPE_TOP) {
745 body->local_iseq = iseq;
746 }
747 else if (type == ISEQ_TYPE_METHOD || type == ISEQ_TYPE_CLASS) {
748 body->local_iseq = iseq;
749 }
750 else if (piseq) {
751 RB_OBJ_WRITE(iseq, &body->local_iseq, ISEQ_BODY(piseq)->local_iseq);
752 }
753
754 if (piseq) {
755 RB_OBJ_WRITE(iseq, &body->parent_iseq, piseq);
756 }
757
758 if (type == ISEQ_TYPE_MAIN) {
759 body->local_iseq = iseq;
760 }
761}
762
763static struct iseq_compile_data_storage *
764new_arena(void)
765{
766 struct iseq_compile_data_storage * new_arena =
768 ALLOC_N(char, INITIAL_ISEQ_COMPILE_DATA_STORAGE_BUFF_SIZE +
769 offsetof(struct iseq_compile_data_storage, buff));
770
771 new_arena->pos = 0;
772 new_arena->next = 0;
773 new_arena->size = INITIAL_ISEQ_COMPILE_DATA_STORAGE_BUFF_SIZE;
774
775 return new_arena;
776}
777
778static int
779prepare_node_id(const NODE *node)
780{
781 if (!node) return -1;
782
783 if (nd_type(node) == NODE_SCOPE && RNODE_SCOPE(node)->nd_parent) {
784 return nd_node_id(RNODE_SCOPE(node)->nd_parent);
785 }
786
787 return nd_node_id(node);
788}
789
790static VALUE
791prepare_iseq_build(rb_iseq_t *iseq,
792 VALUE name, VALUE path, VALUE realpath, int first_lineno, const rb_code_location_t *code_location, const int node_id,
793 const rb_iseq_t *parent, int isolated_depth, enum rb_iseq_type type,
794 VALUE script_lines, const rb_compile_option_t *option)
795{
796 VALUE coverage = Qfalse;
797 VALUE err_info = Qnil;
798 struct rb_iseq_constant_body *const body = ISEQ_BODY(iseq);
799
800 if (parent && (type == ISEQ_TYPE_MAIN || type == ISEQ_TYPE_TOP))
801 err_info = Qfalse;
802
803 body->type = type;
804 set_relation(iseq, parent);
805
806 name = rb_fstring(name);
807 iseq_location_setup(iseq, name, path, realpath, first_lineno, code_location, node_id);
808 ISEQ_ORIGINAL_ISEQ_CLEAR(iseq);
809 if (body->variable) {
810 body->variable->flip_count = 0;
811 RB_OBJ_WRITE(iseq, &body->variable->script_lines, Qnil);
812 RB_OBJ_WRITE(iseq, &body->variable->coverage, Qnil);
813 }
814
815 if (!NIL_P(script_lines)) {
816 struct rb_iseq_variable *v = rb_iseq_variable_ensure(iseq);
817 RB_OBJ_WRITE(iseq, &v->script_lines, rb_ractor_make_shareable(script_lines));
818 }
819
820 ISEQ_COMPILE_DATA_ALLOC(iseq);
821 RB_OBJ_WRITE(iseq, &ISEQ_COMPILE_DATA(iseq)->err_info, err_info);
822 RB_OBJ_WRITE(iseq, &ISEQ_COMPILE_DATA(iseq)->catch_table_ary, Qnil);
823
824 ISEQ_COMPILE_DATA(iseq)->node.storage_head = ISEQ_COMPILE_DATA(iseq)->node.storage_current = new_arena();
825 ISEQ_COMPILE_DATA(iseq)->insn.storage_head = ISEQ_COMPILE_DATA(iseq)->insn.storage_current = new_arena();
826 ISEQ_COMPILE_DATA(iseq)->isolated_depth = isolated_depth;
827 ISEQ_COMPILE_DATA(iseq)->option = option;
828 ISEQ_COMPILE_DATA(iseq)->ivar_cache_table = NULL;
829 ISEQ_COMPILE_DATA(iseq)->builtin_function_table = GET_VM()->builtin_function_table;
830
831 if (option->coverage_enabled) {
832 VALUE coverages = rb_get_coverages();
833 if (RTEST(coverages)) {
834 coverage = rb_hash_lookup(coverages, rb_iseq_path(iseq));
835 if (NIL_P(coverage)) coverage = Qfalse;
836 }
837 }
838 ISEQ_COVERAGE_SET(iseq, coverage);
839 if (coverage && ISEQ_BRANCH_COVERAGE(iseq))
840 ISEQ_PC2BRANCHINDEX_SET(iseq, rb_ary_hidden_new(0));
841
842 return Qtrue;
843}
844
845#if VM_CHECK_MODE > 0 && VM_INSN_INFO_TABLE_IMPL > 0
846static void validate_get_insn_info(const rb_iseq_t *iseq);
847#endif
848
849void
850rb_iseq_insns_info_encode_positions(const rb_iseq_t *iseq)
851{
852#if VM_INSN_INFO_TABLE_IMPL == 2
853 /* create succ_index_table */
854 struct rb_iseq_constant_body *const body = ISEQ_BODY(iseq);
855 int size = body->insns_info.size;
856 int max_pos = body->iseq_size;
857 unsigned int *positions = body->insns_info.positions_or_succ_index_table.positions;
858 struct succ_index_table *sd = succ_index_table_create(max_pos, (int *)positions, size);
859 SIZED_FREE_N(positions, size);
860 body->insns_info.positions_or_succ_index_table.succ_index_table = sd;
861#endif
862}
863
864#if VM_INSN_INFO_TABLE_IMPL == 2
865unsigned int *
866rb_iseq_insns_info_decode_positions(const struct rb_iseq_constant_body *body)
867{
868 int size = body->insns_info.size;
869 int max_pos = body->iseq_size;
870 struct succ_index_table *sd = body->insns_info.positions_or_succ_index_table.succ_index_table;
871 return succ_index_table_invert(max_pos, sd, size);
872}
873#endif
874
875void
876rb_iseq_init_trace(rb_iseq_t *iseq)
877{
878 iseq->aux.exec.global_trace_events = 0;
879 if (ruby_vm_event_enabled_global_flags & ISEQ_TRACE_EVENTS) {
880 rb_iseq_trace_set(iseq, ruby_vm_event_enabled_global_flags & ISEQ_TRACE_EVENTS);
881 }
882}
883
884static VALUE
885finish_iseq_build(rb_iseq_t *iseq)
886{
887 struct iseq_compile_data *data = ISEQ_COMPILE_DATA(iseq);
888 const struct rb_iseq_constant_body *const body = ISEQ_BODY(iseq);
889 VALUE err = data->err_info;
890 ISEQ_COMPILE_DATA_CLEAR(iseq);
891 compile_data_free(data);
892
893#if VM_CHECK_MODE > 0 && VM_INSN_INFO_TABLE_IMPL > 0
894 validate_get_insn_info(iseq);
895#endif
896
897 if (RTEST(err)) {
898 VALUE path = pathobj_path(body->location.pathobj);
899 if (err == Qtrue) err = rb_exc_new_cstr(rb_eSyntaxError, "compile error");
900 rb_funcallv(err, rb_intern("set_backtrace"), 1, &path);
901 rb_exc_raise(err);
902 }
903
904 RB_DEBUG_COUNTER_INC(iseq_num);
905 RB_DEBUG_COUNTER_ADD(iseq_cd_num, ISEQ_BODY(iseq)->ci_size);
906
907 rb_iseq_init_trace(iseq);
908 return Qtrue;
909}
910
911static rb_compile_option_t COMPILE_OPTION_DEFAULT = {
912 .inline_const_cache = OPT_INLINE_CONST_CACHE,
913 .peephole_optimization = OPT_PEEPHOLE_OPTIMIZATION,
914 .tailcall_optimization = OPT_TAILCALL_OPTIMIZATION,
915 .specialized_instruction = OPT_SPECIALISED_INSTRUCTION,
916 .operands_unification = OPT_OPERANDS_UNIFICATION,
917 .instructions_unification = OPT_INSTRUCTIONS_UNIFICATION,
918 .frozen_string_literal = OPT_FROZEN_STRING_LITERAL,
919 .debug_frozen_string_literal = OPT_DEBUG_FROZEN_STRING_LITERAL,
920 .coverage_enabled = TRUE,
921};
922
923static const rb_compile_option_t COMPILE_OPTION_FALSE = {
924 .frozen_string_literal = -1, // unspecified
925};
926
927int
928rb_iseq_opt_frozen_string_literal(void)
929{
930 return COMPILE_OPTION_DEFAULT.frozen_string_literal;
931}
932
933static void
934set_compile_option_from_hash(rb_compile_option_t *option, VALUE opt)
935{
936#define SET_COMPILE_OPTION(o, h, mem) \
937 { VALUE flag = rb_hash_aref((h), ID2SYM(rb_intern(#mem))); \
938 if (flag == Qtrue) { (o)->mem = 1; } \
939 else if (flag == Qfalse) { (o)->mem = 0; } \
940 }
941#define SET_COMPILE_OPTION_NUM(o, h, mem) \
942 { VALUE num = rb_hash_aref((h), ID2SYM(rb_intern(#mem))); \
943 if (!NIL_P(num)) (o)->mem = NUM2INT(num); \
944 }
945 SET_COMPILE_OPTION(option, opt, inline_const_cache);
946 SET_COMPILE_OPTION(option, opt, peephole_optimization);
947 SET_COMPILE_OPTION(option, opt, tailcall_optimization);
948 SET_COMPILE_OPTION(option, opt, specialized_instruction);
949 SET_COMPILE_OPTION(option, opt, operands_unification);
950 SET_COMPILE_OPTION(option, opt, instructions_unification);
951 SET_COMPILE_OPTION(option, opt, frozen_string_literal);
952 SET_COMPILE_OPTION(option, opt, debug_frozen_string_literal);
953 SET_COMPILE_OPTION(option, opt, coverage_enabled);
954 SET_COMPILE_OPTION_NUM(option, opt, debug_level);
955#undef SET_COMPILE_OPTION
956#undef SET_COMPILE_OPTION_NUM
957}
958
959static rb_compile_option_t *
960set_compile_option_from_ast(rb_compile_option_t *option, const rb_ast_body_t *ast)
961{
962 if (ast->frozen_string_literal >= 0) {
963 option->frozen_string_literal = ast->frozen_string_literal;
964 }
965 return option;
966}
967
968static void
969make_compile_option(rb_compile_option_t *option, VALUE opt)
970{
971 if (NIL_P(opt)) {
972 *option = COMPILE_OPTION_DEFAULT;
973 }
974 else if (opt == Qfalse) {
975 *option = COMPILE_OPTION_FALSE;
976 }
977 else if (opt == Qtrue) {
978 int i;
979 for (i = 0; i < (int)(sizeof(rb_compile_option_t) / sizeof(int)); ++i)
980 ((int *)option)[i] = 1;
981 }
982 else if (RB_TYPE_P(opt, T_HASH)) {
983 *option = COMPILE_OPTION_DEFAULT;
984 set_compile_option_from_hash(option, opt);
985 }
986 else {
987 rb_raise(rb_eTypeError, "Compile option must be Hash/true/false/nil");
988 }
989}
990
991static VALUE
992make_compile_option_value(rb_compile_option_t *option)
993{
994 VALUE opt = rb_hash_new_capa(11);
995#define SET_COMPILE_OPTION(o, h, mem) \
996 rb_hash_aset((h), ID2SYM(rb_intern(#mem)), RBOOL((o)->mem))
997#define SET_COMPILE_OPTION_NUM(o, h, mem) \
998 rb_hash_aset((h), ID2SYM(rb_intern(#mem)), INT2NUM((o)->mem))
999 {
1000 SET_COMPILE_OPTION(option, opt, inline_const_cache);
1001 SET_COMPILE_OPTION(option, opt, peephole_optimization);
1002 SET_COMPILE_OPTION(option, opt, tailcall_optimization);
1003 SET_COMPILE_OPTION(option, opt, specialized_instruction);
1004 SET_COMPILE_OPTION(option, opt, operands_unification);
1005 SET_COMPILE_OPTION(option, opt, instructions_unification);
1006 SET_COMPILE_OPTION(option, opt, debug_frozen_string_literal);
1007 SET_COMPILE_OPTION(option, opt, coverage_enabled);
1008 SET_COMPILE_OPTION_NUM(option, opt, debug_level);
1009 }
1010#undef SET_COMPILE_OPTION
1011#undef SET_COMPILE_OPTION_NUM
1012 VALUE frozen_string_literal = option->frozen_string_literal == -1 ? Qnil : RBOOL(option->frozen_string_literal);
1013 rb_hash_aset(opt, ID2SYM(rb_intern("frozen_string_literal")), frozen_string_literal);
1014 return opt;
1015}
1016
1017rb_iseq_t *
1018rb_iseq_new(const VALUE ast_value, VALUE name, VALUE path, VALUE realpath,
1019 const rb_iseq_t *parent, enum rb_iseq_type type)
1020{
1021 return rb_iseq_new_with_opt(ast_value, name, path, realpath, 0, parent,
1022 0, type, &COMPILE_OPTION_DEFAULT,
1023 Qnil);
1024}
1025
1026static int
1027ast_line_count(const VALUE ast_value)
1028{
1029 rb_ast_t *ast = rb_ruby_ast_data_get(ast_value);
1030 return ast->body.line_count;
1031}
1032
1033static VALUE
1034iseq_setup_coverage(VALUE coverages, VALUE path, int line_count)
1035{
1036 if (line_count >= 0) {
1037 int len = (rb_get_coverage_mode() & COVERAGE_TARGET_ONESHOT_LINES) ? 0 : line_count;
1038
1039 VALUE coverage = rb_default_coverage(len);
1040 rb_hash_aset(coverages, path, coverage);
1041
1042 return coverage;
1043 }
1044
1045 return Qnil;
1046}
1047
1048static inline void
1049iseq_new_setup_coverage(VALUE path, int line_count)
1050{
1051 VALUE coverages = rb_get_coverages();
1052
1053 if (RTEST(coverages)) {
1054 iseq_setup_coverage(coverages, path, line_count);
1055 }
1056}
1057
1058rb_iseq_t *
1059rb_iseq_new_top(const VALUE ast_value, VALUE name, VALUE path, VALUE realpath, const rb_iseq_t *parent)
1060{
1061 iseq_new_setup_coverage(path, ast_line_count(ast_value));
1062
1063 return rb_iseq_new_with_opt(ast_value, name, path, realpath, 0, parent, 0,
1064 ISEQ_TYPE_TOP, &COMPILE_OPTION_DEFAULT,
1065 Qnil);
1066}
1067
1071rb_iseq_t *
1072pm_iseq_new_top(pm_scope_node_t *node, VALUE name, VALUE path, VALUE realpath, const rb_iseq_t *parent, int *error_state)
1073{
1074 iseq_new_setup_coverage(path, (int) (pm_parser_line_offsets(node->parser)->size - 1));
1075
1076 return pm_iseq_new_with_opt(node, name, path, realpath, 0, parent, 0,
1077 ISEQ_TYPE_TOP, &COMPILE_OPTION_DEFAULT, error_state);
1078}
1079
1080rb_iseq_t *
1081rb_iseq_new_main(const VALUE ast_value, VALUE path, VALUE realpath, const rb_iseq_t *parent, int opt)
1082{
1083 iseq_new_setup_coverage(path, ast_line_count(ast_value));
1084
1085 return rb_iseq_new_with_opt(ast_value, rb_fstring_lit("<main>"),
1086 path, realpath, 0,
1087 parent, 0, ISEQ_TYPE_MAIN, opt ? &COMPILE_OPTION_DEFAULT : &COMPILE_OPTION_FALSE,
1088 Qnil);
1089}
1090
1095rb_iseq_t *
1096pm_iseq_new_main(pm_scope_node_t *node, VALUE path, VALUE realpath, const rb_iseq_t *parent, int opt, int *error_state)
1097{
1098 iseq_new_setup_coverage(path, (int) (pm_parser_line_offsets(node->parser)->size - 1));
1099
1100 return pm_iseq_new_with_opt(node, rb_fstring_lit("<main>"),
1101 path, realpath, 0,
1102 parent, 0, ISEQ_TYPE_MAIN, opt ? &COMPILE_OPTION_DEFAULT : &COMPILE_OPTION_FALSE, error_state);
1103}
1104
1105rb_iseq_t *
1106rb_iseq_new_eval(const VALUE ast_value, VALUE name, VALUE path, VALUE realpath, int first_lineno, const rb_iseq_t *parent, int isolated_depth)
1107{
1108 if (rb_get_coverage_mode() & COVERAGE_TARGET_EVAL) {
1109 VALUE coverages = rb_get_coverages();
1110 if (RTEST(coverages) && RTEST(path) && !RTEST(rb_hash_has_key(coverages, path))) {
1111 iseq_setup_coverage(coverages, path, ast_line_count(ast_value) + first_lineno - 1);
1112 }
1113 }
1114
1115 rb_compile_option_t option = COMPILE_OPTION_DEFAULT;
1116 rb_ast_t *ast = rb_ruby_ast_data_get(ast_value);
1117 if (ast->body.coverage_enabled >= 0) {
1118 option.coverage_enabled = ast->body.coverage_enabled;
1119 }
1120 return rb_iseq_new_with_opt(ast_value, name, path, realpath, first_lineno,
1121 parent, isolated_depth, ISEQ_TYPE_EVAL, &option,
1122 Qnil);
1123}
1124
1125rb_iseq_t *
1126pm_iseq_new_eval(pm_scope_node_t *node, VALUE name, VALUE path, VALUE realpath,
1127 int first_lineno, const rb_iseq_t *parent, int isolated_depth, int *error_state)
1128{
1129 if (rb_get_coverage_mode() & COVERAGE_TARGET_EVAL) {
1130 VALUE coverages = rb_get_coverages();
1131 if (RTEST(coverages) && RTEST(path) && !RTEST(rb_hash_has_key(coverages, path))) {
1132 iseq_setup_coverage(coverages, path, ((int) (pm_parser_line_offsets(node->parser)->size - 1)) + first_lineno - 1);
1133 }
1134 }
1135
1136 return pm_iseq_new_with_opt(node, name, path, realpath, first_lineno,
1137 parent, isolated_depth, ISEQ_TYPE_EVAL, &COMPILE_OPTION_DEFAULT, error_state);
1138}
1139
1140static inline rb_iseq_t *
1141iseq_translate(rb_iseq_t *iseq)
1142{
1143 if (rb_respond_to(rb_cISeq, rb_intern("translate"))) {
1144 VALUE v1 = iseqw_new(iseq);
1145 VALUE v2 = rb_funcall(rb_cISeq, rb_intern("translate"), 1, v1);
1146 if (v1 != v2 && CLASS_OF(v2) == rb_cISeq) {
1147 iseq = (rb_iseq_t *)iseqw_check(v2);
1148 }
1149 }
1150
1151 return iseq;
1152}
1153
1154rb_iseq_t *
1155rb_iseq_new_with_opt(VALUE ast_value, VALUE name, VALUE path, VALUE realpath,
1156 int first_lineno, const rb_iseq_t *parent, int isolated_depth,
1157 enum rb_iseq_type type, const rb_compile_option_t *option,
1158 VALUE script_lines)
1159{
1160 rb_ast_t *ast = rb_ruby_ast_data_get(ast_value);
1161 rb_ast_body_t *body = ast ? &ast->body : NULL;
1162 const NODE *node = body ? body->root : 0;
1163 /* TODO: argument check */
1164 rb_iseq_t *iseq = iseq_alloc();
1165 rb_compile_option_t new_opt;
1166
1167 if (!option) option = &COMPILE_OPTION_DEFAULT;
1168 if (body) {
1169 new_opt = *option;
1170 option = set_compile_option_from_ast(&new_opt, body);
1171 }
1172
1173 if (!NIL_P(script_lines)) {
1174 // noop
1175 }
1176 else if (body && body->script_lines) {
1177 script_lines = rb_parser_build_script_lines_from(body->script_lines);
1178 }
1179 else if (parent) {
1180 script_lines = ISEQ_SCRIPT_LINES(parent);
1181 }
1182
1183 prepare_iseq_build(iseq, name, path, realpath, first_lineno, node ? &node->nd_loc : NULL, prepare_node_id(node),
1184 parent, isolated_depth, type, script_lines, option);
1185
1186 if (body && body->has_source_hash) {
1187 ISEQ_BODY(iseq)->source_hash = body->source_hash;
1188 RUBY_ASSERT(ISEQ_BODY(iseq)->source_hash != 0);
1189 }
1190
1191 rb_iseq_compile_node(iseq, node);
1192 finish_iseq_build(iseq);
1193 RB_GC_GUARD(ast_value);
1194
1195 return iseq_translate(iseq);
1196}
1197
1203rb_iseq_t *
1204pm_iseq_build(pm_scope_node_t *node, VALUE name, VALUE path, VALUE realpath,
1205 int first_lineno, const rb_iseq_t *parent, int isolated_depth,
1206 enum rb_iseq_type type, const rb_compile_option_t *option)
1207{
1208 rb_iseq_t *iseq = iseq_alloc();
1209 ISEQ_BODY(iseq)->prism = true;
1210
1211 ISEQ_BODY(iseq)->source_hash = node->source_hash;
1212 RUBY_ASSERT(ISEQ_BODY(iseq)->source_hash != 0);
1213
1214 rb_compile_option_t next_option;
1215 if (!option) option = &COMPILE_OPTION_DEFAULT;
1216
1217 next_option = *option;
1218 next_option.coverage_enabled = node->coverage_enabled < 0 ? 0 : node->coverage_enabled > 0;
1219 option = &next_option;
1220
1221 pm_location_t *location = &node->base.location;
1222 int32_t start_line = pm_parser_start_line(node->parser);
1223 const pm_line_offset_list_t *line_offsets = pm_parser_line_offsets(node->parser);
1224
1225 pm_line_column_t start = pm_line_offset_list_line_column(line_offsets, location->start, start_line);
1226 pm_line_column_t end = pm_line_offset_list_line_column(line_offsets, location->start + location->length, start_line);
1227
1228 rb_code_location_t code_location = (rb_code_location_t) {
1229 .beg_pos = { .lineno = (int) start.line, .column = (int) start.column },
1230 .end_pos = { .lineno = (int) end.line, .column = (int) end.column }
1231 };
1232
1233 prepare_iseq_build(iseq, name, path, realpath, first_lineno, &code_location, node->ast_node->node_id,
1234 parent, isolated_depth, type, node->script_lines == NULL ? Qnil : *node->script_lines, option);
1235
1236 pm_iseq_compile_node(iseq, node);
1237 finish_iseq_build(iseq);
1238
1239 return iseq_translate(iseq);
1240}
1241
1243 rb_iseq_t *iseq;
1244 pm_scope_node_t *node;
1245 VALUE name, path, realpath;
1246 int first_lineno, isolated_depth;
1247 const rb_iseq_t *parent;
1248 enum rb_iseq_type type;
1249 const rb_compile_option_t *option;
1250};
1251
1252static VALUE
1253pm_iseq_new_with_opt_try(VALUE d)
1254{
1255 struct pm_iseq_new_with_opt_data *data = (struct pm_iseq_new_with_opt_data *)d;
1256 data->iseq = pm_iseq_build(data->node, data->name, data->path, data->realpath,
1257 data->first_lineno, data->parent, data->isolated_depth,
1258 data->type, data->option);
1259 return Qundef;
1260}
1261
1274rb_iseq_t *
1275pm_iseq_new_with_opt(pm_scope_node_t *node, VALUE name, VALUE path, VALUE realpath,
1276 int first_lineno, const rb_iseq_t *parent, int isolated_depth,
1277 enum rb_iseq_type type, const rb_compile_option_t *option, int *error_state)
1278{
1279 struct pm_iseq_new_with_opt_data data = {
1280 .node = node, .name = name, .path = path, .realpath = realpath,
1281 .first_lineno = first_lineno, .parent = parent,
1282 .isolated_depth = isolated_depth, .type = type, .option = option
1283 };
1284 rb_protect(pm_iseq_new_with_opt_try, (VALUE)&data, error_state);
1285
1286 if (*error_state) return NULL;
1287
1288 return data.iseq;
1289}
1290
1291rb_iseq_t *
1292rb_iseq_new_with_callback(
1293 const struct rb_iseq_new_with_callback_callback_func * ifunc,
1294 VALUE name, VALUE path, VALUE realpath,
1295 int first_lineno, const rb_iseq_t *parent,
1296 enum rb_iseq_type type, const rb_compile_option_t *option)
1297{
1298 /* TODO: argument check */
1299 rb_iseq_t *iseq = iseq_alloc();
1300
1301 if (!option) option = &COMPILE_OPTION_DEFAULT;
1302 prepare_iseq_build(iseq, name, path, realpath, first_lineno, NULL, -1, parent, 0, type, Qnil, option);
1303
1304 rb_iseq_compile_callback(iseq, ifunc);
1305 finish_iseq_build(iseq);
1306
1307 return iseq;
1308}
1309
1310const rb_iseq_t *
1311rb_iseq_load_iseq(VALUE fname)
1312{
1313 VALUE iseqv = rb_check_funcall(rb_cISeq, rb_intern("load_iseq"), 1, &fname);
1314
1315 if (!SPECIAL_CONST_P(iseqv) && RBASIC_CLASS(iseqv) == rb_cISeq) {
1316 return iseqw_check(iseqv);
1317 }
1318
1319 return NULL;
1320}
1321
1322const rb_iseq_t *
1323rb_iseq_compile_iseq(VALUE str, VALUE fname)
1324{
1325 VALUE args[] = {
1326 str, fname
1327 };
1328 VALUE iseqv = rb_check_funcall(rb_cISeq, rb_intern("compile"), 2, args);
1329
1330 if (!SPECIAL_CONST_P(iseqv) && RBASIC_CLASS(iseqv) == rb_cISeq) {
1331 return iseqw_check(iseqv);
1332 }
1333
1334 return NULL;
1335}
1336
1337#define CHECK_ARRAY(v) rb_to_array_type(v)
1338#define CHECK_HASH(v) rb_to_hash_type(v)
1339#define CHECK_STRING(v) rb_str_to_str(v)
1340#define CHECK_SYMBOL(v) rb_to_symbol_type(v)
1341static inline VALUE CHECK_INTEGER(VALUE v) {(void)NUM2LONG(v); return v;}
1342
1343static enum rb_iseq_type
1344iseq_type_from_sym(VALUE type)
1345{
1346 const ID id_top = rb_intern("top");
1347 const ID id_method = rb_intern("method");
1348 const ID id_block = rb_intern("block");
1349 const ID id_class = rb_intern("class");
1350 const ID id_rescue = rb_intern("rescue");
1351 const ID id_ensure = rb_intern("ensure");
1352 const ID id_eval = rb_intern("eval");
1353 const ID id_main = rb_intern("main");
1354 const ID id_plain = rb_intern("plain");
1355 /* ensure all symbols are static or pinned down before
1356 * conversion */
1357 const ID typeid = rb_check_id(&type);
1358 if (typeid == id_top) return ISEQ_TYPE_TOP;
1359 if (typeid == id_method) return ISEQ_TYPE_METHOD;
1360 if (typeid == id_block) return ISEQ_TYPE_BLOCK;
1361 if (typeid == id_class) return ISEQ_TYPE_CLASS;
1362 if (typeid == id_rescue) return ISEQ_TYPE_RESCUE;
1363 if (typeid == id_ensure) return ISEQ_TYPE_ENSURE;
1364 if (typeid == id_eval) return ISEQ_TYPE_EVAL;
1365 if (typeid == id_main) return ISEQ_TYPE_MAIN;
1366 if (typeid == id_plain) return ISEQ_TYPE_PLAIN;
1367 return (enum rb_iseq_type)-1;
1368}
1369
1370static VALUE
1371iseq_load(VALUE data, const rb_iseq_t *parent, VALUE opt)
1372{
1373 rb_iseq_t *iseq = iseq_alloc();
1374
1375 VALUE magic, version1, version2, format_type, misc;
1376 VALUE name, path, realpath, code_location, node_id;
1377 VALUE type, body, locals, params, exception;
1378
1379 st_data_t iseq_type;
1380 rb_compile_option_t option;
1381 int i = 0;
1382 rb_code_location_t tmp_loc = { {0, 0}, {-1, -1} };
1383
1384 /* [magic, major_version, minor_version, format_type, misc,
1385 * label, path, first_lineno,
1386 * type, locals, args, exception_table, body]
1387 */
1388
1389 data = CHECK_ARRAY(data);
1390
1391 magic = CHECK_STRING(rb_ary_entry(data, i++));
1392 version1 = CHECK_INTEGER(rb_ary_entry(data, i++));
1393 version2 = CHECK_INTEGER(rb_ary_entry(data, i++));
1394 format_type = CHECK_INTEGER(rb_ary_entry(data, i++));
1395 misc = CHECK_HASH(rb_ary_entry(data, i++));
1396 ((void)magic, (void)version1, (void)version2, (void)format_type);
1397
1398 name = CHECK_STRING(rb_ary_entry(data, i++));
1399 path = CHECK_STRING(rb_ary_entry(data, i++));
1400 realpath = rb_ary_entry(data, i++);
1401 realpath = NIL_P(realpath) ? Qnil : CHECK_STRING(realpath);
1402 int first_lineno = RB_NUM2INT(rb_ary_entry(data, i++));
1403
1404 type = CHECK_SYMBOL(rb_ary_entry(data, i++));
1405 locals = CHECK_ARRAY(rb_ary_entry(data, i++));
1406 params = CHECK_HASH(rb_ary_entry(data, i++));
1407 exception = CHECK_ARRAY(rb_ary_entry(data, i++));
1408 body = CHECK_ARRAY(rb_ary_entry(data, i++));
1409
1410 ISEQ_BODY(iseq)->local_iseq = iseq;
1411
1412 iseq_type = iseq_type_from_sym(type);
1413 if (iseq_type == (enum rb_iseq_type)-1) {
1414 rb_raise(rb_eTypeError, "unsupported type: :%"PRIsVALUE, rb_sym2str(type));
1415 }
1416
1417 node_id = rb_hash_aref(misc, ID2SYM(rb_intern("node_id")));
1418
1419 code_location = rb_hash_aref(misc, ID2SYM(rb_intern("code_location")));
1420 if (RB_TYPE_P(code_location, T_ARRAY) && RARRAY_LEN(code_location) == 4) {
1421 tmp_loc.beg_pos.lineno = NUM2INT(rb_ary_entry(code_location, 0));
1422 tmp_loc.beg_pos.column = NUM2INT(rb_ary_entry(code_location, 1));
1423 tmp_loc.end_pos.lineno = NUM2INT(rb_ary_entry(code_location, 2));
1424 tmp_loc.end_pos.column = NUM2INT(rb_ary_entry(code_location, 3));
1425 }
1426
1427 if (SYM2ID(rb_hash_aref(misc, ID2SYM(rb_intern("parser")))) == rb_intern("prism")) {
1428 ISEQ_BODY(iseq)->prism = true;
1429 }
1430
1431 make_compile_option(&option, opt);
1432 option.peephole_optimization = FALSE; /* because peephole optimization can modify original iseq */
1433 prepare_iseq_build(iseq, name, path, realpath, first_lineno, &tmp_loc, NUM2INT(node_id),
1434 parent, 0, (enum rb_iseq_type)iseq_type, Qnil, &option);
1435
1436 rb_iseq_build_from_ary(iseq, misc, locals, params, exception, body);
1437
1438 finish_iseq_build(iseq);
1439
1440 return iseqw_new(iseq);
1441}
1442
1443/*
1444 * :nodoc:
1445 */
1446static VALUE
1447iseq_s_load(int argc, VALUE *argv, VALUE self)
1448{
1449 VALUE data, opt=Qnil;
1450 rb_scan_args(argc, argv, "11", &data, &opt);
1451 return iseq_load(data, NULL, opt);
1452}
1453
1454VALUE
1455rb_iseq_load(VALUE data, VALUE parent, VALUE opt)
1456{
1457 return iseq_load(data, RTEST(parent) ? (rb_iseq_t *)parent : NULL, opt);
1458}
1459
1460static rb_iseq_t *
1461rb_iseq_compile_with_option(VALUE src, VALUE file, VALUE realpath, VALUE line, VALUE opt)
1462{
1463 rb_iseq_t *iseq = NULL;
1464 rb_compile_option_t option;
1465#if !defined(__GNUC__)
1466# define INITIALIZED volatile /* suppress warnings */
1467#else
1468# define INITIALIZED /* volatile */
1469#endif
1470 VALUE (*parse)(VALUE vparser, VALUE fname, VALUE file, int start);
1471 int ln;
1472 VALUE INITIALIZED ast_value;
1473 rb_ast_t *ast;
1474 VALUE name = rb_fstring_lit("<compiled>");
1475
1476 /* safe results first */
1477 make_compile_option(&option, opt);
1478 ln = NUM2INT(line);
1479 StringValueCStr(file);
1480 if (RB_TYPE_P(src, T_FILE)) {
1481 parse = rb_parser_compile_file_path;
1482 }
1483 else {
1484 parse = rb_parser_compile_string_path;
1485 StringValue(src);
1486 }
1487 {
1488 const VALUE parser = rb_parser_new();
1489 const rb_iseq_t *outer_scope = rb_iseq_new(Qnil, name, name, Qnil, 0, ISEQ_TYPE_TOP);
1490 VALUE outer_scope_v = (VALUE)outer_scope;
1491 rb_parser_set_context(parser, outer_scope, FALSE);
1492 if (ruby_vm_keep_script_lines) rb_parser_set_script_lines(parser);
1493 RB_GC_GUARD(outer_scope_v);
1494 ast_value = (*parse)(parser, file, src, ln);
1495 }
1496
1497 ast = rb_ruby_ast_data_get(ast_value);
1498
1499 if (!ast || !ast->body.root) {
1500 rb_ast_dispose(ast);
1501 rb_exc_raise(GET_EC()->errinfo);
1502 }
1503 else {
1504 if (option.coverage_enabled) iseq_new_setup_coverage(file, ast_line_count(ast_value));
1505 iseq = rb_iseq_new_with_opt(ast_value, name, file, realpath, ln,
1506 NULL, 0, ISEQ_TYPE_TOP, &option,
1507 Qnil);
1508 rb_ast_dispose(ast);
1509 }
1510
1511 return iseq;
1512}
1513
1514static rb_iseq_t *
1515pm_iseq_compile_with_option(VALUE src, VALUE file, VALUE realpath, VALUE line, VALUE opt)
1516{
1517 rb_iseq_t *iseq = NULL;
1518 rb_compile_option_t option;
1519 int ln;
1520 VALUE name = rb_fstring_lit("<compiled>");
1521
1522 /* safe results first */
1523 make_compile_option(&option, opt);
1524 ln = NUM2INT(line);
1525 StringValueCStr(file);
1526
1527 bool parse_file = false;
1528 if (RB_TYPE_P(src, T_FILE)) {
1529 parse_file = true;
1530 src = rb_io_path(src);
1531 }
1532 else {
1533 src = StringValue(src);
1534 }
1535
1536 pm_parse_result_t result;
1537 pm_parse_result_init(&result);
1538 pm_options_line_set(result.options, NUM2INT(line));
1539 pm_options_scopes_init(result.options, 1);
1540 result.node.coverage_enabled = option.coverage_enabled;
1541
1542 switch (option.frozen_string_literal) {
1543 case ISEQ_FROZEN_STRING_LITERAL_UNSET:
1544 break;
1545 case ISEQ_FROZEN_STRING_LITERAL_DISABLED:
1546 pm_options_frozen_string_literal_set(result.options, false);
1547 break;
1548 case ISEQ_FROZEN_STRING_LITERAL_ENABLED:
1549 pm_options_frozen_string_literal_set(result.options, true);
1550 break;
1551 default:
1552 rb_bug("pm_iseq_compile_with_option: invalid frozen_string_literal=%d", option.frozen_string_literal);
1553 break;
1554 }
1555
1556 VALUE script_lines;
1557 VALUE error;
1558
1559 if (parse_file) {
1560 error = pm_load_parse_file(&result, src, ruby_vm_keep_script_lines ? &script_lines : NULL);
1561 }
1562 else {
1563 error = pm_parse_string(&result, src, file, ruby_vm_keep_script_lines ? &script_lines : NULL);
1564 }
1565
1566 RB_GC_GUARD(src);
1567
1568 if (error == Qnil) {
1569 int error_state;
1570 if (option.coverage_enabled) iseq_new_setup_coverage(file, (int) (pm_parser_line_offsets(result.node.parser)->size - 1));
1571 iseq = pm_iseq_new_with_opt(&result.node, name, file, realpath, ln, NULL, 0, ISEQ_TYPE_TOP, &option, &error_state);
1572
1573 pm_parse_result_free(&result);
1574
1575 if (error_state) {
1576 RUBY_ASSERT(iseq == NULL);
1577 rb_jump_tag(error_state);
1578 }
1579 }
1580 else {
1581 pm_parse_result_free(&result);
1582 rb_exc_raise(error);
1583 }
1584
1585 return iseq;
1586}
1587
1588VALUE
1589rb_iseq_path(const rb_iseq_t *iseq)
1590{
1591 return pathobj_path(ISEQ_BODY(iseq)->location.pathobj);
1592}
1593
1594VALUE
1595rb_iseq_realpath(const rb_iseq_t *iseq)
1596{
1597 return pathobj_realpath(ISEQ_BODY(iseq)->location.pathobj);
1598}
1599
1600VALUE
1601rb_iseq_absolute_path(const rb_iseq_t *iseq)
1602{
1603 return rb_iseq_realpath(iseq);
1604}
1605
1606int
1607rb_iseq_from_eval_p(const rb_iseq_t *iseq)
1608{
1609 return NIL_P(rb_iseq_realpath(iseq));
1610}
1611
1612VALUE
1613rb_iseq_label(const rb_iseq_t *iseq)
1614{
1615 return ISEQ_BODY(iseq)->location.label;
1616}
1617
1618VALUE
1619rb_iseq_base_label(const rb_iseq_t *iseq)
1620{
1621 const struct rb_iseq_constant_body *body = ISEQ_BODY(iseq);
1622 const rb_iseq_t *local_iseq = body->local_iseq;
1623
1624 if (local_iseq == NULL || local_iseq == iseq) {
1625 return body->location.label;
1626 }
1627 else {
1628 return ISEQ_BODY(rb_iseq_check(local_iseq))->location.label;
1629 }
1630}
1631
1632VALUE
1633rb_iseq_first_lineno(const rb_iseq_t *iseq)
1634{
1635 return RB_INT2NUM(ISEQ_BODY(iseq)->location.first_lineno);
1636}
1637
1638VALUE
1639rb_iseq_method_name(const rb_iseq_t *iseq)
1640{
1641 struct rb_iseq_constant_body *const body = ISEQ_BODY(ISEQ_BODY(iseq)->local_iseq);
1642
1643 if (body->type == ISEQ_TYPE_METHOD) {
1644 return body->location.label;
1645 }
1646 else {
1647 return Qnil;
1648 }
1649}
1650
1651void
1652rb_iseq_code_location(const rb_iseq_t *iseq, int *beg_pos_lineno, int *beg_pos_column, int *end_pos_lineno, int *end_pos_column)
1653{
1654 const rb_code_location_t *loc = &ISEQ_BODY(iseq)->location.code_location;
1655 if (beg_pos_lineno) *beg_pos_lineno = loc->beg_pos.lineno;
1656 if (beg_pos_column) *beg_pos_column = loc->beg_pos.column;
1657 if (end_pos_lineno) *end_pos_lineno = loc->end_pos.lineno;
1658 if (end_pos_column) *end_pos_column = loc->end_pos.column;
1659}
1660
1661static ID iseq_type_id(enum rb_iseq_type type);
1662
1663VALUE
1664rb_iseq_type(const rb_iseq_t *iseq)
1665{
1666 return ID2SYM(iseq_type_id(ISEQ_BODY(iseq)->type));
1667}
1668
1669VALUE
1670rb_iseq_coverage(const rb_iseq_t *iseq)
1671{
1672 return ISEQ_COVERAGE(iseq);
1673}
1674
1675static int
1676remove_coverage_i(void *vstart, void *vend, size_t stride, void *data)
1677{
1678 VALUE v = (VALUE)vstart;
1679 for (; v != (VALUE)vend; v += stride) {
1680 void *ptr = rb_asan_poisoned_object_p(v);
1681 rb_asan_unpoison_object(v, false);
1682
1683 if (rb_obj_is_iseq(v)) {
1684 rb_iseq_t *iseq = (rb_iseq_t *)v;
1685 if (ISEQ_VARIABLE(iseq)) {
1686 ISEQ_COVERAGE_SET(iseq, Qnil);
1687 }
1688 }
1689
1690 asan_poison_object_if(ptr, v);
1691 }
1692 return 0;
1693}
1694
1695void
1696rb_iseq_remove_coverage_all(void)
1697{
1698 rb_objspace_each_objects(remove_coverage_i, NULL);
1699}
1700
1701/* define wrapper class methods (RubyVM::InstructionSequence) */
1702
1703static void
1704iseqw_mark_and_move(void *ptr)
1705{
1706 rb_gc_mark_and_move((VALUE *)ptr);
1707}
1708
1709static size_t
1710iseqw_memsize(const void *ptr)
1711{
1712 return rb_iseq_memsize(*(const rb_iseq_t **)ptr);
1713}
1714
1715static const rb_data_type_t iseqw_data_type = {
1716 "T_IMEMO/iseq",
1717 {
1718 iseqw_mark_and_move,
1720 iseqw_memsize,
1721 iseqw_mark_and_move,
1722 },
1723 0, 0, RUBY_TYPED_THREAD_SAFE_FREE|RUBY_TYPED_WB_PROTECTED
1724};
1725
1726static VALUE
1727iseqw_new(const rb_iseq_t *iseq)
1728{
1729 rb_iseq_t **ptr;
1730 VALUE obj = TypedData_Make_Struct(rb_cISeq, rb_iseq_t *, &iseqw_data_type, ptr);
1731 RB_OBJ_WRITE(obj, ptr, iseq);
1733 return obj;
1734}
1735
1736VALUE
1737rb_iseqw_new(const rb_iseq_t *iseq)
1738{
1739 return iseqw_new(iseq);
1740}
1741
1747static VALUE
1748iseqw_s_compile_parser(int argc, VALUE *argv, VALUE self, bool prism)
1749{
1750 VALUE src, file = Qnil, path = Qnil, line = Qnil, opt = Qnil;
1751 int i;
1752
1753 i = rb_scan_args(argc, argv, "1*:", &src, NULL, &opt);
1754 if (i > 4+NIL_P(opt)) rb_error_arity(argc, 1, 5);
1755 switch (i) {
1756 case 5: opt = argv[--i];
1757 case 4: line = argv[--i];
1758 case 3: path = argv[--i];
1759 case 2: file = argv[--i];
1760 }
1761
1762 if (NIL_P(file)) file = rb_fstring_lit("<compiled>");
1763 if (NIL_P(path)) path = file;
1764 if (NIL_P(line)) line = INT2FIX(1);
1765
1766 Check_Type(path, T_STRING);
1767 Check_Type(file, T_STRING);
1768
1769 rb_iseq_t *iseq;
1770 if (prism) {
1771 iseq = pm_iseq_compile_with_option(src, file, path, line, opt);
1772 }
1773 else {
1774 iseq = rb_iseq_compile_with_option(src, file, path, line, opt);
1775 }
1776
1777 return iseqw_new(iseq);
1778}
1779
1780/*
1781 * call-seq:
1782 * InstructionSequence.compile(source[, file[, path[, line[, options]]]]) -> iseq
1783 * InstructionSequence.new(source[, file[, path[, line[, options]]]]) -> iseq
1784 *
1785 * Takes +source+, which can be a string of Ruby code, or an open +File+ object.
1786 * that contains Ruby source code.
1787 *
1788 * Optionally takes +file+, +path+, and +line+ which describe the file path,
1789 * real path and first line number of the ruby code in +source+ which are
1790 * metadata attached to the returned +iseq+.
1791 *
1792 * +file+ is used for +__FILE__+ and exception backtrace. +path+ is used for
1793 * +require_relative+ base. It is recommended these should be the same full
1794 * path.
1795 *
1796 * +options+, which can be +true+, +false+ or a +Hash+, is used to
1797 * modify the default behavior of the Ruby iseq compiler.
1798 *
1799 * For details regarding valid compile options see ::compile_option=.
1800 *
1801 * RubyVM::InstructionSequence.compile("a = 1 + 2")
1802 * #=> <RubyVM::InstructionSequence:<compiled>@<compiled>>
1803 *
1804 * path = "test.rb"
1805 * RubyVM::InstructionSequence.compile(File.read(path), path, File.expand_path(path))
1806 * #=> <RubyVM::InstructionSequence:<compiled>@test.rb:1>
1807 *
1808 * file = File.open("test.rb")
1809 * RubyVM::InstructionSequence.compile(file)
1810 * #=> <RubyVM::InstructionSequence:<compiled>@<compiled>:1>
1811 *
1812 * path = File.expand_path("test.rb")
1813 * RubyVM::InstructionSequence.compile(File.read(path), path, path)
1814 * #=> <RubyVM::InstructionSequence:<compiled>@/absolute/path/to/test.rb:1>
1815 *
1816 */
1817static VALUE
1818iseqw_s_compile(int argc, VALUE *argv, VALUE self)
1819{
1820 return iseqw_s_compile_parser(argc, argv, self, rb_ruby_prism_p());
1821}
1822
1823/*
1824 * call-seq:
1825 * InstructionSequence.compile_parsey(source[, file[, path[, line[, options]]]]) -> iseq
1826 *
1827 * Takes +source+, which can be a string of Ruby code, or an open +File+ object.
1828 * that contains Ruby source code. It parses and compiles using parse.y.
1829 *
1830 * Optionally takes +file+, +path+, and +line+ which describe the file path,
1831 * real path and first line number of the ruby code in +source+ which are
1832 * metadata attached to the returned +iseq+.
1833 *
1834 * +file+ is used for +__FILE__+ and exception backtrace. +path+ is used for
1835 * +require_relative+ base. It is recommended these should be the same full
1836 * path.
1837 *
1838 * +options+, which can be +true+, +false+ or a +Hash+, is used to
1839 * modify the default behavior of the Ruby iseq compiler.
1840 *
1841 * For details regarding valid compile options see ::compile_option=.
1842 *
1843 * RubyVM::InstructionSequence.compile_parsey("a = 1 + 2")
1844 * #=> <RubyVM::InstructionSequence:<compiled>@<compiled>>
1845 *
1846 * path = "test.rb"
1847 * RubyVM::InstructionSequence.compile_parsey(File.read(path), path, File.expand_path(path))
1848 * #=> <RubyVM::InstructionSequence:<compiled>@test.rb:1>
1849 *
1850 * file = File.open("test.rb")
1851 * RubyVM::InstructionSequence.compile_parsey(file)
1852 * #=> <RubyVM::InstructionSequence:<compiled>@<compiled>:1>
1853 *
1854 * path = File.expand_path("test.rb")
1855 * RubyVM::InstructionSequence.compile_parsey(File.read(path), path, path)
1856 * #=> <RubyVM::InstructionSequence:<compiled>@/absolute/path/to/test.rb:1>
1857 *
1858 */
1859static VALUE
1860iseqw_s_compile_parsey(int argc, VALUE *argv, VALUE self)
1861{
1862 return iseqw_s_compile_parser(argc, argv, self, false);
1863}
1864
1865/*
1866 * call-seq:
1867 * InstructionSequence.compile_prism(source[, file[, path[, line[, options]]]]) -> iseq
1868 *
1869 * Takes +source+, which can be a string of Ruby code, or an open +File+ object.
1870 * that contains Ruby source code. It parses and compiles using prism.
1871 *
1872 * Optionally takes +file+, +path+, and +line+ which describe the file path,
1873 * real path and first line number of the ruby code in +source+ which are
1874 * metadata attached to the returned +iseq+.
1875 *
1876 * +file+ is used for +__FILE__+ and exception backtrace. +path+ is used for
1877 * +require_relative+ base. It is recommended these should be the same full
1878 * path.
1879 *
1880 * +options+, which can be +true+, +false+ or a +Hash+, is used to
1881 * modify the default behavior of the Ruby iseq compiler.
1882 *
1883 * For details regarding valid compile options see ::compile_option=.
1884 *
1885 * RubyVM::InstructionSequence.compile_prism("a = 1 + 2")
1886 * #=> <RubyVM::InstructionSequence:<compiled>@<compiled>>
1887 *
1888 * path = "test.rb"
1889 * RubyVM::InstructionSequence.compile_prism(File.read(path), path, File.expand_path(path))
1890 * #=> <RubyVM::InstructionSequence:<compiled>@test.rb:1>
1891 *
1892 * file = File.open("test.rb")
1893 * RubyVM::InstructionSequence.compile_prism(file)
1894 * #=> <RubyVM::InstructionSequence:<compiled>@<compiled>:1>
1895 *
1896 * path = File.expand_path("test.rb")
1897 * RubyVM::InstructionSequence.compile_prism(File.read(path), path, path)
1898 * #=> <RubyVM::InstructionSequence:<compiled>@/absolute/path/to/test.rb:1>
1899 *
1900 */
1901static VALUE
1902iseqw_s_compile_prism(int argc, VALUE *argv, VALUE self)
1903{
1904 return iseqw_s_compile_parser(argc, argv, self, true);
1905}
1906
1907static VALUE iseqw_s_compile_file_prism(int argc, VALUE *argv, VALUE self);
1908
1909/*
1910 * call-seq:
1911 * InstructionSequence.compile_file(file[, options]) -> iseq
1912 *
1913 * Takes +file+, a String with the location of a Ruby source file, reads,
1914 * parses and compiles the file, and returns +iseq+, the compiled
1915 * InstructionSequence with source location metadata set.
1916 *
1917 * Optionally takes +options+, which can be +true+, +false+ or a +Hash+, to
1918 * modify the default behavior of the Ruby iseq compiler.
1919 *
1920 * For details regarding valid compile options see ::compile_option=.
1921 *
1922 * # /tmp/hello.rb
1923 * puts "Hello, world!"
1924 *
1925 * # elsewhere
1926 * RubyVM::InstructionSequence.compile_file("/tmp/hello.rb")
1927 * #=> <RubyVM::InstructionSequence:<main>@/tmp/hello.rb>
1928 */
1929static VALUE
1930iseqw_s_compile_file(int argc, VALUE *argv, VALUE self)
1931{
1932 if (rb_ruby_prism_p()) {
1933 return iseqw_s_compile_file_prism(argc, argv, self);
1934 }
1935
1936 VALUE file, opt = Qnil;
1937 VALUE parser, f, exc = Qnil, ret;
1938 rb_ast_t *ast;
1939 VALUE ast_value;
1940 rb_compile_option_t option;
1941 int i;
1942
1943 i = rb_scan_args(argc, argv, "1*:", &file, NULL, &opt);
1944 if (i > 1+NIL_P(opt)) rb_error_arity(argc, 1, 2);
1945 switch (i) {
1946 case 2: opt = argv[--i];
1947 }
1948 FilePathValue(file);
1949 file = rb_fstring(file); /* rb_io_t->pathv gets frozen anyways */
1950
1951 make_compile_option(&option, opt);
1952
1953 f = rb_file_open_str(file, "r");
1954
1955 rb_execution_context_t *ec = GET_EC();
1956 VALUE v = rb_vm_push_frame_fname(ec, file);
1957
1958 parser = rb_parser_new();
1959 rb_parser_set_context(parser, NULL, FALSE);
1960 ast_value = rb_parser_load_file(parser, file);
1961 if (option.coverage_enabled) iseq_new_setup_coverage(file, ast_line_count(ast_value));
1962 ast = rb_ruby_ast_data_get(ast_value);
1963 if (!ast->body.root) exc = GET_EC()->errinfo;
1964
1965 rb_io_close(f);
1966 if (!ast->body.root) {
1967 rb_ast_dispose(ast);
1968 rb_exc_raise(exc);
1969 }
1970
1971 ret = iseqw_new(rb_iseq_new_with_opt(ast_value, rb_fstring_lit("<main>"),
1972 file,
1973 rb_realpath_internal(Qnil, file, 1),
1974 1, NULL, 0, ISEQ_TYPE_TOP, &option,
1975 Qnil));
1976 rb_ast_dispose(ast);
1977 RB_GC_GUARD(ast_value);
1978
1979 rb_vm_pop_frame(ec);
1980 RB_GC_GUARD(v);
1981 return ret;
1982}
1983
1984/*
1985 * call-seq:
1986 * InstructionSequence.compile_file_prism(file[, options]) -> iseq
1987 *
1988 * Takes +file+, a String with the location of a Ruby source file, reads,
1989 * parses and compiles the file, and returns +iseq+, the compiled
1990 * InstructionSequence with source location metadata set. It parses and
1991 * compiles using prism.
1992 *
1993 * Optionally takes +options+, which can be +true+, +false+ or a +Hash+, to
1994 * modify the default behavior of the Ruby iseq compiler.
1995 *
1996 * For details regarding valid compile options see ::compile_option=.
1997 *
1998 * # /tmp/hello.rb
1999 * puts "Hello, world!"
2000 *
2001 * # elsewhere
2002 * RubyVM::InstructionSequence.compile_file_prism("/tmp/hello.rb")
2003 * #=> <RubyVM::InstructionSequence:<main>@/tmp/hello.rb>
2004 */
2005static VALUE
2006iseqw_s_compile_file_prism(int argc, VALUE *argv, VALUE self)
2007{
2008 VALUE file, opt = Qnil, ret;
2009 rb_compile_option_t option;
2010 int i;
2011
2012 i = rb_scan_args(argc, argv, "1*:", &file, NULL, &opt);
2013 if (i > 1+NIL_P(opt)) rb_error_arity(argc, 1, 2);
2014 switch (i) {
2015 case 2: opt = argv[--i];
2016 }
2017 FilePathValue(file);
2018 file = rb_fstring(file); /* rb_io_t->pathv gets frozen anyways */
2019
2020 rb_execution_context_t *ec = GET_EC();
2021 VALUE v = rb_vm_push_frame_fname(ec, file);
2022
2023 make_compile_option(&option, opt);
2024
2025 pm_parse_result_t result;
2026 pm_parse_result_init(&result);
2027 result.node.coverage_enabled = option.coverage_enabled;
2028
2029 switch (option.frozen_string_literal) {
2030 case ISEQ_FROZEN_STRING_LITERAL_UNSET:
2031 break;
2032 case ISEQ_FROZEN_STRING_LITERAL_DISABLED:
2033 pm_options_frozen_string_literal_set(result.options, false);
2034 break;
2035 case ISEQ_FROZEN_STRING_LITERAL_ENABLED:
2036 pm_options_frozen_string_literal_set(result.options, true);
2037 break;
2038 default:
2039 rb_bug("iseqw_s_compile_file_prism: invalid frozen_string_literal=%d", option.frozen_string_literal);
2040 break;
2041 }
2042
2043 VALUE script_lines;
2044 VALUE error = pm_load_parse_file(&result, file, ruby_vm_keep_script_lines ? &script_lines : NULL);
2045
2046 if (error == Qnil) {
2047 int error_state;
2048 if (option.coverage_enabled) iseq_new_setup_coverage(file, (int) (pm_parser_line_offsets(result.node.parser)->size - 1));
2049 rb_iseq_t *iseq = pm_iseq_new_with_opt(&result.node, rb_fstring_lit("<main>"),
2050 file,
2051 rb_realpath_internal(Qnil, file, 1),
2052 1, NULL, 0, ISEQ_TYPE_TOP, &option, &error_state);
2053
2054 pm_parse_result_free(&result);
2055
2056 if (error_state) {
2057 RUBY_ASSERT(iseq == NULL);
2058 rb_jump_tag(error_state);
2059 }
2060
2061 ret = iseqw_new(iseq);
2062 rb_vm_pop_frame(ec);
2063 RB_GC_GUARD(v);
2064 return ret;
2065 }
2066 else {
2067 pm_parse_result_free(&result);
2068 rb_vm_pop_frame(ec);
2069 RB_GC_GUARD(v);
2070 rb_exc_raise(error);
2071 }
2072}
2073
2074/*
2075 * call-seq:
2076 * InstructionSequence.compile_option = options
2077 *
2078 * Sets the default values for various optimizations in the Ruby iseq
2079 * compiler.
2080 *
2081 * Possible values for +options+ include +true+, which enables all options,
2082 * +false+ which disables all options, and +nil+ which leaves all options
2083 * unchanged.
2084 *
2085 * You can also pass a +Hash+ of +options+ that you want to change, any
2086 * options not present in the hash will be left unchanged.
2087 *
2088 * Possible option names (which are keys in +options+) which can be set to
2089 * +true+ or +false+ include:
2090 *
2091 * * +:inline_const_cache+
2092 * * +:instructions_unification+
2093 * * +:operands_unification+
2094 * * +:peephole_optimization+
2095 * * +:specialized_instruction+
2096 * * +:tailcall_optimization+
2097 *
2098 * Additionally, +:debug_level+ can be set to an integer.
2099 *
2100 * These default options can be overwritten for a single run of the iseq
2101 * compiler by passing any of the above values as the +options+ parameter to
2102 * ::new, ::compile and ::compile_file.
2103 */
2104static VALUE
2105iseqw_s_compile_option_set(VALUE self, VALUE opt)
2106{
2107 rb_compile_option_t option;
2108 make_compile_option(&option, opt);
2109 COMPILE_OPTION_DEFAULT = option;
2110 return opt;
2111}
2112
2113/*
2114 * call-seq:
2115 * InstructionSequence.compile_option -> options
2116 *
2117 * Returns a hash of default options used by the Ruby iseq compiler.
2118 *
2119 * For details, see InstructionSequence.compile_option=.
2120 */
2121static VALUE
2122iseqw_s_compile_option_get(VALUE self)
2123{
2124 return make_compile_option_value(&COMPILE_OPTION_DEFAULT);
2125}
2126
2127static const rb_iseq_t *
2128iseqw_check(VALUE iseqw)
2129{
2130 rb_iseq_t **iseq_ptr;
2131 TypedData_Get_Struct(iseqw, rb_iseq_t *, &iseqw_data_type, iseq_ptr);
2132 rb_iseq_t *iseq = *iseq_ptr;
2133
2134 if (!ISEQ_BODY(iseq)) {
2135 rb_ibf_load_iseq_complete(iseq);
2136 }
2137
2138 if (!ISEQ_BODY(iseq)->location.label) {
2139 rb_raise(rb_eTypeError, "uninitialized InstructionSequence");
2140 }
2141 return iseq;
2142}
2143
2144const rb_iseq_t *
2145rb_iseqw_to_iseq(VALUE iseqw)
2146{
2147 return iseqw_check(iseqw);
2148}
2149
2150/*
2151 * call-seq:
2152 * iseq.eval -> obj
2153 *
2154 * Evaluates the instruction sequence and returns the result.
2155 *
2156 * RubyVM::InstructionSequence.compile("1 + 2").eval #=> 3
2157 */
2158static VALUE
2159iseqw_eval(VALUE self)
2160{
2161 const rb_iseq_t *iseq = iseqw_check(self);
2162 if (0 == ISEQ_BODY(iseq)->iseq_size) {
2163 rb_raise(rb_eTypeError, "attempt to evaluate dummy InstructionSequence");
2164 }
2165 return rb_iseq_eval(iseq, rb_current_box());
2166}
2167
2168/*
2169 * Returns a human-readable string representation of this instruction
2170 * sequence, including the #label and #path.
2171 */
2172static VALUE
2173iseqw_inspect(VALUE self)
2174{
2175 const rb_iseq_t *iseq = iseqw_check(self);
2176 const struct rb_iseq_constant_body *const body = ISEQ_BODY(iseq);
2177 VALUE klass = rb_class_name(rb_obj_class(self));
2178
2179 if (!body->location.label) {
2180 return rb_sprintf("#<%"PRIsVALUE": uninitialized>", klass);
2181 }
2182 else {
2183 return rb_sprintf("<%"PRIsVALUE":%"PRIsVALUE"@%"PRIsVALUE":%d>",
2184 klass,
2185 body->location.label, rb_iseq_path(iseq),
2186 FIX2INT(rb_iseq_first_lineno(iseq)));
2187 }
2188}
2189
2190/*
2191 * Returns the path of this instruction sequence.
2192 *
2193 * <code><compiled></code> if the iseq was evaluated from a string.
2194 *
2195 * For example, using irb:
2196 *
2197 * iseq = RubyVM::InstructionSequence.compile('num = 1 + 2')
2198 * #=> <RubyVM::InstructionSequence:<compiled>@<compiled>>
2199 * iseq.path
2200 * #=> "<compiled>"
2201 *
2202 * Using ::compile_file:
2203 *
2204 * # /tmp/method.rb
2205 * def hello
2206 * puts "hello, world"
2207 * end
2208 *
2209 * # in irb
2210 * > iseq = RubyVM::InstructionSequence.compile_file('/tmp/method.rb')
2211 * > iseq.path #=> /tmp/method.rb
2212 */
2213static VALUE
2214iseqw_path(VALUE self)
2215{
2216 return rb_iseq_path(iseqw_check(self));
2217}
2218
2219/*
2220 * Returns the absolute path of this instruction sequence.
2221 *
2222 * +nil+ if the iseq was evaluated from a string.
2223 *
2224 * For example, using ::compile_file:
2225 *
2226 * # /tmp/method.rb
2227 * def hello
2228 * puts "hello, world"
2229 * end
2230 *
2231 * # in irb
2232 * > iseq = RubyVM::InstructionSequence.compile_file('/tmp/method.rb')
2233 * > iseq.absolute_path #=> /tmp/method.rb
2234 */
2235static VALUE
2236iseqw_absolute_path(VALUE self)
2237{
2238 return rb_iseq_realpath(iseqw_check(self));
2239}
2240
2241/* Returns the label of this instruction sequence.
2242 *
2243 * <code><main></code> if it's at the top level, <code><compiled></code> if it
2244 * was evaluated from a string.
2245 *
2246 * For example, using irb:
2247 *
2248 * iseq = RubyVM::InstructionSequence.compile('num = 1 + 2')
2249 * #=> <RubyVM::InstructionSequence:<compiled>@<compiled>>
2250 * iseq.label
2251 * #=> "<compiled>"
2252 *
2253 * Using ::compile_file:
2254 *
2255 * # /tmp/method.rb
2256 * def hello
2257 * puts "hello, world"
2258 * end
2259 *
2260 * # in irb
2261 * > iseq = RubyVM::InstructionSequence.compile_file('/tmp/method.rb')
2262 * > iseq.label #=> <main>
2263 */
2264static VALUE
2265iseqw_label(VALUE self)
2266{
2267 return rb_iseq_label(iseqw_check(self));
2268}
2269
2270/* Returns the base label of this instruction sequence.
2271 *
2272 * For example, using irb:
2273 *
2274 * iseq = RubyVM::InstructionSequence.compile('num = 1 + 2')
2275 * #=> <RubyVM::InstructionSequence:<compiled>@<compiled>>
2276 * iseq.base_label
2277 * #=> "<compiled>"
2278 *
2279 * Using ::compile_file:
2280 *
2281 * # /tmp/method.rb
2282 * def hello
2283 * puts "hello, world"
2284 * end
2285 *
2286 * # in irb
2287 * > iseq = RubyVM::InstructionSequence.compile_file('/tmp/method.rb')
2288 * > iseq.base_label #=> <main>
2289 */
2290static VALUE
2291iseqw_base_label(VALUE self)
2292{
2293 return rb_iseq_base_label(iseqw_check(self));
2294}
2295
2296/* Returns the number of the first source line where the instruction sequence
2297 * was loaded from.
2298 *
2299 * For example, using irb:
2300 *
2301 * iseq = RubyVM::InstructionSequence.compile('num = 1 + 2')
2302 * #=> <RubyVM::InstructionSequence:<compiled>@<compiled>>
2303 * iseq.first_lineno
2304 * #=> 1
2305 */
2306static VALUE
2307iseqw_first_lineno(VALUE self)
2308{
2309 return rb_iseq_first_lineno(iseqw_check(self));
2310}
2311
2312static VALUE iseq_data_to_ary(const rb_iseq_t *iseq);
2313
2314/*
2315 * call-seq:
2316 * iseq.to_a -> ary
2317 *
2318 * Returns an Array with 14 elements representing the instruction sequence
2319 * with the following data:
2320 *
2321 * [magic]
2322 * A string identifying the data format. <b>Always
2323 * +YARVInstructionSequence/SimpleDataFormat+.</b>
2324 *
2325 * [major_version]
2326 * The major version of the instruction sequence.
2327 *
2328 * [minor_version]
2329 * The minor version of the instruction sequence.
2330 *
2331 * [format_type]
2332 * A number identifying the data format. <b>Always 1</b>.
2333 *
2334 * [misc]
2335 * A hash containing:
2336 *
2337 * [+:arg_size+]
2338 * the total number of arguments taken by the method or the block (0 if
2339 * _iseq_ doesn't represent a method or block)
2340 * [+:local_size+]
2341 * the number of local variables + 1
2342 * [+:stack_max+]
2343 * used in calculating the stack depth at which a SystemStackError is
2344 * thrown.
2345 *
2346 * [#label]
2347 * The name of the context (block, method, class, module, etc.) that this
2348 * instruction sequence belongs to.
2349 *
2350 * <code><main></code> if it's at the top level, <code><compiled></code> if
2351 * it was evaluated from a string.
2352 *
2353 * [#path]
2354 * The relative path to the Ruby file where the instruction sequence was
2355 * loaded from.
2356 *
2357 * <code><compiled></code> if the iseq was evaluated from a string.
2358 *
2359 * [#absolute_path]
2360 * The absolute path to the Ruby file where the instruction sequence was
2361 * loaded from.
2362 *
2363 * +nil+ if the iseq was evaluated from a string.
2364 *
2365 * [#first_lineno]
2366 * The number of the first source line where the instruction sequence was
2367 * loaded from.
2368 *
2369 * [type]
2370 * The type of the instruction sequence.
2371 *
2372 * Valid values are +:top+, +:method+, +:block+, +:class+, +:rescue+,
2373 * +:ensure+, +:eval+, +:main+, and +plain+.
2374 *
2375 * [locals]
2376 * An array containing the names of all arguments and local variables as
2377 * symbols.
2378 *
2379 * [params]
2380 * An Hash object containing parameter information.
2381 *
2382 * More info about these values can be found in +vm_core.h+.
2383 *
2384 * [catch_table]
2385 * A list of exceptions and control flow operators (rescue, next, redo,
2386 * break, etc.).
2387 *
2388 * [bytecode]
2389 * An array of arrays containing the instruction names and operands that
2390 * make up the body of the instruction sequence.
2391 *
2392 * Note that this format is MRI specific and version dependent.
2393 *
2394 */
2395static VALUE
2396iseqw_to_a(VALUE self)
2397{
2398 const rb_iseq_t *iseq = iseqw_check(self);
2399 return iseq_data_to_ary(iseq);
2400}
2401
2402#if VM_INSN_INFO_TABLE_IMPL == 1 /* binary search */
2403static const struct iseq_insn_info_entry *
2404get_insn_info_binary_search(const rb_iseq_t *iseq, size_t pos)
2405{
2406 const struct rb_iseq_constant_body *const body = ISEQ_BODY(iseq);
2407 size_t size = body->insns_info.size;
2408 const struct iseq_insn_info_entry *insns_info = body->insns_info.body;
2409 const unsigned int *positions = body->insns_info.positions_or_succ_index_table.positions;
2410 const int debug = 0;
2411
2412 if (debug) {
2413 printf("size: %"PRIuSIZE"\n", size);
2414 printf("insns_info[%"PRIuSIZE"]: position: %d, line: %d, pos: %"PRIuSIZE"\n",
2415 (size_t)0, positions[0], insns_info[0].line_no, pos);
2416 }
2417
2418 if (size == 0) {
2419 return NULL;
2420 }
2421 else if (size == 1) {
2422 return &insns_info[0];
2423 }
2424 else {
2425 size_t l = 1, r = size - 1;
2426 while (l <= r) {
2427 size_t m = l + (r - l) / 2;
2428 if (positions[m] == pos) {
2429 return &insns_info[m];
2430 }
2431 if (positions[m] < pos) {
2432 l = m + 1;
2433 }
2434 else {
2435 r = m - 1;
2436 }
2437 }
2438 if (l >= size) {
2439 return &insns_info[size-1];
2440 }
2441 if (positions[l] > pos) {
2442 return &insns_info[l-1];
2443 }
2444 return &insns_info[l];
2445 }
2446}
2447
2448static const struct iseq_insn_info_entry *
2449get_insn_info(const rb_iseq_t *iseq, size_t pos)
2450{
2451 return get_insn_info_binary_search(iseq, pos);
2452}
2453#endif
2454
2455#if VM_INSN_INFO_TABLE_IMPL == 2 /* succinct bitvector */
2456static const struct iseq_insn_info_entry *
2457get_insn_info_succinct_bitvector(const rb_iseq_t *iseq, size_t pos)
2458{
2459 const struct rb_iseq_constant_body *const body = ISEQ_BODY(iseq);
2460 size_t size = body->insns_info.size;
2461 const struct iseq_insn_info_entry *insns_info = body->insns_info.body;
2462 const int debug = 0;
2463
2464 if (debug) {
2465 printf("size: %"PRIuSIZE"\n", size);
2466 printf("insns_info[%"PRIuSIZE"]: line: %d, pos: %"PRIuSIZE"\n",
2467 (size_t)0, insns_info[0].line_no, pos);
2468 }
2469
2470 if (size == 0) {
2471 return NULL;
2472 }
2473 else if (size == 1) {
2474 return &insns_info[0];
2475 }
2476 else {
2477 int index;
2478 VM_ASSERT(body->insns_info.positions_or_succ_index_table.succ_index_table != NULL);
2479 index = succ_index_lookup(body->insns_info.positions_or_succ_index_table.succ_index_table, (int)pos);
2480 return &insns_info[index-1];
2481 }
2482}
2483
2484static const struct iseq_insn_info_entry *
2485get_insn_info(const rb_iseq_t *iseq, size_t pos)
2486{
2487 return get_insn_info_succinct_bitvector(iseq, pos);
2488}
2489#endif
2490
2491#if VM_CHECK_MODE > 0 || VM_INSN_INFO_TABLE_IMPL == 0
2492static const struct iseq_insn_info_entry *
2493get_insn_info_linear_search(const rb_iseq_t *iseq, const unsigned int *positions, size_t pos)
2494{
2495 const struct rb_iseq_constant_body *const body = ISEQ_BODY(iseq);
2496 size_t i = 0, size = body->insns_info.size;
2497 const struct iseq_insn_info_entry *insns_info = body->insns_info.body;
2498 const int debug = 0;
2499
2500 if (debug) {
2501 printf("size: %"PRIuSIZE"\n", size);
2502 printf("insns_info[%"PRIuSIZE"]: position: %d, line: %d, pos: %"PRIuSIZE"\n",
2503 i, positions[i], insns_info[i].line_no, pos);
2504 }
2505
2506 if (size == 0) {
2507 return NULL;
2508 }
2509 else if (size == 1) {
2510 return &insns_info[0];
2511 }
2512 else {
2513 for (i=1; i<size; i++) {
2514 if (debug) printf("insns_info[%"PRIuSIZE"]: position: %d, line: %d, pos: %"PRIuSIZE"\n",
2515 i, positions[i], insns_info[i].line_no, pos);
2516
2517 if (positions[i] == pos) {
2518 return &insns_info[i];
2519 }
2520 if (positions[i] > pos) {
2521 return &insns_info[i-1];
2522 }
2523 }
2524 }
2525 return &insns_info[i-1];
2526}
2527#endif
2528
2529#if VM_INSN_INFO_TABLE_IMPL == 0 /* linear search */
2530static const struct iseq_insn_info_entry *
2531get_insn_info(const rb_iseq_t *iseq, size_t pos)
2532{
2533 return get_insn_info_linear_search(iseq, ISEQ_BODY(iseq)->insns_info.positions_or_succ_index_table.positions, pos);
2534}
2535#endif
2536
2537#if VM_CHECK_MODE > 0 && VM_INSN_INFO_TABLE_IMPL > 0
2538static void
2539validate_get_insn_info(const rb_iseq_t *iseq)
2540{
2541 const struct rb_iseq_constant_body *const body = ISEQ_BODY(iseq);
2542 size_t i;
2543#if VM_INSN_INFO_TABLE_IMPL == 2
2544 unsigned int *positions = rb_iseq_insns_info_decode_positions(body);
2545#else
2546 const unsigned int *positions = body->insns_info.positions_or_succ_index_table.positions;
2547#endif
2548 for (i = 0; i < body->iseq_size; i++) {
2549 if (get_insn_info_linear_search(iseq, positions, i) != get_insn_info(iseq, i)) {
2550 rb_bug("validate_get_insn_info: get_insn_info_linear_search(iseq, %"PRIuSIZE") != get_insn_info(iseq, %"PRIuSIZE")", i, i);
2551 }
2552 }
2553#if VM_INSN_INFO_TABLE_IMPL == 2
2554 SIZED_FREE_N(positions, body->insns_info.size);
2555#endif
2556}
2557#endif
2558
2559unsigned int
2560rb_iseq_line_no(const rb_iseq_t *iseq, size_t pos)
2561{
2562 const struct iseq_insn_info_entry *entry = get_insn_info(iseq, pos);
2563
2564 if (entry) {
2565 return entry->line_no;
2566 }
2567 else {
2568 return 0;
2569 }
2570}
2571
2572#ifdef USE_ISEQ_NODE_ID
2573int
2574rb_iseq_node_id(const rb_iseq_t *iseq, size_t pos)
2575{
2576 const struct iseq_insn_info_entry *entry = get_insn_info(iseq, pos);
2577
2578 if (entry) {
2579 return entry->node_id;
2580 }
2581 else {
2582 return 0;
2583 }
2584}
2585#endif
2586
2588rb_iseq_event_flags(const rb_iseq_t *iseq, size_t pos)
2589{
2590 const struct iseq_insn_info_entry *entry = get_insn_info(iseq, pos);
2591 if (entry) {
2592 return entry->events;
2593 }
2594 else {
2595 return 0;
2596 }
2597}
2598
2599static void rb_iseq_trace_flag_cleared(const rb_iseq_t *iseq, size_t pos);
2600
2601// Clear tracing event flags and turn off tracing for a given instruction as needed.
2602// This is currently used after updating a one-shot line coverage for the current instruction.
2603void
2604rb_iseq_clear_event_flags(const rb_iseq_t *iseq, size_t pos, rb_event_flag_t reset)
2605{
2606 RB_VM_LOCKING() {
2607 rb_vm_barrier();
2608
2609 struct iseq_insn_info_entry *entry = (struct iseq_insn_info_entry *)get_insn_info(iseq, pos);
2610 if (entry) {
2611 entry->events &= ~reset;
2612 if (!(entry->events & iseq->aux.exec.global_trace_events)) {
2613 rb_iseq_trace_flag_cleared(iseq, pos);
2614 }
2615 }
2616 }
2617}
2618
2619static VALUE
2620local_var_name(const rb_iseq_t *diseq, VALUE level, VALUE op)
2621{
2622 VALUE i;
2623 VALUE name;
2624 ID lid;
2625 int idx;
2626
2627 for (i = 0; i < level; i++) {
2628 diseq = ISEQ_BODY(diseq)->parent_iseq;
2629 }
2630 idx = ISEQ_BODY(diseq)->local_table_size - (int)op - 1;
2631 lid = ISEQ_BODY(diseq)->local_table[idx];
2632 name = rb_id2str(lid);
2633 if (!name) {
2634 name = rb_str_new_cstr("?");
2635 }
2636 else if (!rb_is_local_id(lid)) {
2637 name = rb_str_inspect(name);
2638 }
2639 else {
2640 name = rb_str_dup(name);
2641 }
2642 rb_str_catf(name, "@%d", idx);
2643 return name;
2644}
2645
2646int rb_insn_unified_local_var_level(VALUE);
2647VALUE rb_dump_literal(VALUE lit);
2648
2649VALUE
2650rb_insn_operand_intern(const rb_iseq_t *iseq,
2651 VALUE insn, int op_no, VALUE op,
2652 int len, size_t pos, const VALUE *pnop, VALUE child)
2653{
2654 const char *types = insn_op_types(insn);
2655 char type = types[op_no];
2656 VALUE ret = Qundef;
2657
2658 switch (type) {
2659 case TS_OFFSET: /* LONG */
2660 ret = rb_sprintf("%"PRIdVALUE, (VALUE)(pos + len + op));
2661 break;
2662
2663 case TS_NUM: /* ULONG */
2664 if (insn == BIN(defined) && op_no == 0) {
2665 enum defined_type deftype = (enum defined_type)op;
2666 switch (deftype) {
2667 case DEFINED_FUNC:
2668 ret = rb_fstring_lit("func");
2669 break;
2670 case DEFINED_REF:
2671 ret = rb_fstring_lit("ref");
2672 break;
2673 case DEFINED_CONST_FROM:
2674 ret = rb_fstring_lit("constant-from");
2675 break;
2676 default:
2677 ret = rb_iseq_defined_string(deftype);
2678 break;
2679 }
2680 if (ret) break;
2681 }
2682 else if (insn == BIN(checktype) && op_no == 0) {
2683 const char *type_str = rb_type_str((enum ruby_value_type)op);
2684 if (type_str) {
2685 ret = rb_str_new_cstr(type_str); break;
2686 }
2687 }
2688 ret = rb_sprintf("%"PRIuVALUE, op);
2689 break;
2690
2691 case TS_LINDEX:{
2692 int level;
2693 if (types[op_no+1] == TS_NUM && pnop) {
2694 ret = local_var_name(iseq, *pnop, op - VM_ENV_DATA_SIZE);
2695 }
2696 else if ((level = rb_insn_unified_local_var_level(insn)) >= 0) {
2697 ret = local_var_name(iseq, (VALUE)level, op - VM_ENV_DATA_SIZE);
2698 }
2699 else {
2700 ret = rb_inspect(INT2FIX(op));
2701 }
2702 break;
2703 }
2704 case TS_ID: /* ID (symbol) */
2705 ret = rb_inspect(ID2SYM(op));
2706 break;
2707
2708 case TS_VALUE: /* VALUE */
2709 op = obj_resurrect(op);
2710 if (insn == BIN(defined) && op_no == 1 && FIXNUM_P(op)) {
2711 /* should be DEFINED_REF */
2712 int type = NUM2INT(op);
2713 if (type) {
2714 if (type & 1) {
2715 ret = rb_sprintf(":$%c", (type >> 1));
2716 }
2717 else {
2718 ret = rb_sprintf(":$%d", (type >> 1));
2719 }
2720 break;
2721 }
2722 }
2723 ret = rb_dump_literal(op);
2724 if (CLASS_OF(op) == rb_cISeq) {
2725 if (child) {
2726 rb_ary_push(child, op);
2727 }
2728 }
2729 break;
2730
2731 case TS_ISEQ: /* iseq */
2732 {
2733 if (op) {
2734 const rb_iseq_t *iseq = rb_iseq_check((rb_iseq_t *)op);
2735 ret = ISEQ_BODY(iseq)->location.label;
2736 if (child) {
2737 rb_ary_push(child, (VALUE)iseq);
2738 }
2739 }
2740 else {
2741 ret = rb_str_new2("nil");
2742 }
2743 break;
2744 }
2745
2746 case TS_IC:
2747 {
2748 ret = rb_sprintf("<ic:%"PRIdPTRDIFF" ", (union iseq_inline_storage_entry *)op - ISEQ_BODY(iseq)->is_entries);
2749 const ID *segments = ((IC)op)->segments;
2750 rb_str_cat2(ret, rb_id2name(*segments++));
2751 while (*segments) {
2752 rb_str_catf(ret, "::%s", rb_id2name(*segments++));
2753 }
2754 rb_str_cat2(ret, ">");
2755 }
2756 break;
2757 case TS_IVC:
2758 case TS_ICVARC:
2759 case TS_ISE:
2760 ret = rb_sprintf("<is:%"PRIdPTRDIFF">", (union iseq_inline_storage_entry *)op - ISEQ_BODY(iseq)->is_entries);
2761 break;
2762
2763 case TS_CALLDATA:
2764 {
2765 struct rb_call_data *cd = (struct rb_call_data *)op;
2766 const struct rb_callinfo *ci = cd->ci;
2767 VALUE ary = rb_ary_new();
2768 ID mid = vm_ci_mid(ci);
2769
2770 if (mid) {
2771 rb_ary_push(ary, rb_sprintf("mid:%"PRIsVALUE, rb_id2str(mid)));
2772 }
2773
2774 rb_ary_push(ary, rb_sprintf("argc:%d", vm_ci_argc(ci)));
2775
2776 if (vm_ci_flag(ci) & VM_CALL_KWARG) {
2777 const struct rb_callinfo_kwarg *kw_args = vm_ci_kwarg(ci);
2778 VALUE kw_ary = rb_ary_new_from_values(kw_args->keyword_len, kw_args->keywords);
2779 rb_ary_push(ary, rb_sprintf("kw:[%"PRIsVALUE"]", rb_ary_join(kw_ary, rb_str_new2(","))));
2780 }
2781
2782 if (vm_ci_flag(ci)) {
2783 VALUE flags = rb_ary_new();
2784# define CALL_FLAG(n) if (vm_ci_flag(ci) & VM_CALL_##n) rb_ary_push(flags, rb_str_new2(#n))
2785 CALL_FLAG(ARGS_SPLAT);
2786 CALL_FLAG(ARGS_SPLAT_MUT);
2787 CALL_FLAG(ARGS_BLOCKARG);
2788 CALL_FLAG(FCALL);
2789 CALL_FLAG(VCALL);
2790 CALL_FLAG(ARGS_SIMPLE);
2791 CALL_FLAG(TAILCALL);
2792 CALL_FLAG(SUPER);
2793 CALL_FLAG(ZSUPER);
2794 CALL_FLAG(KWARG);
2795 CALL_FLAG(KW_SPLAT);
2796 CALL_FLAG(KW_SPLAT_MUT);
2797 CALL_FLAG(FORWARDING);
2798 CALL_FLAG(OPT_SEND); /* maybe not reachable */
2799 rb_ary_push(ary, rb_ary_join(flags, rb_str_new2("|")));
2800 }
2801
2802 ret = rb_sprintf("<calldata!%"PRIsVALUE">", rb_ary_join(ary, rb_str_new2(", ")));
2803 }
2804 break;
2805
2806 case TS_CDHASH:
2807 ret = rb_str_new2("<cdhash>");
2808 break;
2809
2810 case TS_FUNCPTR:
2811 {
2812#ifdef HAVE_DLADDR
2813 Dl_info info;
2814 if (dladdr((void *)op, &info) && info.dli_sname) {
2815 ret = rb_str_new_cstr(info.dli_sname);
2816 break;
2817 }
2818#endif
2819 ret = rb_str_new2("<funcptr>");
2820 }
2821 break;
2822
2823 case TS_BUILTIN:
2824 {
2825 const struct rb_builtin_function *bf = (const struct rb_builtin_function *)op;
2826 ret = rb_sprintf("<builtin!%s/%d>",
2827 bf->name, bf->argc);
2828 }
2829 break;
2830
2831 default:
2832 rb_bug("unknown operand type: %c", type);
2833 }
2834 return ret;
2835}
2836
2837static VALUE
2838right_strip(VALUE str)
2839{
2840 const char *beg = RSTRING_PTR(str), *end = RSTRING_END(str);
2841 while (end-- > beg && *end == ' ');
2842 rb_str_set_len(str, end - beg + 1);
2843 return str;
2844}
2845
2850int
2851rb_iseq_disasm_insn(VALUE ret, const VALUE *code, size_t pos,
2852 const rb_iseq_t *iseq, VALUE child)
2853{
2854 VALUE insn = code[pos];
2855 int len = insn_len(insn);
2856 int j;
2857 const char *types = insn_op_types(insn);
2858 VALUE str = rb_str_new(0, 0);
2859 const char *insn_name_buff;
2860
2861 insn_name_buff = insn_name(insn);
2862 if (1) {
2863 extern const int rb_vm_max_insn_name_size;
2864 rb_str_catf(str, "%04"PRIuSIZE" %-*s ", pos, rb_vm_max_insn_name_size, insn_name_buff);
2865 }
2866 else {
2867 rb_str_catf(str, "%04"PRIuSIZE" %-28.*s ", pos,
2868 (int)strcspn(insn_name_buff, "_"), insn_name_buff);
2869 }
2870
2871 for (j = 0; types[j]; j++) {
2872 VALUE opstr = rb_insn_operand_intern(iseq, insn, j, code[pos + j + 1],
2873 len, pos, &code[pos + j + 2],
2874 child);
2875 rb_str_concat(str, opstr);
2876
2877 if (types[j + 1]) {
2878 rb_str_cat2(str, ", ");
2879 }
2880 }
2881
2882 {
2883 unsigned int line_no = rb_iseq_line_no(iseq, pos);
2884 unsigned int prev = pos == 0 ? 0 : rb_iseq_line_no(iseq, pos - 1);
2885 if (line_no && line_no != prev) {
2886 long slen = RSTRING_LEN(str);
2887 slen = (slen > 70) ? 0 : (70 - slen);
2888 str = rb_str_catf(str, "%*s(%4d)", (int)slen, "", line_no);
2889 }
2890 }
2891
2892 {
2893 rb_event_flag_t events = rb_iseq_event_flags(iseq, pos);
2894 if (events) {
2895 str = rb_str_catf(str, "[%s%s%s%s%s%s%s%s%s%s%s%s]",
2896 events & RUBY_EVENT_LINE ? "Li" : "",
2897 events & RUBY_EVENT_CLASS ? "Cl" : "",
2898 events & RUBY_EVENT_END ? "En" : "",
2899 events & RUBY_EVENT_CALL ? "Ca" : "",
2900 events & RUBY_EVENT_RETURN ? "Re" : "",
2901 events & RUBY_EVENT_C_CALL ? "Cc" : "",
2902 events & RUBY_EVENT_C_RETURN ? "Cr" : "",
2903 events & RUBY_EVENT_B_CALL ? "Bc" : "",
2904 events & RUBY_EVENT_B_RETURN ? "Br" : "",
2905 events & RUBY_EVENT_RESCUE ? "Rs" : "",
2906 events & RUBY_EVENT_COVERAGE_LINE ? "Cli" : "",
2907 events & RUBY_EVENT_COVERAGE_BRANCH ? "Cbr" : "");
2908 }
2909 }
2910
2911 right_strip(str);
2912 if (ret) {
2913 rb_str_cat2(str, "\n");
2914 rb_str_concat(ret, str);
2915 }
2916 else {
2917 printf("%.*s\n", (int)RSTRING_LEN(str), RSTRING_PTR(str));
2918 }
2919 return len;
2920}
2921
2922static const char *
2923catch_type(int type)
2924{
2925 switch (type) {
2926 case CATCH_TYPE_RESCUE:
2927 return "rescue";
2928 case CATCH_TYPE_ENSURE:
2929 return "ensure";
2930 case CATCH_TYPE_RETRY:
2931 return "retry";
2932 case CATCH_TYPE_BREAK:
2933 return "break";
2934 case CATCH_TYPE_REDO:
2935 return "redo";
2936 case CATCH_TYPE_NEXT:
2937 return "next";
2938 default:
2939 rb_bug("unknown catch type: %d", type);
2940 return 0;
2941 }
2942}
2943
2944static VALUE
2945iseq_inspect(const rb_iseq_t *iseq)
2946{
2947 const struct rb_iseq_constant_body *const body = ISEQ_BODY(iseq);
2948 if (!body->location.label) {
2949 return rb_sprintf("#<ISeq: uninitialized>");
2950 }
2951 else {
2952 const rb_code_location_t *loc = &body->location.code_location;
2953 return rb_sprintf("#<ISeq:%"PRIsVALUE"@%"PRIsVALUE":%d (%d,%d)-(%d,%d)>",
2954 body->location.label, rb_iseq_path(iseq),
2955 loc->beg_pos.lineno,
2956 loc->beg_pos.lineno,
2957 loc->beg_pos.column,
2958 loc->end_pos.lineno,
2959 loc->end_pos.column);
2960 }
2961}
2962
2963static const rb_data_type_t tmp_set = {
2964 "tmpset",
2965 {(void (*)(void *))rb_mark_set, (void (*)(void *))st_free_table, 0, 0,},
2966 0, 0, RUBY_TYPED_THREAD_SAFE_FREE
2967};
2968
2969static VALUE
2970rb_iseq_disasm_recursive(const rb_iseq_t *iseq, VALUE indent)
2971{
2972 const struct rb_iseq_constant_body *const body = ISEQ_BODY(iseq);
2973 VALUE *code;
2974 VALUE str = rb_str_new(0, 0);
2975 VALUE child = rb_ary_hidden_new(3);
2976 unsigned int size;
2977 unsigned int i;
2978 long l;
2979 size_t n;
2980 enum {header_minlen = 72};
2981 st_table *done_iseq = 0;
2982 VALUE done_iseq_wrapper = Qnil;
2983 const char *indent_str;
2984 long indent_len;
2985
2986 size = body->iseq_size;
2987
2988 indent_len = RSTRING_LEN(indent);
2989 indent_str = RSTRING_PTR(indent);
2990
2991 rb_str_cat(str, indent_str, indent_len);
2992 rb_str_cat2(str, "== disasm: ");
2993
2994 rb_str_append(str, iseq_inspect(iseq));
2995 if ((l = RSTRING_LEN(str) - indent_len) < header_minlen) {
2996 rb_str_modify_expand(str, header_minlen - l);
2997 memset(RSTRING_END(str), '=', header_minlen - l);
2998 }
2999 if (ISEQ_BODY(iseq)->builtin_attrs) {
3000#define disasm_builtin_attr(str, iseq, attr) \
3001 if (ISEQ_BODY(iseq)->builtin_attrs & BUILTIN_ATTR_ ## attr) { \
3002 rb_str_cat2(str, " " #attr); \
3003 }
3004 disasm_builtin_attr(str, iseq, LEAF);
3005 disasm_builtin_attr(str, iseq, SINGLE_NOARG_LEAF);
3006 disasm_builtin_attr(str, iseq, INLINE_BLOCK);
3007 disasm_builtin_attr(str, iseq, C_TRACE);
3008 }
3009 rb_str_cat2(str, "\n");
3010
3011 /* show catch table information */
3012 if (body->catch_table) {
3013 rb_str_cat(str, indent_str, indent_len);
3014 rb_str_cat2(str, "== catch table\n");
3015 }
3016 if (body->catch_table) {
3017 rb_str_cat_cstr(indent, "| ");
3018 indent_str = RSTRING_PTR(indent);
3019 for (i = 0; i < body->catch_table->size; i++) {
3020 const struct iseq_catch_table_entry *entry =
3021 UNALIGNED_MEMBER_PTR(body->catch_table, entries[i]);
3022 rb_str_cat(str, indent_str, indent_len);
3023 rb_str_catf(str,
3024 "| catch type: %-6s st: %04d ed: %04d sp: %04d cont: %04d\n",
3025 catch_type((int)entry->type), (int)entry->start,
3026 (int)entry->end, (int)entry->sp, (int)entry->cont);
3027 if (entry->iseq && !(done_iseq && st_is_member(done_iseq, (st_data_t)entry->iseq))) {
3028 rb_str_concat(str, rb_iseq_disasm_recursive(rb_iseq_check(entry->iseq), indent));
3029 if (!done_iseq) {
3030 done_iseq = st_init_numtable();
3031 done_iseq_wrapper = TypedData_Wrap_Struct(0, &tmp_set, done_iseq);
3032 }
3033 st_insert(done_iseq, (st_data_t)entry->iseq, (st_data_t)0);
3034 indent_str = RSTRING_PTR(indent);
3035 }
3036 }
3037 rb_str_resize(indent, indent_len);
3038 indent_str = RSTRING_PTR(indent);
3039 }
3040 if (body->catch_table) {
3041 rb_str_cat(str, indent_str, indent_len);
3042 rb_str_cat2(str, "|-------------------------------------"
3043 "-----------------------------------\n");
3044 }
3045
3046 /* show local table information */
3047 if (body->local_table) {
3048 const struct rb_iseq_param_keyword *const keyword = body->param.keyword;
3049 rb_str_cat(str, indent_str, indent_len);
3050 rb_str_catf(str,
3051 "local table (size: %d, argc: %d "
3052 "[opts: %d, rest: %d, post: %d, block: %d, kw: %d@%d, kwrest: %d])\n",
3053 body->local_table_size,
3054 body->param.lead_num,
3055 body->param.opt_num,
3056 body->param.flags.has_rest ? body->param.rest_start : -1,
3057 body->param.post_num,
3058 body->param.flags.has_block ? body->param.block_start : -1,
3059 body->param.flags.has_kw ? keyword->num : -1,
3060 body->param.flags.has_kw ? keyword->required_num : -1,
3061 body->param.flags.has_kwrest ? keyword->rest_start : -1);
3062
3063 for (i = body->local_table_size; i > 0;) {
3064 int li = body->local_table_size - --i - 1;
3065 long width;
3066 VALUE name = local_var_name(iseq, 0, i);
3067 char argi[0x100];
3068 char opti[0x100];
3069
3070 opti[0] = '\0';
3071 if (body->param.flags.has_opt) {
3072 int argc = body->param.lead_num;
3073 int opts = body->param.opt_num;
3074 if (li >= argc && li < argc + opts) {
3075 snprintf(opti, sizeof(opti), "Opt=%"PRIdVALUE,
3076 body->param.opt_table[li - argc]);
3077 }
3078 }
3079
3080 snprintf(argi, sizeof(argi), "%s%s%s%s%s%s", /* arg, opts, rest, post, kwrest, block */
3081 (body->param.lead_num > li) ? (body->param.flags.ambiguous_param0 ? "AmbiguousArg" : "Arg") : "",
3082 opti,
3083 (body->param.flags.has_rest && body->param.rest_start == li) ? (body->param.flags.anon_rest ? "AnonRest" : "Rest") : "",
3084 (body->param.flags.has_post && body->param.post_start <= li && li < body->param.post_start + body->param.post_num) ? "Post" : "",
3085 (body->param.flags.has_kwrest && keyword->rest_start == li) ? (body->param.flags.anon_kwrest ? "AnonKwrest" : "Kwrest") : "",
3086 (body->param.flags.has_block && body->param.block_start == li) ? "Block" : "");
3087
3088 rb_str_cat(str, indent_str, indent_len);
3089 rb_str_catf(str, "[%2d] ", i + 1);
3090 width = RSTRING_LEN(str) + 11;
3091 rb_str_append(str, name);
3092 if (*argi) rb_str_catf(str, "<%s>", argi);
3093 if ((width -= RSTRING_LEN(str)) > 0) rb_str_catf(str, "%*s", (int)width, "");
3094 }
3095 rb_str_cat_cstr(right_strip(str), "\n");
3096 }
3097
3098 /* show each line */
3099 code = rb_iseq_original_iseq(iseq);
3100 for (n = 0; n < size;) {
3101 rb_str_cat(str, indent_str, indent_len);
3102 n += rb_iseq_disasm_insn(str, code, n, iseq, child);
3103 }
3104
3105 if (body->mandatory_only_iseq) {
3106 rb_ary_push(child, (VALUE)body->mandatory_only_iseq);
3107 }
3108
3109 for (l = 0; l < RARRAY_LEN(child); l++) {
3110 VALUE isv = rb_ary_entry(child, l);
3111 if (done_iseq && st_is_member(done_iseq, (st_data_t)isv)) continue;
3112 rb_str_cat_cstr(str, "\n");
3113 rb_str_concat(str, rb_iseq_disasm_recursive(rb_iseq_check((rb_iseq_t *)isv), indent));
3114 indent_str = RSTRING_PTR(indent);
3115 }
3116 RB_GC_GUARD(done_iseq_wrapper);
3117
3118 return str;
3119}
3120
3121VALUE
3122rb_iseq_disasm(const rb_iseq_t *iseq)
3123{
3124 VALUE str = rb_iseq_disasm_recursive(iseq, rb_str_new(0, 0));
3125 rb_str_resize(str, RSTRING_LEN(str));
3126 return str;
3127}
3128
3129/*
3130 * Estimates the number of instance variables that will be set on
3131 * a given `class` with the initialize method defined in
3132 * `initialize_iseq`
3133 */
3134attr_index_t
3135rb_estimate_iv_count(VALUE klass, const rb_iseq_t * initialize_iseq)
3136{
3137 set_table iv_names = { 0 };
3138 set_init_embedded_numtable_with_size(&iv_names, 0);
3139
3140 for (unsigned int i = 0; i < ISEQ_BODY(initialize_iseq)->ivc_size; i++) {
3141 IVC cache = (IVC)&ISEQ_BODY(initialize_iseq)->is_entries[i];
3142
3143 if (cache->iv_set_name) {
3144 set_insert(&iv_names, cache->iv_set_name);
3145 }
3146 }
3147
3148 size_t count = iv_names.num_entries;
3149
3150 VALUE superclass = rb_class_superclass(klass);
3151 if (!NIL_P(superclass)) { // BasicObject doesn't have a superclass
3152 count += RCLASS_MAX_IV_COUNT(superclass);
3153 }
3154
3155 set_free_embedded_table(&iv_names);
3156
3157 if (count > (attr_index_t)-1) {
3158 return (attr_index_t)-1;
3159 }
3160
3161 return (attr_index_t)count;
3162}
3163
3164/*
3165 * call-seq:
3166 * iseq.disasm -> str
3167 * iseq.disassemble -> str
3168 *
3169 * Returns the instruction sequence as a +String+ in human readable form.
3170 *
3171 * puts RubyVM::InstructionSequence.compile('1 + 2').disasm
3172 *
3173 * Produces:
3174 *
3175 * == disasm: <RubyVM::InstructionSequence:<compiled>@<compiled>>==========
3176 * 0000 trace 1 ( 1)
3177 * 0002 putobject 1
3178 * 0004 putobject 2
3179 * 0006 opt_plus <ic:1>
3180 * 0008 leave
3181 */
3182static VALUE
3183iseqw_disasm(VALUE self)
3184{
3185 return rb_iseq_disasm(iseqw_check(self));
3186}
3187
3188static int
3189iseq_iterate_children(const rb_iseq_t *iseq, void (*iter_func)(const rb_iseq_t *child_iseq, void *data), void *data)
3190{
3191 unsigned int i;
3192 VALUE *code = rb_iseq_original_iseq(iseq);
3193 const struct rb_iseq_constant_body *const body = ISEQ_BODY(iseq);
3194 const rb_iseq_t *child;
3195 VALUE all_children = rb_obj_hide(rb_ident_hash_new());
3196
3197 if (body->catch_table) {
3198 for (i = 0; i < body->catch_table->size; i++) {
3199 const struct iseq_catch_table_entry *entry =
3200 UNALIGNED_MEMBER_PTR(body->catch_table, entries[i]);
3201 child = entry->iseq;
3202 if (child) {
3203 if (NIL_P(rb_hash_aref(all_children, (VALUE)child))) {
3204 rb_hash_aset(all_children, (VALUE)child, Qtrue);
3205 (*iter_func)(child, data);
3206 }
3207 }
3208 }
3209 }
3210
3211 for (i=0; i<body->iseq_size;) {
3212 VALUE insn = code[i];
3213 int len = insn_len(insn);
3214 const char *types = insn_op_types(insn);
3215 int j;
3216
3217 for (j=0; types[j]; j++) {
3218 switch (types[j]) {
3219 case TS_ISEQ:
3220 child = (const rb_iseq_t *)code[i+j+1];
3221 if (child) {
3222 if (NIL_P(rb_hash_aref(all_children, (VALUE)child))) {
3223 rb_hash_aset(all_children, (VALUE)child, Qtrue);
3224 (*iter_func)(child, data);
3225 }
3226 }
3227 break;
3228 default:
3229 break;
3230 }
3231 }
3232 i += len;
3233 }
3234
3235 return (int)RHASH_SIZE(all_children);
3236}
3237
3238static void
3239yield_each_children(const rb_iseq_t *child_iseq, void *data)
3240{
3241 rb_yield(iseqw_new(child_iseq));
3242}
3243
3244/*
3245 * call-seq:
3246 * iseq.each_child{|child_iseq| ...} -> iseq
3247 *
3248 * Iterate all direct child instruction sequences.
3249 * Iteration order is implementation/version defined
3250 * so that people should not rely on the order.
3251 */
3252static VALUE
3253iseqw_each_child(VALUE self)
3254{
3255 const rb_iseq_t *iseq = iseqw_check(self);
3256 iseq_iterate_children(iseq, yield_each_children, NULL);
3257 return self;
3258}
3259
3260static void
3261push_event_info(const rb_iseq_t *iseq, rb_event_flag_t events, int line, VALUE ary)
3262{
3263#define C(ev, cstr, l) if (events & ev) rb_ary_push(ary, rb_ary_new_from_args(2, l, ID2SYM(rb_intern(cstr))));
3264 C(RUBY_EVENT_CLASS, "class", rb_iseq_first_lineno(iseq));
3265 C(RUBY_EVENT_CALL, "call", rb_iseq_first_lineno(iseq));
3266 C(RUBY_EVENT_B_CALL, "b_call", rb_iseq_first_lineno(iseq));
3267 C(RUBY_EVENT_LINE, "line", INT2FIX(line));
3268 C(RUBY_EVENT_END, "end", INT2FIX(line));
3269 C(RUBY_EVENT_RETURN, "return", INT2FIX(line));
3270 C(RUBY_EVENT_B_RETURN, "b_return", INT2FIX(line));
3271 C(RUBY_EVENT_RESCUE, "rescue", INT2FIX(line));
3272#undef C
3273}
3274
3275/*
3276 * call-seq:
3277 * iseq.trace_points -> ary
3278 *
3279 * Return trace points in the instruction sequence.
3280 * Return an array of [line, event_symbol] pair.
3281 */
3282static VALUE
3283iseqw_trace_points(VALUE self)
3284{
3285 const rb_iseq_t *iseq = iseqw_check(self);
3286 const struct rb_iseq_constant_body *const body = ISEQ_BODY(iseq);
3287 unsigned int i;
3288 VALUE ary = rb_ary_new();
3289
3290 for (i=0; i<body->insns_info.size; i++) {
3291 const struct iseq_insn_info_entry *entry = &body->insns_info.body[i];
3292 if (entry->events) {
3293 push_event_info(iseq, entry->events, entry->line_no, ary);
3294 }
3295 }
3296 return ary;
3297}
3298
3299/*
3300 * Returns the instruction sequence containing the given proc or method.
3301 *
3302 * For example, using irb:
3303 *
3304 * # a proc
3305 * > p = proc { num = 1 + 2 }
3306 * > RubyVM::InstructionSequence.of(p)
3307 * > #=> <RubyVM::InstructionSequence:block in irb_binding@(irb)>
3308 *
3309 * # for a method
3310 * > def foo(bar); puts bar; end
3311 * > RubyVM::InstructionSequence.of(method(:foo))
3312 * > #=> <RubyVM::InstructionSequence:foo@(irb)>
3313 *
3314 * Using ::compile_file:
3315 *
3316 * # /tmp/iseq_of.rb
3317 * def hello
3318 * puts "hello, world"
3319 * end
3320 *
3321 * $a_global_proc = proc { str = 'a' + 'b' }
3322 *
3323 * # in irb
3324 * > require '/tmp/iseq_of.rb'
3325 *
3326 * # first the method hello
3327 * > RubyVM::InstructionSequence.of(method(:hello))
3328 * > #=> #<RubyVM::InstructionSequence:0x007fb73d7cb1d0>
3329 *
3330 * # then the global proc
3331 * > RubyVM::InstructionSequence.of($a_global_proc)
3332 * > #=> #<RubyVM::InstructionSequence:0x007fb73d7caf78>
3333 */
3334static VALUE
3335iseqw_s_of(VALUE klass, VALUE body)
3336{
3337 const rb_iseq_t *iseq = NULL;
3338
3339 if (rb_frame_info_p(body)) {
3340 iseq = rb_get_iseq_from_frame_info(body);
3341 }
3342 else if (rb_obj_is_proc(body)) {
3343 iseq = vm_proc_iseq(body);
3344
3345 if (!rb_obj_is_iseq((VALUE)iseq)) {
3346 iseq = NULL;
3347 }
3348 }
3349 else if (rb_obj_is_method(body)) {
3350 iseq = rb_method_iseq(body);
3351 }
3352 else if (rb_typeddata_is_instance_of(body, &iseqw_data_type)) {
3353 return body;
3354 }
3355
3356 return iseq ? iseqw_new(iseq) : Qnil;
3357}
3358
3359/*
3360 * call-seq:
3361 * InstructionSequence.disasm(body) -> str
3362 * InstructionSequence.disassemble(body) -> str
3363 *
3364 * Takes +body+, a +Method+ or +Proc+ object, and returns a +String+
3365 * with the human readable instructions for +body+.
3366 *
3367 * For a +Method+ object:
3368 *
3369 * # /tmp/method.rb
3370 * def hello
3371 * puts "hello, world"
3372 * end
3373 *
3374 * puts RubyVM::InstructionSequence.disasm(method(:hello))
3375 *
3376 * Produces:
3377 *
3378 * == disasm: <RubyVM::InstructionSequence:hello@/tmp/method.rb>============
3379 * 0000 trace 8 ( 1)
3380 * 0002 trace 1 ( 2)
3381 * 0004 putself
3382 * 0005 dupstring "hello, world"
3383 * 0007 send :puts, 1, nil, 8, <ic:0>
3384 * 0013 trace 16 ( 3)
3385 * 0015 leave ( 2)
3386 *
3387 * For a +Proc+ object:
3388 *
3389 * # /tmp/proc.rb
3390 * p = proc { num = 1 + 2 }
3391 * puts RubyVM::InstructionSequence.disasm(p)
3392 *
3393 * Produces:
3394 *
3395 * == disasm: <RubyVM::InstructionSequence:block in <main>@/tmp/proc.rb>===
3396 * == catch table
3397 * | catch type: redo st: 0000 ed: 0012 sp: 0000 cont: 0000
3398 * | catch type: next st: 0000 ed: 0012 sp: 0000 cont: 0012
3399 * |------------------------------------------------------------------------
3400 * local table (size: 2, argc: 0 [opts: 0, rest: -1, post: 0, block: -1] s1)
3401 * [ 2] num
3402 * 0000 trace 1 ( 1)
3403 * 0002 putobject 1
3404 * 0004 putobject 2
3405 * 0006 opt_plus <ic:1>
3406 * 0008 dup
3407 * 0009 setlocal num, 0
3408 * 0012 leave
3409 *
3410 */
3411static VALUE
3412iseqw_s_disasm(VALUE klass, VALUE body)
3413{
3414 VALUE iseqw = iseqw_s_of(klass, body);
3415 return NIL_P(iseqw) ? Qnil : rb_iseq_disasm(iseqw_check(iseqw));
3416}
3417
3418static VALUE
3419register_label(struct st_table *table, unsigned long idx)
3420{
3421 VALUE sym = rb_str_intern(rb_sprintf("label_%lu", idx));
3422 st_insert(table, idx, sym);
3423 return sym;
3424}
3425
3426static VALUE
3427exception_type2symbol(VALUE type)
3428{
3429 ID id;
3430 switch (type) {
3431 case CATCH_TYPE_RESCUE: CONST_ID(id, "rescue"); break;
3432 case CATCH_TYPE_ENSURE: CONST_ID(id, "ensure"); break;
3433 case CATCH_TYPE_RETRY: CONST_ID(id, "retry"); break;
3434 case CATCH_TYPE_BREAK: CONST_ID(id, "break"); break;
3435 case CATCH_TYPE_REDO: CONST_ID(id, "redo"); break;
3436 case CATCH_TYPE_NEXT: CONST_ID(id, "next"); break;
3437 default:
3438 rb_bug("unknown exception type: %d", (int)type);
3439 }
3440 return ID2SYM(id);
3441}
3442
3443static int
3444cdhash_each(VALUE key, VALUE value, VALUE ary)
3445{
3446 rb_ary_push(ary, obj_resurrect(key));
3447 rb_ary_push(ary, INT2FIX(value));
3448 return ST_CONTINUE;
3449}
3450
3451static const rb_data_type_t label_wrapper = {
3452 "label_wrapper",
3453 {(void (*)(void *))rb_mark_tbl, (void (*)(void *))st_free_table, 0, 0,},
3454 0, 0, RUBY_TYPED_THREAD_SAFE_FREE
3455};
3456
3457#define DECL_ID(name) \
3458 static ID id_##name
3459
3460#define INIT_ID(name) \
3461 id_##name = rb_intern(#name)
3462
3463static VALUE
3464iseq_type_id(enum rb_iseq_type type)
3465{
3466 DECL_ID(top);
3467 DECL_ID(method);
3468 DECL_ID(block);
3469 DECL_ID(class);
3470 DECL_ID(rescue);
3471 DECL_ID(ensure);
3472 DECL_ID(eval);
3473 DECL_ID(main);
3474 DECL_ID(plain);
3475
3476 if (id_top == 0) {
3477 INIT_ID(top);
3478 INIT_ID(method);
3479 INIT_ID(block);
3480 INIT_ID(class);
3481 INIT_ID(rescue);
3482 INIT_ID(ensure);
3483 INIT_ID(eval);
3484 INIT_ID(main);
3485 INIT_ID(plain);
3486 }
3487
3488 switch (type) {
3489 case ISEQ_TYPE_TOP: return id_top;
3490 case ISEQ_TYPE_METHOD: return id_method;
3491 case ISEQ_TYPE_BLOCK: return id_block;
3492 case ISEQ_TYPE_CLASS: return id_class;
3493 case ISEQ_TYPE_RESCUE: return id_rescue;
3494 case ISEQ_TYPE_ENSURE: return id_ensure;
3495 case ISEQ_TYPE_EVAL: return id_eval;
3496 case ISEQ_TYPE_MAIN: return id_main;
3497 case ISEQ_TYPE_PLAIN: return id_plain;
3498 };
3499
3500 rb_bug("unsupported iseq type: %d", (int)type);
3501}
3502
3503static VALUE
3504iseq_data_to_ary(const rb_iseq_t *iseq)
3505{
3506 VALUE iseq_value = (VALUE)iseq;
3507 unsigned int i;
3508 long l;
3509 const struct rb_iseq_constant_body *const iseq_body = ISEQ_BODY(iseq);
3510 const struct iseq_insn_info_entry *prev_insn_info;
3511 unsigned int pos;
3512 int last_line = 0;
3513 VALUE *seq, *iseq_original;
3514
3515 VALUE val = rb_ary_new();
3516 ID type; /* Symbol */
3517 VALUE locals = rb_ary_new();
3518 VALUE params = rb_hash_new();
3519 VALUE body = rb_ary_new(); /* [[:insn1, ...], ...] */
3520 VALUE nbody;
3521 VALUE exception = rb_ary_new(); /* [[....]] */
3522 VALUE misc = rb_hash_new();
3523
3524 static ID insn_syms[VM_BARE_INSTRUCTION_SIZE]; /* w/o-trace only */
3525 struct st_table *labels_table = st_init_numtable();
3526 VALUE labels_wrapper = TypedData_Wrap_Struct(0, &label_wrapper, labels_table);
3527
3528 if (insn_syms[0] == 0) {
3529 int i;
3530 for (i=0; i<numberof(insn_syms); i++) {
3531 insn_syms[i] = rb_intern(insn_name(i));
3532 }
3533 }
3534
3535 /* type */
3536 type = iseq_type_id(iseq_body->type);
3537
3538 /* locals */
3539 for (i=0; i<iseq_body->local_table_size; i++) {
3540 ID lid = iseq_body->local_table[i];
3541 if (lid) {
3542 if (lid != idItImplicit && rb_id2str(lid)) {
3543 rb_ary_push(locals, ID2SYM(lid));
3544 }
3545 else { /* hidden variable from id_internal() */
3546 rb_ary_push(locals, ULONG2NUM(iseq_body->local_table_size-i+1));
3547 }
3548 }
3549 else {
3550 rb_ary_push(locals, ID2SYM(rb_intern("#arg_rest")));
3551 }
3552 }
3553
3554 /* params */
3555 {
3556 const struct rb_iseq_param_keyword *const keyword = iseq_body->param.keyword;
3557 int j;
3558
3559 if (iseq_body->param.flags.has_opt) {
3560 int len = iseq_body->param.opt_num + 1;
3561 VALUE arg_opt_labels = rb_ary_new2(len);
3562
3563 for (j = 0; j < len; j++) {
3564 VALUE l = register_label(labels_table, iseq_body->param.opt_table[j]);
3565 rb_ary_push(arg_opt_labels, l);
3566 }
3567 rb_hash_aset(params, ID2SYM(rb_intern("opt")), arg_opt_labels);
3568 }
3569
3570 /* commit */
3571 if (iseq_body->param.flags.has_lead) rb_hash_aset(params, ID2SYM(rb_intern("lead_num")), INT2FIX(iseq_body->param.lead_num));
3572 if (iseq_body->param.flags.has_post) rb_hash_aset(params, ID2SYM(rb_intern("post_num")), INT2FIX(iseq_body->param.post_num));
3573 if (iseq_body->param.flags.has_post) rb_hash_aset(params, ID2SYM(rb_intern("post_start")), INT2FIX(iseq_body->param.post_start));
3574 if (iseq_body->param.flags.has_rest) rb_hash_aset(params, ID2SYM(rb_intern("rest_start")), INT2FIX(iseq_body->param.rest_start));
3575 if (iseq_body->param.flags.has_block) rb_hash_aset(params, ID2SYM(rb_intern("block_start")), INT2FIX(iseq_body->param.block_start));
3576 if (iseq_body->param.flags.has_kw) {
3577 VALUE keywords = rb_ary_new();
3578 int i, j;
3579 for (i=0; i<keyword->required_num; i++) {
3580 rb_ary_push(keywords, ID2SYM(keyword->table[i]));
3581 }
3582 for (j=0; i<keyword->num; i++, j++) {
3583 VALUE key = rb_ary_new_from_args(1, ID2SYM(keyword->table[i]));
3584 if (!UNDEF_P(keyword->default_values[j])) {
3585 rb_ary_push(key, keyword->default_values[j]);
3586 }
3587 rb_ary_push(keywords, key);
3588 }
3589
3590 rb_hash_aset(params, ID2SYM(rb_intern("kwbits")),
3591 INT2FIX(keyword->bits_start));
3592 rb_hash_aset(params, ID2SYM(rb_intern("keyword")), keywords);
3593 }
3594 if (iseq_body->param.flags.has_kwrest) rb_hash_aset(params, ID2SYM(rb_intern("kwrest")), INT2FIX(keyword->rest_start));
3595 if (iseq_body->param.flags.ambiguous_param0) rb_hash_aset(params, ID2SYM(rb_intern("ambiguous_param0")), Qtrue);
3596 if (iseq_body->param.flags.use_block) rb_hash_aset(params, ID2SYM(rb_intern("use_block")), Qtrue);
3597 }
3598
3599 /* body */
3600 iseq_original = rb_iseq_original_iseq((rb_iseq_t *)iseq);
3601
3602 for (seq = iseq_original; seq < iseq_original + iseq_body->iseq_size; ) {
3603 VALUE insn = *seq++;
3604 int j, len = insn_len(insn);
3605 VALUE *nseq = seq + len - 1;
3606 VALUE ary = rb_ary_new2(len);
3607
3608 rb_ary_push(ary, ID2SYM(insn_syms[insn%numberof(insn_syms)]));
3609 for (j=0; j<len-1; j++, seq++) {
3610 enum ruby_insn_type_chars op_type = insn_op_type(insn, j);
3611
3612 switch (op_type) {
3613 case TS_OFFSET: {
3614 unsigned long idx = nseq - iseq_original + *seq;
3615 rb_ary_push(ary, register_label(labels_table, idx));
3616 break;
3617 }
3618 case TS_LINDEX:
3619 case TS_NUM:
3620 rb_ary_push(ary, INT2FIX(*seq));
3621 break;
3622 case TS_VALUE:
3623 rb_ary_push(ary, obj_resurrect(*seq));
3624 break;
3625 case TS_ISEQ:
3626 {
3627 const rb_iseq_t *iseq = (rb_iseq_t *)*seq;
3628 if (iseq) {
3629 VALUE val = iseq_data_to_ary(rb_iseq_check(iseq));
3630 rb_ary_push(ary, val);
3631 }
3632 else {
3633 rb_ary_push(ary, Qnil);
3634 }
3635 }
3636 break;
3637 case TS_IC:
3638 {
3639 VALUE list = rb_ary_new();
3640 const ID *ids = ((IC)*seq)->segments;
3641 while (*ids) {
3642 rb_ary_push(list, ID2SYM(*ids++));
3643 }
3644 rb_ary_push(ary, list);
3645 }
3646 break;
3647 case TS_IVC:
3648 case TS_ICVARC:
3649 case TS_ISE:
3650 {
3651 union iseq_inline_storage_entry *is = (union iseq_inline_storage_entry *)*seq;
3652 rb_ary_push(ary, INT2FIX(is - ISEQ_IS_ENTRY_START(ISEQ_BODY(iseq), op_type)));
3653 }
3654 break;
3655 case TS_CALLDATA:
3656 {
3657 struct rb_call_data *cd = (struct rb_call_data *)*seq;
3658 const struct rb_callinfo *ci = cd->ci;
3659 VALUE e = rb_hash_new();
3660 int argc = vm_ci_argc(ci);
3661
3662 ID mid = vm_ci_mid(ci);
3663 rb_hash_aset(e, ID2SYM(rb_intern("mid")), mid ? ID2SYM(mid) : Qnil);
3664 rb_hash_aset(e, ID2SYM(rb_intern("flag")), UINT2NUM(vm_ci_flag(ci)));
3665
3666 if (vm_ci_flag(ci) & VM_CALL_KWARG) {
3667 const struct rb_callinfo_kwarg *kwarg = vm_ci_kwarg(ci);
3668 int i;
3669 VALUE kw = rb_ary_new2((long)kwarg->keyword_len);
3670
3671 argc -= kwarg->keyword_len;
3672 for (i = 0; i < kwarg->keyword_len; i++) {
3673 rb_ary_push(kw, kwarg->keywords[i]);
3674 }
3675 rb_hash_aset(e, ID2SYM(rb_intern("kw_arg")), kw);
3676 }
3677
3678 rb_hash_aset(e, ID2SYM(rb_intern("orig_argc")),
3679 INT2FIX(argc));
3680 rb_ary_push(ary, e);
3681 }
3682 break;
3683 case TS_ID:
3684 rb_ary_push(ary, ID2SYM(*seq));
3685 break;
3686 case TS_CDHASH:
3687 {
3688 VALUE cdhash = *seq;
3689 VALUE val = rb_ary_new();
3690 int i;
3691
3692 st_foreach(rb_imemo_cdhash_tbl(cdhash), cdhash_each, val);
3693
3694 for (i=0; i<RARRAY_LEN(val); i+=2) {
3695 VALUE pos = FIX2INT(rb_ary_entry(val, i+1));
3696 unsigned long idx = nseq - iseq_original + pos;
3697
3698 rb_ary_store(val, i+1,
3699 register_label(labels_table, idx));
3700 }
3701 rb_ary_push(ary, val);
3702 }
3703 break;
3704 case TS_FUNCPTR:
3705 {
3706#if SIZEOF_VALUE <= SIZEOF_LONG
3707 VALUE val = LONG2NUM((SIGNED_VALUE)*seq);
3708#else
3709 VALUE val = LL2NUM((SIGNED_VALUE)*seq);
3710#endif
3711 rb_ary_push(ary, val);
3712 }
3713 break;
3714 case TS_BUILTIN:
3715 {
3716 VALUE val = rb_hash_new();
3717#if SIZEOF_VALUE <= SIZEOF_LONG
3718 VALUE func_ptr = LONG2NUM((SIGNED_VALUE)((RB_BUILTIN)*seq)->func_ptr);
3719#else
3720 VALUE func_ptr = LL2NUM((SIGNED_VALUE)((RB_BUILTIN)*seq)->func_ptr);
3721#endif
3722 rb_hash_aset(val, ID2SYM(rb_intern("func_ptr")), func_ptr);
3723 rb_hash_aset(val, ID2SYM(rb_intern("argc")), INT2NUM(((RB_BUILTIN)*seq)->argc));
3724 rb_hash_aset(val, ID2SYM(rb_intern("index")), INT2NUM(((RB_BUILTIN)*seq)->index));
3725 rb_hash_aset(val, ID2SYM(rb_intern("name")), rb_str_new_cstr(((RB_BUILTIN)*seq)->name));
3726 rb_ary_push(ary, val);
3727 }
3728 break;
3729 default:
3730 rb_bug("unknown operand: %c", insn_op_type(insn, j));
3731 }
3732 }
3733 rb_ary_push(body, ary);
3734 }
3735
3736 nbody = body;
3737
3738 /* exception */
3739 if (iseq_body->catch_table) for (i=0; i<iseq_body->catch_table->size; i++) {
3740 VALUE ary = rb_ary_new();
3741 const struct iseq_catch_table_entry *entry =
3742 UNALIGNED_MEMBER_PTR(iseq_body->catch_table, entries[i]);
3743 rb_ary_push(ary, exception_type2symbol(entry->type));
3744 if (entry->iseq) {
3745 rb_ary_push(ary, iseq_data_to_ary(rb_iseq_check(entry->iseq)));
3746 }
3747 else {
3748 rb_ary_push(ary, Qnil);
3749 }
3750 rb_ary_push(ary, register_label(labels_table, entry->start));
3751 rb_ary_push(ary, register_label(labels_table, entry->end));
3752 rb_ary_push(ary, register_label(labels_table, entry->cont));
3753 rb_ary_push(ary, UINT2NUM(entry->sp));
3754 rb_ary_push(exception, ary);
3755 }
3756
3757 /* make body with labels and insert line number */
3758 body = rb_ary_new();
3759 prev_insn_info = NULL;
3760#ifdef USE_ISEQ_NODE_ID
3761 VALUE node_ids = rb_ary_new();
3762#endif
3763
3764 for (l=0, pos=0; l<RARRAY_LEN(nbody); l++) {
3765 const struct iseq_insn_info_entry *info;
3766 VALUE ary = RARRAY_AREF(nbody, l);
3767 st_data_t label;
3768
3769 if (st_lookup(labels_table, pos, &label)) {
3770 rb_ary_push(body, (VALUE)label);
3771 }
3772
3773 info = get_insn_info(iseq, pos);
3774#ifdef USE_ISEQ_NODE_ID
3775 rb_ary_push(node_ids, INT2FIX(info->node_id));
3776#endif
3777
3778 if (prev_insn_info != info) {
3779 int line = info->line_no;
3780 rb_event_flag_t events = info->events;
3781
3782 if (line > 0 && last_line != line) {
3783 rb_ary_push(body, INT2FIX(line));
3784 last_line = line;
3785 }
3786#define CHECK_EVENT(ev) if (events & ev) rb_ary_push(body, ID2SYM(rb_intern(#ev)));
3787 CHECK_EVENT(RUBY_EVENT_LINE);
3788 CHECK_EVENT(RUBY_EVENT_CLASS);
3789 CHECK_EVENT(RUBY_EVENT_END);
3790 CHECK_EVENT(RUBY_EVENT_CALL);
3791 CHECK_EVENT(RUBY_EVENT_RETURN);
3792 CHECK_EVENT(RUBY_EVENT_B_CALL);
3793 CHECK_EVENT(RUBY_EVENT_B_RETURN);
3794 CHECK_EVENT(RUBY_EVENT_RESCUE);
3795#undef CHECK_EVENT
3796 prev_insn_info = info;
3797 }
3798
3799 rb_ary_push(body, ary);
3800 pos += RARRAY_LENINT(ary); /* reject too huge data */
3801 }
3802 RB_GC_GUARD(nbody);
3803 RB_GC_GUARD(labels_wrapper);
3804
3805 rb_hash_aset(misc, ID2SYM(rb_intern("arg_size")), INT2FIX(iseq_body->param.size));
3806 rb_hash_aset(misc, ID2SYM(rb_intern("local_size")), INT2FIX(iseq_body->local_table_size));
3807 rb_hash_aset(misc, ID2SYM(rb_intern("stack_max")), INT2FIX(iseq_body->stack_max));
3808 rb_hash_aset(misc, ID2SYM(rb_intern("node_id")), INT2FIX(iseq_body->location.node_id));
3809 rb_hash_aset(misc, ID2SYM(rb_intern("source_hash")), iseq_body->source_hash ? ULL2NUM(iseq_body->source_hash) : Qnil);
3810 rb_hash_aset(misc, ID2SYM(rb_intern("code_location")),
3811 rb_ary_new_from_args(4,
3812 INT2FIX(iseq_body->location.code_location.beg_pos.lineno),
3813 INT2FIX(iseq_body->location.code_location.beg_pos.column),
3814 INT2FIX(iseq_body->location.code_location.end_pos.lineno),
3815 INT2FIX(iseq_body->location.code_location.end_pos.column)));
3816#ifdef USE_ISEQ_NODE_ID
3817 rb_hash_aset(misc, ID2SYM(rb_intern("node_ids")), node_ids);
3818#endif
3819 rb_hash_aset(misc, ID2SYM(rb_intern("parser")), iseq_body->prism ? ID2SYM(rb_intern("prism")) : ID2SYM(rb_intern("parse.y")));
3820
3821 /*
3822 * [:magic, :major_version, :minor_version, :format_type, :misc,
3823 * :name, :path, :absolute_path, :start_lineno, :type, :locals, :args,
3824 * :catch_table, :bytecode]
3825 */
3826 rb_ary_push(val, rb_str_new2("YARVInstructionSequence/SimpleDataFormat"));
3827 rb_ary_push(val, INT2FIX(ISEQ_MAJOR_VERSION)); /* major */
3828 rb_ary_push(val, INT2FIX(ISEQ_MINOR_VERSION)); /* minor */
3829 rb_ary_push(val, INT2FIX(1));
3830 rb_ary_push(val, misc);
3831 rb_ary_push(val, iseq_body->location.label);
3832 rb_ary_push(val, rb_iseq_path(iseq));
3833 rb_ary_push(val, rb_iseq_realpath(iseq));
3834 rb_ary_push(val, RB_INT2NUM(iseq_body->location.first_lineno));
3835 rb_ary_push(val, ID2SYM(type));
3836 rb_ary_push(val, locals);
3837 rb_ary_push(val, params);
3838 rb_ary_push(val, exception);
3839 rb_ary_push(val, body);
3840
3841 RB_GC_GUARD(iseq_value);
3842
3843 return val;
3844}
3845
3846VALUE
3847rb_iseq_parameters(const rb_iseq_t *iseq, int is_proc)
3848{
3849 int i, r;
3850 const struct rb_iseq_constant_body *const body = ISEQ_BODY(iseq);
3851 const struct rb_iseq_param_keyword *const keyword = body->param.keyword;
3852 VALUE a, args = rb_ary_new2(body->param.size);
3853 ID req, opt, rest, block, key, keyrest;
3854#define PARAM_TYPE(type) rb_ary_push(a = rb_ary_new2(2), ID2SYM(type))
3855#define PARAM_ID(i) body->local_table[(i)]
3856#define PARAM(i, type) ( \
3857 PARAM_TYPE(type), \
3858 PARAM_ID(i) != idItImplicit && rb_id2str(PARAM_ID(i)) ? \
3859 rb_ary_push(a, ID2SYM(PARAM_ID(i))) : \
3860 a)
3861
3862 CONST_ID(req, "req");
3863 CONST_ID(opt, "opt");
3864
3865 if (body->param.flags.forwardable) {
3866 // [[:rest, :*], [:keyrest, :**], [:block, :&]]
3867 CONST_ID(rest, "rest");
3868 CONST_ID(keyrest, "keyrest");
3869 CONST_ID(block, "block");
3870 rb_ary_push(args, rb_ary_new_from_args(2, ID2SYM(rest), ID2SYM(idMULT)));
3871 rb_ary_push(args, rb_ary_new_from_args(2, ID2SYM(keyrest), ID2SYM(idPow)));
3872 rb_ary_push(args, rb_ary_new_from_args(2, ID2SYM(block), ID2SYM(idAnd)));
3873 }
3874
3875 if (is_proc) {
3876 for (i = 0; i < body->param.lead_num; i++) {
3877 rb_ary_push(args, PARAM(i, opt));
3878 }
3879 }
3880 else {
3881 for (i = 0; i < body->param.lead_num; i++) {
3882 rb_ary_push(args, PARAM(i, req));
3883 }
3884 }
3885 r = body->param.lead_num + body->param.opt_num;
3886 for (; i < r; i++) {
3887 rb_ary_push(args, PARAM(i, opt));
3888 }
3889 if (body->param.flags.has_rest) {
3890 CONST_ID(rest, "rest");
3891 rb_ary_push(args, PARAM(body->param.rest_start, rest));
3892 }
3893 r = body->param.post_start + body->param.post_num;
3894 if (is_proc) {
3895 for (i = body->param.post_start; i < r; i++) {
3896 rb_ary_push(args, PARAM(i, opt));
3897 }
3898 }
3899 else {
3900 for (i = body->param.post_start; i < r; i++) {
3901 rb_ary_push(args, PARAM(i, req));
3902 }
3903 }
3904 if (body->param.flags.accepts_no_kwarg) {
3905 ID nokey;
3906 CONST_ID(nokey, "nokey");
3907 PARAM_TYPE(nokey);
3908 rb_ary_push(args, a);
3909 }
3910 if (body->param.flags.has_kw) {
3911 i = 0;
3912 if (keyword->required_num > 0) {
3913 ID keyreq;
3914 CONST_ID(keyreq, "keyreq");
3915 for (; i < keyword->required_num; i++) {
3916 PARAM_TYPE(keyreq);
3917 if (rb_id2str(keyword->table[i])) {
3918 rb_ary_push(a, ID2SYM(keyword->table[i]));
3919 }
3920 rb_ary_push(args, a);
3921 }
3922 }
3923 CONST_ID(key, "key");
3924 for (; i < keyword->num; i++) {
3925 PARAM_TYPE(key);
3926 if (rb_id2str(keyword->table[i])) {
3927 rb_ary_push(a, ID2SYM(keyword->table[i]));
3928 }
3929 rb_ary_push(args, a);
3930 }
3931 }
3932 if (body->param.flags.has_kwrest || body->param.flags.ruby2_keywords) {
3933 ID param;
3934 CONST_ID(keyrest, "keyrest");
3935 PARAM_TYPE(keyrest);
3936 if (body->param.flags.has_kwrest &&
3937 rb_id2str(param = PARAM_ID(keyword->rest_start))) {
3938 rb_ary_push(a, ID2SYM(param));
3939 }
3940 else if (body->param.flags.ruby2_keywords) {
3941 rb_ary_push(a, ID2SYM(idPow));
3942 }
3943 rb_ary_push(args, a);
3944 }
3945 if (body->param.flags.accepts_no_block) {
3946 ID noblock;
3947 CONST_ID(noblock, "noblock");
3948 PARAM_TYPE(noblock);
3949 rb_ary_push(args, a);
3950 }
3951 else if (body->param.flags.has_block) {
3952 CONST_ID(block, "block");
3953 rb_ary_push(args, PARAM(body->param.block_start, block));
3954 }
3955 return args;
3956}
3957
3958VALUE
3959rb_iseq_defined_string(enum defined_type type)
3960{
3961 static const char expr_names[][18] = {
3962 "nil",
3963 "instance-variable",
3964 "local-variable",
3965 "global-variable",
3966 "class variable",
3967 "constant",
3968 "method",
3969 "yield",
3970 "super",
3971 "self",
3972 "true",
3973 "false",
3974 "assignment",
3975 "expression",
3976 };
3977 const char *estr;
3978
3979 if ((unsigned)(type - 1) >= (unsigned)numberof(expr_names)) rb_bug("unknown defined type %d", type);
3980 estr = expr_names[type - 1];
3981 return rb_fstring_cstr(estr);
3982}
3983
3984// A map from encoded_insn to insn_data: decoded insn number, its len,
3985// decoded ZJIT insn number, non-trace version of encoded insn,
3986// trace version, and zjit version.
3987static st_table *encoded_insn_data;
3988typedef struct insn_data_struct {
3989 int insn;
3990 int insn_len;
3991 void *notrace_encoded_insn;
3992 void *trace_encoded_insn;
3993#if USE_ZJIT
3994 int zjit_insn;
3995 void *zjit_encoded_insn;
3996#endif
3997} insn_data_t;
3998static insn_data_t insn_data[VM_BARE_INSTRUCTION_SIZE];
3999
4000void
4001rb_free_encoded_insn_data(void)
4002{
4003 st_free_table(encoded_insn_data);
4004}
4005
4006// Initialize a table to decode bare, trace, and zjit instructions.
4007// This function also determines which instructions are used when TracePoint is enabled.
4008void
4009rb_vm_encoded_insn_data_table_init(void)
4010{
4011#if OPT_DIRECT_THREADED_CODE || OPT_CALL_THREADED_CODE
4012 const void * const *table = rb_vm_get_insns_address_table();
4013#define INSN_CODE(insn) ((VALUE)table[insn])
4014#else
4015#define INSN_CODE(insn) ((VALUE)(insn))
4016#endif
4017 encoded_insn_data = st_init_numtable_with_size(VM_BARE_INSTRUCTION_SIZE);
4018
4019 for (int insn = 0; insn < VM_BARE_INSTRUCTION_SIZE; insn++) {
4020 insn_data[insn].insn = insn;
4021 insn_data[insn].insn_len = insn_len(insn);
4022
4023 // When tracing :return events, we convert opt_invokebuiltin_delegate_leave + leave into
4024 // opt_invokebuiltin_delegate + trace_leave, presumably because we don't want to fire
4025 // :return events before invokebuiltin. https://github.com/ruby/ruby/pull/3256
4026 int notrace_insn = (insn != BIN(opt_invokebuiltin_delegate_leave)) ? insn : BIN(opt_invokebuiltin_delegate);
4027 insn_data[insn].notrace_encoded_insn = (void *)INSN_CODE(notrace_insn);
4028 insn_data[insn].trace_encoded_insn = (void *)INSN_CODE(notrace_insn + VM_BARE_INSTRUCTION_SIZE);
4029
4030 st_data_t key1 = (st_data_t)INSN_CODE(insn);
4031 st_data_t key2 = (st_data_t)INSN_CODE(insn + VM_BARE_INSTRUCTION_SIZE);
4032 st_add_direct(encoded_insn_data, key1, (st_data_t)&insn_data[insn]);
4033 st_add_direct(encoded_insn_data, key2, (st_data_t)&insn_data[insn]);
4034
4035#if USE_ZJIT
4036 int zjit_insn = vm_bare_insn_to_zjit_insn(insn);
4037 insn_data[insn].zjit_insn = zjit_insn;
4038 insn_data[insn].zjit_encoded_insn = (insn != zjit_insn) ? (void *)INSN_CODE(zjit_insn) : 0;
4039
4040 if (insn != zjit_insn) {
4041 st_data_t key3 = (st_data_t)INSN_CODE(zjit_insn);
4042 st_add_direct(encoded_insn_data, key3, (st_data_t)&insn_data[insn]);
4043 }
4044#endif
4045 }
4046}
4047
4048// Decode an insn address to an insn. This returns bare instructions
4049// even if they're trace/zjit instructions. Use rb_vm_insn_addr2opcode
4050// to decode trace/zjit instructions as is.
4051int
4052rb_vm_insn_addr2insn(const void *addr)
4053{
4054 st_data_t key = (st_data_t)addr;
4055 st_data_t val;
4056
4057 if (st_lookup(encoded_insn_data, key, &val)) {
4058 insn_data_t *e = (insn_data_t *)val;
4059 return (int)e->insn;
4060 }
4061
4062 rb_bug("rb_vm_insn_addr2insn: invalid insn address: %p", addr);
4063}
4064
4065// Decode an insn address to an insn. Unlike rb_vm_insn_addr2insn,
4066// this function can return trace/zjit opcode variants.
4067int
4068rb_vm_insn_addr2opcode(const void *addr)
4069{
4070 st_data_t key = (st_data_t)addr;
4071 st_data_t val;
4072
4073 if (st_lookup(encoded_insn_data, key, &val)) {
4074 insn_data_t *e = (insn_data_t *)val;
4075 int opcode = e->insn;
4076 if (addr == e->trace_encoded_insn) {
4077 opcode += VM_BARE_INSTRUCTION_SIZE;
4078 }
4079#if USE_ZJIT
4080 else if (addr == e->zjit_encoded_insn) {
4081 opcode = e->zjit_insn;
4082 }
4083#endif
4084 return opcode;
4085 }
4086
4087 rb_bug("rb_vm_insn_addr2opcode: invalid insn address: %p", addr);
4088}
4089
4090// Decode `ISEQ_BODY(iseq)->iseq_encoded[i]` to an insn. This returns
4091// bare instructions even if they're trace/zjit instructions. Use
4092// rb_vm_insn_addr2opcode to decode trace/zjit instructions as is.
4093int
4094rb_vm_insn_decode(const VALUE encoded)
4095{
4096#if OPT_DIRECT_THREADED_CODE || OPT_CALL_THREADED_CODE
4097 int insn = rb_vm_insn_addr2insn((void *)encoded);
4098#else
4099 int insn = (int)encoded;
4100#endif
4101 return insn;
4102}
4103
4104// Turn on or off tracing for a given instruction address
4105static inline int
4106encoded_iseq_trace_instrument(VALUE *iseq_encoded_insn, rb_event_flag_t turnon, bool remain_traced)
4107{
4108 st_data_t key = (st_data_t)*iseq_encoded_insn;
4109 st_data_t val;
4110
4111 if (st_lookup(encoded_insn_data, key, &val)) {
4112 insn_data_t *e = (insn_data_t *)val;
4113 if (remain_traced && key == (st_data_t)e->trace_encoded_insn) {
4114 turnon = 1;
4115 }
4116 *iseq_encoded_insn = (VALUE) (turnon ? e->trace_encoded_insn : e->notrace_encoded_insn);
4117 return e->insn_len;
4118 }
4119
4120 rb_bug("trace_instrument: invalid insn address: %p", (void *)*iseq_encoded_insn);
4121}
4122
4123// Turn off tracing for an instruction at pos after tracing event flags are cleared
4124static void
4125rb_iseq_trace_flag_cleared(const rb_iseq_t *iseq, size_t pos)
4126{
4127 const struct rb_iseq_constant_body *const body = ISEQ_BODY(iseq);
4128 VALUE *iseq_encoded = (VALUE *)body->iseq_encoded;
4129 encoded_iseq_trace_instrument(&iseq_encoded[pos], 0, false);
4130}
4131
4132// We need to fire call events on instructions with b_call events if the block
4133// is running as a method. So, if we are listening for call events, then
4134// instructions that have b_call events need to become trace variants.
4135// Use this function when making decisions about recompiling to trace variants.
4136static inline rb_event_flag_t
4137add_bmethod_events(rb_event_flag_t events)
4138{
4139 if (events & RUBY_EVENT_CALL) {
4140 events |= RUBY_EVENT_B_CALL;
4141 }
4142 if (events & RUBY_EVENT_RETURN) {
4143 events |= RUBY_EVENT_B_RETURN;
4144 }
4145 return events;
4146}
4147
4148// Note, to support call/return events for bmethods, turnon_event can have more events than tpval.
4149static int
4150iseq_add_local_tracepoint(const rb_iseq_t *iseq, rb_event_flag_t turnon_events, VALUE tpval, unsigned int target_line, rb_ractor_t *r)
4151{
4152 unsigned int pc;
4153 int n = 0;
4154 const struct rb_iseq_constant_body *const body = ISEQ_BODY(iseq);
4155 VALUE *iseq_encoded = (VALUE *)body->iseq_encoded;
4156 rb_iseq_t *iseq_mut = (rb_iseq_t*)iseq;
4157
4158 VM_ASSERT(ISEQ_EXECUTABLE_P(iseq));
4159 ASSERT_vm_locking_with_barrier();
4160
4161 for (pc=0; pc<body->iseq_size;) {
4162 const struct iseq_insn_info_entry *entry = get_insn_info(iseq, pc);
4163 rb_event_flag_t pc_events = entry->events;
4164 rb_event_flag_t target_events = turnon_events;
4165 unsigned int line = (int)entry->line_no;
4166
4167 if (target_line == 0 || target_line == line) {
4168 /* ok */
4169 }
4170 else {
4171 target_events &= ~RUBY_EVENT_LINE;
4172 }
4173
4174 if (pc_events & target_events) {
4175 n++;
4176 }
4177 pc += encoded_iseq_trace_instrument(&iseq_encoded[pc], pc_events & (target_events | iseq->aux.exec.global_trace_events), true);
4178 }
4179
4180 if (n > 0) {
4181 rb_hook_list_t *hook_list = rb_iseq_local_hooks(iseq, r, true);
4182 rb_hook_list_connect_local_tracepoint(hook_list, tpval, target_line);
4183 iseq_mut->aux.exec.local_hooks_cnt++;
4184 }
4185
4186 return n;
4187}
4188
4190 rb_event_flag_t turnon_events;
4191 VALUE tpval;
4192 unsigned int target_line;
4193 int n;
4194 rb_ractor_t *r;
4195};
4196
4197static void
4198iseq_add_local_tracepoint_i(const rb_iseq_t *iseq, void *p)
4199{
4201 data->n += iseq_add_local_tracepoint(iseq, data->turnon_events, data->tpval, data->target_line, data->r);
4202 iseq_iterate_children(iseq, iseq_add_local_tracepoint_i, p);
4203}
4204
4205int
4206rb_iseq_add_local_tracepoint_recursively(const rb_iseq_t *iseq, rb_event_flag_t turnon_events, VALUE tpval, unsigned int target_line, bool target_bmethod)
4207{
4208 ASSERT_vm_locking_with_barrier();
4210 if (target_bmethod) {
4211 turnon_events = add_bmethod_events(turnon_events);
4212 }
4213 data.turnon_events = turnon_events;
4214 data.tpval = tpval;
4215 data.target_line = target_line;
4216 data.n = 0;
4217 data.r = GET_RACTOR();
4218
4219 iseq_add_local_tracepoint_i(iseq, (void *)&data);
4220 if (0) {
4221 VALUE disasm = rb_iseq_disasm(iseq);
4222 fprintf(stderr, "Iseq disasm:\n:%.*s",
4223 RSTRING_LENINT(disasm), RSTRING_PTR(disasm));
4224 }
4225 return data.n;
4226}
4227
4228static int
4229iseq_remove_local_tracepoint(const rb_iseq_t *iseq, VALUE tpval, rb_ractor_t *r)
4230{
4231 int n = 0;
4232 unsigned int num_hooks_left;
4233 unsigned int pc;
4234 const struct rb_iseq_constant_body *body;
4235 rb_iseq_t *iseq_mut = (rb_iseq_t*)iseq;
4236 rb_hook_list_t *hook_list;
4237 VALUE *iseq_encoded;
4238 ASSERT_vm_locking_with_barrier();
4239
4240 hook_list = rb_iseq_local_hooks(iseq, r, false);
4241
4242 if (hook_list) {
4243 rb_event_flag_t local_events = 0;
4244
4245 rb_event_flag_t prev_events = hook_list->events;
4246 if (rb_hook_list_remove_local_tracepoint(hook_list, tpval)) {
4247 RUBY_ASSERT(iseq->aux.exec.local_hooks_cnt > 0);
4248 iseq_mut->aux.exec.local_hooks_cnt--;
4249 local_events = hook_list->events; // remaining events for this ractor
4250 num_hooks_left = rb_hook_list_count(hook_list);
4251 if (local_events == 0 && prev_events != 0) {
4252 st_delete(rb_ractor_targeted_hooks(r), (st_data_t*)&iseq, NULL);
4253 rb_hook_list_free(hook_list);
4254 }
4255
4256 if (iseq->aux.exec.local_hooks_cnt == num_hooks_left) {
4257 body = ISEQ_BODY(iseq);
4258 iseq_encoded = (VALUE *)body->iseq_encoded;
4259 local_events = add_bmethod_events(local_events);
4260 for (pc = 0; pc<body->iseq_size;) {
4261 rb_event_flag_t pc_events = rb_iseq_event_flags(iseq, pc);
4262 pc += encoded_iseq_trace_instrument(&iseq_encoded[pc], pc_events & (local_events | iseq->aux.exec.global_trace_events), false);
4263 }
4264 }
4265
4266 n++;
4267 }
4268 }
4269 return n;
4270}
4271
4273 VALUE tpval;
4274 int n;
4275 rb_ractor_t *r;
4276};
4277
4278static void
4279iseq_remove_local_tracepoint_i(const rb_iseq_t *iseq, void *p)
4280{
4282 data->n += iseq_remove_local_tracepoint(iseq, data->tpval, data->r);
4283 iseq_iterate_children(iseq, iseq_remove_local_tracepoint_i, p);
4284}
4285
4286int
4287rb_iseq_remove_local_tracepoint_recursively(const rb_iseq_t *iseq, VALUE tpval, rb_ractor_t *r)
4288{
4290 ASSERT_vm_locking_with_barrier();
4291 data.tpval = tpval;
4292 data.n = 0;
4293 data.r = r;
4294
4295 iseq_remove_local_tracepoint_i(iseq, (void *)&data);
4296 return data.n;
4297}
4298
4299void
4300rb_iseq_trace_set(const rb_iseq_t *iseq, rb_event_flag_t turnon_events)
4301{
4302 if (iseq->aux.exec.global_trace_events == turnon_events) {
4303 return;
4304 }
4305
4306 if (!ISEQ_EXECUTABLE_P(iseq)) {
4307 /* this is building ISeq */
4308 return;
4309 }
4310 else {
4311 // NOTE: this does not need VM barrier if it's a new ISEQ
4312 unsigned int pc;
4313 const struct rb_iseq_constant_body *const body = ISEQ_BODY(iseq);
4314
4315 VALUE *iseq_encoded = (VALUE *)body->iseq_encoded;
4316 rb_event_flag_t enabled_events;
4317 rb_hook_list_t *local_hooks = rb_iseq_local_hooks(iseq, GET_RACTOR(), false);
4318 rb_event_flag_t local_events = local_hooks ? local_hooks->events : 0;
4319 ((rb_iseq_t *)iseq)->aux.exec.global_trace_events = turnon_events;
4320 enabled_events = add_bmethod_events(turnon_events | local_events);
4321
4322 for (pc=0; pc<body->iseq_size;) {
4323 rb_event_flag_t pc_events = rb_iseq_event_flags(iseq, pc);
4324 pc += encoded_iseq_trace_instrument(&iseq_encoded[pc], pc_events & enabled_events, true);
4325 }
4326 }
4327}
4328
4329void rb_vm_cc_general(const struct rb_callcache *cc);
4330
4331static bool
4332clear_attr_cc(VALUE v)
4333{
4334 ASSERT_vm_locking_with_barrier();
4335 if (imemo_type_p(v, imemo_callcache) && vm_cc_ivar_p((const struct rb_callcache *)v)) {
4336 rb_vm_cc_general((struct rb_callcache *)v);
4337 return true;
4338 }
4339 else {
4340 return false;
4341 }
4342}
4343
4344static bool
4345clear_bf_cc(VALUE v)
4346{
4347 ASSERT_vm_locking_with_barrier();
4348 if (imemo_type_p(v, imemo_callcache) && vm_cc_bf_p((const struct rb_callcache *)v)) {
4349 rb_vm_cc_general((struct rb_callcache *)v);
4350 return true;
4351 }
4352 else {
4353 return false;
4354 }
4355}
4356
4357static int
4358clear_attr_ccs_i(void *vstart, void *vend, size_t stride, void *data)
4359{
4360 VALUE v = (VALUE)vstart;
4361 for (; v != (VALUE)vend; v += stride) {
4362 void *ptr = rb_asan_poisoned_object_p(v);
4363 rb_asan_unpoison_object(v, false);
4364 clear_attr_cc(v);
4365 asan_poison_object_if(ptr, v);
4366 }
4367 return 0;
4368}
4369
4370void
4371rb_clear_attr_ccs(void)
4372{
4373 rb_objspace_each_objects(clear_attr_ccs_i, NULL);
4374}
4375
4376static int
4377clear_bf_ccs_i(void *vstart, void *vend, size_t stride, void *data)
4378{
4379 VALUE v = (VALUE)vstart;
4380 for (; v != (VALUE)vend; v += stride) {
4381 void *ptr = rb_asan_poisoned_object_p(v);
4382 rb_asan_unpoison_object(v, false);
4383 clear_bf_cc(v);
4384 asan_poison_object_if(ptr, v);
4385 }
4386 return 0;
4387}
4388
4389void
4390rb_clear_bf_ccs(void)
4391{
4392 rb_objspace_each_objects(clear_bf_ccs_i, NULL);
4393}
4394
4395static int
4396trace_set_i(void *vstart, void *vend, size_t stride, void *data)
4397{
4398 rb_event_flag_t turnon_events = *(rb_event_flag_t *)data;
4399
4400 VALUE v = (VALUE)vstart;
4401 for (; v != (VALUE)vend; v += stride) {
4402 void *ptr = rb_asan_poisoned_object_p(v);
4403 rb_asan_unpoison_object(v, false);
4404
4405 if (rb_obj_is_iseq(v)) {
4406 rb_iseq_trace_set(rb_iseq_check((rb_iseq_t *)v), turnon_events);
4407 }
4408 else if (clear_attr_cc(v)) {
4409 }
4410 else if (clear_bf_cc(v)) {
4411 }
4412
4413 asan_poison_object_if(ptr, v);
4414 }
4415 return 0;
4416}
4417
4418void
4419rb_iseq_trace_set_all(rb_event_flag_t turnon_events)
4420{
4421 rb_objspace_each_objects(trace_set_i, &turnon_events);
4422}
4423
4424VALUE
4425rb_iseqw_local_variables(VALUE iseqval)
4426{
4427 return rb_iseq_local_variables(iseqw_check(iseqval));
4428}
4429
4430/*
4431 * call-seq:
4432 * iseq.to_binary(extra_data = nil) -> binary str
4433 *
4434 * Returns serialized iseq binary format data as a String object.
4435 * A corresponding iseq object is created by
4436 * RubyVM::InstructionSequence.load_from_binary() method.
4437 *
4438 * String extra_data will be saved with binary data.
4439 * You can access this data with
4440 * RubyVM::InstructionSequence.load_from_binary_extra_data(binary).
4441 *
4442 * Note that the translated binary data is not portable.
4443 * You can not move this binary data to another machine.
4444 * You can not use the binary data which is created by another
4445 * version/another architecture of Ruby.
4446 */
4447static VALUE
4448iseqw_to_binary(int argc, VALUE *argv, VALUE self)
4449{
4450 VALUE opt = !rb_check_arity(argc, 0, 1) ? Qnil : argv[0];
4451 return rb_iseq_ibf_dump(iseqw_check(self), opt);
4452}
4453
4454/*
4455 * call-seq:
4456 * RubyVM::InstructionSequence.load_from_binary(binary) -> iseq
4457 *
4458 * Load an iseq object from binary format String object
4459 * created by RubyVM::InstructionSequence.to_binary.
4460 *
4461 * This loader does not have a verifier, so that loading broken/modified
4462 * binary causes critical problem.
4463 *
4464 * You should not load binary data provided by others.
4465 * You should only use binary data translated by yourself.
4466 */
4467static VALUE
4468iseqw_s_load_from_binary(VALUE self, VALUE str)
4469{
4470 return iseqw_new(rb_iseq_ibf_load(str));
4471}
4472
4473VALUE
4474rb_iseq_load_from_binary(const char *ptr, size_t len)
4475{
4476 return iseqw_new(rb_iseq_ibf_load_bytes(ptr, len));
4477}
4478
4479/*
4480 * call-seq:
4481 * RubyVM::InstructionSequence.load_from_binary_extra_data(binary) -> str
4482 *
4483 * Load extra data embed into binary format String object.
4484 */
4485static VALUE
4486iseqw_s_load_from_binary_extra_data(VALUE self, VALUE str)
4487{
4488 return rb_iseq_ibf_load_extra_data(str);
4489}
4490
4491#if VM_INSN_INFO_TABLE_IMPL == 2
4492
4493/* An implementation of succinct bit-vector for insn_info table.
4494 *
4495 * A succinct bit-vector is a small and efficient data structure that provides
4496 * a bit-vector augmented with an index for O(1) rank operation:
4497 *
4498 * rank(bv, n): the number of 1's within a range from index 0 to index n
4499 *
4500 * This can be used to lookup insn_info table from PC.
4501 * For example, consider the following iseq and insn_info_table:
4502 *
4503 * iseq insn_info_table
4504 * PC insn+operand position lineno event
4505 * 0: insn1 0: 1 [Li]
4506 * 2: insn2 2: 2 [Li] <= (A)
4507 * 5: insn3 8: 3 [Li] <= (B)
4508 * 8: insn4
4509 *
4510 * In this case, a succinct bit-vector whose indexes 0, 2, 8 is "1" and
4511 * other indexes is "0", i.e., "101000001", is created.
4512 * To lookup the lineno of insn2, calculate rank("10100001", 2) = 2, so
4513 * the line (A) is the entry in question.
4514 * To lookup the lineno of insn4, calculate rank("10100001", 8) = 3, so
4515 * the line (B) is the entry in question.
4516 *
4517 * A naive implementation of succinct bit-vector works really well
4518 * not only for large size but also for small size. However, it has
4519 * tiny overhead for very small size. So, this implementation consist
4520 * of two parts: one part is the "immediate" table that keeps rank result
4521 * as a raw table, and the other part is a normal succinct bit-vector.
4522 */
4523
4524#define IMMEDIATE_TABLE_SIZE 54 /* a multiple of 9, and < 128 */
4525
4526struct succ_index_table {
4527 uint64_t imm_part[IMMEDIATE_TABLE_SIZE / 9];
4528 struct succ_dict_block {
4529 unsigned int rank;
4530 uint64_t small_block_ranks; /* 9 bits * 7 = 63 bits */
4531 uint64_t bits[512/64];
4532 } succ_part[FLEX_ARY_LEN];
4533};
4534
4535#define imm_block_rank_set(v, i, r) (v) |= (uint64_t)(r) << (7 * (i))
4536#define imm_block_rank_get(v, i) (((int)((v) >> ((i) * 7))) & 0x7f)
4537#define small_block_rank_set(v, i, r) (v) |= (uint64_t)(r) << (9 * ((i) - 1))
4538#define small_block_rank_get(v, i) ((i) == 0 ? 0 : (((int)((v) >> (((i) - 1) * 9))) & 0x1ff))
4539
4540static struct succ_index_table *
4541succ_index_table_create(int max_pos, int *data, int size)
4542{
4543 const int imm_size = (max_pos < IMMEDIATE_TABLE_SIZE ? max_pos + 8 : IMMEDIATE_TABLE_SIZE) / 9;
4544 const int succ_size = (max_pos < IMMEDIATE_TABLE_SIZE ? 0 : (max_pos - IMMEDIATE_TABLE_SIZE + 511)) / 512;
4545 struct succ_index_table *sd =
4546 rb_xcalloc_mul_add_mul(
4547 imm_size, sizeof(uint64_t),
4548 succ_size, sizeof(struct succ_dict_block));
4549 int i, j, k, r;
4550
4551 r = 0;
4552 for (j = 0; j < imm_size; j++) {
4553 for (i = 0; i < 9; i++) {
4554 if (r < size && data[r] == j * 9 + i) r++;
4555 imm_block_rank_set(sd->imm_part[j], i, r);
4556 }
4557 }
4558 for (k = 0; k < succ_size; k++) {
4559 struct succ_dict_block *sd_block = &sd->succ_part[k];
4560 int small_rank = 0;
4561 sd_block->rank = r;
4562 for (j = 0; j < 8; j++) {
4563 uint64_t bits = 0;
4564 if (j) small_block_rank_set(sd_block->small_block_ranks, j, small_rank);
4565 for (i = 0; i < 64; i++) {
4566 if (r < size && data[r] == k * 512 + j * 64 + i + IMMEDIATE_TABLE_SIZE) {
4567 bits |= ((uint64_t)1) << i;
4568 r++;
4569 }
4570 }
4571 sd_block->bits[j] = bits;
4572 small_rank += rb_popcount64(bits);
4573 }
4574 }
4575 return sd;
4576}
4577
4578static unsigned int *
4579succ_index_table_invert(int max_pos, struct succ_index_table *sd, int size)
4580{
4581 const int imm_size = (max_pos < IMMEDIATE_TABLE_SIZE ? max_pos + 8 : IMMEDIATE_TABLE_SIZE) / 9;
4582 const int succ_size = (max_pos < IMMEDIATE_TABLE_SIZE ? 0 : (max_pos - IMMEDIATE_TABLE_SIZE + 511)) / 512;
4583 unsigned int *positions = ALLOC_N(unsigned int, size), *p;
4584 int i, j, k, r = -1;
4585 p = positions;
4586 for (j = 0; j < imm_size; j++) {
4587 for (i = 0; i < 9; i++) {
4588 int nr = imm_block_rank_get(sd->imm_part[j], i);
4589 if (r != nr) *p++ = j * 9 + i;
4590 r = nr;
4591 }
4592 }
4593 for (k = 0; k < succ_size; k++) {
4594 for (j = 0; j < 8; j++) {
4595 for (i = 0; i < 64; i++) {
4596 if (sd->succ_part[k].bits[j] & (((uint64_t)1) << i)) {
4597 *p++ = k * 512 + j * 64 + i + IMMEDIATE_TABLE_SIZE;
4598 }
4599 }
4600 }
4601 }
4602 return positions;
4603}
4604
4605static int
4606succ_index_lookup(const struct succ_index_table *sd, int x)
4607{
4608 if (x < IMMEDIATE_TABLE_SIZE) {
4609 const int i = x / 9;
4610 const int j = x % 9;
4611 return imm_block_rank_get(sd->imm_part[i], j);
4612 }
4613 else {
4614 const int block_index = (x - IMMEDIATE_TABLE_SIZE) / 512;
4615 const struct succ_dict_block *block = &sd->succ_part[block_index];
4616 const int block_bit_index = (x - IMMEDIATE_TABLE_SIZE) % 512;
4617 const int small_block_index = block_bit_index / 64;
4618 const int small_block_popcount = small_block_rank_get(block->small_block_ranks, small_block_index);
4619 const int popcnt = rb_popcount64(block->bits[small_block_index] << (63 - block_bit_index % 64));
4620
4621 return block->rank + small_block_popcount + popcnt;
4622 }
4623}
4624#endif
4625
4626
4627/*
4628 * call-seq:
4629 * iseq.script_lines -> array or nil
4630 *
4631 * It returns recorded script lines if it is available.
4632 * The script lines are not limited to the iseq range, but
4633 * are entire lines of the source file.
4634 *
4635 * Note that this is an API for ruby internal use, debugging,
4636 * and research. Do not use this for any other purpose.
4637 * The compatibility is not guaranteed.
4638 */
4639static VALUE
4640iseqw_script_lines(VALUE self)
4641{
4642 const rb_iseq_t *iseq = iseqw_check(self);
4643 return ISEQ_SCRIPT_LINES(iseq);
4644}
4645
4646/* Returns the hash of the source this iseq was compiled from, or nil if it
4647 * is unavailable. */
4648static VALUE
4649iseqw_source_hash(VALUE self)
4650{
4651 const rb_iseq_t *iseq = iseqw_check(self);
4652 if (!ISEQ_BODY(iseq)->source_hash) return Qnil;
4653 return ULL2NUM(ISEQ_BODY(iseq)->source_hash);
4654}
4655
4656/* Returns the node id of the AST node this iseq corresponds to. */
4657static VALUE
4658iseqw_node_id(VALUE self)
4659{
4660 const rb_iseq_t *iseq = iseqw_check(self);
4661 return INT2NUM(ISEQ_BODY(iseq)->location.node_id);
4662}
4663
4664/*
4665 * Document-class: RubyVM::InstructionSequence
4666 *
4667 * The InstructionSequence class represents a compiled sequence of
4668 * instructions for the Virtual Machine used in MRI. Not all implementations of Ruby
4669 * may implement this class, and for the implementations that implement it,
4670 * the methods defined and behavior of the methods can change in any version.
4671 *
4672 * With it, you can get a handle to the instructions that make up a method or
4673 * a proc, compile strings of Ruby code down to VM instructions, and
4674 * disassemble instruction sequences to strings for easy inspection. It is
4675 * mostly useful if you want to learn how YARV works, but it also lets
4676 * you control various settings for the Ruby iseq compiler.
4677 *
4678 * You can find the source for the VM instructions in +insns.def+ in the Ruby
4679 * source.
4680 *
4681 * The instruction sequence results will almost certainly change as Ruby
4682 * changes, so example output in this documentation may be different from what
4683 * you see.
4684 *
4685 * Of course, this class is MRI specific.
4686 */
4687
4688void
4689Init_ISeq(void)
4690{
4691 /* declare ::RubyVM::InstructionSequence */
4692 rb_cISeq = rb_define_class_under(rb_cRubyVM, "InstructionSequence", rb_cObject);
4693 rb_undef_alloc_func(rb_cISeq);
4694 rb_define_method(rb_cISeq, "inspect", iseqw_inspect, 0);
4695 rb_define_method(rb_cISeq, "disasm", iseqw_disasm, 0);
4696 rb_define_method(rb_cISeq, "disassemble", iseqw_disasm, 0);
4697 rb_define_method(rb_cISeq, "to_a", iseqw_to_a, 0);
4698 rb_define_method(rb_cISeq, "eval", iseqw_eval, 0);
4699
4700 rb_define_method(rb_cISeq, "to_binary", iseqw_to_binary, -1);
4701 rb_define_singleton_method(rb_cISeq, "load_from_binary", iseqw_s_load_from_binary, 1);
4702 rb_define_singleton_method(rb_cISeq, "load_from_binary_extra_data", iseqw_s_load_from_binary_extra_data, 1);
4703
4704 /* location APIs */
4705 rb_define_method(rb_cISeq, "path", iseqw_path, 0);
4706 rb_define_method(rb_cISeq, "absolute_path", iseqw_absolute_path, 0);
4707 rb_define_method(rb_cISeq, "label", iseqw_label, 0);
4708 rb_define_method(rb_cISeq, "base_label", iseqw_base_label, 0);
4709 rb_define_method(rb_cISeq, "first_lineno", iseqw_first_lineno, 0);
4710 rb_define_method(rb_cISeq, "trace_points", iseqw_trace_points, 0);
4711 rb_define_method(rb_cISeq, "each_child", iseqw_each_child, 0);
4712
4713#if 0 /* TBD */
4714 rb_define_private_method(rb_cISeq, "marshal_dump", iseqw_marshal_dump, 0);
4715 rb_define_private_method(rb_cISeq, "marshal_load", iseqw_marshal_load, 1);
4716 /* disable this feature because there is no verifier. */
4717 rb_define_singleton_method(rb_cISeq, "load", iseq_s_load, -1);
4718#endif
4719 (void)iseq_s_load;
4720
4721 rb_define_singleton_method(rb_cISeq, "compile", iseqw_s_compile, -1);
4722 rb_define_singleton_method(rb_cISeq, "compile_parsey", iseqw_s_compile_parsey, -1);
4723 rb_define_singleton_method(rb_cISeq, "compile_prism", iseqw_s_compile_prism, -1);
4724 rb_define_singleton_method(rb_cISeq, "compile_file_prism", iseqw_s_compile_file_prism, -1);
4725 rb_define_singleton_method(rb_cISeq, "new", iseqw_s_compile, -1);
4726 rb_define_singleton_method(rb_cISeq, "compile_file", iseqw_s_compile_file, -1);
4727 rb_define_singleton_method(rb_cISeq, "compile_option", iseqw_s_compile_option_get, 0);
4728 rb_define_singleton_method(rb_cISeq, "compile_option=", iseqw_s_compile_option_set, 1);
4729 rb_define_singleton_method(rb_cISeq, "disasm", iseqw_s_disasm, 1);
4730 rb_define_singleton_method(rb_cISeq, "disassemble", iseqw_s_disasm, 1);
4731 rb_define_singleton_method(rb_cISeq, "of", iseqw_s_of, 1);
4732
4733 // script lines
4734 rb_define_method(rb_cISeq, "script_lines", iseqw_script_lines, 0);
4735 rb_define_method(rb_cISeq, "source_hash", iseqw_source_hash, 0);
4736 rb_define_method(rb_cISeq, "node_id", iseqw_node_id, 0);
4737
4738 rb_undef_method(CLASS_OF(rb_cISeq), "translate");
4739 rb_undef_method(CLASS_OF(rb_cISeq), "load_iseq");
4740}
#define RUBY_ASSERT(...)
Asserts that the given expression is truthy if and only if RUBY_DEBUG is truthy.
Definition assert.h:219
#define rb_define_method(klass, mid, func, arity)
Defines klass#mid.
#define rb_define_singleton_method(klass, mid, func, arity)
Defines klass.mid.
#define rb_define_private_method(klass, mid, func, arity)
Defines klass#mid and makes it private.
#define RUBY_EVENT_END
Encountered an end of a class clause.
Definition event.h:40
#define RUBY_EVENT_C_CALL
A method, written in C, is called.
Definition event.h:43
#define RUBY_EVENT_B_RETURN
Encountered a next statement.
Definition event.h:56
#define RUBY_EVENT_CLASS
Encountered a new class.
Definition event.h:39
#define RUBY_EVENT_LINE
Encountered a new line.
Definition event.h:38
#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
#define RUBY_EVENT_B_CALL
Encountered an yield statement.
Definition event.h:55
uint32_t rb_event_flag_t
Represents event(s).
Definition event.h:108
#define RUBY_EVENT_CALL
A method, written in Ruby, is called.
Definition event.h:41
#define RUBY_EVENT_RESCUE
Encountered a rescue statement.
Definition event.h:61
void rb_undef_method(VALUE klass, const char *name)
Defines an undef of a method.
Definition class.c:2893
int rb_scan_args(int argc, const VALUE *argv, const char *fmt,...)
Retrieves argument from argc and argv to given VALUE references according to the format string.
Definition class.c:3376
#define rb_str_new2
Old name of rb_str_new_cstr.
Definition string.h:1676
#define T_FILE
Old name of RUBY_T_FILE.
Definition value_type.h:62
#define ALLOC
Old name of RB_ALLOC.
Definition memory.h:400
#define T_STRING
Old name of RUBY_T_STRING.
Definition value_type.h:78
#define xfree
Old name of ruby_xfree.
Definition xmalloc.h:58
#define Qundef
Old name of RUBY_Qundef.
#define INT2FIX
Old name of RB_INT2FIX.
Definition long.h:48
#define rb_str_cat2
Old name of rb_str_cat_cstr.
Definition string.h:1684
#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 SYM2ID
Old name of RB_SYM2ID.
Definition symbol.h:45
#define ZALLOC
Old name of RB_ZALLOC.
Definition memory.h:402
#define LL2NUM
Old name of RB_LL2NUM.
Definition long_long.h:30
#define CLASS_OF
Old name of rb_class_of.
Definition globals.h:205
#define FIX2INT
Old name of RB_FIX2INT.
Definition int.h:41
#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:399
#define FL_TEST_RAW
Old name of RB_FL_TEST_RAW.
Definition fl_type.h:128
#define LONG2NUM
Old name of RB_LONG2NUM.
Definition long.h:50
#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 INT2NUM
Old name of RB_INT2NUM.
Definition int.h:43
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#define T_ARRAY
Old name of RUBY_T_ARRAY.
Definition value_type.h:56
#define NIL_P
Old name of RB_NIL_P.
#define BUILTIN_TYPE
Old name of RB_BUILTIN_TYPE.
Definition value_type.h:85
#define NUM2LONG
Old name of RB_NUM2LONG.
Definition long.h:51
#define UINT2NUM
Old name of RB_UINT2NUM.
Definition int.h:46
#define FIXNUM_P
Old name of RB_FIXNUM_P.
#define CONST_ID
Old name of RUBY_CONST_ID.
Definition symbol.h:47
#define rb_ary_new2
Old name of rb_ary_new_capa.
Definition array.h:657
void rb_exc_raise(VALUE mesg)
Raises an exception in the current thread.
Definition eval.c:678
VALUE rb_eTypeError
TypeError exception.
Definition error.c:1463
VALUE rb_eSyntaxError
SyntaxError exception.
Definition error.c:1480
VALUE rb_class_superclass(VALUE klass)
Queries the parent of the given class.
Definition object.c:2307
VALUE rb_cObject
Object class.
Definition object.c:60
VALUE rb_obj_hide(VALUE obj)
Make the object invisible from Ruby code.
Definition object.c:94
VALUE rb_obj_class(VALUE obj)
Queries the class of an object.
Definition object.c:234
VALUE rb_inspect(VALUE obj)
Generates a human-readable textual representation of the given object.
Definition object.c:668
#define RB_OBJ_WRITE(old, slot, young)
Declaration of a "back" pointer.
Definition gc.h:469
VALUE rb_funcall(VALUE recv, ID mid, int n,...)
Calls a method.
Definition vm_eval.c:1123
VALUE rb_funcallv(VALUE recv, ID mid, int argc, const VALUE *argv)
Identical to rb_funcall(), except it takes the method arguments as a C array.
Definition vm_eval.c:1081
VALUE rb_iseq_load_from_binary(const char *ptr, size_t len)
Load an iseq object from binary format String object created by RubyVM::InstructionSequence....
Definition iseq.c:4474
Defines RBIMPL_HAS_BUILTIN.
VALUE rb_ary_new_from_values(long n, const VALUE *elts)
Identical to rb_ary_new_from_args(), except how objects are passed.
VALUE rb_ary_resurrect(VALUE ary)
I guess there is no use case of this function in extension libraries, but this is a routine identical...
VALUE rb_ary_new(void)
Allocates a new, empty array.
VALUE rb_ary_hidden_new(long 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.
VALUE rb_ary_freeze(VALUE obj)
Freeze an array, preventing further modifications.
VALUE rb_ary_entry(VALUE ary, long off)
Queries an element of an array.
VALUE rb_ary_join(VALUE ary, VALUE sep)
Recursively stringises the elements of the passed array, flattens that result, then joins the sequenc...
void rb_ary_store(VALUE ary, long key, VALUE val)
Destructively stores the passed value to the passed array's passed index.
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_file_open_str(VALUE fname, const char *fmode)
Identical to rb_file_open(), except it takes the pathname as a Ruby's string instead of C's.
Definition io.c:7405
VALUE rb_io_close(VALUE io)
Closes the IO.
Definition io.c:5877
int rb_is_local_id(ID id)
Classifies the given ID, then sees if it is a local variable.
Definition symbol.c:1265
VALUE rb_obj_is_method(VALUE recv)
Queries if the given object is a method.
Definition proc.c:2454
VALUE rb_obj_is_proc(VALUE recv)
Queries if the given object is a proc.
Definition proc.c:386
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:3898
#define rb_str_new(str, len)
Allocates an instance of rb_cString.
Definition string.h:1499
#define rb_exc_new_cstr(exc, str)
Identical to rb_exc_new(), except it assumes the passed pointer is a pointer to a C string.
Definition string.h:1671
VALUE rb_str_dup(VALUE str)
Duplicates a string.
Definition string.c:2023
VALUE rb_str_cat(VALUE dst, const char *src, long srclen)
Destructively appends the passed contents to the string.
Definition string.c:3666
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:2041
void rb_str_set_len(VALUE str, long len)
Overwrites the length of the string.
Definition string.c:3485
VALUE rb_str_inspect(VALUE str)
Generates a "readable" version of the receiver.
Definition string.c:8137
int rb_str_cmp(VALUE lhs, VALUE rhs)
Compares two strings, as in strcmp(3).
Definition string.c:4315
VALUE rb_str_concat(VALUE dst, VALUE src)
Identical to rb_str_append(), except it also accepts an integer as a codepoint.
Definition string.c:4135
#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:1657
void rb_str_modify_expand(VALUE str, long capa)
Identical to rb_str_modify(), except it additionally expands the capacity of the receiver.
Definition string.c:2801
#define rb_str_new_cstr(str)
Identical to rb_str_new, except it assumes the passed pointer is a pointer to a C string.
Definition string.h:1515
VALUE rb_str_intern(VALUE str)
Identical to rb_to_symbol(), except it assumes the receiver being an instance of RString.
Definition symbol.c:1085
VALUE rb_class_name(VALUE obj)
Queries the name of the given object's class.
Definition variable.c:518
int rb_respond_to(VALUE obj, ID mid)
Queries if the object responds to the method.
Definition vm_method.c:3673
void rb_undef_alloc_func(VALUE klass)
Deletes the allocator function of a class.
Definition vm_method.c:1843
VALUE rb_check_funcall(VALUE recv, ID mid, int argc, const VALUE *argv)
Identical to rb_funcallv(), except it returns RUBY_Qundef instead of raising rb_eNoMethodError.
Definition vm_eval.c:691
ID rb_check_id(volatile VALUE *namep)
Detects if the given name is already interned or not.
Definition symbol.c:1289
VALUE rb_sym2str(VALUE symbol)
Obtain a frozen string representation of a symbol (not including the leading colon).
Definition symbol.c:1148
VALUE rb_io_path(VALUE io)
Returns the path for the given IO.
Definition io.c:3071
int len
Length of the buffer.
Definition io.h:8
#define RB_OBJ_SET_SHAREABLE(obj)
Wrapper of rb_obj_set_shareable().
Definition ractor.h:290
#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:1933
#define RB_NUM2INT
Just another name of rb_num2int_inline.
Definition int.h:38
#define RB_INT2NUM
Just another name of rb_int2num_inline.
Definition int.h:37
VALUE rb_yield(VALUE val)
Yields the block.
Definition vm_eval.c:1378
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
Definition memory.h:167
#define RB_ZALLOC(type)
Shorthand of RB_ZALLOC_N with n=1.
Definition memory.h:249
VALUE type(ANYARGS)
ANYARGS-ed function type.
#define RARRAY_LEN
Just another name of rb_array_len.
Definition rarray.h:50
static int RARRAY_LENINT(VALUE ary)
Identical to rb_array_len(), except it differs for the return type.
Definition rarray.h:280
#define RARRAY_AREF(a, i)
Definition rarray.h:402
static VALUE RBASIC_CLASS(VALUE obj)
Queries the class of an object.
Definition rbasic.h:166
#define RHASH_SIZE(h)
Queries the size of the hash.
Definition rhash.h:69
#define StringValue(v)
Ensures that the parameter object is a String.
Definition rstring.h:66
static int RSTRING_LENINT(VALUE str)
Identical to RSTRING_LEN(), except it differs for the return type.
Definition rstring.h:438
static char * RSTRING_END(VALUE str)
Queries the end of the contents pointer of the string.
Definition rstring.h:409
#define StringValueCStr(v)
Identical to StringValuePtr, except it additionally checks for the contents for viability as a C stri...
Definition rstring.h:89
#define RUBY_TYPED_DEFAULT_FREE
This is a value you can set to rb_data_type_struct::dfree.
Definition rtypeddata.h:81
#define TypedData_Get_Struct(obj, type, data_type, sval)
Obtains a C struct from inside of a wrapper Ruby object.
Definition rtypeddata.h:773
#define TypedData_Wrap_Struct(klass, data_type, sval)
Converts sval, a pointer to your struct, into a Ruby object.
Definition rtypeddata.h:557
#define TypedData_Make_Struct(klass, type, data_type, sval)
Identical to TypedData_Wrap_Struct, except it allocates a new data region internally instead of takin...
Definition rtypeddata.h:604
#define FilePathValue(v)
Ensures that the parameter object is a path.
Definition ruby.h:90
#define RTEST
This is an old name of RB_TEST.
Definition iseq.h:367
const ID * segments
A null-terminated list of ids, used to represent a constant's path idNULL is used to represent the ::...
Definition vm_core.h:287
Definition vm_core.h:295
Definition vm_core.h:290
Definition iseq.h:338
A line and column in a string.
uint32_t column
The column in bytes.
int32_t line
The line number.
A list of offsets of the start of lines in a string.
size_t size
The number of offsets in the list.
This struct represents a slice in the source code, defined by an offset and a length.
Definition ast.h:572
uint32_t start
The offset of the location from the start of the source.
Definition ast.h:574
uint32_t length
The length of the location.
Definition ast.h:577
uint32_t node_id
The unique identifier for this node, which is deterministic based on the source.
Definition ast.h:1100
pm_location_t location
This is the location of the node in the source.
Definition ast.h:1106
pm_scope_node_t node
The resulting scope node that will hold the generated AST.
pm_options_t * options
The options that will be passed to the parser.
uint64_t source_hash
The source hash of the parsed source, propagated to every iseq.
VALUE * script_lines
This is a pointer to the list of script lines for the ISEQs that will be associated with this scope n...
This is the struct that holds necessary info for a struct.
Definition rtypeddata.h:242
Definition st.h:79
Definition vm_core.h:299
intptr_t SIGNED_VALUE
A signed integer type that has the same width with VALUE.
Definition value.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 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