Ruby 2.0.0p247(2013-06-27revision41674)

- Main Page
- Modules
- Data Structures
- Files

- File List
- Globals

iseq.c
Go to the documentation of this file.
1 /**********************************************************************
2
3 iseq.c -
4
5 $Author: nagachika $
6 created at: 2006-07-11(Tue) 09:00:03 +0900
7
8 Copyright (C) 2006 Koichi Sasada
9
10 **********************************************************************/
11
12 #include "ruby/ruby.h"
13 #include "internal.h"
14 #include "eval_intern.h"
15
16 /* #define RUBY_MARK_FREE_DEBUG 1 */
17 #include "gc.h"
18 #include "vm_core.h"
19 #include "iseq.h"
20
21 #define numberof(array) (int)(sizeof(array) / sizeof((array)[0]))
22
23 #include "insns.inc"
24 #include "insns_info.inc"
25
26 #define ISEQ_MAJOR_VERSION 2
27 #define ISEQ_MINOR_VERSION 0
28
29 VALUE rb_cISeq;
30
31 #define hidden_obj_p(obj) (!SPECIAL_CONST_P(obj) && !RBASIC(obj)->klass)
32
33 static inline VALUE
34 obj_resurrect(VALUE obj)
35 {
36 if (hidden_obj_p(obj)) {
37 switch (BUILTIN_TYPE(obj)) {
38 case T_STRING:
39 obj = rb_str_resurrect(obj);
40 break;
41 case T_ARRAY:
42 obj = rb_ary_resurrect(obj);
43 break;
44 }
45 }
46 return obj;
47 }
48
49 static void
50 compile_data_free(struct iseq_compile_data *compile_data)
51 {
52 if (compile_data) {
53 struct iseq_compile_data_storage *cur, *next;
54 cur = compile_data->storage_head;
55 while (cur) {
56 next = cur->next;
57 ruby_xfree(cur);
58 cur = next;
59 }
60 ruby_xfree(compile_data);
61 }
62 }
63
64 static void
65 iseq_free(void *ptr)
66 {
67 rb_iseq_t *iseq;
68 RUBY_FREE_ENTER("iseq");
69
70 if (ptr) {
71 iseq = ptr;
72 if (!iseq->orig) {
73 /* It's possible that strings are freed */
74 if (0) {
75 RUBY_GC_INFO("%s @ %s\n", RSTRING_PTR(iseq->location.label),
76 RSTRING_PTR(iseq->location.path));
77 }
78
79 if (iseq->iseq != iseq->iseq_encoded) {
80 RUBY_FREE_UNLESS_NULL(iseq->iseq_encoded);
81 }
82
83 RUBY_FREE_UNLESS_NULL(iseq->iseq);
84 RUBY_FREE_UNLESS_NULL(iseq->line_info_table);
85 RUBY_FREE_UNLESS_NULL(iseq->local_table);
86 RUBY_FREE_UNLESS_NULL(iseq->ic_entries);
87 RUBY_FREE_UNLESS_NULL(iseq->callinfo_entries);
88 RUBY_FREE_UNLESS_NULL(iseq->catch_table);
89 RUBY_FREE_UNLESS_NULL(iseq->arg_opt_table);
90 RUBY_FREE_UNLESS_NULL(iseq->arg_keyword_table);
91 compile_data_free(iseq->compile_data);
92 }
93 ruby_xfree(ptr);
94 }
95 RUBY_FREE_LEAVE("iseq");
96 }
97
98 static void
99 iseq_mark(void *ptr)
100 {
101 RUBY_MARK_ENTER("iseq");
102
103 if (ptr) {
104 rb_iseq_t *iseq = ptr;
105
106 RUBY_GC_INFO("%s @ %s\n", RSTRING_PTR(iseq->location.label), RSTRING_PTR(iseq->location.path));
107 RUBY_MARK_UNLESS_NULL(iseq->mark_ary);
108
109 RUBY_MARK_UNLESS_NULL(iseq->location.label);
110 RUBY_MARK_UNLESS_NULL(iseq->location.base_label);
111 RUBY_MARK_UNLESS_NULL(iseq->location.path);
112 RUBY_MARK_UNLESS_NULL(iseq->location.absolute_path);
113
114 RUBY_MARK_UNLESS_NULL((VALUE)iseq->cref_stack);
115 RUBY_MARK_UNLESS_NULL(iseq->klass);
116 RUBY_MARK_UNLESS_NULL(iseq->coverage);
117 #if 0
118 RUBY_MARK_UNLESS_NULL((VALUE)iseq->node);
119 RUBY_MARK_UNLESS_NULL(iseq->cached_special_block);
120 #endif
121 RUBY_MARK_UNLESS_NULL(iseq->orig);
122
123 if (iseq->compile_data != 0) {
124 struct iseq_compile_data *const compile_data = iseq->compile_data;
125 RUBY_MARK_UNLESS_NULL(compile_data->mark_ary);
126 RUBY_MARK_UNLESS_NULL(compile_data->err_info);
127 RUBY_MARK_UNLESS_NULL(compile_data->catch_table_ary);
128 }
129 }
130 RUBY_MARK_LEAVE("iseq");
131 }
132
133 static size_t
134 iseq_memsize(const void *ptr)
135 {
136 size_t size = sizeof(rb_iseq_t);
137 const rb_iseq_t *iseq;
138
139 if (ptr) {
140 iseq = ptr;
141 if (!iseq->orig) {
142 if (iseq->iseq != iseq->iseq_encoded) {
143 size += iseq->iseq_size * sizeof(VALUE);
144 }
145
146 size += iseq->iseq_size * sizeof(VALUE);
147 size += iseq->line_info_size * sizeof(struct iseq_line_info_entry);
148 size += iseq->local_table_size * sizeof(ID);
149 size += iseq->catch_table_size * sizeof(struct iseq_catch_table_entry);
150 size += iseq->arg_opts * sizeof(VALUE);
151 size += iseq->ic_size * sizeof(struct iseq_inline_cache_entry);
152 size += iseq->callinfo_size * sizeof(rb_call_info_t);
153
154 if (iseq->compile_data) {
155 struct iseq_compile_data_storage *cur;
156
157 cur = iseq->compile_data->storage_head;
158 while (cur) {
159 size += cur->size + sizeof(struct iseq_compile_data_storage);
160 cur = cur->next;
161 }
162 size += sizeof(struct iseq_compile_data);
163 }
164 }
165 }
166
167 return size;
168 }
169
170 static const rb_data_type_t iseq_data_type = {
171 "iseq",
172 {
173 iseq_mark,
174 iseq_free,
175 iseq_memsize,
176 },
177 };
178
179 static VALUE
180 iseq_alloc(VALUE klass)
181 {
182 rb_iseq_t *iseq;
183 return TypedData_Make_Struct(klass, rb_iseq_t, &iseq_data_type, iseq);
184 }
185
186 static rb_iseq_location_t *
187 iseq_location_setup(rb_iseq_t *iseq, VALUE path, VALUE absolute_path, VALUE name, size_t first_lineno)
188 {
189 rb_iseq_location_t *loc = &iseq->location;
190 loc->path = path;
191 loc->absolute_path = absolute_path;
192 loc->label = loc->base_label = name;
193 loc->first_lineno = first_lineno;
194 return loc;
195 }
196
197 static void
198 set_relation(rb_iseq_t *iseq, const VALUE parent)
199 {
200 const VALUE type = iseq->type;
201 rb_thread_t *th = GET_THREAD();
202 rb_iseq_t *piseq;
203
204 /* set class nest stack */
205 if (type == ISEQ_TYPE_TOP) {
206 /* toplevel is private */
207 iseq->cref_stack = NEW_CREF(rb_cObject);
208 iseq->cref_stack->nd_refinements = Qnil;
209 iseq->cref_stack->nd_visi = NOEX_PRIVATE;
210 if (th->top_wrapper) {
211 NODE *cref = NEW_CREF(th->top_wrapper);
212 cref->nd_refinements = Qnil;
213 cref->nd_visi = NOEX_PRIVATE;
214 cref->nd_next = iseq->cref_stack;
215 iseq->cref_stack = cref;
216 }
217 iseq->local_iseq = iseq;
218 }
219 else if (type == ISEQ_TYPE_METHOD || type == ISEQ_TYPE_CLASS) {
220 iseq->cref_stack = NEW_CREF(0); /* place holder */
221 iseq->cref_stack->nd_refinements = Qnil;
222 iseq->local_iseq = iseq;
223 }
224 else if (RTEST(parent)) {
225 GetISeqPtr(parent, piseq);
226 iseq->cref_stack = piseq->cref_stack;
227 iseq->local_iseq = piseq->local_iseq;
228 }
229
230 if (RTEST(parent)) {
231 GetISeqPtr(parent, piseq);
232 iseq->parent_iseq = piseq;
233 }
234
235 if (type == ISEQ_TYPE_MAIN) {
236 iseq->local_iseq = iseq;
237 }
238 }
239
240 static VALUE
241 prepare_iseq_build(rb_iseq_t *iseq,
242 VALUE name, VALUE path, VALUE absolute_path, VALUE first_lineno,
243 VALUE parent, enum iseq_type type, VALUE block_opt,
244 const rb_compile_option_t *option)
245 {
246 iseq->type = type;
247 iseq->arg_rest = -1;
248 iseq->arg_block = -1;
249 iseq->arg_keyword = -1;
250 iseq->klass = 0;
251 set_relation(iseq, parent);
252
253 OBJ_FREEZE(name);
254 OBJ_FREEZE(path);
255
256 iseq_location_setup(iseq, path, absolute_path, name, first_lineno);
257 if (iseq != iseq->local_iseq) {
258 iseq->location.base_label = iseq->local_iseq->location.label;
259 }
260
261 iseq->defined_method_id = 0;
262 iseq->mark_ary = rb_ary_tmp_new(3);
263 OBJ_UNTRUST(iseq->mark_ary);
264 RBASIC(iseq->mark_ary)->klass = 0;
265
266
267 /*
268 * iseq->special_block_builder = GC_GUARDED_PTR_REF(block_opt);
269 * iseq->cached_special_block_builder = 0;
270 * iseq->cached_special_block = 0;
271 */
272
273 iseq->compile_data = ALLOC(struct iseq_compile_data);
274 MEMZERO(iseq->compile_data, struct iseq_compile_data, 1);
275 iseq->compile_data->err_info = Qnil;
276 iseq->compile_data->mark_ary = rb_ary_tmp_new(3);
277
278 iseq->compile_data->storage_head = iseq->compile_data->storage_current =
279 (struct iseq_compile_data_storage *)
280 ALLOC_N(char, INITIAL_ISEQ_COMPILE_DATA_STORAGE_BUFF_SIZE +
281 sizeof(struct iseq_compile_data_storage));
282
283 iseq->compile_data->catch_table_ary = rb_ary_new();
284 iseq->compile_data->storage_head->pos = 0;
285 iseq->compile_data->storage_head->next = 0;
286 iseq->compile_data->storage_head->size =
287 INITIAL_ISEQ_COMPILE_DATA_STORAGE_BUFF_SIZE;
288 iseq->compile_data->storage_head->buff =
289 (char *)(&iseq->compile_data->storage_head->buff + 1);
290 iseq->compile_data->option = option;
291 iseq->compile_data->last_coverable_line = -1;
292
293 iseq->coverage = Qfalse;
294 if (!GET_THREAD()->parse_in_eval) {
295 VALUE coverages = rb_get_coverages();
296 if (RTEST(coverages)) {
297 iseq->coverage = rb_hash_lookup(coverages, path);
298 if (NIL_P(iseq->coverage)) iseq->coverage = Qfalse;
299 }
300 }
301
302 return Qtrue;
303 }
304
305 static VALUE
306 cleanup_iseq_build(rb_iseq_t *iseq)
307 {
308 struct iseq_compile_data *data = iseq->compile_data;
309 VALUE err = data->err_info;
310 iseq->compile_data = 0;
311 compile_data_free(data);
312
313 if (RTEST(err)) {
314 rb_funcall2(err, rb_intern("set_backtrace"), 1, &iseq->location.path);
315 rb_exc_raise(err);
316 }
317 return Qtrue;
318 }
319
320 static rb_compile_option_t COMPILE_OPTION_DEFAULT = {
321 OPT_INLINE_CONST_CACHE, /* int inline_const_cache; */
322 OPT_PEEPHOLE_OPTIMIZATION, /* int peephole_optimization; */
323 OPT_TAILCALL_OPTIMIZATION, /* int tailcall_optimization */
324 OPT_SPECIALISED_INSTRUCTION, /* int specialized_instruction; */
325 OPT_OPERANDS_UNIFICATION, /* int operands_unification; */
326 OPT_INSTRUCTIONS_UNIFICATION, /* int instructions_unification; */
327 OPT_STACK_CACHING, /* int stack_caching; */
328 OPT_TRACE_INSTRUCTION, /* int trace_instruction */
329 };
330 static const rb_compile_option_t COMPILE_OPTION_FALSE = {0};
331
332 static void
333 make_compile_option(rb_compile_option_t *option, VALUE opt)
334 {
335 if (opt == Qnil) {
336 *option = COMPILE_OPTION_DEFAULT;
337 }
338 else if (opt == Qfalse) {
339 *option = COMPILE_OPTION_FALSE;
340 }
341 else if (opt == Qtrue) {
342 memset(option, 1, sizeof(rb_compile_option_t));
343 }
344 else if (CLASS_OF(opt) == rb_cHash) {
345 *option = COMPILE_OPTION_DEFAULT;
346
347 #define SET_COMPILE_OPTION(o, h, mem) \
348 { VALUE flag = rb_hash_aref((h), ID2SYM(rb_intern(#mem))); \
349 if (flag == Qtrue) { (o)->mem = 1; } \
350 else if (flag == Qfalse) { (o)->mem = 0; } \
351 }
352 #define SET_COMPILE_OPTION_NUM(o, h, mem) \
353 { VALUE num = rb_hash_aref(opt, ID2SYM(rb_intern(#mem))); \
354 if (!NIL_P(num)) (o)->mem = NUM2INT(num); \
355 }
356 SET_COMPILE_OPTION(option, opt, inline_const_cache);
357 SET_COMPILE_OPTION(option, opt, peephole_optimization);
358 SET_COMPILE_OPTION(option, opt, tailcall_optimization);
359 SET_COMPILE_OPTION(option, opt, specialized_instruction);
360 SET_COMPILE_OPTION(option, opt, operands_unification);
361 SET_COMPILE_OPTION(option, opt, instructions_unification);
362 SET_COMPILE_OPTION(option, opt, stack_caching);
363 SET_COMPILE_OPTION(option, opt, trace_instruction);
364 SET_COMPILE_OPTION_NUM(option, opt, debug_level);
365 #undef SET_COMPILE_OPTION
366 #undef SET_COMPILE_OPTION_NUM
367 }
368 else {
369 rb_raise(rb_eTypeError, "Compile option must be Hash/true/false/nil");
370 }
371 }
372
373 static VALUE
374 make_compile_option_value(rb_compile_option_t *option)
375 {
376 VALUE opt = rb_hash_new();
377 #define SET_COMPILE_OPTION(o, h, mem) \
378 rb_hash_aset((h), ID2SYM(rb_intern(#mem)), (o)->mem ? Qtrue : Qfalse)
379 #define SET_COMPILE_OPTION_NUM(o, h, mem) \
380 rb_hash_aset((h), ID2SYM(rb_intern(#mem)), INT2NUM((o)->mem))
381 {
382 SET_COMPILE_OPTION(option, opt, inline_const_cache);
383 SET_COMPILE_OPTION(option, opt, peephole_optimization);
384 SET_COMPILE_OPTION(option, opt, tailcall_optimization);
385 SET_COMPILE_OPTION(option, opt, specialized_instruction);
386 SET_COMPILE_OPTION(option, opt, operands_unification);
387 SET_COMPILE_OPTION(option, opt, instructions_unification);
388 SET_COMPILE_OPTION(option, opt, stack_caching);
389 SET_COMPILE_OPTION(option, opt, trace_instruction);
390 SET_COMPILE_OPTION_NUM(option, opt, debug_level);
391 }
392 #undef SET_COMPILE_OPTION
393 #undef SET_COMPILE_OPTION_NUM
394 return opt;
395 }
396
397 VALUE
398 rb_iseq_new(NODE *node, VALUE name, VALUE path, VALUE absolute_path,
399 VALUE parent, enum iseq_type type)
400 {
401 return rb_iseq_new_with_opt(node, name, path, absolute_path, INT2FIX(0), parent, type,
402 &COMPILE_OPTION_DEFAULT);
403 }
404
405 VALUE
406 rb_iseq_new_top(NODE *node, VALUE name, VALUE path, VALUE absolute_path, VALUE parent)
407 {
408 return rb_iseq_new_with_opt(node, name, path, absolute_path, INT2FIX(0), parent, ISEQ_TYPE_TOP,
409 &COMPILE_OPTION_DEFAULT);
410 }
411
412 VALUE
413 rb_iseq_new_main(NODE *node, VALUE path, VALUE absolute_path)
414 {
415 rb_thread_t *th = GET_THREAD();
416 VALUE parent = th->base_block->iseq->self;
417 return rb_iseq_new_with_opt(node, rb_str_new2("<main>"), path, absolute_path, INT2FIX(0),
418 parent, ISEQ_TYPE_MAIN, &COMPILE_OPTION_DEFAULT);
419 }
420
421 static VALUE
422 rb_iseq_new_with_bopt_and_opt(NODE *node, VALUE name, VALUE path, VALUE absolute_path, VALUE first_lineno,
423 VALUE parent, enum iseq_type type, VALUE bopt,
424 const rb_compile_option_t *option)
425 {
426 rb_iseq_t *iseq;
427 VALUE self = iseq_alloc(rb_cISeq);
428
429 GetISeqPtr(self, iseq);
430 iseq->self = self;
431
432 prepare_iseq_build(iseq, name, path, absolute_path, first_lineno, parent, type, bopt, option);
433 rb_iseq_compile_node(self, node);
434 cleanup_iseq_build(iseq);
435 return self;
436 }
437
438 VALUE
439 rb_iseq_new_with_opt(NODE *node, VALUE name, VALUE path, VALUE absolute_path, VALUE first_lineno,
440 VALUE parent, enum iseq_type type,
441 const rb_compile_option_t *option)
442 {
443 /* TODO: argument check */
444 return rb_iseq_new_with_bopt_and_opt(node, name, path, absolute_path, first_lineno, parent, type,
445 Qfalse, option);
446 }
447
448 VALUE
449 rb_iseq_new_with_bopt(NODE *node, VALUE name, VALUE path, VALUE absolute_path, VALUE first_lineno,
450 VALUE parent, enum iseq_type type, VALUE bopt)
451 {
452 /* TODO: argument check */
453 return rb_iseq_new_with_bopt_and_opt(node, name, path, absolute_path, first_lineno, parent, type,
454 bopt, &COMPILE_OPTION_DEFAULT);
455 }
456
457 #define CHECK_ARRAY(v) rb_convert_type((v), T_ARRAY, "Array", "to_ary")
458 #define CHECK_STRING(v) rb_convert_type((v), T_STRING, "String", "to_str")
459 #define CHECK_SYMBOL(v) rb_convert_type((v), T_SYMBOL, "Symbol", "to_sym")
460 static inline VALUE CHECK_INTEGER(VALUE v) {(void)NUM2LONG(v); return v;}
461 static VALUE
462 iseq_load(VALUE self, VALUE data, VALUE parent, VALUE opt)
463 {
464 VALUE iseqval = iseq_alloc(self);
465
466 VALUE magic, version1, version2, format_type, misc;
467 VALUE name, path, absolute_path, first_lineno;
468 VALUE type, body, locals, args, exception;
469
470 st_data_t iseq_type;
471 struct st_table *type_map = 0;
472 rb_iseq_t *iseq;
473 rb_compile_option_t option;
474 int i = 0;
475
476 /* [magic, major_version, minor_version, format_type, misc,
477 * label, path, first_lineno,
478 * type, locals, args, exception_table, body]
479 */
480
481 data = CHECK_ARRAY(data);
482
483 magic = CHECK_STRING(rb_ary_entry(data, i++));
484 version1 = CHECK_INTEGER(rb_ary_entry(data, i++));
485 version2 = CHECK_INTEGER(rb_ary_entry(data, i++));
486 format_type = CHECK_INTEGER(rb_ary_entry(data, i++));
487 misc = rb_ary_entry(data, i++); /* TODO */
488 ((void)magic, (void)version1, (void)version2, (void)format_type, (void)misc);
489
490 name = CHECK_STRING(rb_ary_entry(data, i++));
491 path = CHECK_STRING(rb_ary_entry(data, i++));
492 absolute_path = rb_ary_entry(data, i++);
493 absolute_path = NIL_P(absolute_path) ? Qnil : CHECK_STRING(absolute_path);
494 first_lineno = CHECK_INTEGER(rb_ary_entry(data, i++));
495
496 type = CHECK_SYMBOL(rb_ary_entry(data, i++));
497 locals = CHECK_ARRAY(rb_ary_entry(data, i++));
498
499 args = rb_ary_entry(data, i++);
500 if (FIXNUM_P(args) || (args = CHECK_ARRAY(args))) {
501 /* */
502 }
503
504 exception = CHECK_ARRAY(rb_ary_entry(data, i++));
505 body = CHECK_ARRAY(rb_ary_entry(data, i++));
506
507 GetISeqPtr(iseqval, iseq);
508 iseq->self = iseqval;
509
510 if (type_map == 0) {
511 type_map = st_init_numtable();
512 st_insert(type_map, ID2SYM(rb_intern("top")), ISEQ_TYPE_TOP);
513 st_insert(type_map, ID2SYM(rb_intern("method")), ISEQ_TYPE_METHOD);
514 st_insert(type_map, ID2SYM(rb_intern("block")), ISEQ_TYPE_BLOCK);
515 st_insert(type_map, ID2SYM(rb_intern("class")), ISEQ_TYPE_CLASS);
516 st_insert(type_map, ID2SYM(rb_intern("rescue")), ISEQ_TYPE_RESCUE);
517 st_insert(type_map, ID2SYM(rb_intern("ensure")), ISEQ_TYPE_ENSURE);
518 st_insert(type_map, ID2SYM(rb_intern("eval")), ISEQ_TYPE_EVAL);
519 st_insert(type_map, ID2SYM(rb_intern("main")), ISEQ_TYPE_MAIN);
520 st_insert(type_map, ID2SYM(rb_intern("defined_guard")), ISEQ_TYPE_DEFINED_GUARD);
521 }
522
523 if (st_lookup(type_map, type, &iseq_type) == 0) {
524 ID typeid = SYM2ID(type);
525 VALUE typename = rb_id2str(typeid);
526 if (typename)
527 rb_raise(rb_eTypeError, "unsupport type: :%"PRIsVALUE, typename);
528 else
529 rb_raise(rb_eTypeError, "unsupport type: %p", (void *)typeid);
530 }
531
532 if (parent == Qnil) {
533 parent = 0;
534 }
535
536 make_compile_option(&option, opt);
537 prepare_iseq_build(iseq, name, path, absolute_path, first_lineno,
538 parent, (enum iseq_type)iseq_type, 0, &option);
539
540 rb_iseq_build_from_ary(iseq, locals, args, exception, body);
541
542 cleanup_iseq_build(iseq);
543 return iseqval;
544 }
545
546 /*
547 * :nodoc:
548 */
549 static VALUE
550 iseq_s_load(int argc, VALUE *argv, VALUE self)
551 {
552 VALUE data, opt=Qnil;
553 rb_scan_args(argc, argv, "11", &data, &opt);
554
555 return iseq_load(self, data, 0, opt);
556 }
557
558 VALUE
559 rb_iseq_load(VALUE data, VALUE parent, VALUE opt)
560 {
561 return iseq_load(rb_cISeq, data, parent, opt);
562 }
563
564 static NODE *
565 parse_string(VALUE str, const char *file, int line)
566 {
567 VALUE parser = rb_parser_new();
568 NODE *node = rb_parser_compile_string(parser, file, str, line);
569
570 if (!node) {
571 rb_exc_raise(GET_THREAD()->errinfo); /* TODO: check err */
572 }
573 return node;
574 }
575
576 VALUE
577 rb_iseq_compile_with_option(VALUE src, VALUE file, VALUE absolute_path, VALUE line, rb_block_t *base_block, VALUE opt)
578 {
579 int state;
580 rb_thread_t *th = GET_THREAD();
581 rb_block_t *prev_base_block = th->base_block;
582 VALUE iseqval = Qundef;
583
584 th->base_block = base_block;
585
586 TH_PUSH_TAG(th);
587 if ((state = EXEC_TAG()) == 0) {
588 int ln = NUM2INT(line);
589 const char *fn = StringValueCStr(file);
590 NODE *node;
591 rb_compile_option_t option;
592
593 make_compile_option(&option, opt);
594
595 if (RB_TYPE_P((src), T_FILE))
596 node = rb_compile_file(fn, src, ln);
597 else
598 node = parse_string(StringValue(src), fn, ln);
599
600 if (base_block && base_block->iseq) {
601 iseqval = rb_iseq_new_with_opt(node, base_block->iseq->location.label,
602 file, absolute_path, line, base_block->iseq->self,
603 ISEQ_TYPE_EVAL, &option);
604 }
605 else {
606 iseqval = rb_iseq_new_with_opt(node, rb_str_new2("<compiled>"), file, absolute_path, line, Qfalse,
607 ISEQ_TYPE_TOP, &option);
608 }
609 }
610 TH_POP_TAG();
611
612 th->base_block = prev_base_block;
613
614 if (state) {
615 JUMP_TAG(state);
616 }
617
618 return iseqval;
619 }
620
621 VALUE
622 rb_iseq_compile(VALUE src, VALUE file, VALUE line)
623 {
624 return rb_iseq_compile_with_option(src, file, Qnil, line, 0, Qnil);
625 }
626
627 VALUE
628 rb_iseq_compile_on_base(VALUE src, VALUE file, VALUE line, rb_block_t *base_block)
629 {
630 return rb_iseq_compile_with_option(src, file, Qnil, line, base_block, Qnil);
631 }
632
633 /*
634 * call-seq:
635 * InstructionSequence.compile(source[, file[, path[, line[, options]]]]) -> iseq
636 * InstructionSequence.new(source[, file[, path[, line[, options]]]]) -> iseq
637 *
638 * Takes +source+, a String of Ruby code and compiles it to an
639 * InstructionSequence.
640 *
641 * Optionally takes +file+, +path+, and +line+ which describe the filename,
642 * absolute path and first line number of the ruby code in +source+ which are
643 * metadata attached to the returned +iseq+.
644 *
645 * +options+, which can be +true+, +false+ or a +Hash+, is used to
646 * modify the default behavior of the Ruby iseq compiler.
647 *
648 * For details regarding valid compile options see ::compile_option=.
649 *
650 * RubyVM::InstructionSequence.compile("a = 1 + 2")
651 * #=> <RubyVM::InstructionSequence:<compiled>@<compiled>>
652 *
653 */
654 static VALUE
655 iseq_s_compile(int argc, VALUE *argv, VALUE self)
656 {
657 VALUE src, file = Qnil, path = Qnil, line = INT2FIX(1), opt = Qnil;
658
659 rb_secure(1);
660
661 rb_scan_args(argc, argv, "14", &src, &file, &path, &line, &opt);
662 if (NIL_P(file)) file = rb_str_new2("<compiled>");
663 if (NIL_P(line)) line = INT2FIX(1);
664
665 return rb_iseq_compile_with_option(src, file, path, line, 0, opt);
666 }
667
668 /*
669 * call-seq:
670 * InstructionSequence.compile_file(file[, options]) -> iseq
671 *
672 * Takes +file+, a String with the location of a Ruby source file, reads,
673 * parses and compiles the file, and returns +iseq+, the compiled
674 * InstructionSequence with source location metadata set.
675 *
676 * Optionally takes +options+, which can be +true+, +false+ or a +Hash+, to
677 * modify the default behavior of the Ruby iseq compiler.
678 *
679 * For details regarding valid compile options see ::compile_option=.
680 *
681 * # /tmp/hello.rb
682 * puts "Hello, world!"
683 *
684 * # elsewhere
685 * RubyVM::InstructionSequence.compile_file("/tmp/hello.rb")
686 * #=> <RubyVM::InstructionSequence:<main>@/tmp/hello.rb>
687 */
688 static VALUE
689 iseq_s_compile_file(int argc, VALUE *argv, VALUE self)
690 {
691 VALUE file, line = INT2FIX(1), opt = Qnil;
692 VALUE parser;
693 VALUE f;
694 NODE *node;
695 const char *fname;
696 rb_compile_option_t option;
697
698 rb_secure(1);
699 rb_scan_args(argc, argv, "11", &file, &opt);
700 FilePathValue(file);
701 fname = StringValueCStr(file);
702
703 f = rb_file_open_str(file, "r");
704
705 parser = rb_parser_new();
706 node = rb_parser_compile_file(parser, fname, f, NUM2INT(line));
707 make_compile_option(&option, opt);
708 return rb_iseq_new_with_opt(node, rb_str_new2("<main>"), file,
709 rb_realpath_internal(Qnil, file, 1), line, Qfalse,
710 ISEQ_TYPE_TOP, &option);
711 }
712
713 /*
714 * call-seq:
715 * InstructionSequence.compile_option = options
716 *
717 * Sets the default values for various optimizations in the Ruby iseq
718 * compiler.
719 *
720 * Possible values for +options+ include +true+, which enables all options,
721 * +false+ which disables all options, and +nil+ which leaves all options
722 * unchanged.
723 *
724 * You can also pass a +Hash+ of +options+ that you want to change, any
725 * options not present in the hash will be left unchanged.
726 *
727 * Possible option names (which are keys in +options+) which can be set to
728 * +true+ or +false+ include:
729 *
730 * * +:inline_const_cache+
731 * * +:instructions_unification+
732 * * +:operands_unification+
733 * * +:peephole_optimization+
734 * * +:specialized_instruction+
735 * * +:stack_caching+
736 * * +:tailcall_optimization+
737 * * +:trace_instruction+
738 *
739 * Additionally, +:debug_level+ can be set to an integer.
740 *
741 * These default options can be overwritten for a single run of the iseq
742 * compiler by passing any of the above values as the +options+ parameter to
743 * ::new, ::compile and ::compile_file.
744 */
745 static VALUE
746 iseq_s_compile_option_set(VALUE self, VALUE opt)
747 {
748 rb_compile_option_t option;
749 rb_secure(1);
750 make_compile_option(&option, opt);
751 COMPILE_OPTION_DEFAULT = option;
752 return opt;
753 }
754
755 /*
756 * call-seq:
757 * InstructionSequence.compile_option -> options
758 *
759 * Returns a hash of default options used by the Ruby iseq compiler.
760 *
761 * For details, see InstructionSequence.compile_option=.
762 */
763 static VALUE
764 iseq_s_compile_option_get(VALUE self)
765 {
766 return make_compile_option_value(&COMPILE_OPTION_DEFAULT);
767 }
768
769 static rb_iseq_t *
770 iseq_check(VALUE val)
771 {
772 rb_iseq_t *iseq;
773 GetISeqPtr(val, iseq);
774 if (!iseq->location.label) {
775 rb_raise(rb_eTypeError, "uninitialized InstructionSequence");
776 }
777 return iseq;
778 }
779
780 /*
781 * call-seq:
782 * iseq.eval -> obj
783 *
784 * Evaluates the instruction sequence and returns the result.
785 *
786 * RubyVM::InstructionSequence.compile("1 + 2").eval #=> 3
787 */
788 static VALUE
789 iseq_eval(VALUE self)
790 {
791 rb_secure(1);
792 return rb_iseq_eval(self);
793 }
794
795 /*
796 * Returns a human-readable string representation of this instruction
797 * sequence, including the #label and #path.
798 */
799 static VALUE
800 iseq_inspect(VALUE self)
801 {
802 rb_iseq_t *iseq;
803 GetISeqPtr(self, iseq);
804 if (!iseq->location.label) {
805 return rb_sprintf("#<%s: uninitialized>", rb_obj_classname(self));
806 }
807
808 return rb_sprintf("<%s:%s@%s>",
809 rb_obj_classname(self),
810 RSTRING_PTR(iseq->location.label), RSTRING_PTR(iseq->location.path));
811 }
812
813 /*
814 * Returns the path of this instruction sequence.
815 *
816 * <code><compiled></code> if the iseq was evaluated from a string.
817 *
818 * For example, using irb:
819 *
820 * iseq = RubyVM::InstructionSequence.compile('num = 1 + 2')
821 * #=> <RubyVM::InstructionSequence:<compiled>@<compiled>>
822 * iseq.path
823 * #=> "<compiled>"
824 *
825 * Using ::compile_file:
826 *
827 * # /tmp/method.rb
828 * def hello
829 * puts "hello, world"
830 * end
831 *
832 * # in irb
833 * > iseq = RubyVM::InstructionSequence.compile_file('/tmp/method.rb')
834 * > iseq.path #=> /tmp/method.rb
835 */
836 static VALUE
837 iseq_path(VALUE self)
838 {
839 rb_iseq_t *iseq;
840 GetISeqPtr(self, iseq);
841 return iseq->location.path;
842 }
843
844 /*
845 * Returns the absolute path of this instruction sequence.
846 *
847 * +nil+ if the iseq was evaluated from a string.
848 *
849 * For example, using ::compile_file:
850 *
851 * # /tmp/method.rb
852 * def hello
853 * puts "hello, world"
854 * end
855 *
856 * # in irb
857 * > iseq = RubyVM::InstructionSequence.compile_file('/tmp/method.rb')
858 * > iseq.absolute_path #=> /tmp/method.rb
859 */
860 static VALUE
861 iseq_absolute_path(VALUE self)
862 {
863 rb_iseq_t *iseq;
864 GetISeqPtr(self, iseq);
865 return iseq->location.absolute_path;
866 }
867
868 /* Returns the label of this instruction sequence.
869 *
870 * <code><main></code> if it's at the top level, <code><compiled></code> if it
871 * was evaluated from a string.
872 *
873 * For example, using irb:
874 *
875 * iseq = RubyVM::InstructionSequence.compile('num = 1 + 2')
876 * #=> <RubyVM::InstructionSequence:<compiled>@<compiled>>
877 * iseq.label
878 * #=> "<compiled>"
879 *
880 * Using ::compile_file:
881 *
882 * # /tmp/method.rb
883 * def hello
884 * puts "hello, world"
885 * end
886 *
887 * # in irb
888 * > iseq = RubyVM::InstructionSequence.compile_file('/tmp/method.rb')
889 * > iseq.label #=> <main>
890 */
891 static VALUE
892 iseq_label(VALUE self)
893 {
894 rb_iseq_t *iseq;
895 GetISeqPtr(self, iseq);
896 return iseq->location.label;
897 }
898
899 /* Returns the base label of this instruction sequence.
900 *
901 * For example, using irb:
902 *
903 * iseq = RubyVM::InstructionSequence.compile('num = 1 + 2')
904 * #=> <RubyVM::InstructionSequence:<compiled>@<compiled>>
905 * iseq.base_label
906 * #=> "<compiled>"
907 *
908 * Using ::compile_file:
909 *
910 * # /tmp/method.rb
911 * def hello
912 * puts "hello, world"
913 * end
914 *
915 * # in irb
916 * > iseq = RubyVM::InstructionSequence.compile_file('/tmp/method.rb')
917 * > iseq.base_label #=> <main>
918 */
919 static VALUE
920 iseq_base_label(VALUE self)
921 {
922 rb_iseq_t *iseq;
923 GetISeqPtr(self, iseq);
924 return iseq->location.base_label;
925 }
926
927 /* Returns the number of the first source line where the instruction sequence
928 * was loaded from.
929 *
930 * For example, using irb:
931 *
932 * iseq = RubyVM::InstructionSequence.compile('num = 1 + 2')
933 * #=> <RubyVM::InstructionSequence:<compiled>@<compiled>>
934 * iseq.first_lineno
935 * #=> 1
936 */
937 static VALUE
938 iseq_first_lineno(VALUE self)
939 {
940 rb_iseq_t *iseq;
941 GetISeqPtr(self, iseq);
942 return iseq->location.first_lineno;
943 }
944
945 static
946 VALUE iseq_data_to_ary(rb_iseq_t *iseq);
947
948 /*
949 * call-seq:
950 * iseq.to_a -> ary
951 *
952 * Returns an Array with 14 elements representing the instruction sequence
953 * with the following data:
954 *
955 * [magic]
956 * A string identifying the data format. <b>Always
957 * +YARVInstructionSequence/SimpleDataFormat+.</b>
958 *
959 * [major_version]
960 * The major version of the instruction sequence.
961 *
962 * [minor_version]
963 * The minor version of the instruction sequence.
964 *
965 * [format_type]
966 * A number identifying the data format. <b>Always 1</b>.
967 *
968 * [misc]
969 * A hash containing:
970 *
971 * [+:arg_size+]
972 * the total number of arguments taken by the method or the block (0 if
973 * _iseq_ doesn't represent a method or block)
974 * [+:local_size+]
975 * the number of local variables + 1
976 * [+:stack_max+]
977 * used in calculating the stack depth at which a SystemStackError is
978 * thrown.
979 *
980 * [#label]
981 * The name of the context (block, method, class, module, etc.) that this
982 * instruction sequence belongs to.
983 *
984 * <code><main></code> if it's at the top level, <code><compiled></code> if
985 * it was evaluated from a string.
986 *
987 * [#path]
988 * The relative path to the Ruby file where the instruction sequence was
989 * loaded from.
990 *
991 * <code><compiled></code> if the iseq was evaluated from a string.
992 *
993 * [#absolute_path]
994 * The absolute path to the Ruby file where the instruction sequence was
995 * loaded from.
996 *
997 * +nil+ if the iseq was evaluated from a string.
998 *
999 * [#first_lineno]
1000 * The number of the first source line where the instruction sequence was
1001 * loaded from.
1002 *
1003 * [type]
1004 * The type of the instruction sequence.
1005 *
1006 * Valid values are +:top+, +:method+, +:block+, +:class+, +:rescue+,
1007 * +:ensure+, +:eval+, +:main+, and +:defined_guard+.
1008 *
1009 * [locals]
1010 * An array containing the names of all arguments and local variables as
1011 * symbols.
1012 *
1013 * [args]
1014 * The arity if the method or block only has required arguments.
1015 *
1016 * Otherwise an array of:
1017 *
1018 * [required_argc, [optional_arg_labels, ...],
1019 * splat_index, post_splat_argc, post_splat_index,
1020 * block_index, simple]
1021 *
1022 * More info about these values can be found in +vm_core.h+.
1023 *
1024 * [catch_table]
1025 * A list of exceptions and control flow operators (rescue, next, redo,
1026 * break, etc.).
1027 *
1028 * [bytecode]
1029 * An array of arrays containing the instruction names and operands that
1030 * make up the body of the instruction sequence.
1031 *
1032 */
1033 static VALUE
1034 iseq_to_a(VALUE self)
1035 {
1036 rb_iseq_t *iseq = iseq_check(self);
1037 rb_secure(1);
1038 return iseq_data_to_ary(iseq);
1039 }
1040
1041 int
1042 rb_iseq_first_lineno(const rb_iseq_t *iseq)
1043 {
1044 return FIX2INT(iseq->location.first_lineno);
1045 }
1046
1047 /* TODO: search algorithm is brute force.
1048 this should be binary search or so. */
1049
1050 static struct iseq_line_info_entry *
1051 get_line_info(const rb_iseq_t *iseq, size_t pos)
1052 {
1053 size_t i = 0, size = iseq->line_info_size;
1054 struct iseq_line_info_entry *table = iseq->line_info_table;
1055 const int debug = 0;
1056
1057 if (debug) {
1058 printf("size: %"PRIdSIZE"\n", size);
1059 printf("table[%"PRIdSIZE"]: position: %d, line: %d, pos: %"PRIdSIZE"\n",
1060 i, table[i].position, table[i].line_no, pos);
1061 }
1062
1063 if (size == 0) {
1064 return 0;
1065 }
1066 else if (size == 1) {
1067 return &table[0];
1068 }
1069 else {
1070 for (i=1; i<size; i++) {
1071 if (debug) printf("table[%"PRIdSIZE"]: position: %d, line: %d, pos: %"PRIdSIZE"\n",
1072 i, table[i].position, table[i].line_no, pos);
1073
1074 if (table[i].position == pos) {
1075 return &table[i];
1076 }
1077 if (table[i].position > pos) {
1078 return &table[i-1];
1079 }
1080 }
1081 }
1082 return &table[i-1];
1083 }
1084
1085 static unsigned int
1086 find_line_no(const rb_iseq_t *iseq, size_t pos)
1087 {
1088 struct iseq_line_info_entry *entry = get_line_info(iseq, pos);
1089 if (entry) {
1090 return entry->line_no;
1091 }
1092 else {
1093 return 0;
1094 }
1095 }
1096
1097 unsigned int
1098 rb_iseq_line_no(const rb_iseq_t *iseq, size_t pos)
1099 {
1100 if (pos == 0) {
1101 return find_line_no(iseq, pos);
1102 }
1103 else {
1104 return find_line_no(iseq, pos - 1);
1105 }
1106 }
1107
1108 static VALUE
1109 id_to_name(ID id, VALUE default_value)
1110 {
1111 VALUE str = rb_id2str(id);
1112 if (!str) {
1113 str = default_value;
1114 }
1115 else if (!rb_str_symname_p(str)) {
1116 str = rb_str_inspect(str);
1117 }
1118 return str;
1119 }
1120
1121 VALUE
1122 insn_operand_intern(rb_iseq_t *iseq,
1123 VALUE insn, int op_no, VALUE op,
1124 int len, size_t pos, VALUE *pnop, VALUE child)
1125 {
1126 const char *types = insn_op_types(insn);
1127 char type = types[op_no];
1128 VALUE ret;
1129
1130 switch (type) {
1131 case TS_OFFSET: /* LONG */
1132 ret = rb_sprintf("%"PRIdVALUE, (VALUE)(pos + len + op));
1133 break;
1134
1135 case TS_NUM: /* ULONG */
1136 ret = rb_sprintf("%"PRIuVALUE, op);
1137 break;
1138
1139 case TS_LINDEX:{
1140 if (insn == BIN(getlocal) || insn == BIN(setlocal)) {
1141 if (pnop) {
1142 rb_iseq_t *diseq = iseq;
1143 VALUE level = *pnop, i;
1144
1145 for (i = 0; i < level; i++) {
1146 diseq = diseq->parent_iseq;
1147 }
1148 ret = id_to_name(diseq->local_table[diseq->local_size - op], INT2FIX('*'));
1149 }
1150 else {
1151 ret = rb_sprintf("%"PRIuVALUE, op);
1152 }
1153 }
1154 else {
1155 ret = rb_inspect(INT2FIX(op));
1156 }
1157 break;
1158 }
1159 case TS_ID: /* ID (symbol) */
1160 op = ID2SYM(op);
1161
1162 case TS_VALUE: /* VALUE */
1163 op = obj_resurrect(op);
1164 ret = rb_inspect(op);
1165 if (CLASS_OF(op) == rb_cISeq) {
1166 if (child) {
1167 rb_ary_push(child, op);
1168 }
1169 }
1170 break;
1171
1172 case TS_ISEQ: /* iseq */
1173 {
1174 rb_iseq_t *iseq = (rb_iseq_t *)op;
1175 if (iseq) {
1176 ret = iseq->location.label;
1177 if (child) {
1178 rb_ary_push(child, iseq->self);
1179 }
1180 }
1181 else {
1182 ret = rb_str_new2("nil");
1183 }
1184 break;
1185 }
1186 case TS_GENTRY:
1187 {
1188 struct rb_global_entry *entry = (struct rb_global_entry *)op;
1189 ret = rb_str_dup(rb_id2str(entry->id));
1190 }
1191 break;
1192
1193 case TS_IC:
1194 ret = rb_sprintf("<ic:%"PRIdPTRDIFF">", (struct iseq_inline_cache_entry *)op - iseq->ic_entries);
1195 break;
1196
1197 case TS_CALLINFO:
1198 {
1199 rb_call_info_t *ci = (rb_call_info_t *)op;
1200 VALUE ary = rb_ary_new();
1201
1202 if (ci->mid) {
1203 rb_ary_push(ary, rb_sprintf("mid:%s", rb_id2name(ci->mid)));
1204 }
1205
1206 rb_ary_push(ary, rb_sprintf("argc:%d", ci->orig_argc));
1207
1208 if (ci->blockiseq) {
1209 if (child) {
1210 rb_ary_push(child, ci->blockiseq->self);
1211 }
1212 rb_ary_push(ary, rb_sprintf("block:%"PRIsVALUE, ci->blockiseq->location.label));
1213 }
1214
1215 if (ci->flag) {
1216 VALUE flags = rb_ary_new();
1217 if (ci->flag & VM_CALL_ARGS_SPLAT) rb_ary_push(flags, rb_str_new2("ARGS_SPLAT"));
1218 if (ci->flag & VM_CALL_ARGS_BLOCKARG) rb_ary_push(flags, rb_str_new2("ARGS_BLOCKARG"));
1219 if (ci->flag & VM_CALL_FCALL) rb_ary_push(flags, rb_str_new2("FCALL"));
1220 if (ci->flag & VM_CALL_VCALL) rb_ary_push(flags, rb_str_new2("VCALL"));
1221 if (ci->flag & VM_CALL_TAILCALL) rb_ary_push(flags, rb_str_new2("TAILCALL"));
1222 if (ci->flag & VM_CALL_SUPER) rb_ary_push(flags, rb_str_new2("SUPER"));
1223 if (ci->flag & VM_CALL_OPT_SEND) rb_ary_push(flags, rb_str_new2("SNED")); /* maybe not reachable */
1224 if (ci->flag & VM_CALL_ARGS_SKIP_SETUP) rb_ary_push(flags, rb_str_new2("ARGS_SKIP")); /* maybe not reachable */
1225 rb_ary_push(ary, rb_ary_join(flags, rb_str_new2("|")));
1226 }
1227 ret = rb_sprintf("<callinfo!%"PRIsVALUE">", rb_ary_join(ary, rb_str_new2(", ")));
1228 }
1229 break;
1230
1231 case TS_CDHASH:
1232 ret = rb_str_new2("<cdhash>");
1233 break;
1234
1235 case TS_FUNCPTR:
1236 ret = rb_str_new2("<funcptr>");
1237 break;
1238
1239 default:
1240 rb_bug("insn_operand_intern: unknown operand type: %c", type);
1241 }
1242 return ret;
1243 }
1244
1249 int
1250 rb_iseq_disasm_insn(VALUE ret, VALUE *iseq, size_t pos,
1251 rb_iseq_t *iseqdat, VALUE child)
1252 {
1253 VALUE insn = iseq[pos];
1254 int len = insn_len(insn);
1255 int j;
1256 const char *types = insn_op_types(insn);
1257 VALUE str = rb_str_new(0, 0);
1258 const char *insn_name_buff;
1259
1260 insn_name_buff = insn_name(insn);
1261 if (1) {
1262 rb_str_catf(str, "%04"PRIdSIZE" %-16s ", pos, insn_name_buff);
1263 }
1264 else {
1265 rb_str_catf(str, "%04"PRIdSIZE" %-16.*s ", pos,
1266 (int)strcspn(insn_name_buff, "_"), insn_name_buff);
1267 }
1268
1269 for (j = 0; types[j]; j++) {
1270 const char *types = insn_op_types(insn);
1271 VALUE opstr = insn_operand_intern(iseqdat, insn, j, iseq[pos + j + 1],
1272 len, pos, &iseq[pos + j + 2],
1273 child);
1274 rb_str_concat(str, opstr);
1275
1276 if (types[j + 1]) {
1277 rb_str_cat2(str, ", ");
1278 }
1279 }
1280
1281 {
1282 unsigned int line_no = find_line_no(iseqdat, pos);
1283 unsigned int prev = pos == 0 ? 0 : find_line_no(iseqdat, pos - 1);
1284 if (line_no && line_no != prev) {
1285 long slen = RSTRING_LEN(str);
1286 slen = (slen > 70) ? 0 : (70 - slen);
1287 str = rb_str_catf(str, "%*s(%4d)", (int)slen, "", line_no);
1288 }
1289 }
1290
1291 if (ret) {
1292 rb_str_cat2(str, "\n");
1293 rb_str_concat(ret, str);
1294 }
1295 else {
1296 printf("%s\n", RSTRING_PTR(str));
1297 }
1298 return len;
1299 }
1300
1301 static const char *
1302 catch_type(int type)
1303 {
1304 switch (type) {
1305 case CATCH_TYPE_RESCUE:
1306 return "rescue";
1307 case CATCH_TYPE_ENSURE:
1308 return "ensure";
1309 case CATCH_TYPE_RETRY:
1310 return "retry";
1311 case CATCH_TYPE_BREAK:
1312 return "break";
1313 case CATCH_TYPE_REDO:
1314 return "redo";
1315 case CATCH_TYPE_NEXT:
1316 return "next";
1317 default:
1318 rb_bug("unknown catch type (%d)", type);
1319 return 0;
1320 }
1321 }
1322
1323 /*
1324 * call-seq:
1325 * iseq.disasm -> str
1326 * iseq.disassemble -> str
1327 *
1328 * Returns the instruction sequence as a +String+ in human readable form.
1329 *
1330 * puts RubyVM::InstructionSequence.compile('1 + 2').disasm
1331 *
1332 * Produces:
1333 *
1334 * == disasm: <RubyVM::InstructionSequence:<compiled>@<compiled>>==========
1335 * 0000 trace 1 ( 1)
1336 * 0002 putobject 1
1337 * 0004 putobject 2
1338 * 0006 opt_plus <ic:1>
1339 * 0008 leave
1340 */
1341 VALUE
1342 rb_iseq_disasm(VALUE self)
1343 {
1344 rb_iseq_t *iseqdat = iseq_check(self);
1345 VALUE *iseq;
1346 VALUE str = rb_str_new(0, 0);
1347 VALUE child = rb_ary_new();
1348 unsigned long size;
1349 int i;
1350 long l;
1351 ID *tbl;
1352 size_t n;
1353 enum {header_minlen = 72};
1354
1355 rb_secure(1);
1356
1357 iseq = iseqdat->iseq;
1358 size = iseqdat->iseq_size;
1359
1360 rb_str_cat2(str, "== disasm: ");
1361
1362 rb_str_concat(str, iseq_inspect(iseqdat->self));
1363 if ((l = RSTRING_LEN(str)) < header_minlen) {
1364 rb_str_resize(str, header_minlen);
1365 memset(RSTRING_PTR(str) + l, '=', header_minlen - l);
1366 }
1367 rb_str_cat2(str, "\n");
1368
1369 /* show catch table information */
1370 if (iseqdat->catch_table_size != 0) {
1371 rb_str_cat2(str, "== catch table\n");
1372 }
1373 for (i = 0; i < iseqdat->catch_table_size; i++) {
1374 struct iseq_catch_table_entry *entry = &iseqdat->catch_table[i];
1375 rb_str_catf(str,
1376 "| catch type: %-6s st: %04d ed: %04d sp: %04d cont: %04d\n",
1377 catch_type((int)entry->type), (int)entry->start,
1378 (int)entry->end, (int)entry->sp, (int)entry->cont);
1379 if (entry->iseq) {
1380 rb_str_concat(str, rb_iseq_disasm(entry->iseq));
1381 }
1382 }
1383 if (iseqdat->catch_table_size != 0) {
1384 rb_str_cat2(str, "|-------------------------------------"
1385 "-----------------------------------\n");
1386 }
1387
1388 /* show local table information */
1389 tbl = iseqdat->local_table;
1390
1391 if (tbl) {
1392 rb_str_catf(str,
1393 "local table (size: %d, argc: %d "
1394 "[opts: %d, rest: %d, post: %d, block: %d] s%d)\n",
1395 iseqdat->local_size, iseqdat->argc,
1396 iseqdat->arg_opts, iseqdat->arg_rest,
1397 iseqdat->arg_post_len, iseqdat->arg_block,
1398 iseqdat->arg_simple);
1399
1400 for (i = 0; i < iseqdat->local_table_size; i++) {
1401 long width;
1402 VALUE name = id_to_name(tbl[i], 0);
1403 char argi[0x100] = "";
1404 char opti[0x100] = "";
1405
1406 if (iseqdat->arg_opts) {
1407 int argc = iseqdat->argc;
1408 int opts = iseqdat->arg_opts;
1409 if (i >= argc && i < argc + opts - 1) {
1410 snprintf(opti, sizeof(opti), "Opt=%"PRIdVALUE,
1411 iseqdat->arg_opt_table[i - argc]);
1412 }
1413 }
1414
1415 snprintf(argi, sizeof(argi), "%s%s%s%s%s", /* arg, opts, rest, post block */
1416 iseqdat->argc > i ? "Arg" : "",
1417 opti,
1418 iseqdat->arg_rest == i ? "Rest" : "",
1419 (iseqdat->arg_post_start <= i &&
1420 i < iseqdat->arg_post_start + iseqdat->arg_post_len) ? "Post" : "",
1421 iseqdat->arg_block == i ? "Block" : "");
1422
1423 rb_str_catf(str, "[%2d] ", iseqdat->local_size - i);
1424 width = RSTRING_LEN(str) + 11;
1425 if (name)
1426 rb_str_append(str, name);
1427 else
1428 rb_str_cat2(str, "?");
1429 if (*argi) rb_str_catf(str, "<%s>", argi);
1430 if ((width -= RSTRING_LEN(str)) > 0) rb_str_catf(str, "%*s", (int)width, "");
1431 }
1432 rb_str_cat2(str, "\n");
1433 }
1434
1435 /* show each line */
1436 for (n = 0; n < size;) {
1437 n += rb_iseq_disasm_insn(str, iseq, n, iseqdat, child);
1438 }
1439
1440 for (i = 0; i < RARRAY_LEN(child); i++) {
1441 VALUE isv = rb_ary_entry(child, i);
1442 rb_str_concat(str, rb_iseq_disasm(isv));
1443 }
1444
1445 return str;
1446 }
1447
1448 /*
1449 * Returns the instruction sequence containing the given proc or method.
1450 *
1451 * For example, using irb:
1452 *
1453 * # a proc
1454 * > p = proc { num = 1 + 2 }
1455 * > RubyVM::InstructionSequence.of(p)
1456 * > #=> <RubyVM::InstructionSequence:block in irb_binding@(irb)>
1457 *
1458 * # for a method
1459 * > def foo(bar); puts bar; end
1460 * > RubyVM::InstructionSequence.of(method(:foo))
1461 * > #=> <RubyVM::InstructionSequence:foo@(irb)>
1462 *
1463 * Using ::compile_file:
1464 *
1465 * # /tmp/iseq_of.rb
1466 * def hello
1467 * puts "hello, world"
1468 * end
1469 *
1470 * $a_global_proc = proc { str = 'a' + 'b' }
1471 *
1472 * # in irb
1473 * > require '/tmp/iseq_of.rb'
1474 *
1475 * # first the method hello
1476 * > RubyVM::InstructionSequence.of(method(:hello))
1477 * > #=> #<RubyVM::InstructionSequence:0x007fb73d7cb1d0>
1478 *
1479 * # then the global proc
1480 * > RubyVM::InstructionSequence.of($a_global_proc)
1481 * > #=> #<RubyVM::InstructionSequence:0x007fb73d7caf78>
1482 */
1483 static VALUE
1484 iseq_s_of(VALUE klass, VALUE body)
1485 {
1486 VALUE ret = Qnil;
1487 rb_iseq_t *iseq;
1488
1489 rb_secure(1);
1490
1491 if (rb_obj_is_proc(body)) {
1492 rb_proc_t *proc;
1493 GetProcPtr(body, proc);
1494 iseq = proc->block.iseq;
1495 if (RUBY_VM_NORMAL_ISEQ_P(iseq)) {
1496 ret = iseq->self;
1497 }
1498 }
1499 else if ((iseq = rb_method_get_iseq(body)) != 0) {
1500 ret = iseq->self;
1501 }
1502 return ret;
1503 }
1504
1505 /*
1506 * call-seq:
1507 * InstructionSequence.disasm(body) -> str
1508 * InstructionSequence.disassemble(body) -> str
1509 *
1510 * Takes +body+, a Method or Proc object, and returns a String with the
1511 * human readable instructions for +body+.
1512 *
1513 * For a Method object:
1514 *
1515 * # /tmp/method.rb
1516 * def hello
1517 * puts "hello, world"
1518 * end
1519 *
1520 * puts RubyVM::InstructionSequence.disasm(method(:hello))
1521 *
1522 * Produces:
1523 *
1524 * == disasm: <RubyVM::InstructionSequence:hello@/tmp/method.rb>============
1525 * 0000 trace 8 ( 1)
1526 * 0002 trace 1 ( 2)
1527 * 0004 putself
1528 * 0005 putstring "hello, world"
1529 * 0007 send :puts, 1, nil, 8, <ic:0>
1530 * 0013 trace 16 ( 3)
1531 * 0015 leave ( 2)
1532 *
1533 * For a Proc:
1534 *
1535 * # /tmp/proc.rb
1536 * p = proc { num = 1 + 2 }
1537 * puts RubyVM::InstructionSequence.disasm(p)
1538 *
1539 * Produces:
1540 *
1541 * == disasm: <RubyVM::InstructionSequence:block in <main>@/tmp/proc.rb>===
1542 * == catch table
1543 * | catch type: redo st: 0000 ed: 0012 sp: 0000 cont: 0000
1544 * | catch type: next st: 0000 ed: 0012 sp: 0000 cont: 0012
1545 * |------------------------------------------------------------------------
1546 * local table (size: 2, argc: 0 [opts: 0, rest: -1, post: 0, block: -1] s1)
1547 * [ 2] num
1548 * 0000 trace 1 ( 1)
1549 * 0002 putobject 1
1550 * 0004 putobject 2
1551 * 0006 opt_plus <ic:1>
1552 * 0008 dup
1553 * 0009 setlocal num, 0
1554 * 0012 leave
1555 *
1556 */
1557
1558 static VALUE
1559 iseq_s_disasm(VALUE klass, VALUE body)
1560 {
1561 VALUE iseqval = iseq_s_of(klass, body);
1562 return NIL_P(iseqval) ? Qnil : rb_iseq_disasm(iseqval);
1563 }
1564
1565 const char *
1566 ruby_node_name(int node)
1567 {
1568 switch (node) {
1569 #include "node_name.inc"
1570 default:
1571 rb_bug("unknown node (%d)", node);
1572 return 0;
1573 }
1574 }
1575
1576 #define DECL_SYMBOL(name) \
1577 static VALUE sym_##name
1578
1579 #define INIT_SYMBOL(name) \
1580 sym_##name = ID2SYM(rb_intern(#name))
1581
1582 static VALUE
1583 register_label(struct st_table *table, unsigned long idx)
1584 {
1585 VALUE sym;
1586 char buff[8 + (sizeof(idx) * CHAR_BIT * 32 / 100)];
1587
1588 snprintf(buff, sizeof(buff), "label_%lu", idx);
1589 sym = ID2SYM(rb_intern(buff));
1590 st_insert(table, idx, sym);
1591 return sym;
1592 }
1593
1594 static VALUE
1595 exception_type2symbol(VALUE type)
1596 {
1597 ID id;
1598 switch (type) {
1599 case CATCH_TYPE_RESCUE: CONST_ID(id, "rescue"); break;
1600 case CATCH_TYPE_ENSURE: CONST_ID(id, "ensure"); break;
1601 case CATCH_TYPE_RETRY: CONST_ID(id, "retry"); break;
1602 case CATCH_TYPE_BREAK: CONST_ID(id, "break"); break;
1603 case CATCH_TYPE_REDO: CONST_ID(id, "redo"); break;
1604 case CATCH_TYPE_NEXT: CONST_ID(id, "next"); break;
1605 default:
1606 rb_bug("...");
1607 }
1608 return ID2SYM(id);
1609 }
1610
1611 static int
1612 cdhash_each(VALUE key, VALUE value, VALUE ary)
1613 {
1614 rb_ary_push(ary, obj_resurrect(key));
1615 rb_ary_push(ary, value);
1616 return ST_CONTINUE;
1617 }
1618
1619 static VALUE
1620 iseq_data_to_ary(rb_iseq_t *iseq)
1621 {
1622 long i;
1623 size_t ti;
1624 unsigned int pos;
1625 unsigned int line = 0;
1626 VALUE *seq;
1627
1628 VALUE val = rb_ary_new();
1629 VALUE type; /* Symbol */
1630 VALUE locals = rb_ary_new();
1631 VALUE args = rb_ary_new();
1632 VALUE body = rb_ary_new(); /* [[:insn1, ...], ...] */
1633 VALUE nbody;
1634 VALUE exception = rb_ary_new(); /* [[....]] */
1635 VALUE misc = rb_hash_new();
1636
1637 static VALUE insn_syms[VM_INSTRUCTION_SIZE];
1638 struct st_table *labels_table = st_init_numtable();
1639
1640 DECL_SYMBOL(top);
1641 DECL_SYMBOL(method);
1642 DECL_SYMBOL(block);
1643 DECL_SYMBOL(class);
1644 DECL_SYMBOL(rescue);
1645 DECL_SYMBOL(ensure);
1646 DECL_SYMBOL(eval);
1647 DECL_SYMBOL(main);
1648 DECL_SYMBOL(defined_guard);
1649
1650 if (sym_top == 0) {
1651 int i;
1652 for (i=0; i<VM_INSTRUCTION_SIZE; i++) {
1653 insn_syms[i] = ID2SYM(rb_intern(insn_name(i)));
1654 }
1655 INIT_SYMBOL(top);
1656 INIT_SYMBOL(method);
1657 INIT_SYMBOL(block);
1658 INIT_SYMBOL(class);
1659 INIT_SYMBOL(rescue);
1660 INIT_SYMBOL(ensure);
1661 INIT_SYMBOL(eval);
1662 INIT_SYMBOL(main);
1663 INIT_SYMBOL(defined_guard);
1664 }
1665
1666 /* type */
1667 switch (iseq->type) {
1668 case ISEQ_TYPE_TOP: type = sym_top; break;
1669 case ISEQ_TYPE_METHOD: type = sym_method; break;
1670 case ISEQ_TYPE_BLOCK: type = sym_block; break;
1671 case ISEQ_TYPE_CLASS: type = sym_class; break;
1672 case ISEQ_TYPE_RESCUE: type = sym_rescue; break;
1673 case ISEQ_TYPE_ENSURE: type = sym_ensure; break;
1674 case ISEQ_TYPE_EVAL: type = sym_eval; break;
1675 case ISEQ_TYPE_MAIN: type = sym_main; break;
1676 case ISEQ_TYPE_DEFINED_GUARD: type = sym_defined_guard; break;
1677 default: rb_bug("unsupported iseq type");
1678 };
1679
1680 /* locals */
1681 for (i=0; i<iseq->local_table_size; i++) {
1682 ID lid = iseq->local_table[i];
1683 if (lid) {
1684 if (rb_id2str(lid)) rb_ary_push(locals, ID2SYM(lid));
1685 }
1686 else {
1687 rb_ary_push(locals, ID2SYM(rb_intern("#arg_rest")));
1688 }
1689 }
1690
1691 /* args */
1692 {
1693 /*
1694 * [argc, # argc
1695 * [label1, label2, ...] # opts
1696 * rest index,
1697 * post_len
1698 * post_start
1699 * block index,
1700 * simple,
1701 * ]
1702 */
1703 VALUE arg_opt_labels = rb_ary_new();
1704 int j;
1705
1706 for (j=0; j<iseq->arg_opts; j++) {
1707 rb_ary_push(arg_opt_labels,
1708 register_label(labels_table, iseq->arg_opt_table[j]));
1709 }
1710
1711 /* commit */
1712 if (iseq->arg_simple == 1) {
1713 args = INT2FIX(iseq->argc);
1714 }
1715 else {
1716 rb_ary_push(args, INT2FIX(iseq->argc));
1717 rb_ary_push(args, arg_opt_labels);
1718 rb_ary_push(args, INT2FIX(iseq->arg_post_len));
1719 rb_ary_push(args, INT2FIX(iseq->arg_post_start));
1720 rb_ary_push(args, INT2FIX(iseq->arg_rest));
1721 rb_ary_push(args, INT2FIX(iseq->arg_block));
1722 rb_ary_push(args, INT2FIX(iseq->arg_simple));
1723 }
1724 }
1725
1726 /* body */
1727 for (seq = iseq->iseq; seq < iseq->iseq + iseq->iseq_size; ) {
1728 VALUE insn = *seq++;
1729 int j, len = insn_len(insn);
1730 VALUE *nseq = seq + len - 1;
1731 VALUE ary = rb_ary_new2(len);
1732
1733 rb_ary_push(ary, insn_syms[insn]);
1734 for (j=0; j<len-1; j++, seq++) {
1735 switch (insn_op_type(insn, j)) {
1736 case TS_OFFSET: {
1737 unsigned long idx = nseq - iseq->iseq + *seq;
1738 rb_ary_push(ary, register_label(labels_table, idx));
1739 break;
1740 }
1741 case TS_LINDEX:
1742 case TS_NUM:
1743 rb_ary_push(ary, INT2FIX(*seq));
1744 break;
1745 case TS_VALUE:
1746 rb_ary_push(ary, obj_resurrect(*seq));
1747 break;
1748 case TS_ISEQ:
1749 {
1750 rb_iseq_t *iseq = (rb_iseq_t *)*seq;
1751 if (iseq) {
1752 VALUE val = iseq_data_to_ary(iseq);
1753 rb_ary_push(ary, val);
1754 }
1755 else {
1756 rb_ary_push(ary, Qnil);
1757 }
1758 }
1759 break;
1760 case TS_GENTRY:
1761 {
1762 struct rb_global_entry *entry = (struct rb_global_entry *)*seq;
1763 rb_ary_push(ary, ID2SYM(entry->id));
1764 }
1765 break;
1766 case TS_IC: {
1767 struct iseq_inline_cache_entry *ic = (struct iseq_inline_cache_entry *)*seq;
1768 rb_ary_push(ary, INT2FIX(ic - iseq->ic_entries));
1769 }
1770 break;
1771 case TS_CALLINFO:
1772 {
1773 rb_call_info_t *ci = (rb_call_info_t *)*seq;
1774 VALUE e = rb_hash_new();
1775 rb_hash_aset(e, ID2SYM(rb_intern("mid")), ci->mid ? ID2SYM(ci->mid) : Qnil);
1776 rb_hash_aset(e, ID2SYM(rb_intern("flag")), ULONG2NUM(ci->flag));
1777 rb_hash_aset(e, ID2SYM(rb_intern("orig_argc")), INT2FIX(ci->orig_argc));
1778 rb_hash_aset(e, ID2SYM(rb_intern("blockptr")), ci->blockiseq ? iseq_data_to_ary(ci->blockiseq) : Qnil);
1779 rb_ary_push(ary, e);
1780 }
1781 break;
1782 case TS_ID:
1783 rb_ary_push(ary, ID2SYM(*seq));
1784 break;
1785 case TS_CDHASH:
1786 {
1787 VALUE hash = *seq;
1788 VALUE val = rb_ary_new();
1789 int i;
1790
1791 rb_hash_foreach(hash, cdhash_each, val);
1792
1793 for (i=0; i<RARRAY_LEN(val); i+=2) {
1794 VALUE pos = FIX2INT(rb_ary_entry(val, i+1));
1795 unsigned long idx = nseq - iseq->iseq + pos;
1796
1797 rb_ary_store(val, i+1,
1798 register_label(labels_table, idx));
1799 }
1800 rb_ary_push(ary, val);
1801 }
1802 break;
1803 default:
1804 rb_bug("unknown operand: %c", insn_op_type(insn, j));
1805 }
1806 }
1807 rb_ary_push(body, ary);
1808 }
1809
1810 nbody = body;
1811
1812 /* exception */
1813 for (i=0; i<iseq->catch_table_size; i++) {
1814 VALUE ary = rb_ary_new();
1815 struct iseq_catch_table_entry *entry = &iseq->catch_table[i];
1816 rb_ary_push(ary, exception_type2symbol(entry->type));
1817 if (entry->iseq) {
1818 rb_iseq_t *eiseq;
1819 GetISeqPtr(entry->iseq, eiseq);
1820 rb_ary_push(ary, iseq_data_to_ary(eiseq));
1821 }
1822 else {
1823 rb_ary_push(ary, Qnil);
1824 }
1825 rb_ary_push(ary, register_label(labels_table, entry->start));
1826 rb_ary_push(ary, register_label(labels_table, entry->end));
1827 rb_ary_push(ary, register_label(labels_table, entry->cont));
1828 rb_ary_push(ary, INT2FIX(entry->sp));
1829 rb_ary_push(exception, ary);
1830 }
1831
1832 /* make body with labels and insert line number */
1833 body = rb_ary_new();
1834 ti = 0;
1835
1836 for (i=0, pos=0; i<RARRAY_LEN(nbody); i++) {
1837 VALUE ary = RARRAY_PTR(nbody)[i];
1838 st_data_t label;
1839
1840 if (st_lookup(labels_table, pos, &label)) {
1841 rb_ary_push(body, (VALUE)label);
1842 }
1843
1844 if (ti < iseq->line_info_size && iseq->line_info_table[ti].position == pos) {
1845 line = iseq->line_info_table[ti].line_no;
1846 rb_ary_push(body, INT2FIX(line));
1847 ti++;
1848 }
1849
1850 rb_ary_push(body, ary);
1851 pos += RARRAY_LENINT(ary); /* reject too huge data */
1852 }
1853
1854 st_free_table(labels_table);
1855
1856 rb_hash_aset(misc, ID2SYM(rb_intern("arg_size")), INT2FIX(iseq->arg_size));
1857 rb_hash_aset(misc, ID2SYM(rb_intern("local_size")), INT2FIX(iseq->local_size));
1858 rb_hash_aset(misc, ID2SYM(rb_intern("stack_max")), INT2FIX(iseq->stack_max));
1859
1860 /* TODO: compatibility issue */
1861 /*
1862 * [:magic, :major_version, :minor_version, :format_type, :misc,
1863 * :name, :path, :absolute_path, :start_lineno, :type, :locals, :args,
1864 * :catch_table, :bytecode]
1865 */
1866 rb_ary_push(val, rb_str_new2("YARVInstructionSequence/SimpleDataFormat"));
1867 rb_ary_push(val, INT2FIX(ISEQ_MAJOR_VERSION)); /* major */
1868 rb_ary_push(val, INT2FIX(ISEQ_MINOR_VERSION)); /* minor */
1869 rb_ary_push(val, INT2FIX(1));
1870 rb_ary_push(val, misc);
1871 rb_ary_push(val, iseq->location.label);
1872 rb_ary_push(val, iseq->location.path);
1873 rb_ary_push(val, iseq->location.absolute_path);
1874 rb_ary_push(val, iseq->location.first_lineno);
1875 rb_ary_push(val, type);
1876 rb_ary_push(val, locals);
1877 rb_ary_push(val, args);
1878 rb_ary_push(val, exception);
1879 rb_ary_push(val, body);
1880 return val;
1881 }
1882
1883 VALUE
1884 rb_iseq_clone(VALUE iseqval, VALUE newcbase)
1885 {
1886 VALUE newiseq = iseq_alloc(rb_cISeq);
1887 rb_iseq_t *iseq0, *iseq1;
1888
1889 GetISeqPtr(iseqval, iseq0);
1890 GetISeqPtr(newiseq, iseq1);
1891
1892 *iseq1 = *iseq0;
1893 iseq1->self = newiseq;
1894 if (!iseq1->orig) {
1895 iseq1->orig = iseqval;
1896 }
1897 if (iseq0->local_iseq == iseq0) {
1898 iseq1->local_iseq = iseq1;
1899 }
1900 if (newcbase) {
1901 iseq1->cref_stack = NEW_CREF(newcbase);
1902 iseq1->cref_stack->nd_refinements = iseq0->cref_stack->nd_refinements;
1903 iseq1->cref_stack->nd_visi = iseq0->cref_stack->nd_visi;
1904 if (iseq0->cref_stack->nd_next) {
1905 iseq1->cref_stack->nd_next = iseq0->cref_stack->nd_next;
1906 }
1907 iseq1->klass = newcbase;
1908 }
1909
1910 return newiseq;
1911 }
1912
1913 VALUE
1914 rb_iseq_parameters(const rb_iseq_t *iseq, int is_proc)
1915 {
1916 int i, r;
1917 VALUE a, args = rb_ary_new2(iseq->arg_size);
1918 ID req, opt, rest, block, key, keyrest;
1919 #define PARAM_TYPE(type) rb_ary_push(a = rb_ary_new2(2), ID2SYM(type))
1920 #define PARAM_ID(i) iseq->local_table[(i)]
1921 #define PARAM(i, type) ( \
1922 PARAM_TYPE(type), \
1923 rb_id2str(PARAM_ID(i)) ? \
1924 rb_ary_push(a, ID2SYM(PARAM_ID(i))) : \
1925 a)
1926
1927 CONST_ID(req, "req");
1928 CONST_ID(opt, "opt");
1929 if (is_proc) {
1930 for (i = 0; i < iseq->argc; i++) {
1931 PARAM_TYPE(opt);
1932 rb_ary_push(a, rb_id2str(PARAM_ID(i)) ? ID2SYM(PARAM_ID(i)) : Qnil);
1933 rb_ary_push(args, a);
1934 }
1935 }
1936 else {
1937 for (i = 0; i < iseq->argc; i++) {
1938 rb_ary_push(args, PARAM(i, req));
1939 }
1940 }
1941 r = iseq->argc + iseq->arg_opts - 1;
1942 for (; i < r; i++) {
1943 PARAM_TYPE(opt);
1944 if (rb_id2str(PARAM_ID(i))) {
1945 rb_ary_push(a, ID2SYM(PARAM_ID(i)));
1946 }
1947 rb_ary_push(args, a);
1948 }
1949 if (iseq->arg_rest != -1) {
1950 CONST_ID(rest, "rest");
1951 rb_ary_push(args, PARAM(iseq->arg_rest, rest));
1952 }
1953 r = iseq->arg_post_start + iseq->arg_post_len;
1954 if (is_proc) {
1955 for (i = iseq->arg_post_start; i < r; i++) {
1956 PARAM_TYPE(opt);
1957 rb_ary_push(a, rb_id2str(PARAM_ID(i)) ? ID2SYM(PARAM_ID(i)) : Qnil);
1958 rb_ary_push(args, a);
1959 }
1960 }
1961 else {
1962 for (i = iseq->arg_post_start; i < r; i++) {
1963 rb_ary_push(args, PARAM(i, req));
1964 }
1965 }
1966 if (iseq->arg_keyword != -1) {
1967 CONST_ID(key, "key");
1968 for (i = 0; i < iseq->arg_keywords; i++) {
1969 PARAM_TYPE(key);
1970 if (rb_id2str(iseq->arg_keyword_table[i])) {
1971 rb_ary_push(a, ID2SYM(iseq->arg_keyword_table[i]));
1972 }
1973 rb_ary_push(args, a);
1974 }
1975 if (rb_id2str(iseq->local_table[iseq->arg_keyword])) {
1976 CONST_ID(keyrest, "keyrest");
1977 rb_ary_push(args, PARAM(iseq->arg_keyword, keyrest));
1978 }
1979 }
1980 if (iseq->arg_block != -1) {
1981 CONST_ID(block, "block");
1982 rb_ary_push(args, PARAM(iseq->arg_block, block));
1983 }
1984 return args;
1985 }
1986
1987 VALUE
1988 rb_iseq_defined_string(enum defined_type type)
1989 {
1990 static const char expr_names[][18] = {
1991 "nil",
1992 "instance-variable",
1993 "local-variable",
1994 "global-variable",
1995 "class variable",
1996 "constant",
1997 "method",
1998 "yield",
1999 "super",
2000 "self",
2001 "true",
2002 "false",
2003 "assignment",
2004 "expression",
2005 };
2006 const char *estr;
2007 VALUE *defs, str;
2008
2009 if ((unsigned)(type - 1) >= (unsigned)numberof(expr_names)) return 0;
2010 estr = expr_names[type - 1];
2011 if (!estr[0]) return 0;
2012 defs = GET_VM()->defined_strings;
2013 if (!defs) {
2014 defs = ruby_xcalloc(numberof(expr_names), sizeof(VALUE));
2015 GET_VM()->defined_strings = defs;
2016 }
2017 str = defs[type-1];
2018 if (!str) {
2019 str = rb_str_new_cstr(estr);;
2020 OBJ_FREEZE(str);
2021 defs[type-1] = str;
2022 }
2023 return str;
2024 }
2025
2026 /* ruby2cext */
2027
2028 VALUE
2029 rb_iseq_build_for_ruby2cext(
2030 const rb_iseq_t *iseq_template,
2031 const rb_insn_func_t *func,
2032 const struct iseq_line_info_entry *line_info_table,
2033 const char **local_table,
2034 const VALUE *arg_opt_table,
2035 const struct iseq_catch_table_entry *catch_table,
2036 const char *name,
2037 const char *path,
2038 const unsigned short first_lineno)
2039 {
2040 unsigned long i;
2041 VALUE iseqval = iseq_alloc(rb_cISeq);
2042 rb_iseq_t *iseq;
2043 GetISeqPtr(iseqval, iseq);
2044
2045 /* copy iseq */
2046 *iseq = *iseq_template;
2047 iseq->location.label = rb_str_new2(name);
2048 iseq->location.path = rb_str_new2(path);
2049 iseq->location.first_lineno = first_lineno;
2050 iseq->mark_ary = rb_ary_tmp_new(3);
2051 OBJ_UNTRUST(iseq->mark_ary);
2052 iseq->self = iseqval;
2053
2054 iseq->iseq = ALLOC_N(VALUE, iseq->iseq_size);
2055
2056 for (i=0; i<iseq->iseq_size; i+=2) {
2057 iseq->iseq[i] = BIN(opt_call_c_function);
2058 iseq->iseq[i+1] = (VALUE)func;
2059 }
2060
2061 rb_iseq_translate_threaded_code(iseq);
2062
2063 #define ALLOC_AND_COPY(dst, src, type, size) do { \
2064 if (size) { \
2065 (dst) = ALLOC_N(type, (size)); \
2066 MEMCPY((dst), (src), type, (size)); \
2067 } \
2068 } while (0)
2069
2070 ALLOC_AND_COPY(iseq->line_info_table, line_info_table,
2071 struct iseq_line_info_entry, iseq->line_info_size);
2072
2073 ALLOC_AND_COPY(iseq->catch_table, catch_table,
2074 struct iseq_catch_table_entry, iseq->catch_table_size);
2075
2076 ALLOC_AND_COPY(iseq->arg_opt_table, arg_opt_table,
2077 VALUE, iseq->arg_opts);
2078
2079 set_relation(iseq, 0);
2080
2081 return iseqval;
2082 }
2083
2084 /* Experimental tracing support: trace(line) -> trace(specified_line)
2085 * MRI Specific.
2086 */
2087
2088 int
2089 rb_iseq_line_trace_each(VALUE iseqval, int (*func)(int line, rb_event_flag_t *events_ptr, void *d), void *data)
2090 {
2091 int trace_num = 0;
2092 size_t pos, insn;
2093 rb_iseq_t *iseq;
2094 int cont = 1;
2095 GetISeqPtr(iseqval, iseq);
2096
2097 for (pos = 0; cont && pos < iseq->iseq_size; pos += insn_len(insn)) {
2098 insn = iseq->iseq[pos];
2099
2100 if (insn == BIN(trace)) {
2101 rb_event_flag_t current_events = (VALUE)iseq->iseq[pos+1];
2102
2103 if (current_events & RUBY_EVENT_LINE) {
2104 rb_event_flag_t events = current_events & RUBY_EVENT_SPECIFIED_LINE;
2105 trace_num++;
2106
2107 if (func) {
2108 int line = find_line_no(iseq, pos);
2109 /* printf("line: %d\n", line); */
2110 cont = (*func)(line, &events, data);
2111 if (current_events != events) {
2112 iseq->iseq[pos+1] = iseq->iseq_encoded[pos+1] =
2113 (VALUE)(current_events | (events & RUBY_EVENT_SPECIFIED_LINE));
2114 }
2115 }
2116 }
2117 }
2118 }
2119 return trace_num;
2120 }
2121
2122 static int
2123 collect_trace(int line, rb_event_flag_t *events_ptr, void *ptr)
2124 {
2125 VALUE result = (VALUE)ptr;
2126 rb_ary_push(result, INT2NUM(line));
2127 return 1;
2128 }
2129
2130 /*
2131 * <b>Experimental MRI specific feature, only available as C level api.</b>
2132 *
2133 * Returns all +specified_line+ events.
2134 */
2135 VALUE
2136 rb_iseq_line_trace_all(VALUE iseqval)
2137 {
2138 VALUE result = rb_ary_new();
2139 rb_iseq_line_trace_each(iseqval, collect_trace, (void *)result);
2140 return result;
2141 }
2142
2143 struct set_specifc_data {
2144 int pos;
2145 int set;
2146 int prev; /* 1: set, 2: unset, 0: not found */
2147 };
2148
2149 static int
2150 line_trace_specify(int line, rb_event_flag_t *events_ptr, void *ptr)
2151 {
2152 struct set_specifc_data *data = (struct set_specifc_data *)ptr;
2153
2154 if (data->pos == 0) {
2155 data->prev = *events_ptr & RUBY_EVENT_SPECIFIED_LINE ? 1 : 2;
2156 if (data->set) {
2157 *events_ptr = *events_ptr | RUBY_EVENT_SPECIFIED_LINE;
2158 }
2159 else {
2160 *events_ptr = *events_ptr & ~RUBY_EVENT_SPECIFIED_LINE;
2161 }
2162 return 0; /* found */
2163 }
2164 else {
2165 data->pos--;
2166 return 1;
2167 }
2168 }
2169
2170 /*
2171 * <b>Experimental MRI specific feature, only available as C level api.</b>
2172 *
2173 * Set a +specified_line+ event at the given line position, if the +set+
2174 * parameter is +true+.
2175 *
2176 * This method is useful for building a debugger breakpoint at a specific line.
2177 *
2178 * A TypeError is raised if +set+ is not boolean.
2179 *
2180 * If +pos+ is a negative integer a TypeError exception is raised.
2181 */
2182 VALUE
2183 rb_iseq_line_trace_specify(VALUE iseqval, VALUE pos, VALUE set)
2184 {
2185 struct set_specifc_data data;
2186
2187 data.prev = 0;
2188 data.pos = NUM2INT(pos);
2189 if (data.pos < 0) rb_raise(rb_eTypeError, "`pos' is negative");
2190
2191 switch (set) {
2192 case Qtrue: data.set = 1; break;
2193 case Qfalse: data.set = 0; break;
2194 default:
2195 rb_raise(rb_eTypeError, "`set' should be true/false");
2196 }
2197
2198 rb_iseq_line_trace_each(iseqval, line_trace_specify, (void *)&data);
2199
2200 if (data.prev == 0) {
2201 rb_raise(rb_eTypeError, "`pos' is out of range.");
2202 }
2203 return data.prev == 1 ? Qtrue : Qfalse;
2204 }
2205
2206 /*
2207 * Document-class: RubyVM::InstructionSequence
2208 *
2209 * The InstructionSequence class represents a compiled sequence of
2210 * instructions for the Ruby Virtual Machine.
2211 *
2212 * With it, you can get a handle to the instructions that make up a method or
2213 * a proc, compile strings of Ruby code down to VM instructions, and
2214 * disassemble instruction sequences to strings for easy inspection. It is
2215 * mostly useful if you want to learn how the Ruby VM works, but it also lets
2216 * you control various settings for the Ruby iseq compiler.
2217 *
2218 * You can find the source for the VM instructions in +insns.def+ in the Ruby
2219 * source.
2220 *
2221 * The instruction sequence results will almost certainly change as Ruby
2222 * changes, so example output in this documentation may be different from what
2223 * you see.
2224 */
2225
2226 void
2227 Init_ISeq(void)
2228 {
2229 /* declare ::RubyVM::InstructionSequence */
2230 rb_cISeq = rb_define_class_under(rb_cRubyVM, "InstructionSequence", rb_cObject);
2231 rb_define_alloc_func(rb_cISeq, iseq_alloc);
2232 rb_define_method(rb_cISeq, "inspect", iseq_inspect, 0);
2233 rb_define_method(rb_cISeq, "disasm", rb_iseq_disasm, 0);
2234 rb_define_method(rb_cISeq, "disassemble", rb_iseq_disasm, 0);
2235 rb_define_method(rb_cISeq, "to_a", iseq_to_a, 0);
2236 rb_define_method(rb_cISeq, "eval", iseq_eval, 0);
2237
2238 /* location APIs */
2239 rb_define_method(rb_cISeq, "path", iseq_path, 0);
2240 rb_define_method(rb_cISeq, "absolute_path", iseq_absolute_path, 0);
2241 rb_define_method(rb_cISeq, "label", iseq_label, 0);
2242 rb_define_method(rb_cISeq, "base_label", iseq_base_label, 0);
2243 rb_define_method(rb_cISeq, "first_lineno", iseq_first_lineno, 0);
2244
2245 #if 0
2246 /* Now, it is experimental. No discussions, no tests. */
2247 /* They can be used from C level. Please give us feedback. */
2248 rb_define_method(rb_cISeq, "line_trace_all", rb_iseq_line_trace_all, 0);
2249 rb_define_method(rb_cISeq, "line_trace_specify", rb_iseq_line_trace_specify, 2);
2250 #else
2251 (void)rb_iseq_line_trace_all;
2252 (void)rb_iseq_line_trace_specify;
2253 #endif
2254
2255 #if 0 /* TBD */
2256 rb_define_private_method(rb_cISeq, "marshal_dump", iseq_marshal_dump, 0);
2257 rb_define_private_method(rb_cISeq, "marshal_load", iseq_marshal_load, 1);
2258 #endif
2259
2260 /* disable this feature because there is no verifier. */
2261 /* rb_define_singleton_method(rb_cISeq, "load", iseq_s_load, -1); */
2262 (void)iseq_s_load;
2263
2264 rb_define_singleton_method(rb_cISeq, "compile", iseq_s_compile, -1);
2265 rb_define_singleton_method(rb_cISeq, "new", iseq_s_compile, -1);
2266 rb_define_singleton_method(rb_cISeq, "compile_file", iseq_s_compile_file, -1);
2267 rb_define_singleton_method(rb_cISeq, "compile_option", iseq_s_compile_option_get, 0);
2268 rb_define_singleton_method(rb_cISeq, "compile_option=", iseq_s_compile_option_set, 1);
2269 rb_define_singleton_method(rb_cISeq, "disasm", iseq_s_disasm, 1);
2270 rb_define_singleton_method(rb_cISeq, "disassemble", iseq_s_disasm, 1);
2271 rb_define_singleton_method(rb_cISeq, "of", iseq_s_of, 1);
2272 }
2273