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