PageRenderTime 65ms CodeModel.GetById 3ms app.highlight 50ms RepoModel.GetById 1ms app.codeStats 0ms

/error.c

https://github.com/lhz/ruby
C | 1991 lines | 1146 code | 253 blank | 592 comment | 166 complexity | 7e8b2df119db5b5966a91d562ce7b73f MD5 | raw file
   1/**********************************************************************
   2
   3  error.c -
   4
   5  $Author$
   6  created at: Mon Aug  9 16:11:34 JST 1993
   7
   8  Copyright (C) 1993-2007 Yukihiro Matsumoto
   9
  10**********************************************************************/
  11
  12#include "ruby/ruby.h"
  13#include "ruby/st.h"
  14#include "ruby/encoding.h"
  15#include "internal.h"
  16#include "vm_core.h"
  17
  18#include <stdio.h>
  19#include <stdarg.h>
  20#ifdef HAVE_STDLIB_H
  21#include <stdlib.h>
  22#endif
  23#include <errno.h>
  24#ifdef HAVE_UNISTD_H
  25#include <unistd.h>
  26#endif
  27
  28#ifndef EXIT_SUCCESS
  29#define EXIT_SUCCESS 0
  30#endif
  31
  32#ifndef WIFEXITED
  33#define WIFEXITED(status) 1
  34#endif
  35
  36#ifndef WEXITSTATUS
  37#define WEXITSTATUS(status) (status)
  38#endif
  39
  40extern const char ruby_description[];
  41
  42#define REPORTBUG_MSG \
  43	"[NOTE]\n" \
  44	"You may have encountered a bug in the Ruby interpreter" \
  45	" or extension libraries.\n" \
  46	"Bug reports are welcome.\n" \
  47	"For details: http://www.ruby-lang.org/bugreport.html\n\n" \
  48
  49static const char *
  50rb_strerrno(int err)
  51{
  52#define defined_error(name, num) if (err == (num)) return (name);
  53#define undefined_error(name)
  54#include "known_errors.inc"
  55#undef defined_error
  56#undef undefined_error
  57    return NULL;
  58}
  59
  60static int
  61err_position_0(char *buf, long len, const char *file, int line)
  62{
  63    if (!file) {
  64	return 0;
  65    }
  66    else if (line == 0) {
  67	return snprintf(buf, len, "%s: ", file);
  68    }
  69    else {
  70	return snprintf(buf, len, "%s:%d: ", file, line);
  71    }
  72}
  73
  74static int
  75err_position(char *buf, long len)
  76{
  77    return err_position_0(buf, len, rb_sourcefile(), rb_sourceline());
  78}
  79
  80static void
  81err_snprintf(char *buf, long len, const char *fmt, va_list args)
  82{
  83    long n;
  84
  85    n = err_position(buf, len);
  86    if (len > n) {
  87	vsnprintf((char*)buf+n, len-n, fmt, args);
  88    }
  89}
  90
  91static void
  92compile_snprintf(char *buf, long len, const char *file, int line, const char *fmt, va_list args)
  93{
  94    long n;
  95
  96    n = err_position_0(buf, len, file, line);
  97    if (len > n) {
  98	vsnprintf((char*)buf+n, len-n, fmt, args);
  99    }
 100}
 101
 102static void err_append(const char*, rb_encoding *);
 103
 104void
 105rb_compile_error_with_enc(const char *file, int line, void *enc, const char *fmt, ...)
 106{
 107    va_list args;
 108    char buf[BUFSIZ];
 109
 110    va_start(args, fmt);
 111    compile_snprintf(buf, BUFSIZ, file, line, fmt, args);
 112    va_end(args);
 113    err_append(buf, (rb_encoding *)enc);
 114}
 115
 116void
 117rb_compile_error(const char *file, int line, const char *fmt, ...)
 118{
 119    va_list args;
 120    char buf[BUFSIZ];
 121
 122    va_start(args, fmt);
 123    compile_snprintf(buf, BUFSIZ, file, line, fmt, args);
 124    va_end(args);
 125    err_append(buf, NULL);
 126}
 127
 128void
 129rb_compile_error_append(const char *fmt, ...)
 130{
 131    va_list args;
 132    char buf[BUFSIZ];
 133
 134    va_start(args, fmt);
 135    vsnprintf(buf, BUFSIZ, fmt, args);
 136    va_end(args);
 137    err_append(buf, NULL);
 138}
 139
 140static void
 141compile_warn_print(const char *file, int line, const char *fmt, va_list args)
 142{
 143    char buf[BUFSIZ];
 144    int len;
 145
 146    compile_snprintf(buf, BUFSIZ, file, line, fmt, args);
 147    len = (int)strlen(buf);
 148    buf[len++] = '\n';
 149    rb_write_error2(buf, len);
 150}
 151
 152void
 153rb_compile_warn(const char *file, int line, const char *fmt, ...)
 154{
 155    char buf[BUFSIZ];
 156    va_list args;
 157
 158    if (NIL_P(ruby_verbose)) return;
 159
 160    snprintf(buf, BUFSIZ, "warning: %s", fmt);
 161
 162    va_start(args, fmt);
 163    compile_warn_print(file, line, buf, args);
 164    va_end(args);
 165}
 166
 167/* rb_compile_warning() reports only in verbose mode */
 168void
 169rb_compile_warning(const char *file, int line, const char *fmt, ...)
 170{
 171    char buf[BUFSIZ];
 172    va_list args;
 173
 174    if (!RTEST(ruby_verbose)) return;
 175
 176    snprintf(buf, BUFSIZ, "warning: %s", fmt);
 177
 178    va_start(args, fmt);
 179    compile_warn_print(file, line, buf, args);
 180    va_end(args);
 181}
 182
 183static void
 184warn_print(const char *fmt, va_list args)
 185{
 186    char buf[BUFSIZ];
 187    int len;
 188
 189    err_snprintf(buf, BUFSIZ, fmt, args);
 190    len = (int)strlen(buf);
 191    buf[len++] = '\n';
 192    rb_write_error2(buf, len);
 193}
 194
 195void
 196rb_warn(const char *fmt, ...)
 197{
 198    char buf[BUFSIZ];
 199    va_list args;
 200
 201    if (NIL_P(ruby_verbose)) return;
 202
 203    snprintf(buf, BUFSIZ, "warning: %s", fmt);
 204
 205    va_start(args, fmt);
 206    warn_print(buf, args);
 207    va_end(args);
 208}
 209
 210/* rb_warning() reports only in verbose mode */
 211void
 212rb_warning(const char *fmt, ...)
 213{
 214    char buf[BUFSIZ];
 215    va_list args;
 216
 217    if (!RTEST(ruby_verbose)) return;
 218
 219    snprintf(buf, BUFSIZ, "warning: %s", fmt);
 220
 221    va_start(args, fmt);
 222    warn_print(buf, args);
 223    va_end(args);
 224}
 225
 226/*
 227 * call-seq:
 228 *    warn(msg, ...)   -> nil
 229 *
 230 * Displays each of the given messages followed by a record separator on
 231 * STDERR unless warnings have been disabled (for example with the
 232 * <code>-W0</code> flag).
 233 *
 234 *    warn("warning 1", "warning 2")
 235 *
 236 *  <em>produces:</em>
 237 *
 238 *    warning 1
 239 *    warning 2
 240 */
 241
 242static VALUE
 243rb_warn_m(int argc, VALUE *argv, VALUE exc)
 244{
 245    if (!NIL_P(ruby_verbose) && argc > 0) {
 246	rb_io_puts(argc, argv, rb_stderr);
 247    }
 248    return Qnil;
 249}
 250
 251static void
 252report_bug(const char *file, int line, const char *fmt, va_list args)
 253{
 254    /* SIGSEGV handler might have a very small stack. Thus we need to use it carefully. */
 255    char buf[256];
 256    FILE *out = stderr;
 257    int len = err_position_0(buf, 256, file, line);
 258
 259    if ((ssize_t)fwrite(buf, 1, len, out) == (ssize_t)len ||
 260	(ssize_t)fwrite(buf, 1, len, (out = stdout)) == (ssize_t)len) {
 261
 262	fputs("[BUG] ", out);
 263	vsnprintf(buf, 256, fmt, args);
 264	fputs(buf, out);
 265	snprintf(buf, 256, "\n%s\n\n", ruby_description);
 266	fputs(buf, out);
 267
 268
 269	rb_vm_bugreport();
 270
 271	fprintf(out, REPORTBUG_MSG);
 272    }
 273}
 274
 275void
 276rb_bug(const char *fmt, ...)
 277{
 278    va_list args;
 279    const char *file = NULL;
 280    int line = 0;
 281
 282    if (GET_THREAD()) {
 283	file = rb_sourcefile();
 284	line = rb_sourceline();
 285    }
 286
 287    va_start(args, fmt);
 288    report_bug(file, line, fmt, args);
 289    va_end(args);
 290
 291#if defined(_WIN32) && defined(RT_VER) && RT_VER >= 80
 292    _set_abort_behavior( 0, _CALL_REPORTFAULT);
 293#endif
 294
 295    abort();
 296}
 297
 298void
 299rb_bug_errno(const char *mesg, int errno_arg)
 300{
 301    if (errno_arg == 0)
 302        rb_bug("%s: errno == 0 (NOERROR)", mesg);
 303    else {
 304        const char *errno_str = rb_strerrno(errno_arg);
 305        if (errno_str)
 306            rb_bug("%s: %s (%s)", mesg, strerror(errno_arg), errno_str);
 307        else
 308            rb_bug("%s: %s (%d)", mesg, strerror(errno_arg), errno_arg);
 309    }
 310}
 311
 312/*
 313 * this is safe to call inside signal handler and timer thread
 314 * (which isn't a Ruby Thread object)
 315 */
 316#define write_or_abort(fd, str, len) (write((fd), (str), (len)) < 0 ? abort() : (void)0)
 317#define WRITE_CONST(fd,str) write_or_abort((fd),(str),sizeof(str) - 1)
 318
 319void
 320rb_async_bug_errno(const char *mesg, int errno_arg)
 321{
 322    WRITE_CONST(2, "[ASYNC BUG] ");
 323    write_or_abort(2, mesg, strlen(mesg));
 324    WRITE_CONST(2, "\n");
 325
 326    if (errno_arg == 0) {
 327	WRITE_CONST(2, "errno == 0 (NOERROR)\n");
 328    }
 329    else {
 330	const char *errno_str = rb_strerrno(errno_arg);
 331
 332	if (!errno_str)
 333	    errno_str = "undefined errno";
 334	write_or_abort(2, errno_str, strlen(errno_str));
 335    }
 336    WRITE_CONST(2, "\n\n");
 337    write_or_abort(2, ruby_description, strlen(ruby_description));
 338    WRITE_CONST(2, "\n\n");
 339    WRITE_CONST(2, REPORTBUG_MSG);
 340    abort();
 341}
 342
 343void
 344rb_compile_bug(const char *file, int line, const char *fmt, ...)
 345{
 346    va_list args;
 347
 348    va_start(args, fmt);
 349    report_bug(file, line, fmt, args);
 350    va_end(args);
 351
 352    abort();
 353}
 354
 355static const struct types {
 356    int type;
 357    const char *name;
 358} builtin_types[] = {
 359    {T_NIL,	"nil"},
 360    {T_OBJECT,	"Object"},
 361    {T_CLASS,	"Class"},
 362    {T_ICLASS,	"iClass"},	/* internal use: mixed-in module holder */
 363    {T_MODULE,	"Module"},
 364    {T_FLOAT,	"Float"},
 365    {T_STRING,	"String"},
 366    {T_REGEXP,	"Regexp"},
 367    {T_ARRAY,	"Array"},
 368    {T_FIXNUM,	"Fixnum"},
 369    {T_HASH,	"Hash"},
 370    {T_STRUCT,	"Struct"},
 371    {T_BIGNUM,	"Bignum"},
 372    {T_FILE,	"File"},
 373    {T_RATIONAL,"Rational"},
 374    {T_COMPLEX, "Complex"},
 375    {T_TRUE,	"true"},
 376    {T_FALSE,	"false"},
 377    {T_SYMBOL,	"Symbol"},	/* :symbol */
 378    {T_DATA,	"Data"},	/* internal use: wrapped C pointers */
 379    {T_MATCH,	"MatchData"},	/* data of $~ */
 380    {T_NODE,	"Node"},	/* internal use: syntax tree node */
 381    {T_UNDEF,	"undef"},	/* internal use: #undef; should not happen */
 382};
 383
 384static const char *
 385builtin_type_name(VALUE x)
 386{
 387    const char *etype;
 388
 389    if (NIL_P(x)) {
 390	etype = "nil";
 391    }
 392    else if (FIXNUM_P(x)) {
 393	etype = "Fixnum";
 394    }
 395    else if (SYMBOL_P(x)) {
 396	etype = "Symbol";
 397    }
 398    else if (RB_TYPE_P(x, T_TRUE)) {
 399	etype = "true";
 400    }
 401    else if (RB_TYPE_P(x, T_FALSE)) {
 402	etype = "false";
 403    }
 404    else {
 405	etype = rb_obj_classname(x);
 406    }
 407    return etype;
 408}
 409
 410void
 411rb_check_type(VALUE x, int t)
 412{
 413    const struct types *type = builtin_types;
 414    const struct types *const typeend = builtin_types +
 415	sizeof(builtin_types) / sizeof(builtin_types[0]);
 416    int xt;
 417
 418    if (x == Qundef) {
 419	rb_bug("undef leaked to the Ruby space");
 420    }
 421
 422    xt = TYPE(x);
 423    if (xt != t || (xt == T_DATA && RTYPEDDATA_P(x))) {
 424	while (type < typeend) {
 425	    if (type->type == t) {
 426		const char *etype;
 427
 428		etype = builtin_type_name(x);
 429		rb_raise(rb_eTypeError, "wrong argument type %s (expected %s)",
 430			 etype, type->name);
 431	    }
 432	    type++;
 433	}
 434	if (xt > T_MASK && xt <= 0x3f) {
 435	    rb_fatal("unknown type 0x%x (0x%x given, probably comes from extension library for ruby 1.8)", t, xt);
 436	}
 437	rb_bug("unknown type 0x%x (0x%x given)", t, xt);
 438    }
 439}
 440
 441int
 442rb_typeddata_inherited_p(const rb_data_type_t *child, const rb_data_type_t *parent)
 443{
 444    while (child) {
 445	if (child == parent) return 1;
 446	child = child->parent;
 447    }
 448    return 0;
 449}
 450
 451int
 452rb_typeddata_is_kind_of(VALUE obj, const rb_data_type_t *data_type)
 453{
 454    if (SPECIAL_CONST_P(obj) || BUILTIN_TYPE(obj) != T_DATA ||
 455	!RTYPEDDATA_P(obj) || !rb_typeddata_inherited_p(RTYPEDDATA_TYPE(obj), data_type)) {
 456	return 0;
 457    }
 458    return 1;
 459}
 460
 461void *
 462rb_check_typeddata(VALUE obj, const rb_data_type_t *data_type)
 463{
 464    const char *etype;
 465    static const char mesg[] = "wrong argument type %s (expected %s)";
 466
 467    if (SPECIAL_CONST_P(obj) || BUILTIN_TYPE(obj) != T_DATA) {
 468	etype = builtin_type_name(obj);
 469	rb_raise(rb_eTypeError, mesg, etype, data_type->wrap_struct_name);
 470    }
 471    if (!RTYPEDDATA_P(obj)) {
 472	etype = rb_obj_classname(obj);
 473	rb_raise(rb_eTypeError, mesg, etype, data_type->wrap_struct_name);
 474    }
 475    else if (!rb_typeddata_inherited_p(RTYPEDDATA_TYPE(obj), data_type)) {
 476	etype = RTYPEDDATA_TYPE(obj)->wrap_struct_name;
 477	rb_raise(rb_eTypeError, mesg, etype, data_type->wrap_struct_name);
 478    }
 479    return DATA_PTR(obj);
 480}
 481
 482/* exception classes */
 483VALUE rb_eException;
 484VALUE rb_eSystemExit;
 485VALUE rb_eInterrupt;
 486VALUE rb_eSignal;
 487VALUE rb_eFatal;
 488VALUE rb_eStandardError;
 489VALUE rb_eRuntimeError;
 490VALUE rb_eTypeError;
 491VALUE rb_eArgError;
 492VALUE rb_eIndexError;
 493VALUE rb_eKeyError;
 494VALUE rb_eRangeError;
 495VALUE rb_eNameError;
 496VALUE rb_eEncodingError;
 497VALUE rb_eEncCompatError;
 498VALUE rb_eNoMethodError;
 499VALUE rb_eSecurityError;
 500VALUE rb_eNotImpError;
 501VALUE rb_eNoMemError;
 502VALUE rb_cNameErrorMesg;
 503
 504VALUE rb_eScriptError;
 505VALUE rb_eSyntaxError;
 506VALUE rb_eLoadError;
 507
 508VALUE rb_eSystemCallError;
 509VALUE rb_mErrno;
 510static VALUE rb_eNOERROR;
 511
 512#undef rb_exc_new2
 513
 514VALUE
 515rb_exc_new(VALUE etype, const char *ptr, long len)
 516{
 517    return rb_funcall(etype, rb_intern("new"), 1, rb_str_new(ptr, len));
 518}
 519
 520VALUE
 521rb_exc_new2(VALUE etype, const char *s)
 522{
 523    return rb_exc_new(etype, s, strlen(s));
 524}
 525
 526VALUE
 527rb_exc_new3(VALUE etype, VALUE str)
 528{
 529    StringValue(str);
 530    return rb_funcall(etype, rb_intern("new"), 1, str);
 531}
 532
 533/*
 534 * call-seq:
 535 *    Exception.new(msg = nil)   ->  exception
 536 *
 537 *  Construct a new Exception object, optionally passing in
 538 *  a message.
 539 */
 540
 541static VALUE
 542exc_initialize(int argc, VALUE *argv, VALUE exc)
 543{
 544    VALUE arg;
 545
 546    rb_scan_args(argc, argv, "01", &arg);
 547    rb_iv_set(exc, "mesg", arg);
 548    rb_iv_set(exc, "bt", Qnil);
 549
 550    return exc;
 551}
 552
 553/*
 554 *  Document-method: exception
 555 *
 556 *  call-seq:
 557 *     exc.exception(string)  ->  an_exception or exc
 558 *
 559 *  With no argument, or if the argument is the same as the receiver,
 560 *  return the receiver. Otherwise, create a new
 561 *  exception object of the same class as the receiver, but with a
 562 *  message equal to <code>string.to_str</code>.
 563 *
 564 */
 565
 566static VALUE
 567exc_exception(int argc, VALUE *argv, VALUE self)
 568{
 569    VALUE exc;
 570
 571    if (argc == 0) return self;
 572    if (argc == 1 && self == argv[0]) return self;
 573    exc = rb_obj_clone(self);
 574    exc_initialize(argc, argv, exc);
 575
 576    return exc;
 577}
 578
 579/*
 580 * call-seq:
 581 *   exception.to_s   ->  string
 582 *
 583 * Returns exception's message (or the name of the exception if
 584 * no message is set).
 585 */
 586
 587static VALUE
 588exc_to_s(VALUE exc)
 589{
 590    VALUE mesg = rb_attr_get(exc, rb_intern("mesg"));
 591    VALUE r = Qnil;
 592
 593    if (NIL_P(mesg)) return rb_class_name(CLASS_OF(exc));
 594    r = rb_String(mesg);
 595    OBJ_INFECT(r, exc);
 596    return r;
 597}
 598
 599/*
 600 * call-seq:
 601 *   exception.message   ->  string
 602 *
 603 * Returns the result of invoking <code>exception.to_s</code>.
 604 * Normally this returns the exception's message or name. By
 605 * supplying a to_str method, exceptions are agreeing to
 606 * be used where Strings are expected.
 607 */
 608
 609static VALUE
 610exc_message(VALUE exc)
 611{
 612    return rb_funcall(exc, rb_intern("to_s"), 0, 0);
 613}
 614
 615/*
 616 * call-seq:
 617 *   exception.inspect   -> string
 618 *
 619 * Return this exception's class name and message
 620 */
 621
 622static VALUE
 623exc_inspect(VALUE exc)
 624{
 625    VALUE str, klass;
 626
 627    klass = CLASS_OF(exc);
 628    exc = rb_obj_as_string(exc);
 629    if (RSTRING_LEN(exc) == 0) {
 630	return rb_str_dup(rb_class_name(klass));
 631    }
 632
 633    str = rb_str_buf_new2("#<");
 634    klass = rb_class_name(klass);
 635    rb_str_buf_append(str, klass);
 636    rb_str_buf_cat(str, ": ", 2);
 637    rb_str_buf_append(str, exc);
 638    rb_str_buf_cat(str, ">", 1);
 639
 640    return str;
 641}
 642
 643/*
 644 *  call-seq:
 645 *     exception.backtrace    -> array
 646 *
 647 *  Returns any backtrace associated with the exception. The backtrace
 648 *  is an array of strings, each containing either ``filename:lineNo: in
 649 *  `method''' or ``filename:lineNo.''
 650 *
 651 *     def a
 652 *       raise "boom"
 653 *     end
 654 *
 655 *     def b
 656 *       a()
 657 *     end
 658 *
 659 *     begin
 660 *       b()
 661 *     rescue => detail
 662 *       print detail.backtrace.join("\n")
 663 *     end
 664 *
 665 *  <em>produces:</em>
 666 *
 667 *     prog.rb:2:in `a'
 668 *     prog.rb:6:in `b'
 669 *     prog.rb:10
 670*/
 671
 672static VALUE
 673exc_backtrace(VALUE exc)
 674{
 675    ID bt;
 676
 677    CONST_ID(bt, "bt");
 678    return rb_attr_get(exc, bt);
 679}
 680
 681VALUE
 682rb_check_backtrace(VALUE bt)
 683{
 684    long i;
 685    static const char err[] = "backtrace must be Array of String";
 686
 687    if (!NIL_P(bt)) {
 688	int t = TYPE(bt);
 689
 690	if (t == T_STRING) return rb_ary_new3(1, bt);
 691	if (t != T_ARRAY) {
 692	    rb_raise(rb_eTypeError, err);
 693	}
 694	for (i=0;i<RARRAY_LEN(bt);i++) {
 695	    if (TYPE(RARRAY_PTR(bt)[i]) != T_STRING) {
 696		rb_raise(rb_eTypeError, err);
 697	    }
 698	}
 699    }
 700    return bt;
 701}
 702
 703/*
 704 *  call-seq:
 705 *     exc.set_backtrace(array)   ->  array
 706 *
 707 *  Sets the backtrace information associated with <i>exc</i>. The
 708 *  argument must be an array of <code>String</code> objects in the
 709 *  format described in <code>Exception#backtrace</code>.
 710 *
 711 */
 712
 713static VALUE
 714exc_set_backtrace(VALUE exc, VALUE bt)
 715{
 716    return rb_iv_set(exc, "bt", rb_check_backtrace(bt));
 717}
 718
 719static VALUE
 720try_convert_to_exception(VALUE obj)
 721{
 722    ID id_exception;
 723    CONST_ID(id_exception, "exception");
 724    return rb_check_funcall(obj, id_exception, 0, 0);
 725}
 726
 727/*
 728 *  call-seq:
 729 *     exc == obj   -> true or false
 730 *
 731 *  Equality---If <i>obj</i> is not an <code>Exception</code>, returns
 732 *  <code>false</code>. Otherwise, returns <code>true</code> if <i>exc</i> and
 733 *  <i>obj</i> share same class, messages, and backtrace.
 734 */
 735
 736static VALUE
 737exc_equal(VALUE exc, VALUE obj)
 738{
 739    VALUE mesg, backtrace;
 740    ID id_mesg;
 741
 742    if (exc == obj) return Qtrue;
 743    CONST_ID(id_mesg, "mesg");
 744
 745    if (rb_obj_class(exc) != rb_obj_class(obj)) {
 746	int status = 0;
 747	ID id_message, id_backtrace;
 748	CONST_ID(id_message, "message");
 749	CONST_ID(id_backtrace, "backtrace");
 750
 751	obj = rb_protect(try_convert_to_exception, obj, &status);
 752	if (status || obj == Qundef) {
 753	    rb_set_errinfo(Qnil);
 754	    return Qfalse;
 755	}
 756	if (rb_obj_class(exc) != rb_obj_class(obj)) return Qfalse;
 757	mesg = rb_check_funcall(obj, id_message, 0, 0);
 758	if (mesg == Qundef) return Qfalse;
 759	backtrace = rb_check_funcall(obj, id_backtrace, 0, 0);
 760	if (backtrace == Qundef) return Qfalse;
 761    }
 762    else {
 763	mesg = rb_attr_get(obj, id_mesg);
 764	backtrace = exc_backtrace(obj);
 765    }
 766
 767    if (!rb_equal(rb_attr_get(exc, id_mesg), mesg))
 768	return Qfalse;
 769    if (!rb_equal(exc_backtrace(exc), backtrace))
 770	return Qfalse;
 771    return Qtrue;
 772}
 773
 774/*
 775 * call-seq:
 776 *   SystemExit.new              -> system_exit
 777 *   SystemExit.new(status)      -> system_exit
 778 *   SystemExit.new(status, msg) -> system_exit
 779 *   SystemExit.new(msg)         -> system_exit
 780 *
 781 * Create a new +SystemExit+ exception with the given status and message.
 782 * Status is true, false, or an integer.
 783 * If status is not given, true is used.
 784 */
 785
 786static VALUE
 787exit_initialize(int argc, VALUE *argv, VALUE exc)
 788{
 789    VALUE status;
 790    if (argc > 0) {
 791	status = *argv;
 792
 793	switch (status) {
 794	  case Qtrue:
 795	    status = INT2FIX(EXIT_SUCCESS);
 796	    ++argv;
 797	    --argc;
 798	    break;
 799	  case Qfalse:
 800	    status = INT2FIX(EXIT_FAILURE);
 801	    ++argv;
 802	    --argc;
 803	    break;
 804	  default:
 805	    status = rb_check_to_int(status);
 806	    if (NIL_P(status)) {
 807		status = INT2FIX(EXIT_SUCCESS);
 808	    }
 809	    else {
 810#if EXIT_SUCCESS != 0
 811		if (status == INT2FIX(0))
 812		    status = INT2FIX(EXIT_SUCCESS);
 813#endif
 814		++argv;
 815		--argc;
 816	    }
 817	    break;
 818	}
 819    }
 820    else {
 821	status = INT2FIX(EXIT_SUCCESS);
 822    }
 823    rb_call_super(argc, argv);
 824    rb_iv_set(exc, "status", status);
 825    return exc;
 826}
 827
 828
 829/*
 830 * call-seq:
 831 *   system_exit.status   -> fixnum
 832 *
 833 * Return the status value associated with this system exit.
 834 */
 835
 836static VALUE
 837exit_status(VALUE exc)
 838{
 839    return rb_attr_get(exc, rb_intern("status"));
 840}
 841
 842
 843/*
 844 * call-seq:
 845 *   system_exit.success?  -> true or false
 846 *
 847 * Returns +true+ if exiting successful, +false+ if not.
 848 */
 849
 850static VALUE
 851exit_success_p(VALUE exc)
 852{
 853    VALUE status_val = rb_attr_get(exc, rb_intern("status"));
 854    int status;
 855
 856    if (NIL_P(status_val))
 857	return Qtrue;
 858    status = NUM2INT(status_val);
 859    if (WIFEXITED(status) && WEXITSTATUS(status) == EXIT_SUCCESS)
 860	return Qtrue;
 861
 862    return Qfalse;
 863}
 864
 865void
 866rb_name_error(ID id, const char *fmt, ...)
 867{
 868    VALUE exc, argv[2];
 869    va_list args;
 870
 871    va_start(args, fmt);
 872    argv[0] = rb_vsprintf(fmt, args);
 873    va_end(args);
 874
 875    argv[1] = ID2SYM(id);
 876    exc = rb_class_new_instance(2, argv, rb_eNameError);
 877    rb_exc_raise(exc);
 878}
 879
 880void
 881rb_name_error_str(VALUE str, const char *fmt, ...)
 882{
 883    VALUE exc, argv[2];
 884    va_list args;
 885
 886    va_start(args, fmt);
 887    argv[0] = rb_vsprintf(fmt, args);
 888    va_end(args);
 889
 890    argv[1] = str;
 891    exc = rb_class_new_instance(2, argv, rb_eNameError);
 892    rb_exc_raise(exc);
 893}
 894
 895/*
 896 * call-seq:
 897 *   NameError.new(msg [, name])  -> name_error
 898 *
 899 * Construct a new NameError exception. If given the <i>name</i>
 900 * parameter may subsequently be examined using the <code>NameError.name</code>
 901 * method.
 902 */
 903
 904static VALUE
 905name_err_initialize(int argc, VALUE *argv, VALUE self)
 906{
 907    VALUE name;
 908
 909    name = (argc > 1) ? argv[--argc] : Qnil;
 910    rb_call_super(argc, argv);
 911    rb_iv_set(self, "name", name);
 912    return self;
 913}
 914
 915/*
 916 *  call-seq:
 917 *    name_error.name    ->  string or nil
 918 *
 919 *  Return the name associated with this NameError exception.
 920 */
 921
 922static VALUE
 923name_err_name(VALUE self)
 924{
 925    return rb_attr_get(self, rb_intern("name"));
 926}
 927
 928/*
 929 * call-seq:
 930 *  name_error.to_s   -> string
 931 *
 932 * Produce a nicely-formatted string representing the +NameError+.
 933 */
 934
 935static VALUE
 936name_err_to_s(VALUE exc)
 937{
 938    VALUE mesg = rb_attr_get(exc, rb_intern("mesg"));
 939    VALUE str = mesg;
 940
 941    if (NIL_P(mesg)) return rb_class_name(CLASS_OF(exc));
 942    StringValue(str);
 943    if (str != mesg) {
 944	rb_iv_set(exc, "mesg", mesg = str);
 945    }
 946    OBJ_INFECT(mesg, exc);
 947    return mesg;
 948}
 949
 950/*
 951 * call-seq:
 952 *   NoMethodError.new(msg, name [, args])  -> no_method_error
 953 *
 954 * Construct a NoMethodError exception for a method of the given name
 955 * called with the given arguments. The name may be accessed using
 956 * the <code>#name</code> method on the resulting object, and the
 957 * arguments using the <code>#args</code> method.
 958 */
 959
 960static VALUE
 961nometh_err_initialize(int argc, VALUE *argv, VALUE self)
 962{
 963    VALUE args = (argc > 2) ? argv[--argc] : Qnil;
 964    name_err_initialize(argc, argv, self);
 965    rb_iv_set(self, "args", args);
 966    return self;
 967}
 968
 969/* :nodoc: */
 970#define NAME_ERR_MESG_COUNT 3
 971
 972static void
 973name_err_mesg_mark(void *p)
 974{
 975    VALUE *ptr = p;
 976    rb_gc_mark_locations(ptr, ptr+NAME_ERR_MESG_COUNT);
 977}
 978
 979#define name_err_mesg_free RUBY_TYPED_DEFAULT_FREE
 980
 981static size_t
 982name_err_mesg_memsize(const void *p)
 983{
 984    return p ? (NAME_ERR_MESG_COUNT * sizeof(VALUE)) : 0;
 985}
 986
 987static const rb_data_type_t name_err_mesg_data_type = {
 988    "name_err_mesg",
 989    {
 990	name_err_mesg_mark,
 991	name_err_mesg_free,
 992	name_err_mesg_memsize,
 993    },
 994};
 995
 996/* :nodoc: */
 997VALUE
 998rb_name_err_mesg_new(VALUE obj, VALUE mesg, VALUE recv, VALUE method)
 999{
1000    VALUE *ptr = ALLOC_N(VALUE, NAME_ERR_MESG_COUNT);
1001    VALUE result;
1002
1003    ptr[0] = mesg;
1004    ptr[1] = recv;
1005    ptr[2] = method;
1006    result = TypedData_Wrap_Struct(rb_cNameErrorMesg, &name_err_mesg_data_type, ptr);
1007    RB_GC_GUARD(mesg);
1008    RB_GC_GUARD(recv);
1009    RB_GC_GUARD(method);
1010    return result;
1011}
1012
1013/* :nodoc: */
1014static VALUE
1015name_err_mesg_equal(VALUE obj1, VALUE obj2)
1016{
1017    VALUE *ptr1, *ptr2;
1018    int i;
1019
1020    if (obj1 == obj2) return Qtrue;
1021    if (rb_obj_class(obj2) != rb_cNameErrorMesg)
1022	return Qfalse;
1023
1024    TypedData_Get_Struct(obj1, VALUE, &name_err_mesg_data_type, ptr1);
1025    TypedData_Get_Struct(obj2, VALUE, &name_err_mesg_data_type, ptr2);
1026    for (i=0; i<NAME_ERR_MESG_COUNT; i++) {
1027	if (!rb_equal(ptr1[i], ptr2[i]))
1028	    return Qfalse;
1029    }
1030    return Qtrue;
1031}
1032
1033/* :nodoc: */
1034static VALUE
1035name_err_mesg_to_str(VALUE obj)
1036{
1037    VALUE *ptr, mesg;
1038    TypedData_Get_Struct(obj, VALUE, &name_err_mesg_data_type, ptr);
1039
1040    mesg = ptr[0];
1041    if (NIL_P(mesg)) return Qnil;
1042    else {
1043	const char *desc = 0;
1044	VALUE d = 0, args[NAME_ERR_MESG_COUNT];
1045	int state = 0;
1046
1047	obj = ptr[1];
1048	switch (TYPE(obj)) {
1049	  case T_NIL:
1050	    desc = "nil";
1051	    break;
1052	  case T_TRUE:
1053	    desc = "true";
1054	    break;
1055	  case T_FALSE:
1056	    desc = "false";
1057	    break;
1058	  default:
1059	    d = rb_protect(rb_inspect, obj, &state);
1060	    if (state)
1061		rb_set_errinfo(Qnil);
1062	    if (NIL_P(d) || RSTRING_LEN(d) > 65) {
1063		d = rb_any_to_s(obj);
1064	    }
1065	    desc = RSTRING_PTR(d);
1066	    break;
1067	}
1068	if (desc && desc[0] != '#') {
1069	    d = d ? rb_str_dup(d) : rb_str_new2(desc);
1070	    rb_str_cat2(d, ":");
1071	    rb_str_cat2(d, rb_obj_classname(obj));
1072	}
1073	args[0] = mesg;
1074	args[1] = ptr[2];
1075	args[2] = d;
1076	mesg = rb_f_sprintf(NAME_ERR_MESG_COUNT, args);
1077    }
1078    OBJ_INFECT(mesg, obj);
1079    return mesg;
1080}
1081
1082/* :nodoc: */
1083static VALUE
1084name_err_mesg_load(VALUE klass, VALUE str)
1085{
1086    return str;
1087}
1088
1089/*
1090 * call-seq:
1091 *   no_method_error.args  -> obj
1092 *
1093 * Return the arguments passed in as the third parameter to
1094 * the constructor.
1095 */
1096
1097static VALUE
1098nometh_err_args(VALUE self)
1099{
1100    return rb_attr_get(self, rb_intern("args"));
1101}
1102
1103void
1104rb_invalid_str(const char *str, const char *type)
1105{
1106    volatile VALUE s = rb_str_inspect(rb_str_new2(str));
1107
1108    rb_raise(rb_eArgError, "invalid value for %s: %s", type, RSTRING_PTR(s));
1109}
1110
1111/*
1112 *  Document-module: Errno
1113 *
1114 *  Ruby exception objects are subclasses of <code>Exception</code>.
1115 *  However, operating systems typically report errors using plain
1116 *  integers. Module <code>Errno</code> is created dynamically to map
1117 *  these operating system errors to Ruby classes, with each error
1118 *  number generating its own subclass of <code>SystemCallError</code>.
1119 *  As the subclass is created in module <code>Errno</code>, its name
1120 *  will start <code>Errno::</code>.
1121 *
1122 *  The names of the <code>Errno::</code> classes depend on
1123 *  the environment in which Ruby runs. On a typical Unix or Windows
1124 *  platform, there are <code>Errno</code> classes such as
1125 *  <code>Errno::EACCES</code>, <code>Errno::EAGAIN</code>,
1126 *  <code>Errno::EINTR</code>, and so on.
1127 *
1128 *  The integer operating system error number corresponding to a
1129 *  particular error is available as the class constant
1130 *  <code>Errno::</code><em>error</em><code>::Errno</code>.
1131 *
1132 *     Errno::EACCES::Errno   #=> 13
1133 *     Errno::EAGAIN::Errno   #=> 11
1134 *     Errno::EINTR::Errno    #=> 4
1135 *
1136 *  The full list of operating system errors on your particular platform
1137 *  are available as the constants of <code>Errno</code>.
1138 *
1139 *     Errno.constants   #=> :E2BIG, :EACCES, :EADDRINUSE, :EADDRNOTAVAIL, ...
1140 */
1141
1142static st_table *syserr_tbl;
1143
1144static VALUE
1145set_syserr(int n, const char *name)
1146{
1147    st_data_t error;
1148
1149    if (!st_lookup(syserr_tbl, n, &error)) {
1150	error = rb_define_class_under(rb_mErrno, name, rb_eSystemCallError);
1151	rb_define_const(error, "Errno", INT2NUM(n));
1152	st_add_direct(syserr_tbl, n, error);
1153    }
1154    else {
1155	rb_define_const(rb_mErrno, name, error);
1156    }
1157    return error;
1158}
1159
1160static VALUE
1161get_syserr(int n)
1162{
1163    st_data_t error;
1164
1165    if (!st_lookup(syserr_tbl, n, &error)) {
1166	char name[8];	/* some Windows' errno have 5 digits. */
1167
1168	snprintf(name, sizeof(name), "E%03d", n);
1169	error = set_syserr(n, name);
1170    }
1171    return error;
1172}
1173
1174/*
1175 * call-seq:
1176 *   SystemCallError.new(msg, errno)  -> system_call_error_subclass
1177 *
1178 * If _errno_ corresponds to a known system error code, constructs
1179 * the appropriate <code>Errno</code> class for that error, otherwise
1180 * constructs a generic <code>SystemCallError</code> object. The
1181 * error number is subsequently available via the <code>errno</code>
1182 * method.
1183 */
1184
1185static VALUE
1186syserr_initialize(int argc, VALUE *argv, VALUE self)
1187{
1188#if !defined(_WIN32)
1189    char *strerror();
1190#endif
1191    const char *err;
1192    VALUE mesg, error;
1193    VALUE klass = rb_obj_class(self);
1194
1195    if (klass == rb_eSystemCallError) {
1196	st_data_t data = (st_data_t)klass;
1197	rb_scan_args(argc, argv, "11", &mesg, &error);
1198	if (argc == 1 && FIXNUM_P(mesg)) {
1199	    error = mesg; mesg = Qnil;
1200	}
1201	if (!NIL_P(error) && st_lookup(syserr_tbl, NUM2LONG(error), &data)) {
1202	    klass = (VALUE)data;
1203	    /* change class */
1204	    if (!RB_TYPE_P(self, T_OBJECT)) { /* insurance to avoid type crash */
1205		rb_raise(rb_eTypeError, "invalid instance type");
1206	    }
1207	    RBASIC(self)->klass = klass;
1208	}
1209    }
1210    else {
1211	rb_scan_args(argc, argv, "01", &mesg);
1212	error = rb_const_get(klass, rb_intern("Errno"));
1213    }
1214    if (!NIL_P(error)) err = strerror(NUM2INT(error));
1215    else err = "unknown error";
1216    if (!NIL_P(mesg)) {
1217	rb_encoding *le = rb_locale_encoding();
1218	VALUE str = StringValue(mesg);
1219	rb_encoding *me = rb_enc_get(mesg);
1220
1221	mesg = rb_sprintf("%s - %.*s", err,
1222			  (int)RSTRING_LEN(str), RSTRING_PTR(str));
1223	if (le != me && rb_enc_asciicompat(me)) {
1224	    le = me;
1225	}/* else assume err is non ASCII string. */
1226	OBJ_INFECT(mesg, str);
1227	rb_enc_associate(mesg, le);
1228    }
1229    else {
1230	mesg = rb_str_new2(err);
1231	rb_enc_associate(mesg, rb_locale_encoding());
1232    }
1233    rb_call_super(1, &mesg);
1234    rb_iv_set(self, "errno", error);
1235    return self;
1236}
1237
1238/*
1239 * call-seq:
1240 *   system_call_error.errno   -> fixnum
1241 *
1242 * Return this SystemCallError's error number.
1243 */
1244
1245static VALUE
1246syserr_errno(VALUE self)
1247{
1248    return rb_attr_get(self, rb_intern("errno"));
1249}
1250
1251/*
1252 * call-seq:
1253 *   system_call_error === other  -> true or false
1254 *
1255 * Return +true+ if the receiver is a generic +SystemCallError+, or
1256 * if the error numbers +self+ and _other_ are the same.
1257 */
1258
1259static VALUE
1260syserr_eqq(VALUE self, VALUE exc)
1261{
1262    VALUE num, e;
1263    ID en;
1264
1265    CONST_ID(en, "errno");
1266
1267    if (!rb_obj_is_kind_of(exc, rb_eSystemCallError)) {
1268	if (!rb_respond_to(exc, en)) return Qfalse;
1269    }
1270    else if (self == rb_eSystemCallError) return Qtrue;
1271
1272    num = rb_attr_get(exc, rb_intern("errno"));
1273    if (NIL_P(num)) {
1274	num = rb_funcall(exc, en, 0, 0);
1275    }
1276    e = rb_const_get(self, rb_intern("Errno"));
1277    if (FIXNUM_P(num) ? num == e : rb_equal(num, e))
1278	return Qtrue;
1279    return Qfalse;
1280}
1281
1282
1283/*
1284 *  Document-class: StandardError
1285 *
1286 *  The most standard error types are subclasses of StandardError. A
1287 *  rescue clause without an explicit Exception class will rescue all
1288 *  StandardErrors (and only those).
1289 *
1290 *     def foo
1291 *       raise "Oups"
1292 *     end
1293 *     foo rescue "Hello"   #=> "Hello"
1294 *
1295 *  On the other hand:
1296 *
1297 *     require 'does/not/exist' rescue "Hi"
1298 *
1299 *  <em>raises the exception:</em>
1300 *
1301 *     LoadError: no such file to load -- does/not/exist
1302 *
1303 */
1304
1305/*
1306 *  Document-class: SystemExit
1307 *
1308 *  Raised by +exit+ to initiate the termination of the script.
1309 */
1310
1311/*
1312 *  Document-class: SignalException
1313 *
1314 *  Raised when a signal is received.
1315 *
1316 *     begin
1317 *       Process.kill('HUP',Process.pid)
1318 *     rescue SignalException => e
1319 *       puts "received Exception #{e}"
1320 *     end
1321 *
1322 *  <em>produces:</em>
1323 *
1324 *     received Exception SIGHUP
1325 */
1326
1327/*
1328 *  Document-class: Interrupt
1329 *
1330 *  Raised with the interrupt signal is received, typically because the
1331 *  user pressed on Control-C (on most posix platforms). As such, it is a
1332 *  subclass of +SignalException+.
1333 *
1334 *     begin
1335 *       puts "Press ctrl-C when you get bored"
1336 *       loop {}
1337 *     rescue Interrupt => e
1338 *       puts "Note: You will typically use Signal.trap instead."
1339 *     end
1340 *
1341 *  <em>produces:</em>
1342 *
1343 *     Press ctrl-C when you get bored
1344 *
1345 *  <em>then waits until it is interrupted with Control-C and then prints:</em>
1346 *
1347 *     Note: You will typically use Signal.trap instead.
1348 */
1349
1350/*
1351 *  Document-class: TypeError
1352 *
1353 *  Raised when encountering an object that is not of the expected type.
1354 *
1355 *     [1, 2, 3].first("two")
1356 *
1357 *  <em>raises the exception:</em>
1358 *
1359 *     TypeError: can't convert String into Integer
1360 *
1361 */
1362
1363/*
1364 *  Document-class: ArgumentError
1365 *
1366 *  Raised when the arguments are wrong and there isn't a more specific
1367 *  Exception class.
1368 *
1369 *  Ex: passing the wrong number of arguments
1370 *
1371 *     [1, 2, 3].first(4, 5)
1372 *
1373 *  <em>raises the exception:</em>
1374 *
1375 *     ArgumentError: wrong number of arguments (2 for 1)
1376 *
1377 *  Ex: passing an argument that is not acceptable:
1378 *
1379 *     [1, 2, 3].first(-4)
1380 *
1381 *  <em>raises the exception:</em>
1382 *
1383 *     ArgumentError: negative array size
1384 */
1385
1386/*
1387 *  Document-class: IndexError
1388 *
1389 *  Raised when the given index is invalid.
1390 *
1391 *     a = [:foo, :bar]
1392 *     a.fetch(0)   #=> :foo
1393 *     a[4]         #=> nil
1394 *     a.fetch(4)   #=> IndexError: index 4 outside of array bounds: -2...2
1395 *
1396 */
1397
1398/*
1399 *  Document-class: KeyError
1400 *
1401 *  Raised when the specified key is not found. It is a subclass of
1402 *  IndexError.
1403 *
1404 *     h = {"foo" => :bar}
1405 *     h.fetch("foo") #=> :bar
1406 *     h.fetch("baz") #=> KeyError: key not found: "baz"
1407 *
1408 */
1409
1410/*
1411 *  Document-class: RangeError
1412 *
1413 *  Raised when a given numerical value is out of range.
1414 *
1415 *     [1, 2, 3].drop(1 << 100)
1416 *
1417 *  <em>raises the exception:</em>
1418 *
1419 *     RangeError: bignum too big to convert into `long'
1420 */
1421
1422/*
1423 *  Document-class: ScriptError
1424 *
1425 *  ScriptError is the superclass for errors raised when a script
1426 *  can not be executed because of a +LoadError+,
1427 *  +NotImplementedError+ or a +SyntaxError+. Note these type of
1428 *  +ScriptErrors+ are not +StandardError+ and will not be
1429 *  rescued unless it is specified explicitly (or its ancestor
1430 *  +Exception+).
1431 */
1432
1433/*
1434 *  Document-class: SyntaxError
1435 *
1436 *  Raised when encountering Ruby code with an invalid syntax.
1437 *
1438 *     eval("1+1=2")
1439 *
1440 *  <em>raises the exception:</em>
1441 *
1442 *     SyntaxError: (eval):1: syntax error, unexpected '=', expecting $end
1443 */
1444
1445/*
1446 *  Document-class: LoadError
1447 *
1448 *  Raised when a file required (a Ruby script, extension library, ...)
1449 *  fails to load.
1450 *
1451 *     require 'this/file/does/not/exist'
1452 *
1453 *  <em>raises the exception:</em>
1454 *
1455 *     LoadError: no such file to load -- this/file/does/not/exist
1456 */
1457
1458/*
1459 *  Document-class: NotImplementedError
1460 *
1461 *  Raised when a feature is not implemented on the current platform. For
1462 *  example, methods depending on the +fsync+ or +fork+ system calls may
1463 *  raise this exception if the underlying operating system or Ruby
1464 *  runtime does not support them.
1465 *
1466 *  Note that if +fork+ raises a +NotImplementedError+, then
1467 *  <code>respond_to?(:fork)</code> returns +false+.
1468 */
1469
1470/*
1471 *  Document-class: NameError
1472 *
1473 *  Raised when a given name is invalid or undefined.
1474 *
1475 *     puts foo
1476 *
1477 *  <em>raises the exception:</em>
1478 *
1479 *     NameError: undefined local variable or method `foo' for main:Object
1480 *
1481 *  Since constant names must start with a capital:
1482 *
1483 *     Fixnum.const_set :answer, 42
1484 *
1485 *  <em>raises the exception:</em>
1486 *
1487 *     NameError: wrong constant name answer
1488 */
1489
1490/*
1491 *  Document-class: NoMethodError
1492 *
1493 *  Raised when a method is called on a receiver which doesn't have it
1494 *  defined and also fails to respond with +method_missing+.
1495 *
1496 *     "hello".to_ary
1497 *
1498 *  <em>raises the exception:</em>
1499 *
1500 *     NoMethodError: undefined method `to_ary' for "hello":String
1501 */
1502
1503/*
1504 *  Document-class: RuntimeError
1505 *
1506 *  A generic error class raised when an invalid operation is attempted.
1507 *
1508 *     [1, 2, 3].freeze << 4
1509 *
1510 *  <em>raises the exception:</em>
1511 *
1512 *     RuntimeError: can't modify frozen array
1513 *
1514 *  Kernel.raise will raise a RuntimeError if no Exception class is
1515 *  specified.
1516 *
1517 *     raise "ouch"
1518 *
1519 *  <em>raises the exception:</em>
1520 *
1521 *     RuntimeError: ouch
1522 */
1523
1524/*
1525 *  Document-class: SecurityError
1526 *
1527 *  Raised when attempting a potential unsafe operation, typically when
1528 *  the $SAFE level is raised above 0.
1529 *
1530 *     foo = "bar"
1531 *     proc = Proc.new do
1532 *       $SAFE = 4
1533 *       foo.gsub! "a", "*"
1534 *     end
1535 *     proc.call
1536 *
1537 *  <em>raises the exception:</em>
1538 *
1539 *     SecurityError: Insecure: can't modify string
1540 */
1541
1542/*
1543 *  Document-class: NoMemoryError
1544 *
1545 *  Raised when memory allocation fails.
1546 */
1547
1548/*
1549 *  Document-class: SystemCallError
1550 *
1551 *  SystemCallError is the base class for all low-level
1552 *  platform-dependent errors.
1553 *
1554 *  The errors available on the current platform are subclasses of
1555 *  SystemCallError and are defined in the Errno module.
1556 *
1557 *     File.open("does/not/exist")
1558 *
1559 *  <em>raises the exception:</em>
1560 *
1561 *     Errno::ENOENT: No such file or directory - does/not/exist
1562 */
1563
1564/*
1565 * Document-class: EncodingError
1566 *
1567 * EncodingError is the base class for encoding errors.
1568 */
1569
1570/*
1571 *  Document-class: Encoding::CompatibilityError
1572 *
1573 *  Raised by Encoding and String methods when the source encoding is
1574 *  incompatible with the target encoding.
1575 */
1576
1577/*
1578 * Document-class: fatal
1579 *
1580 * fatal is an Exception that is raised when ruby has encountered a fatal
1581 * error and must exit.  You are not able to rescue fatal.
1582 */
1583
1584/*
1585 * Document-class: NameError::message
1586 * :nodoc:
1587 */
1588
1589/*
1590 *  Descendants of class Exception are used to communicate between
1591 *  Kernel#raise and +rescue+ statements in <code>begin ... end</code> blocks.
1592 *  Exception objects carry information about the exception -- its type (the
1593 *  exception's class name), an optional descriptive string, and optional
1594 *  traceback information.  Exception subclasses may add additional
1595 *  information like NameError#name.
1596 *
1597 *  Programs may make subclasses of Exception, typically of StandardError or
1598 *  RuntimeError, to provide custom classes and add additional information.
1599 *  See the subclass list below for defaults for +raise+ and +rescue+.
1600 *
1601 *  When an exception has been raised but not yet handled (in +rescue+,
1602 *  +ensure+, +at_exit+ and +END+ blocks) the global variable <code>$!</code>
1603 *  will contain the current exception and <code>$@</code> contains the
1604 *  current exception's backtrace.
1605 *
1606 *  It is recommended that a library should have one subclass of StandardError
1607 *  or RuntimeError and have specific exception types inherit from it.  This
1608 *  allows the user to rescue a generic exception type to catch all exceptions
1609 *  the library may raise even if future versions of the library add new
1610 *  exception subclasses.
1611 *
1612 *  For example:
1613 *
1614 *    class MyLibrary
1615 *      class Error < RuntimeError
1616 *      end
1617 *
1618 *      class WidgetError < Error
1619 *      end
1620 *
1621 *      class FrobError < Error
1622 *      end
1623 *
1624 *    end
1625 *
1626 *  To handle both WidgetError and FrobError the library user can rescue
1627 *  MyLibrary::Error.
1628 *
1629 *  The built-in subclasses of Exception are:
1630 *
1631 *  * NoMemoryError
1632 *  * ScriptError
1633 *    * LoadError
1634 *    * NotImplementedError
1635 *    * SyntaxError
1636 *  * SignalException
1637 *    * Interrupt
1638 *  * StandardError -- default for +rescue+
1639 *    * ArgumentError
1640 *    * IndexError
1641 *      * StopIteration
1642 *    * IOError
1643 *      * EOFError
1644 *    * LocalJumpError
1645 *    * NameError
1646 *      * NoMethodError
1647 *    * RangeError
1648 *      * FloatDomainError
1649 *    * RegexpError
1650 *    * RuntimeError -- default for +raise+
1651 *    * SecurityError
1652 *    * SystemCallError
1653 *      * Errno::*
1654 *    * SystemStackError
1655 *    * ThreadError
1656 *    * TypeError
1657 *    * ZeroDivisionError
1658 *  * SystemExit
1659 *  * fatal -- impossible to rescue
1660 */
1661
1662void
1663Init_Exception(void)
1664{
1665    rb_eException   = rb_define_class("Exception", rb_cObject);
1666    rb_define_singleton_method(rb_eException, "exception", rb_class_new_instance, -1);
1667    rb_define_method(rb_eException, "exception", exc_exception, -1);
1668    rb_define_method(rb_eException, "initialize", exc_initialize, -1);
1669    rb_define_method(rb_eException, "==", exc_equal, 1);
1670    rb_define_method(rb_eException, "to_s", exc_to_s, 0);
1671    rb_define_method(rb_eException, "message", exc_message, 0);
1672    rb_define_method(rb_eException, "inspect", exc_inspect, 0);
1673    rb_define_method(rb_eException, "backtrace", exc_backtrace, 0);
1674    rb_define_method(rb_eException, "set_backtrace", exc_set_backtrace, 1);
1675
1676    rb_eSystemExit  = rb_define_class("SystemExit", rb_eException);
1677    rb_define_method(rb_eSystemExit, "initialize", exit_initialize, -1);
1678    rb_define_method(rb_eSystemExit, "status", exit_status, 0);
1679    rb_define_method(rb_eSystemExit, "success?", exit_success_p, 0);
1680
1681    rb_eFatal  	    = rb_define_class("fatal", rb_eException);
1682    rb_eSignal      = rb_define_class("SignalException", rb_eException);
1683    rb_eInterrupt   = rb_define_class("Interrupt", rb_eSignal);
1684
1685    rb_eStandardError = rb_define_class("StandardError", rb_eException);
1686    rb_eTypeError     = rb_define_class("TypeError", rb_eStandardError);
1687    rb_eArgError      = rb_define_class("ArgumentError", rb_eStandardError);
1688    rb_eIndexError    = rb_define_class("IndexError", rb_eStandardError);
1689    rb_eKeyError      = rb_define_class("KeyError", rb_eIndexError);
1690    rb_eRangeError    = rb_define_class("RangeError", rb_eStandardError);
1691
1692    rb_eScriptError = rb_define_class("ScriptError", rb_eException);
1693    rb_eSyntaxError = rb_define_class("SyntaxError", rb_eScriptError);
1694
1695    rb_eLoadError   = rb_define_class("LoadError", rb_eScriptError);
1696    rb_attr(rb_eLoadError, rb_intern("path"), 1, 0, Qfalse);
1697
1698    rb_eNotImpError = rb_define_class("NotImplementedError", rb_eScriptError);
1699
1700    rb_eNameError     = rb_define_class("NameError", rb_eStandardError);
1701    rb_define_method(rb_eNameError, "initialize", name_err_initialize, -1);
1702    rb_define_method(rb_eNameError, "name", name_err_name, 0);
1703    rb_define_method(rb_eNameError, "to_s", name_err_to_s, 0);
1704    rb_cNameErrorMesg = rb_define_class_under(rb_eNameError, "message", rb_cData);
1705    rb_define_singleton_method(rb_cNameErrorMesg, "!", rb_name_err_mesg_new, NAME_ERR_MESG_COUNT);
1706    rb_define_method(rb_cNameErrorMesg, "==", name_err_mesg_equal, 1);
1707    rb_define_method(rb_cNameErrorMesg, "to_str", name_err_mesg_to_str, 0);
1708    rb_define_method(rb_cNameErrorMesg, "_dump", name_err_mesg_to_str, 1);
1709    rb_define_singleton_method(rb_cNameErrorMesg, "_load", name_err_mesg_load, 1);
1710    rb_eNoMethodError = rb_define_class("NoMethodError", rb_eNameError);
1711    rb_define_method(rb_eNoMethodError, "initialize", nometh_err_initialize, -1);
1712    rb_define_method(rb_eNoMethodError, "args", nometh_err_args, 0);
1713
1714    rb_eRuntimeError = rb_define_class("RuntimeError", rb_eStandardError);
1715    rb_eSecurityError = rb_define_class("SecurityError", rb_eException);
1716    rb_eNoMemError = rb_define_class("NoMemoryError", rb_eException);
1717    rb_eEncodingError = rb_define_class("EncodingError", rb_eStandardError);
1718    rb_eEncCompatError = rb_define_class_under(rb_cEncoding, "CompatibilityError", rb_eEncodingError);
1719
1720    syserr_tbl = st_init_numtable();
1721    rb_eSystemCallError = rb_define_class("SystemCallError", rb_eStandardError);
1722    rb_define_method(rb_eSystemCallError, "initialize", syserr_initialize, -1);
1723    rb_define_method(rb_eSystemCallError, "errno", syserr_errno, 0);
1724    rb_define_singleton_method(rb_eSystemCallError, "===", syserr_eqq, 1);
1725
1726    rb_mErrno = rb_define_module("Errno");
1727
1728    rb_define_global_function("warn", rb_warn_m, -1);
1729}
1730
1731void
1732rb_raise(VALUE exc, const char *fmt, ...)
1733{
1734    va_list args;
1735    VALUE mesg;
1736
1737    va_start(args, fmt);
1738    mesg = rb_vsprintf(fmt, args);
1739    va_end(args);
1740    rb_exc_raise(rb_exc_new3(exc, mesg));
1741}
1742
1743NORETURN(static void raise_loaderror(VALUE path, VALUE mesg));
1744
1745static void
1746raise_loaderror(VALUE path, VALUE mesg)
1747{
1748    VALUE err = rb_exc_new3(rb_eLoadError, mesg);
1749    rb_ivar_set(err, rb_intern("@path"), path);
1750    rb_exc_raise(err);
1751}
1752
1753void
1754rb_loaderror(const char *fmt, ...)
1755{
1756    va_list args;
1757    VALUE mesg;
1758
1759    va_start(args, fmt);
1760    mesg = rb_enc_vsprintf(rb_locale_encoding(), fmt, args);
1761    va_end(args);
1762    raise_loaderror(Qnil, mesg);
1763}
1764
1765void
1766rb_loaderror_with_path(VALUE path, const char *fmt, ...)
1767{
1768    va_list args;
1769    VALUE mesg;
1770
1771    va_start(args, fmt);
1772    mesg = rb_enc_vsprintf(rb_locale_encoding(), fmt, args);
1773    va_end(args);
1774    raise_loaderror(path, mesg);
1775}
1776
1777void
1778rb_notimplement(void)
1779{
1780    rb_raise(rb_eNotImpError,
1781	     "%s() function is unimplemented on this machine",
1782	     rb_id2name(rb_frame_this_func()));
1783}
1784
1785void
1786rb_fatal(const char *fmt, ...)
1787{
1788    va_list args;
1789    VALUE mesg;
1790
1791    va_start(args, fmt);
1792    mesg = rb_vsprintf(fmt, args);
1793    va_end(args);
1794
1795    rb_exc_fatal(rb_exc_new3(rb_eFatal, mesg));
1796}
1797
1798static VALUE
1799make_errno_exc(const char *mesg)
1800{
1801    int n = errno;
1802
1803    errno = 0;
1804    if (n == 0) {
1805	rb_bug("rb_sys_fail(%s) - errno == 0", mesg ? mesg : "");
1806    }
1807    return rb_syserr_new(n, mesg);
1808}
1809
1810static VALUE
1811make_errno_exc_str(VALUE mesg)
1812{
1813    int n = errno;
1814
1815    errno = 0;
1816    if (!mesg) mesg = Qnil;
1817    if (n == 0) {
1818	const char *s = !NIL_P(mesg) ? RSTRING_PTR(mesg) : "";
1819	rb_bug("rb_sys_fail_str(%s) - errno == 0", s);
1820    }
1821    return rb_syserr_new_str(n, mesg);
1822}
1823
1824VALUE
1825rb_syserr_new(int n, const char *mesg)
1826{
1827    VALUE arg;
1828    arg = mesg ? rb_str_new2(mesg) : Qnil;
1829    return rb_syserr_new_str(n, arg);
1830}
1831
1832VALUE
1833rb_syserr_new_str(int n, VALUE arg)
1834{
1835    return rb_class_new_instance(1, &arg, get_syserr(n));
1836}
1837
1838void
1839rb_syserr_fail(int e, const char *mesg)
1840{
1841    rb_exc_raise(rb_syserr_new(e, mesg));
1842}
1843
1844void
1845rb_syserr_fail_str(int e, VALUE mesg)
1846{
1847    rb_exc_raise(rb_syserr_new_str(e, mesg));
1848}
1849
1850void
1851rb_sys_fail(const char *mesg)
1852{
1853    rb_exc_raise(make_errno_exc(mesg));
1854}
1855
1856void
1857rb_sys_fail_str(VALUE mesg)
1858{
1859    rb_exc_raise(make_errno_exc_str(mesg));
1860}
1861
1862void
1863rb_mod_sys_fail(VALUE mod, const char *mesg)
1864{
1865    VALUE exc = make_errno_exc(mesg);
1866    rb_extend_object(exc, mod);
1867    rb_exc_raise(exc);
1868}
1869
1870void
1871rb_mod_sys_fail_str(VALUE mod, VALUE mesg)
1872{
1873    VALUE exc = make_errno_exc_str(mesg);
1874    rb_extend_object(exc, mod);
1875    rb_exc_raise(exc);
1876}
1877
1878void
1879rb_mod_syserr_fail(VALUE mod, int e, const char *mesg)
1880{
1881    VALUE exc = rb_syserr_new(e, mesg);
1882    rb_extend_object(exc, mod);
1883    rb_exc_raise(exc);
1884}
1885
1886void
1887rb_mod_syserr_fail_str(VALUE mod, int e, VALUE mesg)
1888{
1889    VALUE exc = rb_syserr_new_str(e, mesg);
1890    rb_extend_object(exc, mod);
1891    rb_exc_raise(exc);
1892}
1893
1894void
1895rb_sys_warning(const char *fmt, ...)
1896{
1897    char buf[BUFSIZ];
1898    va_list args;
1899    int errno_save;
1900
1901    errno_save = errno;
1902
1903    if (!RTEST(ruby_verbose)) return;
1904
1905    snprintf(buf, BUFSIZ, "warning: %s", fmt);
1906    snprintf(buf+strlen(buf), BUFSIZ-strlen(buf), ": %s", strerror(errno_save));
1907
1908    va_start(args, fmt);
1909    warn_print(buf, args);
1910    va_end(args);
1911    errno = errno_save;
1912}
1913
1914void
1915rb_load_fail(VALUE path, const char *err)
1916{
1917    VALUE mesg = rb_str_buf_new_cstr(err);
1918    rb_str_cat2(mesg, " -- ");
1919    rb_str_append(mesg, path);	/* should be ASCII compatible */
1920    raise_loaderror(path, mesg);
1921}
1922
1923void
1924rb_error_frozen(const char *what)
1925{
1926    rb_raise(rb_eRuntimeError, "can't modify frozen %s", what);
1927}
1928
1929#undef rb_check_frozen
1930void
1931rb_check_frozen(VALUE obj)
1932{
1933    rb_check_frozen_internal(obj);
1934}
1935
1936void
1937rb_error_untrusted(VALUE obj)
1938{
1939    if (rb_safe_level() >= 4) {
1940	rb_raise(rb_eSecurityError, "Insecure: can't modify %s",
1941		 rb_obj_classname(obj));
1942    }
1943}
1944
1945#undef rb_check_trusted
1946void
1947rb_check_trusted(VALUE obj)
1948{
1949    rb_check_trusted_internal(obj);
1950}
1951
1952void
1953Init_syserr(void)
1954{
1955    rb_eNOERROR = set_syserr(0, "NOERROR");
1956#define defined_error(name, num) set_syserr((num), (name));
1957#define undefined_error(name) set_syserr(0, (name));
1958#include "known_errors.inc"
1959#undef defined_error
1960#undef undefined_error
1961}
1962
1963static void
1964err_append(const char *s, rb_encoding *enc)
1965{
1966    rb_thread_t *th = GET_THREAD();
1967    VALUE err = th->errinfo;
1968
1969    if (th->mild_compile_error) {
1970	if (!RTEST(err)) {
1971	    err = rb_exc_new3(rb_eSyntaxError,
1972			      rb_enc_str_new(s, strlen(s), enc));
1973	    th->errinfo = err;
1974	}
1975	else {
1976	    VALUE str = rb_obj_as_string(err);
1977
1978	    rb_str_cat2(str, "\n");
1979	    rb_str_cat2(str, s);
1980	    th->errinfo = rb_exc_new3(rb_eSyntaxError, str);
1981	}
1982    }
1983    else {
1984	if (!RTEST(err)) {
1985	    err = rb_exc_new2(rb_eSyntaxError, "compile error");
1986	    th->errinfo = err;
1987	}
1988	rb_write_error(s);
1989	rb_write_error("\n");
1990    }
1991}