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