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