1 /**********************************************************************
2 
3   eval.c -
4 
5   $Author: usa $
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 "internal.h"
15 #include "eval_intern.h"
16 #include "iseq.h"
17 #include "gc.h"
18 #include "ruby/vm.h"
19 #include "vm_core.h"
20 #include "mjit.h"
21 #include "probes.h"
22 #include "probes_helper.h"
23 #ifdef HAVE_SYS_PRCTL_H
24 #include <sys/prctl.h>
25 #endif
26 
27 NORETURN(void rb_raise_jump(VALUE, VALUE));
28 
29 VALUE rb_eLocalJumpError;
30 VALUE rb_eSysStackError;
31 
32 ID ruby_static_id_signo, ruby_static_id_status;
33 extern ID ruby_static_id_cause;
34 #define id_cause ruby_static_id_cause
35 
36 #define exception_error GET_VM()->special_exceptions[ruby_error_reenter]
37 
38 #include "eval_error.c"
39 #include "eval_jump.c"
40 
41 #define CLASS_OR_MODULE_P(obj) \
42     (!SPECIAL_CONST_P(obj) && \
43      (BUILTIN_TYPE(obj) == T_CLASS || BUILTIN_TYPE(obj) == T_MODULE))
44 
45 /*!
46  * Initializes the Ruby VM and builtin libraries.
47  * @retval 0 if succeeded.
48  * @retval non-zero an error occurred.
49  */
50 int
ruby_setup(void)51 ruby_setup(void)
52 {
53     enum ruby_tag_type state;
54 
55     if (GET_VM())
56 	return 0;
57 
58     ruby_init_stack((void *)&state);
59 
60     /*
61      * Disable THP early before mallocs happen because we want this to
62      * affect as many future pages as possible for CoW-friendliness
63      */
64 #if defined(__linux__) && defined(PR_SET_THP_DISABLE)
65     prctl(PR_SET_THP_DISABLE, 1, 0, 0, 0);
66 #endif
67     Init_BareVM();
68     Init_heap();
69     rb_vm_encoded_insn_data_table_init();
70     Init_vm_objects();
71 
72     EC_PUSH_TAG(GET_EC());
73     if ((state = EC_EXEC_TAG()) == TAG_NONE) {
74 	rb_call_inits();
75 	ruby_prog_init();
76 	GET_VM()->running = 1;
77     }
78     EC_POP_TAG();
79 
80     return state;
81 }
82 
83 /*!
84  * Calls ruby_setup() and check error.
85  *
86  * Prints errors and calls exit(3) if an error occurred.
87  */
88 void
ruby_init(void)89 ruby_init(void)
90 {
91     int state = ruby_setup();
92     if (state) {
93         if (RTEST(ruby_debug))
94             error_print(GET_EC());
95 	exit(EXIT_FAILURE);
96     }
97 }
98 
99 /*! Processes command line arguments and compiles the Ruby source to execute.
100  *
101  * This function does:
102  * \li Processes the given command line flags and arguments for ruby(1)
103  * \li compiles the source code from the given argument, -e or stdin, and
104  * \li returns the compiled source as an opaque pointer to an internal data structure
105  *
106  * @return an opaque pointer to the compiled source or an internal special value.
107  * @sa ruby_executable_node().
108  */
109 void *
ruby_options(int argc,char ** argv)110 ruby_options(int argc, char **argv)
111 {
112     enum ruby_tag_type state;
113     void *volatile iseq = 0;
114 
115     ruby_init_stack((void *)&iseq);
116     EC_PUSH_TAG(GET_EC());
117     if ((state = EC_EXEC_TAG()) == TAG_NONE) {
118 	SAVE_ROOT_JMPBUF(GET_THREAD(), iseq = ruby_process_options(argc, argv));
119     }
120     else {
121 	rb_clear_trace_func();
122 	state = error_handle(state);
123 	iseq = (void *)INT2FIX(state);
124     }
125     EC_POP_TAG();
126     return iseq;
127 }
128 
129 static void
ruby_finalize_0(void)130 ruby_finalize_0(void)
131 {
132     EC_PUSH_TAG(GET_EC());
133     if (EC_EXEC_TAG() == TAG_NONE) {
134 	rb_trap_exit();
135     }
136     EC_POP_TAG();
137     rb_exec_end_proc();
138     rb_clear_trace_func();
139 }
140 
141 static void
ruby_finalize_1(void)142 ruby_finalize_1(void)
143 {
144     ruby_sig_finalize();
145     GET_EC()->errinfo = Qnil;
146     rb_gc_call_finalizer_at_exit();
147 }
148 
149 /** Runs the VM finalization processes.
150  *
151  * <code>END{}</code> and procs registered by <code>Kernel.#at_exit</code> are
152  * executed here. See the Ruby language spec for more details.
153  *
154  * @note This function is allowed to raise an exception if an error occurred.
155  */
156 void
ruby_finalize(void)157 ruby_finalize(void)
158 {
159     ruby_finalize_0();
160     ruby_finalize_1();
161 }
162 
163 /** Destructs the VM.
164  *
165  * Runs the VM finalization processes as well as ruby_finalize(), and frees
166  * resources used by the VM.
167  *
168  * @param ex Default value to the return value.
169  * @return If an error occurred returns a non-zero. If otherwise, returns the
170  *         given ex.
171  * @note This function does not raise any exception.
172  */
173 int
ruby_cleanup(volatile int ex)174 ruby_cleanup(volatile int ex)
175 {
176     int state;
177     volatile VALUE errs[2];
178     rb_thread_t *th = GET_THREAD();
179     int nerr;
180     volatile int sysex = EXIT_SUCCESS;
181     volatile int step = 0;
182 
183     rb_threadptr_interrupt(th);
184     rb_threadptr_check_signal(th);
185     EC_PUSH_TAG(th->ec);
186     if ((state = EC_EXEC_TAG()) == TAG_NONE) {
187 	SAVE_ROOT_JMPBUF(th, { RUBY_VM_CHECK_INTS(th->ec); });
188 
189       step_0: step++;
190 	errs[1] = th->ec->errinfo;
191         if (THROW_DATA_P(th->ec->errinfo)) th->ec->errinfo = Qnil;
192 	rb_set_safe_level_force(0);
193 	ruby_init_stack(&errs[STACK_UPPER(errs, 0, 1)]);
194 
195 	SAVE_ROOT_JMPBUF(th, ruby_finalize_0());
196 
197       step_1: step++;
198 	/* protect from Thread#raise */
199 	th->status = THREAD_KILLED;
200 
201 	errs[0] = th->ec->errinfo;
202 	SAVE_ROOT_JMPBUF(th, rb_thread_terminate_all());
203     }
204     else {
205 	switch (step) {
206 	  case 0: goto step_0;
207 	  case 1: goto step_1;
208 	}
209 	if (ex == 0) ex = state;
210     }
211     th->ec->errinfo = errs[1];
212     sysex = error_handle(ex);
213 
214     state = 0;
215     for (nerr = 0; nerr < numberof(errs); ++nerr) {
216 	VALUE err = ATOMIC_VALUE_EXCHANGE(errs[nerr], Qnil);
217 
218 	if (!RTEST(err)) continue;
219 
220 	/* th->ec->errinfo contains a NODE while break'ing */
221 	if (THROW_DATA_P(err)) continue;
222 
223 	if (rb_obj_is_kind_of(err, rb_eSystemExit)) {
224 	    sysex = sysexit_status(err);
225 	    break;
226 	}
227 	else if (rb_obj_is_kind_of(err, rb_eSignal)) {
228 	    VALUE sig = rb_ivar_get(err, id_signo);
229 	    state = NUM2INT(sig);
230 	    break;
231 	}
232 	else if (sysex == EXIT_SUCCESS) {
233 	    sysex = EXIT_FAILURE;
234 	}
235     }
236 
237     mjit_finish(TRUE); /* We still need ISeqs here. */
238 
239     ruby_finalize_1();
240 
241     /* unlock again if finalizer took mutexes. */
242     rb_threadptr_unlock_all_locking_mutexes(GET_THREAD());
243     EC_POP_TAG();
244     rb_thread_stop_timer_thread();
245     ruby_vm_destruct(GET_VM());
246     if (state) ruby_default_signal(state);
247 
248     return sysex;
249 }
250 
251 static int
ruby_exec_internal(void * n)252 ruby_exec_internal(void *n)
253 {
254     volatile int state;
255     rb_iseq_t *iseq = (rb_iseq_t *)n;
256     rb_thread_t * volatile th = GET_THREAD();
257 
258     if (!n) return 0;
259 
260     EC_PUSH_TAG(th->ec);
261     if ((state = EC_EXEC_TAG()) == TAG_NONE) {
262 	SAVE_ROOT_JMPBUF(th, {
263 	    rb_iseq_eval_main(iseq);
264 	});
265     }
266     EC_POP_TAG();
267     return state;
268 }
269 
270 /*! Calls ruby_cleanup() and exits the process */
271 void
ruby_stop(int ex)272 ruby_stop(int ex)
273 {
274     exit(ruby_cleanup(ex));
275 }
276 
277 /*! Checks the return value of ruby_options().
278  * @param n return value of ruby_options().
279  * @param status pointer to the exit status of this process.
280  *
281  * ruby_options() sometimes returns a special value to indicate this process
282  * should immediately exit. This function checks if the case. Also stores the
283  * exit status that the caller have to pass to exit(3) into
284  * <code>*status</code>.
285  *
286  * @retval non-zero if the given opaque pointer is actually a compiled source.
287  * @retval 0 if the given value is such a special value.
288  */
289 int
ruby_executable_node(void * n,int * status)290 ruby_executable_node(void *n, int *status)
291 {
292     VALUE v = (VALUE)n;
293     int s;
294 
295     switch (v) {
296       case Qtrue:  s = EXIT_SUCCESS; break;
297       case Qfalse: s = EXIT_FAILURE; break;
298       default:
299 	if (!FIXNUM_P(v)) return TRUE;
300 	s = FIX2INT(v);
301     }
302     if (status) *status = s;
303     return FALSE;
304 }
305 
306 /*! Runs the given compiled source and exits this process.
307  * @retval 0 if successfully run the source
308  * @retval non-zero if an error occurred.
309 */
310 int
ruby_run_node(void * n)311 ruby_run_node(void *n)
312 {
313     int status;
314     if (!ruby_executable_node(n, &status)) {
315 	ruby_cleanup(0);
316 	return status;
317     }
318     return ruby_cleanup(ruby_exec_node(n));
319 }
320 
321 /*! Runs the given compiled source */
322 int
ruby_exec_node(void * n)323 ruby_exec_node(void *n)
324 {
325     ruby_init_stack((void *)&n);
326     return ruby_exec_internal(n);
327 }
328 
329 /*
330  *  call-seq:
331  *     Module.nesting    -> array
332  *
333  *  Returns the list of +Modules+ nested at the point of call.
334  *
335  *     module M1
336  *       module M2
337  *         $a = Module.nesting
338  *       end
339  *     end
340  *     $a           #=> [M1::M2, M1]
341  *     $a[0].name   #=> "M1::M2"
342  */
343 
344 static VALUE
rb_mod_nesting(void)345 rb_mod_nesting(void)
346 {
347     VALUE ary = rb_ary_new();
348     const rb_cref_t *cref = rb_vm_cref();
349 
350     while (cref && CREF_NEXT(cref)) {
351 	VALUE klass = CREF_CLASS(cref);
352 	if (!CREF_PUSHED_BY_EVAL(cref) &&
353 	    !NIL_P(klass)) {
354 	    rb_ary_push(ary, klass);
355 	}
356 	cref = CREF_NEXT(cref);
357     }
358     return ary;
359 }
360 
361 /*
362  *  call-seq:
363  *     Module.constants   -> array
364  *     Module.constants(inherited)   -> array
365  *
366  *  In the first form, returns an array of the names of all
367  *  constants accessible from the point of call.
368  *  This list includes the names of all modules and classes
369  *  defined in the global scope.
370  *
371  *     Module.constants.first(4)
372  *        # => [:ARGF, :ARGV, :ArgumentError, :Array]
373  *
374  *     Module.constants.include?(:SEEK_SET)   # => false
375  *
376  *     class IO
377  *       Module.constants.include?(:SEEK_SET) # => true
378  *     end
379  *
380  *  The second form calls the instance method +constants+.
381  */
382 
383 static VALUE
rb_mod_s_constants(int argc,VALUE * argv,VALUE mod)384 rb_mod_s_constants(int argc, VALUE *argv, VALUE mod)
385 {
386     const rb_cref_t *cref = rb_vm_cref();
387     VALUE klass;
388     VALUE cbase = 0;
389     void *data = 0;
390 
391     if (argc > 0 || mod != rb_cModule) {
392 	return rb_mod_constants(argc, argv, mod);
393     }
394 
395     while (cref) {
396 	klass = CREF_CLASS(cref);
397 	if (!CREF_PUSHED_BY_EVAL(cref) &&
398 	    !NIL_P(klass)) {
399 	    data = rb_mod_const_at(CREF_CLASS(cref), data);
400 	    if (!cbase) {
401 		cbase = klass;
402 	    }
403 	}
404 	cref = CREF_NEXT(cref);
405     }
406 
407     if (cbase) {
408 	data = rb_mod_const_of(cbase, data);
409     }
410     return rb_const_list(data);
411 }
412 
413 /*!
414  * Asserts that \a klass is not a frozen class.
415  * \param[in] klass a \c Module object
416  * \exception RuntimeError if \a klass is not a class or frozen.
417  * \ingroup class
418  */
419 void
rb_class_modify_check(VALUE klass)420 rb_class_modify_check(VALUE klass)
421 {
422     if (SPECIAL_CONST_P(klass)) {
423       noclass:
424 	Check_Type(klass, T_CLASS);
425     }
426     if (OBJ_FROZEN(klass)) {
427 	const char *desc;
428 
429 	if (FL_TEST(klass, FL_SINGLETON)) {
430 	    desc = "object";
431 	    klass = rb_ivar_get(klass, id__attached__);
432 	    if (!SPECIAL_CONST_P(klass)) {
433 		switch (BUILTIN_TYPE(klass)) {
434 		  case T_MODULE:
435 		  case T_ICLASS:
436 		    desc = "Module";
437 		    break;
438 		  case T_CLASS:
439 		    desc = "Class";
440 		    break;
441 		}
442 	    }
443 	}
444 	else {
445 	    switch (BUILTIN_TYPE(klass)) {
446 	      case T_MODULE:
447 	      case T_ICLASS:
448 		desc = "module";
449 		break;
450 	      case T_CLASS:
451 		desc = "class";
452 		break;
453 	      default:
454 		goto noclass;
455 	    }
456 	}
457 	rb_error_frozen(desc);
458     }
459 }
460 
461 NORETURN(static void rb_longjmp(rb_execution_context_t *, int, volatile VALUE, VALUE));
462 static VALUE get_errinfo(void);
463 static VALUE get_ec_errinfo(const rb_execution_context_t *ec);
464 
465 static VALUE
exc_setup_cause(VALUE exc,VALUE cause)466 exc_setup_cause(VALUE exc, VALUE cause)
467 {
468 #if SUPPORT_JOKE
469     if (NIL_P(cause)) {
470 	ID id_true_cause;
471 	CONST_ID(id_true_cause, "true_cause");
472 
473 	cause = rb_attr_get(rb_eFatal, id_true_cause);
474 	if (NIL_P(cause)) {
475 	    cause = rb_exc_new_cstr(rb_eFatal, "because using such Ruby");
476 	    rb_ivar_set(cause, id_cause, INT2FIX(42)); /* the answer */
477 	    OBJ_FREEZE(cause);
478 	    rb_ivar_set(rb_eFatal, id_true_cause, cause);
479 	}
480     }
481 #endif
482     if (!NIL_P(cause) && cause != exc) {
483 	rb_ivar_set(exc, id_cause, cause);
484 	if (!rb_ivar_defined(cause, id_cause)) {
485 	    rb_ivar_set(cause, id_cause, Qnil);
486 	}
487     }
488     return exc;
489 }
490 
491 static inline VALUE
exc_setup_message(const rb_execution_context_t * ec,VALUE mesg,VALUE * cause)492 exc_setup_message(const rb_execution_context_t *ec, VALUE mesg, VALUE *cause)
493 {
494     int nocause = 0;
495     int nocircular = 0;
496 
497     if (NIL_P(mesg)) {
498 	mesg = ec->errinfo;
499 	if (INTERNAL_EXCEPTION_P(mesg)) EC_JUMP_TAG(ec, TAG_FATAL);
500 	nocause = 1;
501     }
502     if (NIL_P(mesg)) {
503 	mesg = rb_exc_new(rb_eRuntimeError, 0, 0);
504 	nocause = 0;
505         nocircular = 1;
506     }
507     if (*cause == Qundef) {
508 	if (nocause) {
509 	    *cause = Qnil;
510             nocircular = 1;
511 	}
512 	else if (!rb_ivar_defined(mesg, id_cause)) {
513 	    *cause = get_ec_errinfo(ec);
514 	}
515         else {
516             nocircular = 1;
517         }
518     }
519     else if (!NIL_P(*cause) && !rb_obj_is_kind_of(*cause, rb_eException)) {
520         rb_raise(rb_eTypeError, "exception object expected");
521     }
522 
523     if (!nocircular && !NIL_P(*cause) && *cause != Qundef && *cause != mesg) {
524         VALUE c = *cause;
525         while (!NIL_P(c = rb_attr_get(c, id_cause))) {
526             if (c == mesg) {
527                 rb_raise(rb_eArgError, "circular causes");
528             }
529         }
530     }
531     return mesg;
532 }
533 
534 static void
setup_exception(rb_execution_context_t * ec,int tag,volatile VALUE mesg,VALUE cause)535 setup_exception(rb_execution_context_t *ec, int tag, volatile VALUE mesg, VALUE cause)
536 {
537     VALUE e;
538     const char *file = 0;
539     int line;
540 
541     file = rb_source_location_cstr(&line);
542     if ((file && !NIL_P(mesg)) || (cause != Qundef))  {
543 	volatile int state = 0;
544 
545 	EC_PUSH_TAG(ec);
546 	if (EC_EXEC_TAG() == TAG_NONE && !(state = rb_ec_set_raised(ec))) {
547 	    VALUE bt = rb_get_backtrace(mesg);
548 	    if (!NIL_P(bt) || cause == Qundef) {
549 		if (OBJ_FROZEN(mesg)) {
550 		    mesg = rb_obj_dup(mesg);
551 		}
552 	    }
553             if (cause != Qundef && !THROW_DATA_P(cause)) {
554 		exc_setup_cause(mesg, cause);
555 	    }
556 	    if (NIL_P(bt)) {
557 		VALUE at = rb_ec_backtrace_object(ec);
558 		rb_ivar_set(mesg, idBt_locations, at);
559 		set_backtrace(mesg, at);
560 	    }
561 	    rb_ec_reset_raised(ec);
562 	}
563 	EC_POP_TAG();
564 	if (state) goto fatal;
565     }
566 
567     if (!NIL_P(mesg)) {
568 	ec->errinfo = mesg;
569     }
570 
571     if (RTEST(ruby_debug) && !NIL_P(e = ec->errinfo) &&
572 	!rb_obj_is_kind_of(e, rb_eSystemExit)) {
573 	enum ruby_tag_type state;
574 
575 	mesg = e;
576 	EC_PUSH_TAG(ec);
577 	if ((state = EC_EXEC_TAG()) == TAG_NONE) {
578 	    ec->errinfo = Qnil;
579 	    e = rb_obj_as_string(mesg);
580 	    ec->errinfo = mesg;
581 	    if (file && line) {
582 		e = rb_sprintf("Exception `%"PRIsVALUE"' at %s:%d - %"PRIsVALUE"\n",
583 			       rb_obj_class(mesg), file, line, e);
584 	    }
585 	    else if (file) {
586 		e = rb_sprintf("Exception `%"PRIsVALUE"' at %s - %"PRIsVALUE"\n",
587 			       rb_obj_class(mesg), file, e);
588 	    }
589 	    else {
590 		e = rb_sprintf("Exception `%"PRIsVALUE"' - %"PRIsVALUE"\n",
591 			       rb_obj_class(mesg), e);
592 	    }
593 	    warn_print_str(e);
594 	}
595 	EC_POP_TAG();
596 	if (state == TAG_FATAL && ec->errinfo == exception_error) {
597 	    ec->errinfo = mesg;
598 	}
599 	else if (state) {
600 	    rb_ec_reset_raised(ec);
601 	    EC_JUMP_TAG(ec, state);
602 	}
603     }
604 
605     if (rb_ec_set_raised(ec)) {
606       fatal:
607 	ec->errinfo = exception_error;
608 	rb_ec_reset_raised(ec);
609 	EC_JUMP_TAG(ec, TAG_FATAL);
610     }
611 
612     if (tag != TAG_FATAL) {
613 	RUBY_DTRACE_HOOK(RAISE, rb_obj_classname(ec->errinfo));
614 	EXEC_EVENT_HOOK(ec, RUBY_EVENT_RAISE, ec->cfp->self, 0, 0, 0, mesg);
615     }
616 }
617 
618 /*! \private */
619 void
rb_ec_setup_exception(const rb_execution_context_t * ec,VALUE mesg,VALUE cause)620 rb_ec_setup_exception(const rb_execution_context_t *ec, VALUE mesg, VALUE cause)
621 {
622     if (cause == Qundef) {
623 	cause = get_ec_errinfo(ec);
624     }
625     if (cause != mesg) {
626 	rb_ivar_set(mesg, id_cause, cause);
627     }
628 }
629 
630 static void
rb_longjmp(rb_execution_context_t * ec,int tag,volatile VALUE mesg,VALUE cause)631 rb_longjmp(rb_execution_context_t *ec, int tag, volatile VALUE mesg, VALUE cause)
632 {
633     mesg = exc_setup_message(ec, mesg, &cause);
634     setup_exception(ec, tag, mesg, cause);
635     rb_ec_raised_clear(ec);
636     EC_JUMP_TAG(ec, tag);
637 }
638 
639 static VALUE make_exception(int argc, const VALUE *argv, int isstr);
640 
641 /*!
642  * Raises an exception in the current thread.
643  * \param[in] mesg an Exception class or an \c Exception object.
644  * \exception always raises an instance of the given exception class or
645  *   the given \c Exception object.
646  * \ingroup exception
647  */
648 void
rb_exc_raise(VALUE mesg)649 rb_exc_raise(VALUE mesg)
650 {
651     if (!NIL_P(mesg)) {
652 	mesg = make_exception(1, &mesg, FALSE);
653     }
654     rb_longjmp(GET_EC(), TAG_RAISE, mesg, Qundef);
655 }
656 
657 /*!
658  * Raises a fatal error in the current thread.
659  *
660  * Same as rb_exc_raise() but raises a fatal error, which Ruby codes
661  * cannot rescue.
662  * \ingroup exception
663  */
664 void
rb_exc_fatal(VALUE mesg)665 rb_exc_fatal(VALUE mesg)
666 {
667     if (!NIL_P(mesg)) {
668 	mesg = make_exception(1, &mesg, FALSE);
669     }
670     rb_longjmp(GET_EC(), TAG_FATAL, mesg, Qnil);
671 }
672 
673 /*!
674  * Raises an \c Interrupt exception.
675  * \ingroup exception
676  */
677 void
rb_interrupt(void)678 rb_interrupt(void)
679 {
680     rb_exc_raise(rb_exc_new(rb_eInterrupt, 0, 0));
681 }
682 
683 enum {raise_opt_cause, raise_max_opt}; /*< \private */
684 
685 static int
extract_raise_opts(int argc,const VALUE * argv,VALUE * opts)686 extract_raise_opts(int argc, const VALUE *argv, VALUE *opts)
687 {
688     int i;
689     if (argc > 0) {
690 	VALUE opt = argv[argc-1];
691 	if (RB_TYPE_P(opt, T_HASH)) {
692 	    if (!RHASH_EMPTY_P(opt)) {
693 		ID keywords[1];
694 		CONST_ID(keywords[0], "cause");
695 		rb_get_kwargs(opt, keywords, 0, -1-raise_max_opt, opts);
696 		if (RHASH_EMPTY_P(opt)) --argc;
697 		return argc;
698 	    }
699 	}
700     }
701     for (i = 0; i < raise_max_opt; ++i) {
702 	opts[i] = Qundef;
703     }
704     return argc;
705 }
706 
707 /*
708  *  call-seq:
709  *     raise
710  *     raise(string, cause: $!)
711  *     raise(exception [, string [, array]], cause: $!)
712  *     fail
713  *     fail(string, cause: $!)
714  *     fail(exception [, string [, array]], cause: $!)
715  *
716  *  With no arguments, raises the exception in <code>$!</code> or raises
717  *  a <code>RuntimeError</code> if <code>$!</code> is +nil+.
718  *  With a single +String+ argument, raises a
719  *  +RuntimeError+ with the string as a message. Otherwise,
720  *  the first parameter should be the name of an +Exception+
721  *  class (or an object that returns an +Exception+ object when sent
722  *  an +exception+ message). The optional second parameter sets the
723  *  message associated with the exception, and the third parameter is an
724  *  array of callback information. Exceptions are caught by the
725  *  +rescue+ clause of <code>begin...end</code> blocks.
726  *
727  *     raise "Failed to create socket"
728  *     raise ArgumentError, "No parameters", caller
729  *
730  *  The +cause+ of the generated exception is automatically set to the
731  *  "current" exception (<code>$!</code>) if any.  An alternative
732  *  value, either an +Exception+ object or +nil+, can be specified via
733  *  the +:cause+ argument.
734  */
735 
736 static VALUE
rb_f_raise(int argc,VALUE * argv)737 rb_f_raise(int argc, VALUE *argv)
738 {
739     VALUE err;
740     VALUE opts[raise_max_opt], *const cause = &opts[raise_opt_cause];
741 
742     argc = extract_raise_opts(argc, argv, opts);
743     if (argc == 0) {
744 	if (*cause != Qundef) {
745 	    rb_raise(rb_eArgError, "only cause is given with no arguments");
746 	}
747 	err = get_errinfo();
748 	if (!NIL_P(err)) {
749 	    argc = 1;
750 	    argv = &err;
751 	}
752     }
753     rb_raise_jump(rb_make_exception(argc, argv), *cause);
754 
755     UNREACHABLE_RETURN(Qnil);
756 }
757 
758 static VALUE
make_exception(int argc,const VALUE * argv,int isstr)759 make_exception(int argc, const VALUE *argv, int isstr)
760 {
761     VALUE mesg, exc;
762     int n;
763 
764     mesg = Qnil;
765     switch (argc) {
766       case 0:
767 	break;
768       case 1:
769 	exc = argv[0];
770 	if (NIL_P(exc))
771 	    break;
772 	if (isstr) {
773 	    mesg = rb_check_string_type(exc);
774 	    if (!NIL_P(mesg)) {
775 		mesg = rb_exc_new3(rb_eRuntimeError, mesg);
776 		break;
777 	    }
778 	}
779 	n = 0;
780 	goto exception_call;
781 
782       case 2:
783       case 3:
784 	exc = argv[0];
785 	n = 1;
786       exception_call:
787 	mesg = rb_check_funcall(exc, idException, n, argv+1);
788 	if (mesg == Qundef) {
789 	    rb_raise(rb_eTypeError, "exception class/object expected");
790 	}
791 	break;
792       default:
793 	rb_check_arity(argc, 0, 3);
794 	break;
795     }
796     if (argc > 0) {
797 	if (!rb_obj_is_kind_of(mesg, rb_eException))
798 	    rb_raise(rb_eTypeError, "exception object expected");
799 	if (argc > 2)
800 	    set_backtrace(mesg, argv[2]);
801     }
802 
803     return mesg;
804 }
805 
806 /*!
807  * Make an \c Exception object from the list of arguments in a manner
808  * similar to \c Kernel\#raise.
809  *
810  * \param[in] argc the number of arguments
811  * \param[in] argv a pointer to the array of arguments.
812  *
813  * The first form of this function takes a \c String argument. Then
814  * it returns a \c RuntimeError whose error message is the given value.
815  *
816  * The second from of this function takes an \c Exception object. Then
817  * it just returns the given value.
818  *
819  * The last form takes an exception class, an optional error message and
820  * an optional array of backtrace. Then it passes the optional arguments
821  * to \c #exception method of the exception class.
822  *
823  * \return the exception object, or \c Qnil if \c argc is 0.
824  * \ingroup exception
825  */
826 VALUE
rb_make_exception(int argc,const VALUE * argv)827 rb_make_exception(int argc, const VALUE *argv)
828 {
829     return make_exception(argc, argv, TRUE);
830 }
831 
832 /*! \private
833  * \todo can be static?
834  */
835 void
rb_raise_jump(VALUE mesg,VALUE cause)836 rb_raise_jump(VALUE mesg, VALUE cause)
837 {
838     rb_execution_context_t *ec = GET_EC();
839     const rb_control_frame_t *cfp = ec->cfp;
840     const rb_callable_method_entry_t *me = rb_vm_frame_method_entry(cfp);
841     VALUE klass = me->owner;
842     VALUE self = cfp->self;
843     ID mid = me->called_id;
844 
845     rb_vm_pop_frame(ec);
846     EXEC_EVENT_HOOK(ec, RUBY_EVENT_C_RETURN, self, me->def->original_id, mid, klass, Qnil);
847 
848     rb_longjmp(ec, TAG_RAISE, mesg, cause);
849 }
850 
851 /*!
852  * Continues the exception caught by rb_protect() and rb_eval_string_protect().
853  *
854  * This function never return to the caller.
855  * \param[in] the value of \c *state which the protect function has set to the
856  *   their last parameter.
857  * \ingroup exception
858  */
859 void
rb_jump_tag(int tag)860 rb_jump_tag(int tag)
861 {
862     if (UNLIKELY(tag < TAG_RETURN || tag > TAG_FATAL)) {
863 	unknown_longjmp_status(tag);
864     }
865     EC_JUMP_TAG(GET_EC(), tag);
866 }
867 
868 /*! Determines if the current method is given a block.
869  * \retval zero if not given
870  * \retval non-zero if given
871  * \ingroup defmethod
872  */
873 int
rb_block_given_p(void)874 rb_block_given_p(void)
875 {
876     if (rb_vm_frame_block_handler(GET_EC()->cfp) == VM_BLOCK_HANDLER_NONE) {
877 	return FALSE;
878     }
879     else {
880 	return TRUE;
881     }
882 }
883 
884 VALUE rb_eThreadError;
885 
886 /*! Declares that the current method needs a block.
887  *
888  * Raises a \c LocalJumpError if not given a block.
889  * \ingroup defmethod
890  */
891 void
rb_need_block(void)892 rb_need_block(void)
893 {
894     if (!rb_block_given_p()) {
895 	rb_vm_localjump_error("no block given", Qnil, 0);
896     }
897 }
898 
899 /*!
900  * \copydoc rb_rescue2
901  * \param[in] args exception classes, terminated by 0.
902  */
903 static VALUE
rb_vrescue2(VALUE (* b_proc)(VALUE),VALUE data1,VALUE (* r_proc)(VALUE,VALUE),VALUE data2,va_list args)904 rb_vrescue2(VALUE (* b_proc) (VALUE), VALUE data1,
905             VALUE (* r_proc) (VALUE, VALUE), VALUE data2,
906             va_list args)
907 {
908     enum ruby_tag_type state;
909     rb_execution_context_t * volatile ec = GET_EC();
910     rb_control_frame_t *volatile cfp = ec->cfp;
911     volatile VALUE result = Qfalse;
912     volatile VALUE e_info = ec->errinfo;
913 
914     EC_PUSH_TAG(ec);
915     if ((state = EC_EXEC_TAG()) == TAG_NONE) {
916       retry_entry:
917 	result = (*b_proc) (data1);
918     }
919     else if (result) {
920 	/* escape from r_proc */
921 	if (state == TAG_RETRY) {
922 	    state = 0;
923 	    ec->errinfo = Qnil;
924 	    result = Qfalse;
925 	    goto retry_entry;
926 	}
927     }
928     else {
929 	rb_vm_rewind_cfp(ec, cfp);
930 
931 	if (state == TAG_RAISE) {
932 	    int handle = FALSE;
933 	    VALUE eclass;
934 
935 	    while ((eclass = va_arg(args, VALUE)) != 0) {
936 		if (rb_obj_is_kind_of(ec->errinfo, eclass)) {
937 		    handle = TRUE;
938 		    break;
939 		}
940 	    }
941 
942 	    if (handle) {
943 		result = Qnil;
944 		state = 0;
945 		if (r_proc) {
946 		    result = (*r_proc) (data2, ec->errinfo);
947 		}
948 		ec->errinfo = e_info;
949 	    }
950 	}
951     }
952     EC_POP_TAG();
953     if (state)
954 	EC_JUMP_TAG(ec, state);
955 
956     return result;
957 }
958 
959 /*! An equivalent of \c rescue clause.
960  *
961  * Equivalent to <code>begin .. rescue err_type .. end</code>
962  *
963  * \param[in] b_proc a function which potentially raises an exception.
964  * \param[in] data1 the argument of \a b_proc
965  * \param[in] r_proc a function which rescues an exception in \a b_proc.
966  * \param[in] data2 the first argument of \a r_proc
967  * \param[in] ... 1 or more exception classes. Must be terminated by \c (VALUE)0.
968  *
969  * First it calls the function \a b_proc, with \a data1 as the argument.
970  * When \a b_proc raises an exception, it calls \a r_proc with \a data2 and
971  * the exception object if the exception is a kind of one of the given
972  * exception classes.
973  *
974  * \return the return value of \a b_proc if no exception occurs,
975  *   or the return value of \a r_proc if otherwise.
976  * \sa rb_rescue
977  * \sa rb_ensure
978  * \sa rb_protect
979  * \ingroup exception
980  */
981 VALUE
rb_rescue2(VALUE (* b_proc)(ANYARGS),VALUE data1,VALUE (* r_proc)(ANYARGS),VALUE data2,...)982 rb_rescue2(VALUE (* b_proc) (ANYARGS), VALUE data1,
983 	   VALUE (* r_proc) (ANYARGS), VALUE data2, ...)
984 {
985     va_list ap;
986     va_start(ap, data2);
987     return rb_vrescue2((VALUE (*)(VALUE))b_proc, data1, (VALUE (*)(VALUE, VALUE))r_proc, data2, ap);
988     va_end(ap);
989 }
990 
991 /*! An equivalent of \c rescue clause.
992  *
993  * Equivalent to <code>begin .. rescue .. end</code>.
994  *
995  * It is same as
996  * \code{cpp}
997  * rb_rescue2(b_proc, data1, r_proc, data2, rb_eStandardError, (VALUE)0);
998  * \endcode
999  *
1000  * \sa rb_rescue2
1001  * \sa rb_ensure
1002  * \sa rb_protect
1003  * \ingroup exception
1004  */
1005 VALUE
rb_rescue(VALUE (* b_proc)(ANYARGS),VALUE data1,VALUE (* r_proc)(ANYARGS),VALUE data2)1006 rb_rescue(VALUE (* b_proc)(ANYARGS), VALUE data1,
1007 	  VALUE (* r_proc)(ANYARGS), VALUE data2)
1008 {
1009     return rb_rescue2(b_proc, data1, r_proc, data2, rb_eStandardError,
1010 		      (VALUE)0);
1011 }
1012 
1013 /*! Protects a function call from potential global escapes from the function.
1014  *
1015  * Such global escapes include exceptions, \c Kernel\#throw, \c break in
1016  * an iterator, for example.
1017  * It first calls the function func with arg as the argument.
1018  * If no exception occurred during func, it returns the result of func and
1019  * *state is zero.
1020  * Otherwise, it returns Qnil and sets *state to nonzero.
1021  * If state is NULL, it is not set in both cases.
1022  *
1023  * You have to clear the error info with rb_set_errinfo(Qnil) when
1024  * ignoring the caught exception.
1025  * \ingroup exception
1026  * \sa rb_rescue
1027  * \sa rb_rescue2
1028  * \sa rb_ensure
1029  */
1030 VALUE
rb_protect(VALUE (* proc)(VALUE),VALUE data,int * pstate)1031 rb_protect(VALUE (* proc) (VALUE), VALUE data, int *pstate)
1032 {
1033     volatile VALUE result = Qnil;
1034     volatile enum ruby_tag_type state;
1035     rb_execution_context_t * volatile ec = GET_EC();
1036     rb_control_frame_t *volatile cfp = ec->cfp;
1037     struct rb_vm_protect_tag protect_tag;
1038     rb_jmpbuf_t org_jmpbuf;
1039 
1040     protect_tag.prev = ec->protect_tag;
1041 
1042     EC_PUSH_TAG(ec);
1043     ec->protect_tag = &protect_tag;
1044     MEMCPY(&org_jmpbuf, &rb_ec_thread_ptr(ec)->root_jmpbuf, rb_jmpbuf_t, 1);
1045     if ((state = EC_EXEC_TAG()) == TAG_NONE) {
1046 	SAVE_ROOT_JMPBUF(rb_ec_thread_ptr(ec), result = (*proc) (data));
1047     }
1048     else {
1049 	rb_vm_rewind_cfp(ec, cfp);
1050     }
1051     MEMCPY(&rb_ec_thread_ptr(ec)->root_jmpbuf, &org_jmpbuf, rb_jmpbuf_t, 1);
1052     ec->protect_tag = protect_tag.prev;
1053     EC_POP_TAG();
1054 
1055     if (pstate != NULL) *pstate = state;
1056     return result;
1057 }
1058 
1059 /*!
1060  * An equivalent to \c ensure clause.
1061  *
1062  * Equivalent to <code>begin .. ensure .. end</code>.
1063  *
1064  * Calls the function \a b_proc with \a data1 as the argument,
1065  * then calls \a e_proc with \a data2 when execution terminated.
1066  * \return The return value of \a b_proc if no exception occurred,
1067  *   or \c Qnil if otherwise.
1068  * \sa rb_rescue
1069  * \sa rb_rescue2
1070  * \sa rb_protect
1071  * \ingroup exception
1072  */
1073 VALUE
rb_ensure(VALUE (* b_proc)(ANYARGS),VALUE data1,VALUE (* e_proc)(ANYARGS),VALUE data2)1074 rb_ensure(VALUE (*b_proc)(ANYARGS), VALUE data1, VALUE (*e_proc)(ANYARGS), VALUE data2)
1075 {
1076     int state;
1077     volatile VALUE result = Qnil;
1078     VALUE errinfo;
1079     rb_execution_context_t * volatile ec = GET_EC();
1080     rb_ensure_list_t ensure_list;
1081     ensure_list.entry.marker = 0;
1082     ensure_list.entry.e_proc = e_proc;
1083     ensure_list.entry.data2 = data2;
1084     ensure_list.next = ec->ensure_list;
1085     ec->ensure_list = &ensure_list;
1086     EC_PUSH_TAG(ec);
1087     if ((state = EC_EXEC_TAG()) == TAG_NONE) {
1088 	result = (*b_proc) (data1);
1089     }
1090     EC_POP_TAG();
1091     errinfo = ec->errinfo;
1092     if (!NIL_P(errinfo) && !RB_TYPE_P(errinfo, T_OBJECT)) {
1093 	ec->errinfo = Qnil;
1094     }
1095     ec->ensure_list=ensure_list.next;
1096     (*ensure_list.entry.e_proc)(ensure_list.entry.data2);
1097     ec->errinfo = errinfo;
1098     if (state)
1099 	EC_JUMP_TAG(ec, state);
1100     return result;
1101 }
1102 
1103 static ID
frame_func_id(const rb_control_frame_t * cfp)1104 frame_func_id(const rb_control_frame_t *cfp)
1105 {
1106     const rb_callable_method_entry_t *me = rb_vm_frame_method_entry(cfp);
1107 
1108     if (me) {
1109 	return me->def->original_id;
1110     }
1111     else {
1112 	return 0;
1113     }
1114 }
1115 
1116 static ID
frame_called_id(rb_control_frame_t * cfp)1117 frame_called_id(rb_control_frame_t *cfp)
1118 {
1119     const rb_callable_method_entry_t *me = rb_vm_frame_method_entry(cfp);
1120 
1121     if (me) {
1122 	return me->called_id;
1123     }
1124     else {
1125 	return 0;
1126     }
1127 }
1128 
1129 /*!
1130  * The original name of the current method.
1131  *
1132  * The function returns the original name of the method even if
1133  * an alias of the method is called.
1134  * The function can also return 0 if it is not in a method. This
1135  * case can happen in a toplevel of a source file, for example.
1136  *
1137  * \returns the ID of the name or 0
1138  * \sa rb_frame_callee
1139  * \ingroup defmethod
1140  */
1141 ID
rb_frame_this_func(void)1142 rb_frame_this_func(void)
1143 {
1144     return frame_func_id(GET_EC()->cfp);
1145 }
1146 
1147 /*!
1148  * The name of the current method.
1149  *
1150  * The function returns the alias if an alias of the method is called.
1151  * The function can also return 0 if it is not in a method. This
1152  * case can happen in a toplevel of a source file, for example.
1153  *
1154  * \returns the ID of the name or 0.
1155  * \sa rb_frame_this_func
1156  * \ingroup defmethod
1157  */
1158 ID
rb_frame_callee(void)1159 rb_frame_callee(void)
1160 {
1161     return frame_called_id(GET_EC()->cfp);
1162 }
1163 
1164 static rb_control_frame_t *
previous_frame(const rb_execution_context_t * ec)1165 previous_frame(const rb_execution_context_t *ec)
1166 {
1167     rb_control_frame_t *prev_cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(ec->cfp);
1168     /* check if prev_cfp can be accessible */
1169     if ((void *)(ec->vm_stack + ec->vm_stack_size) == (void *)(prev_cfp)) {
1170         return 0;
1171     }
1172     return prev_cfp;
1173 }
1174 
1175 static ID
prev_frame_callee(void)1176 prev_frame_callee(void)
1177 {
1178     rb_control_frame_t *prev_cfp = previous_frame(GET_EC());
1179     if (!prev_cfp) return 0;
1180     return frame_called_id(prev_cfp);
1181 }
1182 
1183 static ID
prev_frame_func(void)1184 prev_frame_func(void)
1185 {
1186     rb_control_frame_t *prev_cfp = previous_frame(GET_EC());
1187     if (!prev_cfp) return 0;
1188     return frame_func_id(prev_cfp);
1189 }
1190 
1191 /*!
1192  * \private
1193  * Returns the ID of the last method in the call stack.
1194  * \sa rb_frame_this_func
1195  * \ingroup defmethod
1196  */
1197 ID
rb_frame_last_func(void)1198 rb_frame_last_func(void)
1199 {
1200     const rb_execution_context_t *ec = GET_EC();
1201     const rb_control_frame_t *cfp = ec->cfp;
1202     ID mid;
1203 
1204     while (!(mid = frame_func_id(cfp)) &&
1205 	   (cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp),
1206 	    !RUBY_VM_CONTROL_FRAME_STACK_OVERFLOW_P(ec, cfp)));
1207     return mid;
1208 }
1209 
1210 /*
1211  *  call-seq:
1212  *     append_features(mod)   -> mod
1213  *
1214  *  When this module is included in another, Ruby calls
1215  *  <code>append_features</code> in this module, passing it the
1216  *  receiving module in _mod_. Ruby's default implementation is
1217  *  to add the constants, methods, and module variables of this module
1218  *  to _mod_ if this module has not already been added to
1219  *  _mod_ or one of its ancestors. See also <code>Module#include</code>.
1220  */
1221 
1222 static VALUE
rb_mod_append_features(VALUE module,VALUE include)1223 rb_mod_append_features(VALUE module, VALUE include)
1224 {
1225     if (!CLASS_OR_MODULE_P(include)) {
1226 	Check_Type(include, T_CLASS);
1227     }
1228     rb_include_module(include, module);
1229 
1230     return module;
1231 }
1232 
1233 /*
1234  *  call-seq:
1235  *     include(module, ...)    -> self
1236  *
1237  *  Invokes <code>Module.append_features</code> on each parameter in reverse order.
1238  */
1239 
1240 static VALUE
rb_mod_include(int argc,VALUE * argv,VALUE module)1241 rb_mod_include(int argc, VALUE *argv, VALUE module)
1242 {
1243     int i;
1244     ID id_append_features, id_included;
1245 
1246     CONST_ID(id_append_features, "append_features");
1247     CONST_ID(id_included, "included");
1248 
1249     rb_check_arity(argc, 1, UNLIMITED_ARGUMENTS);
1250     for (i = 0; i < argc; i++)
1251 	Check_Type(argv[i], T_MODULE);
1252     while (argc--) {
1253 	rb_funcall(argv[argc], id_append_features, 1, module);
1254 	rb_funcall(argv[argc], id_included, 1, module);
1255     }
1256     return module;
1257 }
1258 
1259 /*
1260  *  call-seq:
1261  *     prepend_features(mod)   -> mod
1262  *
1263  *  When this module is prepended in another, Ruby calls
1264  *  <code>prepend_features</code> in this module, passing it the
1265  *  receiving module in _mod_. Ruby's default implementation is
1266  *  to overlay the constants, methods, and module variables of this module
1267  *  to _mod_ if this module has not already been added to
1268  *  _mod_ or one of its ancestors. See also <code>Module#prepend</code>.
1269  */
1270 
1271 static VALUE
rb_mod_prepend_features(VALUE module,VALUE prepend)1272 rb_mod_prepend_features(VALUE module, VALUE prepend)
1273 {
1274     if (!CLASS_OR_MODULE_P(prepend)) {
1275 	Check_Type(prepend, T_CLASS);
1276     }
1277     rb_prepend_module(prepend, module);
1278 
1279     return module;
1280 }
1281 
1282 /*
1283  *  call-seq:
1284  *     prepend(module, ...)    -> self
1285  *
1286  *  Invokes <code>Module.prepend_features</code> on each parameter in reverse order.
1287  */
1288 
1289 static VALUE
rb_mod_prepend(int argc,VALUE * argv,VALUE module)1290 rb_mod_prepend(int argc, VALUE *argv, VALUE module)
1291 {
1292     int i;
1293     ID id_prepend_features, id_prepended;
1294 
1295     CONST_ID(id_prepend_features, "prepend_features");
1296     CONST_ID(id_prepended, "prepended");
1297 
1298     rb_check_arity(argc, 1, UNLIMITED_ARGUMENTS);
1299     for (i = 0; i < argc; i++)
1300 	Check_Type(argv[i], T_MODULE);
1301     while (argc--) {
1302 	rb_funcall(argv[argc], id_prepend_features, 1, module);
1303 	rb_funcall(argv[argc], id_prepended, 1, module);
1304     }
1305     return module;
1306 }
1307 
1308 static void
ensure_class_or_module(VALUE obj)1309 ensure_class_or_module(VALUE obj)
1310 {
1311     if (!RB_TYPE_P(obj, T_CLASS) && !RB_TYPE_P(obj, T_MODULE)) {
1312 	rb_raise(rb_eTypeError,
1313 		 "wrong argument type %"PRIsVALUE" (expected Class or Module)",
1314 		 rb_obj_class(obj));
1315     }
1316 }
1317 
1318 static VALUE
hidden_identity_hash_new(void)1319 hidden_identity_hash_new(void)
1320 {
1321     VALUE hash = rb_ident_hash_new();
1322 
1323     RBASIC_CLEAR_CLASS(hash); /* hide from ObjectSpace */
1324     return hash;
1325 }
1326 
1327 static VALUE
refinement_superclass(VALUE superclass)1328 refinement_superclass(VALUE superclass)
1329 {
1330     if (RB_TYPE_P(superclass, T_MODULE)) {
1331 	/* FIXME: Should ancestors of superclass be used here? */
1332 	return rb_include_class_new(superclass, rb_cBasicObject);
1333     }
1334     else {
1335 	return superclass;
1336     }
1337 }
1338 
1339 /*!
1340  * \private
1341  * \todo can be static?
1342  */
1343 void
rb_using_refinement(rb_cref_t * cref,VALUE klass,VALUE module)1344 rb_using_refinement(rb_cref_t *cref, VALUE klass, VALUE module)
1345 {
1346     VALUE iclass, c, superclass = klass;
1347 
1348     ensure_class_or_module(klass);
1349     Check_Type(module, T_MODULE);
1350     if (NIL_P(CREF_REFINEMENTS(cref))) {
1351 	CREF_REFINEMENTS_SET(cref, hidden_identity_hash_new());
1352     }
1353     else {
1354 	if (CREF_OMOD_SHARED(cref)) {
1355 	    CREF_REFINEMENTS_SET(cref, rb_hash_dup(CREF_REFINEMENTS(cref)));
1356 	    CREF_OMOD_SHARED_UNSET(cref);
1357 	}
1358 	if (!NIL_P(c = rb_hash_lookup(CREF_REFINEMENTS(cref), klass))) {
1359 	    superclass = c;
1360 	    while (c && RB_TYPE_P(c, T_ICLASS)) {
1361 		if (RBASIC(c)->klass == module) {
1362 		    /* already used refinement */
1363 		    return;
1364 		}
1365 		c = RCLASS_SUPER(c);
1366 	    }
1367 	}
1368     }
1369     FL_SET(module, RMODULE_IS_OVERLAID);
1370     superclass = refinement_superclass(superclass);
1371     c = iclass = rb_include_class_new(module, superclass);
1372     RCLASS_REFINED_CLASS(c) = klass;
1373 
1374     RCLASS_M_TBL(OBJ_WB_UNPROTECT(c)) =
1375       RCLASS_M_TBL(OBJ_WB_UNPROTECT(module)); /* TODO: check unprotecting */
1376 
1377     module = RCLASS_SUPER(module);
1378     while (module && module != klass) {
1379 	FL_SET(module, RMODULE_IS_OVERLAID);
1380 	c = RCLASS_SET_SUPER(c, rb_include_class_new(module, RCLASS_SUPER(c)));
1381 	RCLASS_REFINED_CLASS(c) = klass;
1382 	module = RCLASS_SUPER(module);
1383     }
1384     rb_hash_aset(CREF_REFINEMENTS(cref), klass, iclass);
1385 }
1386 
1387 static int
using_refinement(VALUE klass,VALUE module,VALUE arg)1388 using_refinement(VALUE klass, VALUE module, VALUE arg)
1389 {
1390     rb_cref_t *cref = (rb_cref_t *) arg;
1391 
1392     rb_using_refinement(cref, klass, module);
1393     return ST_CONTINUE;
1394 }
1395 
1396 static void
using_module_recursive(const rb_cref_t * cref,VALUE klass)1397 using_module_recursive(const rb_cref_t *cref, VALUE klass)
1398 {
1399     ID id_refinements;
1400     VALUE super, module, refinements;
1401 
1402     super = RCLASS_SUPER(klass);
1403     if (super) {
1404 	using_module_recursive(cref, super);
1405     }
1406     switch (BUILTIN_TYPE(klass)) {
1407       case T_MODULE:
1408 	module = klass;
1409 	break;
1410 
1411       case T_ICLASS:
1412 	module = RBASIC(klass)->klass;
1413 	break;
1414 
1415       default:
1416 	rb_raise(rb_eTypeError, "wrong argument type %s (expected Module)",
1417 		 rb_obj_classname(klass));
1418 	break;
1419     }
1420     CONST_ID(id_refinements, "__refinements__");
1421     refinements = rb_attr_get(module, id_refinements);
1422     if (NIL_P(refinements)) return;
1423     rb_hash_foreach(refinements, using_refinement, (VALUE) cref);
1424 }
1425 
1426 /*!
1427  * \private
1428  * \todo can be static?
1429  */
1430 void
rb_using_module(const rb_cref_t * cref,VALUE module)1431 rb_using_module(const rb_cref_t *cref, VALUE module)
1432 {
1433     Check_Type(module, T_MODULE);
1434     using_module_recursive(cref, module);
1435     rb_clear_method_cache_by_class(rb_cObject);
1436 }
1437 
1438 /*! \private */
1439 VALUE
rb_refinement_module_get_refined_class(VALUE module)1440 rb_refinement_module_get_refined_class(VALUE module)
1441 {
1442     ID id_refined_class;
1443 
1444     CONST_ID(id_refined_class, "__refined_class__");
1445     return rb_attr_get(module, id_refined_class);
1446 }
1447 
1448 static void
add_activated_refinement(VALUE activated_refinements,VALUE klass,VALUE refinement)1449 add_activated_refinement(VALUE activated_refinements,
1450 			 VALUE klass, VALUE refinement)
1451 {
1452     VALUE iclass, c, superclass = klass;
1453 
1454     if (!NIL_P(c = rb_hash_lookup(activated_refinements, klass))) {
1455 	superclass = c;
1456 	while (c && RB_TYPE_P(c, T_ICLASS)) {
1457 	    if (RBASIC(c)->klass == refinement) {
1458 		/* already used refinement */
1459 		return;
1460 	    }
1461 	    c = RCLASS_SUPER(c);
1462 	}
1463     }
1464     FL_SET(refinement, RMODULE_IS_OVERLAID);
1465     superclass = refinement_superclass(superclass);
1466     c = iclass = rb_include_class_new(refinement, superclass);
1467     RCLASS_REFINED_CLASS(c) = klass;
1468     refinement = RCLASS_SUPER(refinement);
1469     while (refinement && refinement != klass) {
1470 	FL_SET(refinement, RMODULE_IS_OVERLAID);
1471 	c = RCLASS_SET_SUPER(c, rb_include_class_new(refinement, RCLASS_SUPER(c)));
1472 	RCLASS_REFINED_CLASS(c) = klass;
1473 	refinement = RCLASS_SUPER(refinement);
1474     }
1475     rb_hash_aset(activated_refinements, klass, iclass);
1476 }
1477 
1478 /*
1479  *  call-seq:
1480  *     refine(mod) { block }   -> module
1481  *
1482  *  Refine <i>mod</i> in the receiver.
1483  *
1484  *  Returns a module, where refined methods are defined.
1485  */
1486 
1487 static VALUE
rb_mod_refine(VALUE module,VALUE klass)1488 rb_mod_refine(VALUE module, VALUE klass)
1489 {
1490     VALUE refinement;
1491     ID id_refinements, id_activated_refinements,
1492        id_refined_class, id_defined_at;
1493     VALUE refinements, activated_refinements;
1494     rb_thread_t *th = GET_THREAD();
1495     VALUE block_handler = rb_vm_frame_block_handler(th->ec->cfp);
1496 
1497     if (block_handler == VM_BLOCK_HANDLER_NONE) {
1498 	rb_raise(rb_eArgError, "no block given");
1499     }
1500     if (vm_block_handler_type(block_handler) != block_handler_type_iseq) {
1501 	rb_raise(rb_eArgError, "can't pass a Proc as a block to Module#refine");
1502     }
1503 
1504     ensure_class_or_module(klass);
1505     CONST_ID(id_refinements, "__refinements__");
1506     refinements = rb_attr_get(module, id_refinements);
1507     if (NIL_P(refinements)) {
1508 	refinements = hidden_identity_hash_new();
1509 	rb_ivar_set(module, id_refinements, refinements);
1510     }
1511     CONST_ID(id_activated_refinements, "__activated_refinements__");
1512     activated_refinements = rb_attr_get(module, id_activated_refinements);
1513     if (NIL_P(activated_refinements)) {
1514 	activated_refinements = hidden_identity_hash_new();
1515 	rb_ivar_set(module, id_activated_refinements,
1516 		    activated_refinements);
1517     }
1518     refinement = rb_hash_lookup(refinements, klass);
1519     if (NIL_P(refinement)) {
1520 	VALUE superclass = refinement_superclass(klass);
1521 	refinement = rb_module_new();
1522 	RCLASS_SET_SUPER(refinement, superclass);
1523 	FL_SET(refinement, RMODULE_IS_REFINEMENT);
1524 	CONST_ID(id_refined_class, "__refined_class__");
1525 	rb_ivar_set(refinement, id_refined_class, klass);
1526 	CONST_ID(id_defined_at, "__defined_at__");
1527 	rb_ivar_set(refinement, id_defined_at, module);
1528 	rb_hash_aset(refinements, klass, refinement);
1529 	add_activated_refinement(activated_refinements, klass, refinement);
1530     }
1531     rb_yield_refine_block(refinement, activated_refinements);
1532     return refinement;
1533 }
1534 
1535 static void
ignored_block(VALUE module,const char * klass)1536 ignored_block(VALUE module, const char *klass)
1537 {
1538     const char *anon = "";
1539     Check_Type(module, T_MODULE);
1540     if (!RTEST(rb_search_class_path(module))) {
1541 	anon = ", maybe for Module.new";
1542     }
1543     rb_warn("%s""using doesn't call the given block""%s.", klass, anon);
1544 }
1545 
1546 /*
1547  *  call-seq:
1548  *     using(module)    -> self
1549  *
1550  *  Import class refinements from <i>module</i> into the current class or
1551  *  module definition.
1552  */
1553 
1554 static VALUE
mod_using(VALUE self,VALUE module)1555 mod_using(VALUE self, VALUE module)
1556 {
1557     rb_control_frame_t *prev_cfp = previous_frame(GET_EC());
1558 
1559     if (prev_frame_func()) {
1560 	rb_raise(rb_eRuntimeError,
1561 		 "Module#using is not permitted in methods");
1562     }
1563     if (prev_cfp && prev_cfp->self != self) {
1564 	rb_raise(rb_eRuntimeError, "Module#using is not called on self");
1565     }
1566     if (rb_block_given_p()) {
1567 	ignored_block(module, "Module#");
1568     }
1569     rb_using_module(rb_vm_cref_replace_with_duplicated_cref(), module);
1570     return self;
1571 }
1572 
1573 static int
used_modules_i(VALUE _,VALUE mod,VALUE ary)1574 used_modules_i(VALUE _, VALUE mod, VALUE ary)
1575 {
1576     ID id_defined_at;
1577     CONST_ID(id_defined_at, "__defined_at__");
1578     while (FL_TEST(rb_class_of(mod), RMODULE_IS_REFINEMENT)) {
1579 	rb_ary_push(ary, rb_attr_get(rb_class_of(mod), id_defined_at));
1580 	mod = RCLASS_SUPER(mod);
1581     }
1582     return ST_CONTINUE;
1583 }
1584 
1585 /*
1586  *  call-seq:
1587  *     used_modules -> array
1588  *
1589  *  Returns an array of all modules used in the current scope. The ordering
1590  *  of modules in the resulting array is not defined.
1591  *
1592  *     module A
1593  *       refine Object do
1594  *       end
1595  *     end
1596  *
1597  *     module B
1598  *       refine Object do
1599  *       end
1600  *     end
1601  *
1602  *     using A
1603  *     using B
1604  *     p Module.used_modules
1605  *
1606  *  <em>produces:</em>
1607  *
1608  *     [B, A]
1609  */
1610 static VALUE
rb_mod_s_used_modules(void)1611 rb_mod_s_used_modules(void)
1612 {
1613     const rb_cref_t *cref = rb_vm_cref();
1614     VALUE ary = rb_ary_new();
1615 
1616     while(cref) {
1617 	if(!NIL_P(CREF_REFINEMENTS(cref))) {
1618 	    rb_hash_foreach(CREF_REFINEMENTS(cref), used_modules_i, ary);
1619 	}
1620 	cref = CREF_NEXT(cref);
1621     }
1622 
1623     return rb_funcall(ary, rb_intern("uniq"), 0);
1624 }
1625 
1626 /*!
1627  * Calls \c #initialize method of \a obj with the given arguments.
1628  *
1629  * It also forwards the given block to \c #initialize if given.
1630  *
1631  * \param[in] obj the receiver object
1632  * \param[in] argc the number of arguments
1633  * \param[in] argv a pointer to the array of arguments
1634  * \ingroup object
1635  */
1636 void
rb_obj_call_init(VALUE obj,int argc,const VALUE * argv)1637 rb_obj_call_init(VALUE obj, int argc, const VALUE *argv)
1638 {
1639     PASS_PASSED_BLOCK_HANDLER();
1640     rb_funcallv(obj, idInitialize, argc, argv);
1641 }
1642 
1643 /*!
1644  * Extend the object with the module.
1645  *
1646  * Same as \c Module\#extend_object.
1647  * \ingroup class
1648  */
1649 void
rb_extend_object(VALUE obj,VALUE module)1650 rb_extend_object(VALUE obj, VALUE module)
1651 {
1652     rb_include_module(rb_singleton_class(obj), module);
1653 }
1654 
1655 /*
1656  *  call-seq:
1657  *     extend_object(obj)    -> obj
1658  *
1659  *  Extends the specified object by adding this module's constants and
1660  *  methods (which are added as singleton methods). This is the callback
1661  *  method used by <code>Object#extend</code>.
1662  *
1663  *     module Picky
1664  *       def Picky.extend_object(o)
1665  *         if String === o
1666  *           puts "Can't add Picky to a String"
1667  *         else
1668  *           puts "Picky added to #{o.class}"
1669  *           super
1670  *         end
1671  *       end
1672  *     end
1673  *     (s = Array.new).extend Picky  # Call Object.extend
1674  *     (s = "quick brown fox").extend Picky
1675  *
1676  *  <em>produces:</em>
1677  *
1678  *     Picky added to Array
1679  *     Can't add Picky to a String
1680  */
1681 
1682 static VALUE
rb_mod_extend_object(VALUE mod,VALUE obj)1683 rb_mod_extend_object(VALUE mod, VALUE obj)
1684 {
1685     rb_extend_object(obj, mod);
1686     return obj;
1687 }
1688 
1689 /*
1690  *  call-seq:
1691  *     obj.extend(module, ...)    -> obj
1692  *
1693  *  Adds to _obj_ the instance methods from each module given as a
1694  *  parameter.
1695  *
1696  *     module Mod
1697  *       def hello
1698  *         "Hello from Mod.\n"
1699  *       end
1700  *     end
1701  *
1702  *     class Klass
1703  *       def hello
1704  *         "Hello from Klass.\n"
1705  *       end
1706  *     end
1707  *
1708  *     k = Klass.new
1709  *     k.hello         #=> "Hello from Klass.\n"
1710  *     k.extend(Mod)   #=> #<Klass:0x401b3bc8>
1711  *     k.hello         #=> "Hello from Mod.\n"
1712  */
1713 
1714 static VALUE
rb_obj_extend(int argc,VALUE * argv,VALUE obj)1715 rb_obj_extend(int argc, VALUE *argv, VALUE obj)
1716 {
1717     int i;
1718     ID id_extend_object, id_extended;
1719 
1720     CONST_ID(id_extend_object, "extend_object");
1721     CONST_ID(id_extended, "extended");
1722 
1723     rb_check_arity(argc, 1, UNLIMITED_ARGUMENTS);
1724     for (i = 0; i < argc; i++)
1725 	Check_Type(argv[i], T_MODULE);
1726     while (argc--) {
1727 	rb_funcall(argv[argc], id_extend_object, 1, obj);
1728 	rb_funcall(argv[argc], id_extended, 1, obj);
1729     }
1730     return obj;
1731 }
1732 
1733 /*
1734  *  call-seq:
1735  *     include(module, ...)   -> self
1736  *
1737  *  Invokes <code>Module.append_features</code>
1738  *  on each parameter in turn. Effectively adds the methods and constants
1739  *  in each module to the receiver.
1740  */
1741 
1742 static VALUE
top_include(int argc,VALUE * argv,VALUE self)1743 top_include(int argc, VALUE *argv, VALUE self)
1744 {
1745     rb_thread_t *th = GET_THREAD();
1746 
1747     if (th->top_wrapper) {
1748 	rb_warning("main.include in the wrapped load is effective only in wrapper module");
1749 	return rb_mod_include(argc, argv, th->top_wrapper);
1750     }
1751     return rb_mod_include(argc, argv, rb_cObject);
1752 }
1753 
1754 /*
1755  *  call-seq:
1756  *     using(module)    -> self
1757  *
1758  *  Import class refinements from <i>module</i> into the scope where
1759  *  <code>using</code> is called.
1760  */
1761 
1762 static VALUE
top_using(VALUE self,VALUE module)1763 top_using(VALUE self, VALUE module)
1764 {
1765     const rb_cref_t *cref = rb_vm_cref();
1766     rb_control_frame_t *prev_cfp = previous_frame(GET_EC());
1767 
1768     if (CREF_NEXT(cref) || (prev_cfp && rb_vm_frame_method_entry(prev_cfp))) {
1769 	rb_raise(rb_eRuntimeError, "main.using is permitted only at toplevel");
1770     }
1771     if (rb_block_given_p()) {
1772 	ignored_block(module, "main.");
1773     }
1774     rb_using_module(rb_vm_cref_replace_with_duplicated_cref(), module);
1775     return self;
1776 }
1777 
1778 static const VALUE *
errinfo_place(const rb_execution_context_t * ec)1779 errinfo_place(const rb_execution_context_t *ec)
1780 {
1781     const rb_control_frame_t *cfp = ec->cfp;
1782     const rb_control_frame_t *end_cfp = RUBY_VM_END_CONTROL_FRAME(ec);
1783 
1784     while (RUBY_VM_VALID_CONTROL_FRAME_P(cfp, end_cfp)) {
1785 	if (VM_FRAME_RUBYFRAME_P(cfp)) {
1786 	    if (cfp->iseq->body->type == ISEQ_TYPE_RESCUE) {
1787 		return &cfp->ep[VM_ENV_INDEX_LAST_LVAR];
1788 	    }
1789 	    else if (cfp->iseq->body->type == ISEQ_TYPE_ENSURE &&
1790 		     !THROW_DATA_P(cfp->ep[VM_ENV_INDEX_LAST_LVAR]) &&
1791 		     !FIXNUM_P(cfp->ep[VM_ENV_INDEX_LAST_LVAR])) {
1792 		return &cfp->ep[VM_ENV_INDEX_LAST_LVAR];
1793 	    }
1794 	}
1795 	cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp);
1796     }
1797     return 0;
1798 }
1799 
1800 static VALUE
get_ec_errinfo(const rb_execution_context_t * ec)1801 get_ec_errinfo(const rb_execution_context_t *ec)
1802 {
1803     const VALUE *ptr = errinfo_place(ec);
1804     if (ptr) {
1805 	return *ptr;
1806     }
1807     else {
1808 	return ec->errinfo;
1809     }
1810 }
1811 
1812 static VALUE
get_errinfo(void)1813 get_errinfo(void)
1814 {
1815     return get_ec_errinfo(GET_EC());
1816 }
1817 
1818 static VALUE
errinfo_getter(ID id)1819 errinfo_getter(ID id)
1820 {
1821     return get_errinfo();
1822 }
1823 
1824 /*! The current exception in the current thread.
1825  *
1826  * Same as \c $! in Ruby.
1827  * \return the current exception or \c Qnil
1828  * \ingroup exception
1829  */
1830 VALUE
rb_errinfo(void)1831 rb_errinfo(void)
1832 {
1833     return GET_EC()->errinfo;
1834 }
1835 
1836 /*! Sets the current exception (\c $!) to the given value
1837  *
1838  * \param[in] err an \c Exception object or \c Qnil.
1839  * \exception TypeError if \a err is neither an exception nor \c nil.
1840  * \note this function does not raise the exception.
1841  *   Use \c rb_raise() when you want to raise.
1842  * \ingroup exception
1843  */
1844 void
rb_set_errinfo(VALUE err)1845 rb_set_errinfo(VALUE err)
1846 {
1847     if (!NIL_P(err) && !rb_obj_is_kind_of(err, rb_eException)) {
1848 	rb_raise(rb_eTypeError, "assigning non-exception to $!");
1849     }
1850     GET_EC()->errinfo = err;
1851 }
1852 
1853 static VALUE
errat_getter(ID id)1854 errat_getter(ID id)
1855 {
1856     VALUE err = get_errinfo();
1857     if (!NIL_P(err)) {
1858 	return rb_get_backtrace(err);
1859     }
1860     else {
1861 	return Qnil;
1862     }
1863 }
1864 
1865 static void
errat_setter(VALUE val,ID id,VALUE * var)1866 errat_setter(VALUE val, ID id, VALUE *var)
1867 {
1868     VALUE err = get_errinfo();
1869     if (NIL_P(err)) {
1870 	rb_raise(rb_eArgError, "$! not set");
1871     }
1872     set_backtrace(err, val);
1873 }
1874 
1875 /*
1876  *  call-seq:
1877  *     __method__         -> symbol
1878  *
1879  *  Returns the name at the definition of the current method as a
1880  *  Symbol.
1881  *  If called outside of a method, it returns <code>nil</code>.
1882  *
1883  */
1884 
1885 static VALUE
rb_f_method_name(void)1886 rb_f_method_name(void)
1887 {
1888     ID fname = prev_frame_func(); /* need *method* ID */
1889 
1890     if (fname) {
1891 	return ID2SYM(fname);
1892     }
1893     else {
1894 	return Qnil;
1895     }
1896 }
1897 
1898 /*
1899  *  call-seq:
1900  *     __callee__         -> symbol
1901  *
1902  *  Returns the called name of the current method as a Symbol.
1903  *  If called outside of a method, it returns <code>nil</code>.
1904  *
1905  */
1906 
1907 static VALUE
rb_f_callee_name(void)1908 rb_f_callee_name(void)
1909 {
1910     ID fname = prev_frame_callee(); /* need *callee* ID */
1911 
1912     if (fname) {
1913 	return ID2SYM(fname);
1914     }
1915     else {
1916 	return Qnil;
1917     }
1918 }
1919 
1920 /*
1921  *  call-seq:
1922  *     __dir__         -> string
1923  *
1924  *  Returns the canonicalized absolute path of the directory of the file from
1925  *  which this method is called. It means symlinks in the path is resolved.
1926  *  If <code>__FILE__</code> is <code>nil</code>, it returns <code>nil</code>.
1927  *  The return value equals to <code>File.dirname(File.realpath(__FILE__))</code>.
1928  *
1929  */
1930 static VALUE
f_current_dirname(void)1931 f_current_dirname(void)
1932 {
1933     VALUE base = rb_current_realfilepath();
1934     if (NIL_P(base)) {
1935 	return Qnil;
1936     }
1937     base = rb_file_dirname(base);
1938     return base;
1939 }
1940 
1941 void
Init_eval(void)1942 Init_eval(void)
1943 {
1944     rb_define_virtual_variable("$@", errat_getter, errat_setter);
1945     rb_define_virtual_variable("$!", errinfo_getter, 0);
1946 
1947     rb_define_global_function("raise", rb_f_raise, -1);
1948     rb_define_global_function("fail", rb_f_raise, -1);
1949 
1950     rb_define_global_function("global_variables", rb_f_global_variables, 0);	/* in variable.c */
1951 
1952     rb_define_global_function("__method__", rb_f_method_name, 0);
1953     rb_define_global_function("__callee__", rb_f_callee_name, 0);
1954     rb_define_global_function("__dir__", f_current_dirname, 0);
1955 
1956     rb_define_method(rb_cModule, "include", rb_mod_include, -1);
1957     rb_define_method(rb_cModule, "prepend", rb_mod_prepend, -1);
1958 
1959     rb_define_private_method(rb_cModule, "append_features", rb_mod_append_features, 1);
1960     rb_define_private_method(rb_cModule, "extend_object", rb_mod_extend_object, 1);
1961     rb_define_private_method(rb_cModule, "prepend_features", rb_mod_prepend_features, 1);
1962     rb_define_private_method(rb_cModule, "refine", rb_mod_refine, 1);
1963     rb_define_private_method(rb_cModule, "using", mod_using, 1);
1964     rb_define_singleton_method(rb_cModule, "used_modules",
1965 			       rb_mod_s_used_modules, 0);
1966     rb_undef_method(rb_cClass, "refine");
1967 
1968     rb_undef_method(rb_cClass, "module_function");
1969 
1970     Init_vm_eval();
1971     Init_eval_method();
1972 
1973     rb_define_singleton_method(rb_cModule, "nesting", rb_mod_nesting, 0);
1974     rb_define_singleton_method(rb_cModule, "constants", rb_mod_s_constants, -1);
1975 
1976     rb_define_private_method(rb_singleton_class(rb_vm_top_self()),
1977 			     "include", top_include, -1);
1978     rb_define_private_method(rb_singleton_class(rb_vm_top_self()),
1979 			     "using", top_using, 1);
1980 
1981     rb_define_method(rb_mKernel, "extend", rb_obj_extend, -1);
1982 
1983     rb_define_global_function("trace_var", rb_f_trace_var, -1);	/* in variable.c */
1984     rb_define_global_function("untrace_var", rb_f_untrace_var, -1);	/* in variable.c */
1985 
1986     rb_vm_register_special_exception(ruby_error_reenter, rb_eFatal, "exception reentered");
1987     rb_vm_register_special_exception(ruby_error_stackfatal, rb_eFatal, "machine stack overflow in critical region");
1988 
1989     id_signo = rb_intern_const("signo");
1990     id_status = rb_intern_const("status");
1991 }
1992