1/********************************************************************** 2 3 eval.c - 4 5 $Author: nagachika $ 6 created at: Thu Jun 10 14:22:17 JST 1993 7 8 Copyright (C) 1993-2007 Yukihiro Matsumoto 9 Copyright (C) 2000 Network Applied Communication Laboratory, Inc. 10 Copyright (C) 2000 Information-technology Promotion Agency, Japan 11 12**********************************************************************/ 13 14#include "eval_intern.h" 15#include "iseq.h" 16#include "gc.h" 17#include "ruby/vm.h" 18#include "ruby/encoding.h" 19#include "internal.h" 20#include "vm_core.h" 21#include "probes_helper.h" 22 23#define numberof(array) (int)(sizeof(array) / sizeof((array)[0])) 24 25NORETURN(void rb_raise_jump(VALUE)); 26 27NODE *rb_vm_get_cref(const rb_iseq_t *, const VALUE *); 28 29VALUE rb_eLocalJumpError; 30VALUE rb_eSysStackError; 31 32#define exception_error GET_VM()->special_exceptions[ruby_error_reenter] 33 34#include "eval_error.c" 35#include "eval_jump.c" 36 37/* Initializes the Ruby VM and builtin libraries. 38 * @retval 0 if succeeded. 39 * @retval non-zero an error occured. 40 */ 41int 42ruby_setup(void) 43{ 44 static int initialized = 0; 45 int state; 46 47 if (initialized) 48 return 0; 49 initialized = 1; 50 51 ruby_init_stack((void *)&state); 52 Init_BareVM(); 53 Init_heap(); 54 55 PUSH_TAG(); 56 if ((state = EXEC_TAG()) == 0) { 57 rb_call_inits(); 58 ruby_prog_init(); 59 GET_VM()->running = 1; 60 } 61 POP_TAG(); 62 63 return state; 64} 65 66/* Calls ruby_setup() and check error. 67 * 68 * Prints errors and calls exit(3) if an error occured. 69 */ 70void 71ruby_init(void) 72{ 73 int state = ruby_setup(); 74 if (state) { 75 error_print(); 76 exit(EXIT_FAILURE); 77 } 78} 79 80/*! Processes command line arguments and compiles the Ruby source to execute. 81 * 82 * This function does: 83 * \li Processses the given command line flags and arguments for ruby(1) 84 * \li compiles the source code from the given argument, -e or stdin, and 85 * \li returns the compiled source as an opaque pointer to an internal data structure 86 * 87 * @return an opaque pointer to the compiled source or an internal special value. 88 * @sa ruby_executable_node(). 89 */ 90void * 91ruby_options(int argc, char **argv) 92{ 93 int state; 94 void *volatile iseq = 0; 95 96 ruby_init_stack((void *)&iseq); 97 PUSH_TAG(); 98 if ((state = EXEC_TAG()) == 0) { 99 SAVE_ROOT_JMPBUF(GET_THREAD(), iseq = ruby_process_options(argc, argv)); 100 } 101 else { 102 rb_clear_trace_func(); 103 state = error_handle(state); 104 iseq = (void *)INT2FIX(state); 105 } 106 POP_TAG(); 107 return iseq; 108} 109 110static void 111ruby_finalize_0(void) 112{ 113 PUSH_TAG(); 114 if (EXEC_TAG() == 0) { 115 rb_trap_exit(); 116 } 117 POP_TAG(); 118 rb_exec_end_proc(); 119 rb_clear_trace_func(); 120} 121 122static void 123ruby_finalize_1(void) 124{ 125 ruby_sig_finalize(); 126 GET_THREAD()->errinfo = Qnil; 127 rb_gc_call_finalizer_at_exit(); 128} 129 130/** Runs the VM finalization processes. 131 * 132 * <code>END{}</code> and procs registered by <code>Kernel.#at_exit</code> are 133 * executed here. See the Ruby language spec for more details. 134 * 135 * @note This function is allowed to raise an exception if an error occurred. 136 */ 137void 138ruby_finalize(void) 139{ 140 ruby_finalize_0(); 141 ruby_finalize_1(); 142} 143 144/** Destructs the VM. 145 * 146 * Runs the VM finalization processes as well as ruby_finalize(), and frees 147 * resources used by the VM. 148 * 149 * @param ex Default value to the return value. 150 * @return If an error occured returns a non-zero. If otherwise, returns the 151 * given ex. 152 * @note This function does not raise any exception. 153 */ 154int 155ruby_cleanup(volatile int ex) 156{ 157 int state; 158 volatile VALUE errs[2]; 159 rb_thread_t *th = GET_THREAD(); 160 int nerr; 161 162 rb_threadptr_interrupt(th); 163 rb_threadptr_check_signal(th); 164 PUSH_TAG(); 165 if ((state = EXEC_TAG()) == 0) { 166 SAVE_ROOT_JMPBUF(th, { RUBY_VM_CHECK_INTS(th); }); 167 } 168 POP_TAG(); 169 170 errs[1] = th->errinfo; 171 th->safe_level = 0; 172 ruby_init_stack(&errs[STACK_UPPER(errs, 0, 1)]); 173 174 PUSH_TAG(); 175 if ((state = EXEC_TAG()) == 0) { 176 SAVE_ROOT_JMPBUF(th, ruby_finalize_0()); 177 } 178 POP_TAG(); 179 180 /* protect from Thread#raise */ 181 th->status = THREAD_KILLED; 182 183 errs[0] = th->errinfo; 184 PUSH_TAG(); 185 if ((state = EXEC_TAG()) == 0) { 186 SAVE_ROOT_JMPBUF(th, rb_thread_terminate_all()); 187 } 188 else if (ex == 0) { 189 ex = state; 190 } 191 th->errinfo = errs[1]; 192 ex = error_handle(ex); 193 ruby_finalize_1(); 194 195 /* unlock again if finalizer took mutexes. */ 196 rb_threadptr_unlock_all_locking_mutexes(GET_THREAD()); 197 POP_TAG(); 198 rb_thread_stop_timer_thread(1); 199 200#if EXIT_SUCCESS != 0 || EXIT_FAILURE != 1 201 switch (ex) { 202#if EXIT_SUCCESS != 0 203 case 0: ex = EXIT_SUCCESS; break; 204#endif 205#if EXIT_FAILURE != 1 206 case 1: ex = EXIT_FAILURE; break; 207#endif 208 } 209#endif 210 211 state = 0; 212 for (nerr = 0; nerr < numberof(errs); ++nerr) { 213 VALUE err = errs[nerr]; 214 215 if (!RTEST(err)) continue; 216 217 /* th->errinfo contains a NODE while break'ing */ 218 if (RB_TYPE_P(err, T_NODE)) continue; 219 220 if (rb_obj_is_kind_of(err, rb_eSystemExit)) { 221 ex = sysexit_status(err); 222 break; 223 } 224 else if (rb_obj_is_kind_of(err, rb_eSignal)) { 225 VALUE sig = rb_iv_get(err, "signo"); 226 state = NUM2INT(sig); 227 break; 228 } 229 else if (ex == EXIT_SUCCESS) { 230 ex = EXIT_FAILURE; 231 } 232 } 233 ruby_vm_destruct(GET_VM()); 234 if (state) ruby_default_signal(state); 235 236 return ex; 237} 238 239static int 240ruby_exec_internal(void *n) 241{ 242 volatile int state; 243 VALUE iseq = (VALUE)n; 244 rb_thread_t *th = GET_THREAD(); 245 246 if (!n) return 0; 247 248 PUSH_TAG(); 249 if ((state = EXEC_TAG()) == 0) { 250 SAVE_ROOT_JMPBUF(th, { 251 th->base_block = 0; 252 rb_iseq_eval_main(iseq); 253 }); 254 } 255 POP_TAG(); 256 return state; 257} 258 259/*! Calls ruby_cleanup() and exits the process */ 260void 261ruby_stop(int ex) 262{ 263 exit(ruby_cleanup(ex)); 264} 265 266/*! Checks the return value of ruby_options(). 267 * @param n return value of ruby_options(). 268 * @param status pointer to the exit status of this process. 269 * 270 * ruby_options() sometimes returns a special value to indicate this process 271 * should immediately exit. This function checks if the case. Also stores the 272 * exit status that the caller have to pass to exit(3) into 273 * <code>*status</code>. 274 * 275 * @retval non-zero if the given opaque pointer is actually a compiled source. 276 * @retval 0 if the given value is such a special value. 277 */ 278int 279ruby_executable_node(void *n, int *status) 280{ 281 VALUE v = (VALUE)n; 282 int s; 283 284 switch (v) { 285 case Qtrue: s = EXIT_SUCCESS; break; 286 case Qfalse: s = EXIT_FAILURE; break; 287 default: 288 if (!FIXNUM_P(v)) return TRUE; 289 s = FIX2INT(v); 290 } 291 if (status) *status = s; 292 return FALSE; 293} 294 295/*! Runs the given compiled source and exits this process. 296 * @retval 0 if successfully run thhe source 297 * @retval non-zero if an error occurred. 298*/ 299int 300ruby_run_node(void *n) 301{ 302 int status; 303 if (!ruby_executable_node(n, &status)) { 304 ruby_cleanup(0); 305 return status; 306 } 307 return ruby_cleanup(ruby_exec_node(n)); 308} 309 310/*! Runs the given compiled source */ 311int 312ruby_exec_node(void *n) 313{ 314 ruby_init_stack((void *)&n); 315 return ruby_exec_internal(n); 316} 317 318/* 319 * call-seq: 320 * Module.nesting -> array 321 * 322 * Returns the list of +Modules+ nested at the point of call. 323 * 324 * module M1 325 * module M2 326 * $a = Module.nesting 327 * end 328 * end 329 * $a #=> [M1::M2, M1] 330 * $a[0].name #=> "M1::M2" 331 */ 332 333static VALUE 334rb_mod_nesting(void) 335{ 336 VALUE ary = rb_ary_new(); 337 const NODE *cref = rb_vm_cref(); 338 339 while (cref && cref->nd_next) { 340 VALUE klass = cref->nd_clss; 341 if (!(cref->flags & NODE_FL_CREF_PUSHED_BY_EVAL) && 342 !NIL_P(klass)) { 343 rb_ary_push(ary, klass); 344 } 345 cref = cref->nd_next; 346 } 347 return ary; 348} 349 350/* 351 * call-seq: 352 * Module.constants -> array 353 * Module.constants(inherited) -> array 354 * 355 * In the first form, returns an array of the names of all 356 * constants accessible from the point of call. 357 * This list includes the names of all modules and classes 358 * defined in the global scope. 359 * 360 * Module.constants.first(4) 361 * # => [:ARGF, :ARGV, :ArgumentError, :Array] 362 * 363 * Module.constants.include?(:SEEK_SET) # => false 364 * 365 * class IO 366 * Module.constants.include?(:SEEK_SET) # => true 367 * end 368 * 369 * The second form calls the instance method +constants+. 370 */ 371 372static VALUE 373rb_mod_s_constants(int argc, VALUE *argv, VALUE mod) 374{ 375 const NODE *cref = rb_vm_cref(); 376 VALUE klass; 377 VALUE cbase = 0; 378 void *data = 0; 379 380 if (argc > 0 || mod != rb_cModule) { 381 return rb_mod_constants(argc, argv, mod); 382 } 383 384 while (cref) { 385 klass = cref->nd_clss; 386 if (!(cref->flags & NODE_FL_CREF_PUSHED_BY_EVAL) && 387 !NIL_P(klass)) { 388 data = rb_mod_const_at(cref->nd_clss, data); 389 if (!cbase) { 390 cbase = klass; 391 } 392 } 393 cref = cref->nd_next; 394 } 395 396 if (cbase) { 397 data = rb_mod_const_of(cbase, data); 398 } 399 return rb_const_list(data); 400} 401 402void 403rb_frozen_class_p(VALUE klass) 404{ 405 const char *desc = "something(?!)"; 406 407 if (OBJ_FROZEN(klass)) { 408 if (FL_TEST(klass, FL_SINGLETON)) 409 desc = "object"; 410 else { 411 switch (TYPE(klass)) { 412 case T_MODULE: 413 case T_ICLASS: 414 desc = "module"; 415 break; 416 case T_CLASS: 417 desc = "class"; 418 break; 419 } 420 } 421 rb_error_frozen(desc); 422 } 423} 424 425NORETURN(static void rb_longjmp(int, volatile VALUE)); 426 427static void 428setup_exception(rb_thread_t *th, int tag, volatile VALUE mesg) 429{ 430 VALUE at; 431 VALUE e; 432 const char *file; 433 volatile int line = 0; 434 435 if (NIL_P(mesg)) { 436 mesg = th->errinfo; 437 if (INTERNAL_EXCEPTION_P(mesg)) JUMP_TAG(TAG_FATAL); 438 } 439 if (NIL_P(mesg)) { 440 mesg = rb_exc_new(rb_eRuntimeError, 0, 0); 441 } 442 443 file = rb_sourcefile(); 444 if (file) line = rb_sourceline(); 445 if (file && !NIL_P(mesg)) { 446 if (mesg == sysstack_error) { 447 at = rb_enc_sprintf(rb_usascii_encoding(), "%s:%d", file, line); 448 at = rb_ary_new3(1, at); 449 rb_iv_set(mesg, "bt", at); 450 } 451 else { 452 at = get_backtrace(mesg); 453 if (NIL_P(at)) { 454 at = rb_vm_backtrace_object(); 455 if (OBJ_FROZEN(mesg)) { 456 mesg = rb_obj_dup(mesg); 457 } 458 set_backtrace(mesg, at); 459 } 460 } 461 } 462 if (!NIL_P(mesg)) { 463 th->errinfo = mesg; 464 } 465 466 if (RTEST(ruby_debug) && !NIL_P(e = th->errinfo) && 467 !rb_obj_is_kind_of(e, rb_eSystemExit)) { 468 int status; 469 470 mesg = e; 471 PUSH_TAG(); 472 if ((status = EXEC_TAG()) == 0) { 473 th->errinfo = Qnil; 474 e = rb_obj_as_string(mesg); 475 th->errinfo = mesg; 476 if (file && line) { 477 warn_printf("Exception `%"PRIsVALUE"' at %s:%d - %"PRIsVALUE"\n", 478 rb_obj_class(mesg), file, line, e); 479 } 480 else if (file) { 481 warn_printf("Exception `%"PRIsVALUE"' at %s - %"PRIsVALUE"\n", 482 rb_obj_class(mesg), file, e); 483 } 484 else { 485 warn_printf("Exception `%"PRIsVALUE"' - %"PRIsVALUE"\n", 486 rb_obj_class(mesg), e); 487 } 488 } 489 POP_TAG(); 490 if (status == TAG_FATAL && th->errinfo == exception_error) { 491 th->errinfo = mesg; 492 } 493 else if (status) { 494 rb_threadptr_reset_raised(th); 495 JUMP_TAG(status); 496 } 497 } 498 499 if (rb_threadptr_set_raised(th)) { 500 th->errinfo = exception_error; 501 rb_threadptr_reset_raised(th); 502 JUMP_TAG(TAG_FATAL); 503 } 504 505 if (tag != TAG_FATAL) { 506 if (RUBY_DTRACE_RAISE_ENABLED()) { 507 RUBY_DTRACE_RAISE(rb_obj_classname(th->errinfo), 508 rb_sourcefile(), 509 rb_sourceline()); 510 } 511 EXEC_EVENT_HOOK(th, RUBY_EVENT_RAISE, th->cfp->self, 0, 0, mesg); 512 } 513} 514 515static void 516rb_longjmp(int tag, volatile VALUE mesg) 517{ 518 rb_thread_t *th = GET_THREAD(); 519 setup_exception(th, tag, mesg); 520 rb_thread_raised_clear(th); 521 JUMP_TAG(tag); 522} 523 524static VALUE make_exception(int argc, VALUE *argv, int isstr); 525 526void 527rb_exc_raise(VALUE mesg) 528{ 529 if (!NIL_P(mesg)) { 530 mesg = make_exception(1, &mesg, FALSE); 531 } 532 rb_longjmp(TAG_RAISE, mesg); 533} 534 535void 536rb_exc_fatal(VALUE mesg) 537{ 538 if (!NIL_P(mesg)) { 539 mesg = make_exception(1, &mesg, FALSE); 540 } 541 rb_longjmp(TAG_FATAL, mesg); 542} 543 544void 545rb_interrupt(void) 546{ 547 rb_raise(rb_eInterrupt, "%s", ""); 548} 549 550static VALUE get_errinfo(void); 551 552/* 553 * call-seq: 554 * raise 555 * raise(string) 556 * raise(exception [, string [, array]]) 557 * fail 558 * fail(string) 559 * fail(exception [, string [, array]]) 560 * 561 * With no arguments, raises the exception in <code>$!</code> or raises 562 * a <code>RuntimeError</code> if <code>$!</code> is +nil+. 563 * With a single +String+ argument, raises a 564 * +RuntimeError+ with the string as a message. Otherwise, 565 * the first parameter should be the name of an +Exception+ 566 * class (or an object that returns an +Exception+ object when sent 567 * an +exception+ message). The optional second parameter sets the 568 * message associated with the exception, and the third parameter is an 569 * array of callback information. Exceptions are caught by the 570 * +rescue+ clause of <code>begin...end</code> blocks. 571 * 572 * raise "Failed to create socket" 573 * raise ArgumentError, "No parameters", caller 574 */ 575 576static VALUE 577rb_f_raise(int argc, VALUE *argv) 578{ 579 VALUE err; 580 if (argc == 0) { 581 err = get_errinfo(); 582 if (!NIL_P(err)) { 583 argc = 1; 584 argv = &err; 585 } 586 } 587 rb_raise_jump(rb_make_exception(argc, argv)); 588 589 UNREACHABLE; 590} 591 592static VALUE 593make_exception(int argc, VALUE *argv, int isstr) 594{ 595 VALUE mesg; 596 ID exception; 597 int n; 598 599 mesg = Qnil; 600 switch (argc) { 601 case 0: 602 break; 603 case 1: 604 if (NIL_P(argv[0])) 605 break; 606 if (isstr) { 607 mesg = rb_check_string_type(argv[0]); 608 if (!NIL_P(mesg)) { 609 mesg = rb_exc_new3(rb_eRuntimeError, mesg); 610 break; 611 } 612 } 613 n = 0; 614 goto exception_call; 615 616 case 2: 617 case 3: 618 n = 1; 619 exception_call: 620 if (argv[0] == sysstack_error) return argv[0]; 621 CONST_ID(exception, "exception"); 622 mesg = rb_check_funcall(argv[0], exception, n, argv+1); 623 if (mesg == Qundef) { 624 rb_raise(rb_eTypeError, "exception class/object expected"); 625 } 626 break; 627 default: 628 rb_check_arity(argc, 0, 3); 629 break; 630 } 631 if (argc > 0) { 632 if (!rb_obj_is_kind_of(mesg, rb_eException)) 633 rb_raise(rb_eTypeError, "exception object expected"); 634 if (argc > 2) 635 set_backtrace(mesg, argv[2]); 636 } 637 638 return mesg; 639} 640 641VALUE 642rb_make_exception(int argc, VALUE *argv) 643{ 644 return make_exception(argc, argv, TRUE); 645} 646 647void 648rb_raise_jump(VALUE mesg) 649{ 650 rb_thread_t *th = GET_THREAD(); 651 rb_control_frame_t *cfp = th->cfp; 652 VALUE klass = cfp->me->klass; 653 VALUE self = cfp->self; 654 ID mid = cfp->me->called_id; 655 656 th->cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(th->cfp); 657 658 setup_exception(th, TAG_RAISE, mesg); 659 660 EXEC_EVENT_HOOK(th, RUBY_EVENT_C_RETURN, self, mid, klass, Qnil); 661 rb_thread_raised_clear(th); 662 JUMP_TAG(TAG_RAISE); 663} 664 665void 666rb_jump_tag(int tag) 667{ 668 JUMP_TAG(tag); 669} 670 671int 672rb_block_given_p(void) 673{ 674 rb_thread_t *th = GET_THREAD(); 675 676 if (rb_vm_control_frame_block_ptr(th->cfp)) { 677 return TRUE; 678 } 679 else { 680 return FALSE; 681 } 682} 683 684int 685rb_iterator_p(void) 686{ 687 return rb_block_given_p(); 688} 689 690VALUE rb_eThreadError; 691 692void 693rb_need_block(void) 694{ 695 if (!rb_block_given_p()) { 696 rb_vm_localjump_error("no block given", Qnil, 0); 697 } 698} 699 700VALUE 701rb_rescue2(VALUE (* b_proc) (ANYARGS), VALUE data1, 702 VALUE (* r_proc) (ANYARGS), VALUE data2, ...) 703{ 704 int state; 705 rb_thread_t *th = GET_THREAD(); 706 rb_control_frame_t *cfp = th->cfp; 707 volatile VALUE result; 708 volatile VALUE e_info = th->errinfo; 709 va_list args; 710 711 TH_PUSH_TAG(th); 712 if ((state = TH_EXEC_TAG()) == 0) { 713 retry_entry: 714 result = (*b_proc) (data1); 715 } 716 else { 717 th->cfp = cfp; /* restore */ 718 719 if (state == TAG_RAISE) { 720 int handle = FALSE; 721 VALUE eclass; 722 723 va_init_list(args, data2); 724 while ((eclass = va_arg(args, VALUE)) != 0) { 725 if (rb_obj_is_kind_of(th->errinfo, eclass)) { 726 handle = TRUE; 727 break; 728 } 729 } 730 va_end(args); 731 732 if (handle) { 733 if (r_proc) { 734 PUSH_TAG(); 735 if ((state = EXEC_TAG()) == 0) { 736 result = (*r_proc) (data2, th->errinfo); 737 } 738 POP_TAG(); 739 if (state == TAG_RETRY) { 740 state = 0; 741 th->errinfo = Qnil; 742 goto retry_entry; 743 } 744 } 745 else { 746 result = Qnil; 747 state = 0; 748 } 749 if (state == 0) { 750 th->errinfo = e_info; 751 } 752 } 753 } 754 } 755 TH_POP_TAG(); 756 if (state) 757 JUMP_TAG(state); 758 759 return result; 760} 761 762VALUE 763rb_rescue(VALUE (* b_proc)(ANYARGS), VALUE data1, 764 VALUE (* r_proc)(ANYARGS), VALUE data2) 765{ 766 return rb_rescue2(b_proc, data1, r_proc, data2, rb_eStandardError, 767 (VALUE)0); 768} 769 770VALUE 771rb_protect(VALUE (* proc) (VALUE), VALUE data, int * state) 772{ 773 volatile VALUE result = Qnil; 774 int status; 775 rb_thread_t *th = GET_THREAD(); 776 rb_control_frame_t *cfp = th->cfp; 777 struct rb_vm_protect_tag protect_tag; 778 rb_jmpbuf_t org_jmpbuf; 779 780 protect_tag.prev = th->protect_tag; 781 782 TH_PUSH_TAG(th); 783 th->protect_tag = &protect_tag; 784 MEMCPY(&org_jmpbuf, &(th)->root_jmpbuf, rb_jmpbuf_t, 1); 785 if ((status = TH_EXEC_TAG()) == 0) { 786 SAVE_ROOT_JMPBUF(th, result = (*proc) (data)); 787 } 788 MEMCPY(&(th)->root_jmpbuf, &org_jmpbuf, rb_jmpbuf_t, 1); 789 th->protect_tag = protect_tag.prev; 790 TH_POP_TAG(); 791 792 if (state) { 793 *state = status; 794 } 795 if (status != 0) { 796 th->cfp = cfp; 797 return Qnil; 798 } 799 800 return result; 801} 802 803VALUE 804rb_ensure(VALUE (*b_proc)(ANYARGS), VALUE data1, VALUE (*e_proc)(ANYARGS), VALUE data2) 805{ 806 int state; 807 volatile VALUE result = Qnil; 808 volatile VALUE errinfo; 809 rb_thread_t *const th = GET_THREAD(); 810 811 PUSH_TAG(); 812 if ((state = EXEC_TAG()) == 0) { 813 result = (*b_proc) (data1); 814 } 815 POP_TAG(); 816 /* TODO: fix me */ 817 /* retval = prot_tag ? prot_tag->retval : Qnil; */ /* save retval */ 818 errinfo = th->errinfo; 819 (*e_proc) (data2); 820 th->errinfo = errinfo; 821 if (state) 822 JUMP_TAG(state); 823 return result; 824} 825 826static const rb_method_entry_t * 827method_entry_of_iseq(rb_control_frame_t *cfp, rb_iseq_t *iseq) 828{ 829 rb_thread_t *th = GET_THREAD(); 830 rb_control_frame_t *cfp_limit; 831 832 cfp_limit = (rb_control_frame_t *)(th->stack + th->stack_size); 833 while (cfp_limit > cfp) { 834 if (cfp->iseq == iseq) 835 return cfp->me; 836 cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp); 837 } 838 return 0; 839} 840 841static ID 842frame_func_id(rb_control_frame_t *cfp) 843{ 844 const rb_method_entry_t *me_local; 845 rb_iseq_t *iseq = cfp->iseq; 846 if (cfp->me) { 847 return cfp->me->def->original_id; 848 } 849 while (iseq) { 850 if (RUBY_VM_IFUNC_P(iseq)) { 851 NODE *ifunc = (NODE *)iseq; 852 if (ifunc->nd_aid) return ifunc->nd_aid; 853 return rb_intern("<ifunc>"); 854 } 855 me_local = method_entry_of_iseq(cfp, iseq); 856 if (me_local) { 857 cfp->me = me_local; 858 return me_local->def->original_id; 859 } 860 if (iseq->defined_method_id) { 861 return iseq->defined_method_id; 862 } 863 if (iseq->local_iseq == iseq) { 864 break; 865 } 866 iseq = iseq->parent_iseq; 867 } 868 return 0; 869} 870 871static ID 872frame_called_id(rb_control_frame_t *cfp) 873{ 874 const rb_method_entry_t *me_local; 875 rb_iseq_t *iseq = cfp->iseq; 876 if (cfp->me) { 877 return cfp->me->called_id; 878 } 879 while (iseq) { 880 if (RUBY_VM_IFUNC_P(iseq)) { 881 NODE *ifunc = (NODE *)iseq; 882 if (ifunc->nd_aid) return ifunc->nd_aid; 883 return rb_intern("<ifunc>"); 884 } 885 me_local = method_entry_of_iseq(cfp, iseq); 886 if (me_local) { 887 cfp->me = me_local; 888 return me_local->called_id; 889 } 890 if (iseq->defined_method_id) { 891 return iseq->defined_method_id; 892 } 893 if (iseq->local_iseq == iseq) { 894 break; 895 } 896 iseq = iseq->parent_iseq; 897 } 898 return 0; 899} 900 901ID 902rb_frame_this_func(void) 903{ 904 return frame_func_id(GET_THREAD()->cfp); 905} 906 907static rb_control_frame_t * 908previous_frame(rb_thread_t *th) 909{ 910 rb_control_frame_t *prev_cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(th->cfp); 911 /* check if prev_cfp can be accessible */ 912 if ((void *)(th->stack + th->stack_size) == (void *)(prev_cfp)) { 913 return 0; 914 } 915 return prev_cfp; 916} 917 918ID 919rb_frame_callee(void) 920{ 921 rb_control_frame_t *prev_cfp = previous_frame(GET_THREAD()); 922 if (!prev_cfp) return 0; 923 return frame_called_id(prev_cfp); 924} 925 926static ID 927rb_frame_caller(void) 928{ 929 rb_control_frame_t *prev_cfp = previous_frame(GET_THREAD()); 930 if (!prev_cfp) return 0; 931 return frame_func_id(prev_cfp); 932} 933 934void 935rb_frame_pop(void) 936{ 937 rb_thread_t *th = GET_THREAD(); 938 th->cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(th->cfp); 939} 940 941/* 942 * call-seq: 943 * append_features(mod) -> mod 944 * 945 * When this module is included in another, Ruby calls 946 * <code>append_features</code> in this module, passing it the 947 * receiving module in _mod_. Ruby's default implementation is 948 * to add the constants, methods, and module variables of this module 949 * to _mod_ if this module has not already been added to 950 * _mod_ or one of its ancestors. See also <code>Module#include</code>. 951 */ 952 953static VALUE 954rb_mod_append_features(VALUE module, VALUE include) 955{ 956 switch (TYPE(include)) { 957 case T_CLASS: 958 case T_MODULE: 959 break; 960 default: 961 Check_Type(include, T_CLASS); 962 break; 963 } 964 rb_include_module(include, module); 965 966 return module; 967} 968 969/* 970 * call-seq: 971 * include(module, ...) -> self 972 * 973 * Invokes <code>Module.append_features</code> on each parameter in reverse order. 974 */ 975 976static VALUE 977rb_mod_include(int argc, VALUE *argv, VALUE module) 978{ 979 int i; 980 ID id_append_features, id_included; 981 982 CONST_ID(id_append_features, "append_features"); 983 CONST_ID(id_included, "included"); 984 985 for (i = 0; i < argc; i++) 986 Check_Type(argv[i], T_MODULE); 987 while (argc--) { 988 rb_funcall(argv[argc], id_append_features, 1, module); 989 rb_funcall(argv[argc], id_included, 1, module); 990 } 991 return module; 992} 993 994/* 995 * call-seq: 996 * prepend_features(mod) -> mod 997 * 998 * When this module is prepended in another, Ruby calls 999 * <code>prepend_features</code> in this module, passing it the 1000 * receiving module in _mod_. Ruby's default implementation is 1001 * to overlay the constants, methods, and module variables of this module 1002 * to _mod_ if this module has not already been added to 1003 * _mod_ or one of its ancestors. See also <code>Module#prepend</code>. 1004 */ 1005 1006static VALUE 1007rb_mod_prepend_features(VALUE module, VALUE prepend) 1008{ 1009 switch (TYPE(prepend)) { 1010 case T_CLASS: 1011 case T_MODULE: 1012 break; 1013 default: 1014 Check_Type(prepend, T_CLASS); 1015 break; 1016 } 1017 rb_prepend_module(prepend, module); 1018 1019 return module; 1020} 1021 1022/* 1023 * call-seq: 1024 * prepend(module, ...) -> self 1025 * 1026 * Invokes <code>Module.prepend_features</code> on each parameter in reverse order. 1027 */ 1028 1029static VALUE 1030rb_mod_prepend(int argc, VALUE *argv, VALUE module) 1031{ 1032 int i; 1033 ID id_prepend_features, id_prepended; 1034 1035 CONST_ID(id_prepend_features, "prepend_features"); 1036 CONST_ID(id_prepended, "prepended"); 1037 for (i = 0; i < argc; i++) 1038 Check_Type(argv[i], T_MODULE); 1039 while (argc--) { 1040 rb_funcall(argv[argc], id_prepend_features, 1, module); 1041 rb_funcall(argv[argc], id_prepended, 1, module); 1042 } 1043 return module; 1044} 1045 1046static void 1047warn_refinements_once() 1048{ 1049 static int warned = 0; 1050 1051 if (warned) 1052 return; 1053 rb_warn("Refinements are experimental, and the behavior may change in future versions of Ruby!"); 1054 warned = 1; 1055} 1056 1057static VALUE 1058hidden_identity_hash_new() 1059{ 1060 VALUE hash = rb_hash_new(); 1061 1062 rb_funcall(hash, rb_intern("compare_by_identity"), 0); 1063 RBASIC(hash)->klass = 0; /* hide from ObjectSpace */ 1064 return hash; 1065} 1066 1067void 1068rb_using_refinement(NODE *cref, VALUE klass, VALUE module) 1069{ 1070 VALUE iclass, c, superclass = klass; 1071 1072 Check_Type(klass, T_CLASS); 1073 Check_Type(module, T_MODULE); 1074 if (NIL_P(cref->nd_refinements)) { 1075 cref->nd_refinements = hidden_identity_hash_new(); 1076 } 1077 else { 1078 if (cref->flags & NODE_FL_CREF_OMOD_SHARED) { 1079 cref->nd_refinements = rb_hash_dup(cref->nd_refinements); 1080 cref->flags &= ~NODE_FL_CREF_OMOD_SHARED; 1081 } 1082 if (!NIL_P(c = rb_hash_lookup(cref->nd_refinements, klass))) { 1083 superclass = c; 1084 while (c && RB_TYPE_P(c, T_ICLASS)) { 1085 if (RBASIC(c)->klass == module) { 1086 /* already used refinement */ 1087 return; 1088 } 1089 c = RCLASS_SUPER(c); 1090 } 1091 } 1092 } 1093 FL_SET(module, RMODULE_IS_OVERLAID); 1094 c = iclass = rb_include_class_new(module, superclass); 1095 RCLASS_REFINED_CLASS(c) = klass; 1096 RCLASS_M_TBL(c) = RCLASS_M_TBL(module); 1097 module = RCLASS_SUPER(module); 1098 while (module && module != klass) { 1099 FL_SET(module, RMODULE_IS_OVERLAID); 1100 c = RCLASS_SUPER(c) = rb_include_class_new(module, RCLASS_SUPER(c)); 1101 RCLASS_REFINED_CLASS(c) = klass; 1102 module = RCLASS_SUPER(module); 1103 } 1104 rb_hash_aset(cref->nd_refinements, klass, iclass); 1105} 1106 1107static int 1108using_refinement(VALUE klass, VALUE module, VALUE arg) 1109{ 1110 NODE *cref = (NODE *) arg; 1111 1112 rb_using_refinement(cref, klass, module); 1113 return ST_CONTINUE; 1114} 1115 1116void 1117rb_using_module(NODE *cref, VALUE module) 1118{ 1119 ID id_refinements; 1120 VALUE refinements; 1121 1122 Check_Type(module, T_MODULE); 1123 CONST_ID(id_refinements, "__refinements__"); 1124 refinements = rb_attr_get(module, id_refinements); 1125 if (NIL_P(refinements)) return; 1126 rb_hash_foreach(refinements, using_refinement, (VALUE) cref); 1127} 1128 1129VALUE rb_refinement_module_get_refined_class(VALUE module) 1130{ 1131 ID id_refined_class; 1132 1133 CONST_ID(id_refined_class, "__refined_class__"); 1134 return rb_attr_get(module, id_refined_class); 1135} 1136 1137static void 1138add_activated_refinement(VALUE activated_refinements, 1139 VALUE klass, VALUE refinement) 1140{ 1141 VALUE iclass, c, superclass = klass; 1142 1143 if (!NIL_P(c = rb_hash_lookup(activated_refinements, klass))) { 1144 superclass = c; 1145 while (c && RB_TYPE_P(c, T_ICLASS)) { 1146 if (RBASIC(c)->klass == refinement) { 1147 /* already used refinement */ 1148 return; 1149 } 1150 c = RCLASS_SUPER(c); 1151 } 1152 } 1153 FL_SET(refinement, RMODULE_IS_OVERLAID); 1154 c = iclass = rb_include_class_new(refinement, superclass); 1155 RCLASS_REFINED_CLASS(c) = klass; 1156 refinement = RCLASS_SUPER(refinement); 1157 while (refinement) { 1158 FL_SET(refinement, RMODULE_IS_OVERLAID); 1159 c = RCLASS_SUPER(c) = 1160 rb_include_class_new(refinement, RCLASS_SUPER(c)); 1161 RCLASS_REFINED_CLASS(c) = klass; 1162 refinement = RCLASS_SUPER(refinement); 1163 } 1164 rb_hash_aset(activated_refinements, klass, iclass); 1165} 1166 1167VALUE rb_yield_refine_block(VALUE refinement, VALUE refinements); 1168 1169/* 1170 * call-seq: 1171 * refine(klass) { block } -> module 1172 * 1173 * Refine <i>klass</i> in the receiver. 1174 * 1175 * Returns an overlaid module. 1176 */ 1177 1178static VALUE 1179rb_mod_refine(VALUE module, VALUE klass) 1180{ 1181 VALUE refinement; 1182 ID id_refinements, id_activated_refinements, 1183 id_refined_class, id_defined_at; 1184 VALUE refinements, activated_refinements; 1185 rb_thread_t *th = GET_THREAD(); 1186 rb_block_t *block = rb_vm_control_frame_block_ptr(th->cfp); 1187 1188 warn_refinements_once(); 1189 if (!block) { 1190 rb_raise(rb_eArgError, "no block given"); 1191 } 1192 if (block->proc) { 1193 rb_raise(rb_eArgError, 1194 "can't pass a Proc as a block to Module#refine"); 1195 } 1196 Check_Type(klass, T_CLASS); 1197 CONST_ID(id_refinements, "__refinements__"); 1198 refinements = rb_attr_get(module, id_refinements); 1199 if (NIL_P(refinements)) { 1200 refinements = hidden_identity_hash_new(); 1201 rb_ivar_set(module, id_refinements, refinements); 1202 } 1203 CONST_ID(id_activated_refinements, "__activated_refinements__"); 1204 activated_refinements = rb_attr_get(module, id_activated_refinements); 1205 if (NIL_P(activated_refinements)) { 1206 activated_refinements = hidden_identity_hash_new(); 1207 rb_ivar_set(module, id_activated_refinements, 1208 activated_refinements); 1209 } 1210 refinement = rb_hash_lookup(refinements, klass); 1211 if (NIL_P(refinement)) { 1212 refinement = rb_module_new(); 1213 RCLASS_SUPER(refinement) = klass; 1214 FL_SET(refinement, RMODULE_IS_REFINEMENT); 1215 CONST_ID(id_refined_class, "__refined_class__"); 1216 rb_ivar_set(refinement, id_refined_class, klass); 1217 CONST_ID(id_defined_at, "__defined_at__"); 1218 rb_ivar_set(refinement, id_defined_at, module); 1219 rb_hash_aset(refinements, klass, refinement); 1220 add_activated_refinement(activated_refinements, klass, refinement); 1221 } 1222 rb_yield_refine_block(refinement, activated_refinements); 1223 return refinement; 1224} 1225 1226void 1227rb_obj_call_init(VALUE obj, int argc, VALUE *argv) 1228{ 1229 PASS_PASSED_BLOCK(); 1230 rb_funcall2(obj, idInitialize, argc, argv); 1231} 1232 1233void 1234rb_extend_object(VALUE obj, VALUE module) 1235{ 1236 rb_include_module(rb_singleton_class(obj), module); 1237} 1238 1239/* 1240 * call-seq: 1241 * extend_object(obj) -> obj 1242 * 1243 * Extends the specified object by adding this module's constants and 1244 * methods (which are added as singleton methods). This is the callback 1245 * method used by <code>Object#extend</code>. 1246 * 1247 * module Picky 1248 * def Picky.extend_object(o) 1249 * if String === o 1250 * puts "Can't add Picky to a String" 1251 * else 1252 * puts "Picky added to #{o.class}" 1253 * super 1254 * end 1255 * end 1256 * end 1257 * (s = Array.new).extend Picky # Call Object.extend 1258 * (s = "quick brown fox").extend Picky 1259 * 1260 * <em>produces:</em> 1261 * 1262 * Picky added to Array 1263 * Can't add Picky to a String 1264 */ 1265 1266static VALUE 1267rb_mod_extend_object(VALUE mod, VALUE obj) 1268{ 1269 rb_extend_object(obj, mod); 1270 return obj; 1271} 1272 1273/* 1274 * call-seq: 1275 * obj.extend(module, ...) -> obj 1276 * 1277 * Adds to _obj_ the instance methods from each module given as a 1278 * parameter. 1279 * 1280 * module Mod 1281 * def hello 1282 * "Hello from Mod.\n" 1283 * end 1284 * end 1285 * 1286 * class Klass 1287 * def hello 1288 * "Hello from Klass.\n" 1289 * end 1290 * end 1291 * 1292 * k = Klass.new 1293 * k.hello #=> "Hello from Klass.\n" 1294 * k.extend(Mod) #=> #<Klass:0x401b3bc8> 1295 * k.hello #=> "Hello from Mod.\n" 1296 */ 1297 1298static VALUE 1299rb_obj_extend(int argc, VALUE *argv, VALUE obj) 1300{ 1301 int i; 1302 ID id_extend_object, id_extended; 1303 1304 CONST_ID(id_extend_object, "extend_object"); 1305 CONST_ID(id_extended, "extended"); 1306 1307 rb_check_arity(argc, 1, UNLIMITED_ARGUMENTS); 1308 for (i = 0; i < argc; i++) 1309 Check_Type(argv[i], T_MODULE); 1310 while (argc--) { 1311 rb_funcall(argv[argc], id_extend_object, 1, obj); 1312 rb_funcall(argv[argc], id_extended, 1, obj); 1313 } 1314 return obj; 1315} 1316 1317/* 1318 * call-seq: 1319 * include(module, ...) -> self 1320 * 1321 * Invokes <code>Module.append_features</code> 1322 * on each parameter in turn. Effectively adds the methods and constants 1323 * in each module to the receiver. 1324 */ 1325 1326static VALUE 1327top_include(int argc, VALUE *argv, VALUE self) 1328{ 1329 rb_thread_t *th = GET_THREAD(); 1330 1331 rb_secure(4); 1332 if (th->top_wrapper) { 1333 rb_warning("main.include in the wrapped load is effective only in wrapper module"); 1334 return rb_mod_include(argc, argv, th->top_wrapper); 1335 } 1336 return rb_mod_include(argc, argv, rb_cObject); 1337} 1338 1339/* 1340 * call-seq: 1341 * using(module) -> self 1342 * 1343 * Import class refinements from <i>module</i> into the scope where 1344 * <code>using</code> is called. 1345 */ 1346 1347static VALUE 1348top_using(VALUE self, VALUE module) 1349{ 1350 NODE *cref = rb_vm_cref(); 1351 rb_control_frame_t *prev_cfp = previous_frame(GET_THREAD()); 1352 1353 warn_refinements_once(); 1354 if (cref->nd_next || (prev_cfp && prev_cfp->me)) { 1355 rb_raise(rb_eRuntimeError, "using is permitted only at toplevel"); 1356 } 1357 Check_Type(module, T_MODULE); 1358 rb_using_module(cref, module); 1359 rb_clear_cache(); 1360 return self; 1361} 1362 1363static VALUE * 1364errinfo_place(rb_thread_t *th) 1365{ 1366 rb_control_frame_t *cfp = th->cfp; 1367 rb_control_frame_t *end_cfp = RUBY_VM_END_CONTROL_FRAME(th); 1368 1369 while (RUBY_VM_VALID_CONTROL_FRAME_P(cfp, end_cfp)) { 1370 if (RUBY_VM_NORMAL_ISEQ_P(cfp->iseq)) { 1371 if (cfp->iseq->type == ISEQ_TYPE_RESCUE) { 1372 return &cfp->ep[-2]; 1373 } 1374 else if (cfp->iseq->type == ISEQ_TYPE_ENSURE && 1375 !RB_TYPE_P(cfp->ep[-2], T_NODE) && 1376 !FIXNUM_P(cfp->ep[-2])) { 1377 return &cfp->ep[-2]; 1378 } 1379 } 1380 cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp); 1381 } 1382 return 0; 1383} 1384 1385static VALUE 1386get_thread_errinfo(rb_thread_t *th) 1387{ 1388 VALUE *ptr = errinfo_place(th); 1389 if (ptr) { 1390 return *ptr; 1391 } 1392 else { 1393 return th->errinfo; 1394 } 1395} 1396 1397static VALUE 1398get_errinfo(void) 1399{ 1400 return get_thread_errinfo(GET_THREAD()); 1401} 1402 1403static VALUE 1404errinfo_getter(ID id) 1405{ 1406 return get_errinfo(); 1407} 1408 1409#if 0 1410static void 1411errinfo_setter(VALUE val, ID id, VALUE *var) 1412{ 1413 if (!NIL_P(val) && !rb_obj_is_kind_of(val, rb_eException)) { 1414 rb_raise(rb_eTypeError, "assigning non-exception to $!"); 1415 } 1416 else { 1417 VALUE *ptr = errinfo_place(GET_THREAD()); 1418 if (ptr) { 1419 *ptr = val; 1420 } 1421 else { 1422 rb_raise(rb_eRuntimeError, "errinfo_setter: not in rescue clause."); 1423 } 1424 } 1425} 1426#endif 1427 1428VALUE 1429rb_errinfo(void) 1430{ 1431 rb_thread_t *th = GET_THREAD(); 1432 return th->errinfo; 1433} 1434 1435void 1436rb_set_errinfo(VALUE err) 1437{ 1438 if (!NIL_P(err) && !rb_obj_is_kind_of(err, rb_eException)) { 1439 rb_raise(rb_eTypeError, "assigning non-exception to $!"); 1440 } 1441 GET_THREAD()->errinfo = err; 1442} 1443 1444VALUE 1445rb_rubylevel_errinfo(void) 1446{ 1447 return get_errinfo(); 1448} 1449 1450static VALUE 1451errat_getter(ID id) 1452{ 1453 VALUE err = get_errinfo(); 1454 if (!NIL_P(err)) { 1455 return get_backtrace(err); 1456 } 1457 else { 1458 return Qnil; 1459 } 1460} 1461 1462static void 1463errat_setter(VALUE val, ID id, VALUE *var) 1464{ 1465 VALUE err = get_errinfo(); 1466 if (NIL_P(err)) { 1467 rb_raise(rb_eArgError, "$! not set"); 1468 } 1469 set_backtrace(err, val); 1470} 1471 1472/* 1473 * call-seq: 1474 * __method__ -> symbol 1475 * __callee__ -> symbol 1476 * 1477 * Returns the name of the current method as a Symbol. 1478 * If called outside of a method, it returns <code>nil</code>. 1479 * 1480 */ 1481 1482static VALUE 1483rb_f_method_name(void) 1484{ 1485 ID fname = rb_frame_caller(); /* need *caller* ID */ 1486 1487 if (fname) { 1488 return ID2SYM(fname); 1489 } 1490 else { 1491 return Qnil; 1492 } 1493} 1494 1495static VALUE 1496rb_f_callee_name(void) 1497{ 1498 ID fname = rb_frame_callee(); /* need *callee* ID */ 1499 1500 if (fname) { 1501 return ID2SYM(fname); 1502 } 1503 else { 1504 return Qnil; 1505 } 1506} 1507 1508/* 1509 * call-seq: 1510 * __dir__ -> string 1511 * 1512 * Returns the canonicalized absolute path of the directory of the file from 1513 * which this method is called. It means symlinks in the path is resolved. 1514 * If <code>__FILE__</code> is <code>nil</code>, it returns <code>nil</code>. 1515 * The return value equals to <code>File.dirname(File.realpath(__FILE__))</code>. 1516 * 1517 */ 1518static VALUE 1519f_current_dirname(void) 1520{ 1521 VALUE base = rb_current_realfilepath(); 1522 if (NIL_P(base)) { 1523 return Qnil; 1524 } 1525 base = rb_file_dirname(base); 1526 return base; 1527} 1528 1529void 1530Init_eval(void) 1531{ 1532 rb_define_virtual_variable("$@", errat_getter, errat_setter); 1533 rb_define_virtual_variable("$!", errinfo_getter, 0); 1534 1535 rb_define_global_function("raise", rb_f_raise, -1); 1536 rb_define_global_function("fail", rb_f_raise, -1); 1537 1538 rb_define_global_function("global_variables", rb_f_global_variables, 0); /* in variable.c */ 1539 1540 rb_define_global_function("__method__", rb_f_method_name, 0); 1541 rb_define_global_function("__callee__", rb_f_callee_name, 0); 1542 rb_define_global_function("__dir__", f_current_dirname, 0); 1543 1544 rb_define_private_method(rb_cModule, "append_features", rb_mod_append_features, 1); 1545 rb_define_private_method(rb_cModule, "extend_object", rb_mod_extend_object, 1); 1546 rb_define_private_method(rb_cModule, "include", rb_mod_include, -1); 1547 rb_define_private_method(rb_cModule, "prepend_features", rb_mod_prepend_features, 1); 1548 rb_define_private_method(rb_cModule, "prepend", rb_mod_prepend, -1); 1549 rb_define_private_method(rb_cModule, "refine", rb_mod_refine, 1); 1550 rb_undef_method(rb_cClass, "refine"); 1551 1552 rb_undef_method(rb_cClass, "module_function"); 1553 1554 Init_vm_eval(); 1555 Init_eval_method(); 1556 1557 rb_define_singleton_method(rb_cModule, "nesting", rb_mod_nesting, 0); 1558 rb_define_singleton_method(rb_cModule, "constants", rb_mod_s_constants, -1); 1559 1560 rb_define_private_method(rb_singleton_class(rb_vm_top_self()), 1561 "include", top_include, -1); 1562 rb_define_private_method(rb_singleton_class(rb_vm_top_self()), 1563 "using", top_using, 1); 1564 1565 rb_define_method(rb_mKernel, "extend", rb_obj_extend, -1); 1566 1567 rb_define_global_function("trace_var", rb_f_trace_var, -1); /* in variable.c */ 1568 rb_define_global_function("untrace_var", rb_f_untrace_var, -1); /* in variable.c */ 1569 1570 exception_error = rb_exc_new3(rb_eFatal, 1571 rb_obj_freeze(rb_str_new2("exception reentered"))); 1572 OBJ_TAINT(exception_error); 1573 OBJ_FREEZE(exception_error); 1574} 1575