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