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