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