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