PageRenderTime 27ms CodeModel.GetById 25ms RepoModel.GetById 1ms app.codeStats 0ms

/error.c

http://github.com/ruby/ruby
C | 3091 lines | 1956 code | 369 blank | 766 comment | 274 complexity | 55b901a3fb8c3a0f23239c75d2495816 MD5 | raw file
Possible License(s): GPL-2.0, BSD-3-Clause, AGPL-3.0
  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/internal/config.h"
  8. #include <errno.h>
  9. #include <stdarg.h>
  10. #include <stdio.h>
  11. #ifdef HAVE_STDLIB_H
  12. # include <stdlib.h>
  13. #endif
  14. #ifdef HAVE_UNISTD_H
  15. # include <unistd.h>
  16. #endif
  17. #if defined __APPLE__
  18. # include <AvailabilityMacros.h>
  19. #endif
  20. #include "internal.h"
  21. #include "internal/error.h"
  22. #include "internal/eval.h"
  23. #include "internal/io.h"
  24. #include "internal/load.h"
  25. #include "internal/object.h"
  26. #include "internal/symbol.h"
  27. #include "internal/thread.h"
  28. #include "internal/variable.h"
  29. #include "ruby/encoding.h"
  30. #include "ruby/st.h"
  31. #include "ruby_assert.h"
  32. #include "vm_core.h"
  33. #include "builtin.h"
  34. /*!
  35. * \defgroup exception Exception handlings
  36. * \{
  37. */
  38. #ifndef EXIT_SUCCESS
  39. #define EXIT_SUCCESS 0
  40. #endif
  41. #ifndef WIFEXITED
  42. #define WIFEXITED(status) 1
  43. #endif
  44. #ifndef WEXITSTATUS
  45. #define WEXITSTATUS(status) (status)
  46. #endif
  47. VALUE rb_iseqw_local_variables(VALUE iseqval);
  48. VALUE rb_iseqw_new(const rb_iseq_t *);
  49. int rb_str_end_with_asciichar(VALUE str, int c);
  50. VALUE rb_eEAGAIN;
  51. VALUE rb_eEWOULDBLOCK;
  52. VALUE rb_eEINPROGRESS;
  53. static VALUE rb_mWarning;
  54. static VALUE rb_cWarningBuffer;
  55. static ID id_warn;
  56. extern const char ruby_description[];
  57. static const char *
  58. rb_strerrno(int err)
  59. {
  60. #define defined_error(name, num) if (err == (num)) return (name);
  61. #define undefined_error(name)
  62. #include "known_errors.inc"
  63. #undef defined_error
  64. #undef undefined_error
  65. return NULL;
  66. }
  67. static int
  68. err_position_0(char *buf, long len, const char *file, int line)
  69. {
  70. if (!file) {
  71. return 0;
  72. }
  73. else if (line == 0) {
  74. return snprintf(buf, len, "%s: ", file);
  75. }
  76. else {
  77. return snprintf(buf, len, "%s:%d: ", file, line);
  78. }
  79. }
  80. static VALUE
  81. err_vcatf(VALUE str, const char *pre, const char *file, int line,
  82. const char *fmt, va_list args)
  83. {
  84. if (file) {
  85. rb_str_cat2(str, file);
  86. if (line) rb_str_catf(str, ":%d", line);
  87. rb_str_cat2(str, ": ");
  88. }
  89. if (pre) rb_str_cat2(str, pre);
  90. rb_str_vcatf(str, fmt, args);
  91. return str;
  92. }
  93. VALUE
  94. rb_syntax_error_append(VALUE exc, VALUE file, int line, int column,
  95. rb_encoding *enc, const char *fmt, va_list args)
  96. {
  97. const char *fn = NIL_P(file) ? NULL : RSTRING_PTR(file);
  98. if (!exc) {
  99. VALUE mesg = rb_enc_str_new(0, 0, enc);
  100. err_vcatf(mesg, NULL, fn, line, fmt, args);
  101. rb_str_cat2(mesg, "\n");
  102. rb_write_error_str(mesg);
  103. }
  104. else {
  105. VALUE mesg;
  106. if (NIL_P(exc)) {
  107. mesg = rb_enc_str_new(0, 0, enc);
  108. exc = rb_class_new_instance(1, &mesg, rb_eSyntaxError);
  109. }
  110. else {
  111. mesg = rb_attr_get(exc, idMesg);
  112. if (RSTRING_LEN(mesg) > 0 && *(RSTRING_END(mesg)-1) != '\n')
  113. rb_str_cat_cstr(mesg, "\n");
  114. }
  115. err_vcatf(mesg, NULL, fn, line, fmt, args);
  116. }
  117. return exc;
  118. }
  119. static unsigned int warning_disabled_categories;
  120. static unsigned int
  121. rb_warning_category_mask(VALUE category)
  122. {
  123. return 1U << rb_warning_category_from_name(category);
  124. }
  125. rb_warning_category_t
  126. rb_warning_category_from_name(VALUE category)
  127. {
  128. rb_warning_category_t cat = RB_WARN_CATEGORY_NONE;
  129. Check_Type(category, T_SYMBOL);
  130. if (category == ID2SYM(rb_intern("deprecated"))) {
  131. cat = RB_WARN_CATEGORY_DEPRECATED;
  132. }
  133. else if (category == ID2SYM(rb_intern("experimental"))) {
  134. cat = RB_WARN_CATEGORY_EXPERIMENTAL;
  135. }
  136. else {
  137. rb_raise(rb_eArgError, "unknown category: %"PRIsVALUE, category);
  138. }
  139. return cat;
  140. }
  141. void
  142. rb_warning_category_update(unsigned int mask, unsigned int bits)
  143. {
  144. warning_disabled_categories &= ~mask;
  145. warning_disabled_categories |= mask & ~bits;
  146. }
  147. MJIT_FUNC_EXPORTED bool
  148. rb_warning_category_enabled_p(rb_warning_category_t category)
  149. {
  150. return !(warning_disabled_categories & (1U << category));
  151. }
  152. /*
  153. * call-seq
  154. * Warning[category] -> true or false
  155. *
  156. * Returns the flag to show the warning messages for +category+.
  157. * Supported categories are:
  158. *
  159. * +:deprecated+ :: deprecation warnings
  160. * * assignment of non-nil value to <code>$,</code> and <code>$;</code>
  161. * * keyword arguments
  162. * * proc/lambda without block
  163. * etc.
  164. *
  165. * +:experimental+ :: experimental features
  166. * * Pattern matching
  167. */
  168. static VALUE
  169. rb_warning_s_aref(VALUE mod, VALUE category)
  170. {
  171. rb_warning_category_t cat = rb_warning_category_from_name(category);
  172. if (rb_warning_category_enabled_p(cat))
  173. return Qtrue;
  174. return Qfalse;
  175. }
  176. /*
  177. * call-seq
  178. * Warning[category] = flag -> flag
  179. *
  180. * Sets the warning flags for +category+.
  181. * See Warning.[] for the categories.
  182. */
  183. static VALUE
  184. rb_warning_s_aset(VALUE mod, VALUE category, VALUE flag)
  185. {
  186. unsigned int mask = rb_warning_category_mask(category);
  187. unsigned int disabled = warning_disabled_categories;
  188. if (!RTEST(flag))
  189. disabled |= mask;
  190. else
  191. disabled &= ~mask;
  192. warning_disabled_categories = disabled;
  193. return flag;
  194. }
  195. /*
  196. * call-seq:
  197. * warn(msg) -> nil
  198. *
  199. * Writes warning message +msg+ to $stderr. This method is called by
  200. * Ruby for all emitted warnings.
  201. */
  202. static VALUE
  203. rb_warning_s_warn(VALUE mod, VALUE str)
  204. {
  205. Check_Type(str, T_STRING);
  206. rb_must_asciicompat(str);
  207. rb_write_error_str(str);
  208. return Qnil;
  209. }
  210. /*
  211. * Document-module: Warning
  212. *
  213. * The Warning module contains a single method named #warn, and the
  214. * module extends itself, making Warning.warn available.
  215. * Warning.warn is called for all warnings issued by Ruby.
  216. * By default, warnings are printed to $stderr.
  217. *
  218. * By overriding Warning.warn, you can change how warnings are
  219. * handled by Ruby, either filtering some warnings, and/or outputting
  220. * warnings somewhere other than $stderr. When Warning.warn is
  221. * overridden, super can be called to get the default behavior of
  222. * printing the warning to $stderr.
  223. */
  224. static VALUE
  225. rb_warning_warn(VALUE mod, VALUE str)
  226. {
  227. return rb_funcallv(mod, id_warn, 1, &str);
  228. }
  229. static void
  230. rb_write_warning_str(VALUE str)
  231. {
  232. rb_warning_warn(rb_mWarning, str);
  233. }
  234. static VALUE
  235. warn_vsprintf(rb_encoding *enc, const char *file, int line, const char *fmt, va_list args)
  236. {
  237. VALUE str = rb_enc_str_new(0, 0, enc);
  238. err_vcatf(str, "warning: ", file, line, fmt, args);
  239. return rb_str_cat2(str, "\n");
  240. }
  241. void
  242. rb_compile_warn(const char *file, int line, const char *fmt, ...)
  243. {
  244. VALUE str;
  245. va_list args;
  246. if (NIL_P(ruby_verbose)) return;
  247. va_start(args, fmt);
  248. str = warn_vsprintf(NULL, file, line, fmt, args);
  249. va_end(args);
  250. rb_write_warning_str(str);
  251. }
  252. /* rb_compile_warning() reports only in verbose mode */
  253. void
  254. rb_compile_warning(const char *file, int line, const char *fmt, ...)
  255. {
  256. VALUE str;
  257. va_list args;
  258. if (!RTEST(ruby_verbose)) return;
  259. va_start(args, fmt);
  260. str = warn_vsprintf(NULL, file, line, fmt, args);
  261. va_end(args);
  262. rb_write_warning_str(str);
  263. }
  264. static VALUE
  265. warning_string(rb_encoding *enc, const char *fmt, va_list args)
  266. {
  267. int line;
  268. const char *file = rb_source_location_cstr(&line);
  269. return warn_vsprintf(enc, file, line, fmt, args);
  270. }
  271. #define with_warning_string(mesg, enc, fmt) \
  272. VALUE mesg; \
  273. va_list args; va_start(args, fmt); \
  274. mesg = warning_string(enc, fmt, args); \
  275. va_end(args);
  276. void
  277. rb_warn(const char *fmt, ...)
  278. {
  279. if (!NIL_P(ruby_verbose)) {
  280. with_warning_string(mesg, 0, fmt) {
  281. rb_write_warning_str(mesg);
  282. }
  283. }
  284. }
  285. void
  286. rb_enc_warn(rb_encoding *enc, const char *fmt, ...)
  287. {
  288. if (!NIL_P(ruby_verbose)) {
  289. with_warning_string(mesg, enc, fmt) {
  290. rb_write_warning_str(mesg);
  291. }
  292. }
  293. }
  294. /* rb_warning() reports only in verbose mode */
  295. void
  296. rb_warning(const char *fmt, ...)
  297. {
  298. if (RTEST(ruby_verbose)) {
  299. with_warning_string(mesg, 0, fmt) {
  300. rb_write_warning_str(mesg);
  301. }
  302. }
  303. }
  304. VALUE
  305. rb_warning_string(const char *fmt, ...)
  306. {
  307. with_warning_string(mesg, 0, fmt) {
  308. }
  309. return mesg;
  310. }
  311. #if 0
  312. void
  313. rb_enc_warning(rb_encoding *enc, const char *fmt, ...)
  314. {
  315. if (RTEST(ruby_verbose)) {
  316. with_warning_string(mesg, enc, fmt) {
  317. rb_write_warning_str(mesg);
  318. }
  319. }
  320. }
  321. #endif
  322. void
  323. rb_warn_deprecated(const char *fmt, const char *suggest, ...)
  324. {
  325. if (NIL_P(ruby_verbose)) return;
  326. if (!rb_warning_category_enabled_p(RB_WARN_CATEGORY_DEPRECATED)) return;
  327. va_list args;
  328. va_start(args, suggest);
  329. VALUE mesg = warning_string(0, fmt, args);
  330. va_end(args);
  331. rb_str_set_len(mesg, RSTRING_LEN(mesg) - 1);
  332. rb_str_cat_cstr(mesg, " is deprecated");
  333. if (suggest) rb_str_catf(mesg, "; use %s instead", suggest);
  334. rb_str_cat_cstr(mesg, "\n");
  335. rb_write_warning_str(mesg);
  336. }
  337. void
  338. rb_warn_deprecated_to_remove(const char *fmt, const char *removal, ...)
  339. {
  340. if (NIL_P(ruby_verbose)) return;
  341. if (!rb_warning_category_enabled_p(RB_WARN_CATEGORY_DEPRECATED)) return;
  342. va_list args;
  343. va_start(args, removal);
  344. VALUE mesg = warning_string(0, fmt, args);
  345. va_end(args);
  346. rb_str_set_len(mesg, RSTRING_LEN(mesg) - 1);
  347. rb_str_catf(mesg, " is deprecated and will be removed in Ruby %s\n", removal);
  348. rb_write_warning_str(mesg);
  349. }
  350. static inline int
  351. end_with_asciichar(VALUE str, int c)
  352. {
  353. return RB_TYPE_P(str, T_STRING) &&
  354. rb_str_end_with_asciichar(str, c);
  355. }
  356. /* :nodoc: */
  357. static VALUE
  358. warning_write(int argc, VALUE *argv, VALUE buf)
  359. {
  360. while (argc-- > 0) {
  361. rb_str_append(buf, *argv++);
  362. }
  363. return buf;
  364. }
  365. VALUE rb_ec_backtrace_location_ary(rb_execution_context_t *ec, long lev, long n);
  366. static VALUE
  367. rb_warn_m(rb_execution_context_t *ec, VALUE exc, VALUE msgs, VALUE uplevel)
  368. {
  369. VALUE location = Qnil;
  370. int argc = RARRAY_LENINT(msgs);
  371. const VALUE *argv = RARRAY_CONST_PTR(msgs);
  372. if (!NIL_P(ruby_verbose) && argc > 0) {
  373. VALUE str = argv[0];
  374. if (!NIL_P(uplevel)) {
  375. long lev = NUM2LONG(uplevel);
  376. if (lev < 0) {
  377. rb_raise(rb_eArgError, "negative level (%ld)", lev);
  378. }
  379. location = rb_ec_backtrace_location_ary(ec, lev + 1, 1);
  380. if (!NIL_P(location)) {
  381. location = rb_ary_entry(location, 0);
  382. }
  383. }
  384. if (argc > 1 || !NIL_P(uplevel) || !end_with_asciichar(str, '\n')) {
  385. VALUE path;
  386. if (NIL_P(uplevel)) {
  387. str = rb_str_tmp_new(0);
  388. }
  389. else if (NIL_P(location) ||
  390. NIL_P(path = rb_funcall(location, rb_intern("path"), 0))) {
  391. str = rb_str_new_cstr("warning: ");
  392. }
  393. else {
  394. str = rb_sprintf("%s:%ld: warning: ",
  395. rb_string_value_ptr(&path),
  396. NUM2LONG(rb_funcall(location, rb_intern("lineno"), 0)));
  397. }
  398. RBASIC_SET_CLASS(str, rb_cWarningBuffer);
  399. rb_io_puts(argc, argv, str);
  400. RBASIC_SET_CLASS(str, rb_cString);
  401. }
  402. if (exc == rb_mWarning) {
  403. rb_must_asciicompat(str);
  404. rb_write_error_str(str);
  405. }
  406. else {
  407. rb_write_warning_str(str);
  408. }
  409. }
  410. return Qnil;
  411. }
  412. #define MAX_BUG_REPORTERS 0x100
  413. static struct bug_reporters {
  414. void (*func)(FILE *out, void *data);
  415. void *data;
  416. } bug_reporters[MAX_BUG_REPORTERS];
  417. static int bug_reporters_size;
  418. int
  419. rb_bug_reporter_add(void (*func)(FILE *, void *), void *data)
  420. {
  421. struct bug_reporters *reporter;
  422. if (bug_reporters_size >= MAX_BUG_REPORTERS) {
  423. return 0; /* failed to register */
  424. }
  425. reporter = &bug_reporters[bug_reporters_size++];
  426. reporter->func = func;
  427. reporter->data = data;
  428. return 1;
  429. }
  430. /* SIGSEGV handler might have a very small stack. Thus we need to use it carefully. */
  431. #define REPORT_BUG_BUFSIZ 256
  432. static FILE *
  433. bug_report_file(const char *file, int line)
  434. {
  435. char buf[REPORT_BUG_BUFSIZ];
  436. FILE *out = stderr;
  437. int len = err_position_0(buf, sizeof(buf), file, line);
  438. if ((ssize_t)fwrite(buf, 1, len, out) == (ssize_t)len ||
  439. (ssize_t)fwrite(buf, 1, len, (out = stdout)) == (ssize_t)len) {
  440. return out;
  441. }
  442. return NULL;
  443. }
  444. FUNC_MINIMIZED(static void bug_important_message(FILE *out, const char *const msg, size_t len));
  445. static void
  446. bug_important_message(FILE *out, const char *const msg, size_t len)
  447. {
  448. const char *const endmsg = msg + len;
  449. const char *p = msg;
  450. if (!len) return;
  451. if (isatty(fileno(out))) {
  452. static const char red[] = "\033[;31;1;7m";
  453. static const char green[] = "\033[;32;7m";
  454. static const char reset[] = "\033[m";
  455. const char *e = strchr(p, '\n');
  456. const int w = (int)(e - p);
  457. do {
  458. int i = (int)(e - p);
  459. fputs(*p == ' ' ? green : red, out);
  460. fwrite(p, 1, e - p, out);
  461. for (; i < w; ++i) fputc(' ', out);
  462. fputs(reset, out);
  463. fputc('\n', out);
  464. } while ((p = e + 1) < endmsg && (e = strchr(p, '\n')) != 0 && e > p + 1);
  465. }
  466. fwrite(p, 1, endmsg - p, out);
  467. }
  468. static void
  469. preface_dump(FILE *out)
  470. {
  471. #if defined __APPLE__
  472. static const char msg[] = ""
  473. "-- Crash Report log information "
  474. "--------------------------------------------\n"
  475. " See Crash Report log file under the one of following:\n"
  476. # if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_6
  477. " * ~/Library/Logs/CrashReporter\n"
  478. " * /Library/Logs/CrashReporter\n"
  479. # endif
  480. " * ~/Library/Logs/DiagnosticReports\n"
  481. " * /Library/Logs/DiagnosticReports\n"
  482. " for more details.\n"
  483. "Don't forget to include the above Crash Report log file in bug reports.\n"
  484. "\n";
  485. const size_t msglen = sizeof(msg) - 1;
  486. #else
  487. const char *msg = NULL;
  488. const size_t msglen = 0;
  489. #endif
  490. bug_important_message(out, msg, msglen);
  491. }
  492. static void
  493. postscript_dump(FILE *out)
  494. {
  495. #if defined __APPLE__
  496. static const char msg[] = ""
  497. "[IMPORTANT]"
  498. /*" ------------------------------------------------"*/
  499. "\n""Don't forget to include the Crash Report log file under\n"
  500. # if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_6
  501. "CrashReporter or "
  502. # endif
  503. "DiagnosticReports directory in bug reports.\n"
  504. /*"------------------------------------------------------------\n"*/
  505. "\n";
  506. const size_t msglen = sizeof(msg) - 1;
  507. #else
  508. const char *msg = NULL;
  509. const size_t msglen = 0;
  510. #endif
  511. bug_important_message(out, msg, msglen);
  512. }
  513. static void
  514. bug_report_begin_valist(FILE *out, const char *fmt, va_list args)
  515. {
  516. char buf[REPORT_BUG_BUFSIZ];
  517. fputs("[BUG] ", out);
  518. vsnprintf(buf, sizeof(buf), fmt, args);
  519. fputs(buf, out);
  520. snprintf(buf, sizeof(buf), "\n%s\n\n", ruby_description);
  521. fputs(buf, out);
  522. preface_dump(out);
  523. }
  524. #define bug_report_begin(out, fmt) do { \
  525. va_list args; \
  526. va_start(args, fmt); \
  527. bug_report_begin_valist(out, fmt, args); \
  528. va_end(args); \
  529. } while (0)
  530. static void
  531. bug_report_end(FILE *out)
  532. {
  533. /* call additional bug reporters */
  534. {
  535. int i;
  536. for (i=0; i<bug_reporters_size; i++) {
  537. struct bug_reporters *reporter = &bug_reporters[i];
  538. (*reporter->func)(out, reporter->data);
  539. }
  540. }
  541. postscript_dump(out);
  542. }
  543. #define report_bug(file, line, fmt, ctx) do { \
  544. FILE *out = bug_report_file(file, line); \
  545. if (out) { \
  546. bug_report_begin(out, fmt); \
  547. rb_vm_bugreport(ctx); \
  548. bug_report_end(out); \
  549. } \
  550. } while (0) \
  551. #define report_bug_valist(file, line, fmt, ctx, args) do { \
  552. FILE *out = bug_report_file(file, line); \
  553. if (out) { \
  554. bug_report_begin_valist(out, fmt, args); \
  555. rb_vm_bugreport(ctx); \
  556. bug_report_end(out); \
  557. } \
  558. } while (0) \
  559. NORETURN(static void die(void));
  560. static void
  561. die(void)
  562. {
  563. #if defined(_WIN32) && defined(RUBY_MSVCRT_VERSION) && RUBY_MSVCRT_VERSION >= 80
  564. _set_abort_behavior( 0, _CALL_REPORTFAULT);
  565. #endif
  566. abort();
  567. }
  568. void
  569. rb_bug(const char *fmt, ...)
  570. {
  571. const char *file = NULL;
  572. int line = 0;
  573. if (GET_EC()) {
  574. file = rb_source_location_cstr(&line);
  575. }
  576. report_bug(file, line, fmt, NULL);
  577. die();
  578. }
  579. void
  580. rb_bug_for_fatal_signal(ruby_sighandler_t default_sighandler, int sig, const void *ctx, const char *fmt, ...)
  581. {
  582. const char *file = NULL;
  583. int line = 0;
  584. if (GET_EC()) {
  585. file = rb_source_location_cstr(&line);
  586. }
  587. report_bug(file, line, fmt, ctx);
  588. if (default_sighandler) default_sighandler(sig);
  589. die();
  590. }
  591. void
  592. rb_bug_errno(const char *mesg, int errno_arg)
  593. {
  594. if (errno_arg == 0)
  595. rb_bug("%s: errno == 0 (NOERROR)", mesg);
  596. else {
  597. const char *errno_str = rb_strerrno(errno_arg);
  598. if (errno_str)
  599. rb_bug("%s: %s (%s)", mesg, strerror(errno_arg), errno_str);
  600. else
  601. rb_bug("%s: %s (%d)", mesg, strerror(errno_arg), errno_arg);
  602. }
  603. }
  604. /*
  605. * this is safe to call inside signal handler and timer thread
  606. * (which isn't a Ruby Thread object)
  607. */
  608. #define write_or_abort(fd, str, len) (write((fd), (str), (len)) < 0 ? abort() : (void)0)
  609. #define WRITE_CONST(fd,str) write_or_abort((fd),(str),sizeof(str) - 1)
  610. void
  611. rb_async_bug_errno(const char *mesg, int errno_arg)
  612. {
  613. WRITE_CONST(2, "[ASYNC BUG] ");
  614. write_or_abort(2, mesg, strlen(mesg));
  615. WRITE_CONST(2, "\n");
  616. if (errno_arg == 0) {
  617. WRITE_CONST(2, "errno == 0 (NOERROR)\n");
  618. }
  619. else {
  620. const char *errno_str = rb_strerrno(errno_arg);
  621. if (!errno_str)
  622. errno_str = "undefined errno";
  623. write_or_abort(2, errno_str, strlen(errno_str));
  624. }
  625. WRITE_CONST(2, "\n\n");
  626. write_or_abort(2, ruby_description, strlen(ruby_description));
  627. abort();
  628. }
  629. void
  630. rb_report_bug_valist(VALUE file, int line, const char *fmt, va_list args)
  631. {
  632. report_bug_valist(RSTRING_PTR(file), line, fmt, NULL, args);
  633. }
  634. MJIT_FUNC_EXPORTED void
  635. rb_assert_failure(const char *file, int line, const char *name, const char *expr)
  636. {
  637. FILE *out = stderr;
  638. fprintf(out, "Assertion Failed: %s:%d:", file, line);
  639. if (name) fprintf(out, "%s:", name);
  640. fprintf(out, "%s\n%s\n\n", expr, ruby_description);
  641. preface_dump(out);
  642. rb_vm_bugreport(NULL);
  643. bug_report_end(out);
  644. die();
  645. }
  646. static const char builtin_types[][10] = {
  647. "", /* 0x00, */
  648. "Object",
  649. "Class",
  650. "Module",
  651. "Float",
  652. "String",
  653. "Regexp",
  654. "Array",
  655. "Hash",
  656. "Struct",
  657. "Bignum",
  658. "File",
  659. "Data", /* internal use: wrapped C pointers */
  660. "MatchData", /* data of $~ */
  661. "Complex",
  662. "Rational",
  663. "", /* 0x10 */
  664. "nil",
  665. "true",
  666. "false",
  667. "Symbol", /* :symbol */
  668. "Fixnum",
  669. "undef", /* internal use: #undef; should not happen */
  670. "", /* 0x17 */
  671. "", /* 0x18 */
  672. "", /* 0x19 */
  673. "Memo", /* internal use: general memo */
  674. "Node", /* internal use: syntax tree node */
  675. "iClass", /* internal use: mixed-in module holder */
  676. };
  677. const char *
  678. rb_builtin_type_name(int t)
  679. {
  680. const char *name;
  681. if ((unsigned int)t >= numberof(builtin_types)) return 0;
  682. name = builtin_types[t];
  683. if (*name) return name;
  684. return 0;
  685. }
  686. static const char *
  687. builtin_class_name(VALUE x)
  688. {
  689. const char *etype;
  690. if (NIL_P(x)) {
  691. etype = "nil";
  692. }
  693. else if (FIXNUM_P(x)) {
  694. etype = "Integer";
  695. }
  696. else if (SYMBOL_P(x)) {
  697. etype = "Symbol";
  698. }
  699. else if (RB_TYPE_P(x, T_TRUE)) {
  700. etype = "true";
  701. }
  702. else if (RB_TYPE_P(x, T_FALSE)) {
  703. etype = "false";
  704. }
  705. else {
  706. etype = NULL;
  707. }
  708. return etype;
  709. }
  710. const char *
  711. rb_builtin_class_name(VALUE x)
  712. {
  713. const char *etype = builtin_class_name(x);
  714. if (!etype) {
  715. etype = rb_obj_classname(x);
  716. }
  717. return etype;
  718. }
  719. NORETURN(static void unexpected_type(VALUE, int, int));
  720. #define UNDEF_LEAKED "undef leaked to the Ruby space"
  721. static void
  722. unexpected_type(VALUE x, int xt, int t)
  723. {
  724. const char *tname = rb_builtin_type_name(t);
  725. VALUE mesg, exc = rb_eFatal;
  726. if (tname) {
  727. const char *cname = builtin_class_name(x);
  728. if (cname)
  729. mesg = rb_sprintf("wrong argument type %s (expected %s)",
  730. cname, tname);
  731. else
  732. mesg = rb_sprintf("wrong argument type %"PRIsVALUE" (expected %s)",
  733. rb_obj_class(x), tname);
  734. exc = rb_eTypeError;
  735. }
  736. else if (xt > T_MASK && xt <= 0x3f) {
  737. mesg = rb_sprintf("unknown type 0x%x (0x%x given, probably comes"
  738. " from extension library for ruby 1.8)", t, xt);
  739. }
  740. else {
  741. mesg = rb_sprintf("unknown type 0x%x (0x%x given)", t, xt);
  742. }
  743. rb_exc_raise(rb_exc_new_str(exc, mesg));
  744. }
  745. void
  746. rb_check_type(VALUE x, int t)
  747. {
  748. int xt;
  749. if (x == Qundef) {
  750. rb_bug(UNDEF_LEAKED);
  751. }
  752. xt = TYPE(x);
  753. if (xt != t || (xt == T_DATA && RTYPEDDATA_P(x))) {
  754. unexpected_type(x, xt, t);
  755. }
  756. }
  757. void
  758. rb_unexpected_type(VALUE x, int t)
  759. {
  760. if (x == Qundef) {
  761. rb_bug(UNDEF_LEAKED);
  762. }
  763. unexpected_type(x, TYPE(x), t);
  764. }
  765. int
  766. rb_typeddata_inherited_p(const rb_data_type_t *child, const rb_data_type_t *parent)
  767. {
  768. while (child) {
  769. if (child == parent) return 1;
  770. child = child->parent;
  771. }
  772. return 0;
  773. }
  774. int
  775. rb_typeddata_is_kind_of(VALUE obj, const rb_data_type_t *data_type)
  776. {
  777. if (!RB_TYPE_P(obj, T_DATA) ||
  778. !RTYPEDDATA_P(obj) || !rb_typeddata_inherited_p(RTYPEDDATA_TYPE(obj), data_type)) {
  779. return 0;
  780. }
  781. return 1;
  782. }
  783. #undef rb_typeddata_is_instance_of
  784. int
  785. rb_typeddata_is_instance_of(VALUE obj, const rb_data_type_t *data_type)
  786. {
  787. return rb_typeddata_is_instance_of_inline(obj, data_type);
  788. }
  789. void *
  790. rb_check_typeddata(VALUE obj, const rb_data_type_t *data_type)
  791. {
  792. const char *etype;
  793. if (!RB_TYPE_P(obj, T_DATA)) {
  794. wrong_type:
  795. etype = builtin_class_name(obj);
  796. if (!etype)
  797. rb_raise(rb_eTypeError, "wrong argument type %"PRIsVALUE" (expected %s)",
  798. rb_obj_class(obj), data_type->wrap_struct_name);
  799. wrong_datatype:
  800. rb_raise(rb_eTypeError, "wrong argument type %s (expected %s)",
  801. etype, data_type->wrap_struct_name);
  802. }
  803. if (!RTYPEDDATA_P(obj)) {
  804. goto wrong_type;
  805. }
  806. else if (!rb_typeddata_inherited_p(RTYPEDDATA_TYPE(obj), data_type)) {
  807. etype = RTYPEDDATA_TYPE(obj)->wrap_struct_name;
  808. goto wrong_datatype;
  809. }
  810. return DATA_PTR(obj);
  811. }
  812. /* exception classes */
  813. VALUE rb_eException;
  814. VALUE rb_eSystemExit;
  815. VALUE rb_eInterrupt;
  816. VALUE rb_eSignal;
  817. VALUE rb_eFatal;
  818. VALUE rb_eStandardError;
  819. VALUE rb_eRuntimeError;
  820. VALUE rb_eFrozenError;
  821. VALUE rb_eTypeError;
  822. VALUE rb_eArgError;
  823. VALUE rb_eIndexError;
  824. VALUE rb_eKeyError;
  825. VALUE rb_eRangeError;
  826. VALUE rb_eNameError;
  827. VALUE rb_eEncodingError;
  828. VALUE rb_eEncCompatError;
  829. VALUE rb_eNoMethodError;
  830. VALUE rb_eSecurityError;
  831. VALUE rb_eNotImpError;
  832. VALUE rb_eNoMemError;
  833. VALUE rb_cNameErrorMesg;
  834. VALUE rb_eNoMatchingPatternError;
  835. VALUE rb_eScriptError;
  836. VALUE rb_eSyntaxError;
  837. VALUE rb_eLoadError;
  838. VALUE rb_eSystemCallError;
  839. VALUE rb_mErrno;
  840. static VALUE rb_eNOERROR;
  841. ID ruby_static_id_cause;
  842. #define id_cause ruby_static_id_cause
  843. static ID id_message, id_backtrace;
  844. static ID id_key, id_args, id_Errno, id_errno, id_i_path;
  845. static ID id_receiver, id_recv, id_iseq, id_local_variables;
  846. static ID id_private_call_p, id_top, id_bottom;
  847. #define id_bt idBt
  848. #define id_bt_locations idBt_locations
  849. #define id_mesg idMesg
  850. #define id_name idName
  851. #undef rb_exc_new_cstr
  852. VALUE
  853. rb_exc_new(VALUE etype, const char *ptr, long len)
  854. {
  855. VALUE mesg = rb_str_new(ptr, len);
  856. return rb_class_new_instance(1, &mesg, etype);
  857. }
  858. VALUE
  859. rb_exc_new_cstr(VALUE etype, const char *s)
  860. {
  861. return rb_exc_new(etype, s, strlen(s));
  862. }
  863. VALUE
  864. rb_exc_new_str(VALUE etype, VALUE str)
  865. {
  866. StringValue(str);
  867. return rb_class_new_instance(1, &str, etype);
  868. }
  869. static VALUE
  870. exc_init(VALUE exc, VALUE mesg)
  871. {
  872. rb_ivar_set(exc, id_mesg, mesg);
  873. rb_ivar_set(exc, id_bt, Qnil);
  874. return exc;
  875. }
  876. /*
  877. * call-seq:
  878. * Exception.new(msg = nil) -> exception
  879. *
  880. * Construct a new Exception object, optionally passing in
  881. * a message.
  882. */
  883. static VALUE
  884. exc_initialize(int argc, VALUE *argv, VALUE exc)
  885. {
  886. VALUE arg;
  887. arg = (!rb_check_arity(argc, 0, 1) ? Qnil : argv[0]);
  888. return exc_init(exc, arg);
  889. }
  890. /*
  891. * Document-method: exception
  892. *
  893. * call-seq:
  894. * exc.exception(string) -> an_exception or exc
  895. *
  896. * With no argument, or if the argument is the same as the receiver,
  897. * return the receiver. Otherwise, create a new
  898. * exception object of the same class as the receiver, but with a
  899. * message equal to <code>string.to_str</code>.
  900. *
  901. */
  902. static VALUE
  903. exc_exception(int argc, VALUE *argv, VALUE self)
  904. {
  905. VALUE exc;
  906. argc = rb_check_arity(argc, 0, 1);
  907. if (argc == 0) return self;
  908. if (argc == 1 && self == argv[0]) return self;
  909. exc = rb_obj_clone(self);
  910. rb_ivar_set(exc, id_mesg, argv[0]);
  911. return exc;
  912. }
  913. /*
  914. * call-seq:
  915. * exception.to_s -> string
  916. *
  917. * Returns exception's message (or the name of the exception if
  918. * no message is set).
  919. */
  920. static VALUE
  921. exc_to_s(VALUE exc)
  922. {
  923. VALUE mesg = rb_attr_get(exc, idMesg);
  924. if (NIL_P(mesg)) return rb_class_name(CLASS_OF(exc));
  925. return rb_String(mesg);
  926. }
  927. /* FIXME: Include eval_error.c */
  928. void rb_error_write(VALUE errinfo, VALUE emesg, VALUE errat, VALUE str, VALUE highlight, VALUE reverse);
  929. VALUE
  930. rb_get_message(VALUE exc)
  931. {
  932. VALUE e = rb_check_funcall(exc, id_message, 0, 0);
  933. if (e == Qundef) return Qnil;
  934. if (!RB_TYPE_P(e, T_STRING)) e = rb_check_string_type(e);
  935. return e;
  936. }
  937. /*
  938. * call-seq:
  939. * Exception.to_tty? -> true or false
  940. *
  941. * Returns +true+ if exception messages will be sent to a tty.
  942. */
  943. static VALUE
  944. exc_s_to_tty_p(VALUE self)
  945. {
  946. return rb_stderr_tty_p() ? Qtrue : Qfalse;
  947. }
  948. /*
  949. * call-seq:
  950. * exception.full_message(highlight: bool, order: [:top or :bottom]) -> string
  951. *
  952. * Returns formatted string of _exception_.
  953. * The returned string is formatted using the same format that Ruby uses
  954. * when printing an uncaught exceptions to stderr.
  955. *
  956. * If _highlight_ is +true+ the default error handler will send the
  957. * messages to a tty.
  958. *
  959. * _order_ must be either of +:top+ or +:bottom+, and places the error
  960. * message and the innermost backtrace come at the top or the bottom.
  961. *
  962. * The default values of these options depend on <code>$stderr</code>
  963. * and its +tty?+ at the timing of a call.
  964. */
  965. static VALUE
  966. exc_full_message(int argc, VALUE *argv, VALUE exc)
  967. {
  968. VALUE opt, str, emesg, errat;
  969. enum {kw_highlight, kw_order, kw_max_};
  970. static ID kw[kw_max_];
  971. VALUE args[kw_max_] = {Qnil, Qnil};
  972. rb_scan_args(argc, argv, "0:", &opt);
  973. if (!NIL_P(opt)) {
  974. if (!kw[0]) {
  975. #define INIT_KW(n) kw[kw_##n] = rb_intern_const(#n)
  976. INIT_KW(highlight);
  977. INIT_KW(order);
  978. #undef INIT_KW
  979. }
  980. rb_get_kwargs(opt, kw, 0, kw_max_, args);
  981. switch (args[kw_highlight]) {
  982. default:
  983. rb_raise(rb_eArgError, "expected true or false as "
  984. "highlight: %+"PRIsVALUE, args[kw_highlight]);
  985. case Qundef: args[kw_highlight] = Qnil; break;
  986. case Qtrue: case Qfalse: case Qnil: break;
  987. }
  988. if (args[kw_order] == Qundef) {
  989. args[kw_order] = Qnil;
  990. }
  991. else {
  992. ID id = rb_check_id(&args[kw_order]);
  993. if (id == id_bottom) args[kw_order] = Qtrue;
  994. else if (id == id_top) args[kw_order] = Qfalse;
  995. else {
  996. rb_raise(rb_eArgError, "expected :top or :bottom as "
  997. "order: %+"PRIsVALUE, args[kw_order]);
  998. }
  999. }
  1000. }
  1001. str = rb_str_new2("");
  1002. errat = rb_get_backtrace(exc);
  1003. emesg = rb_get_message(exc);
  1004. rb_error_write(exc, emesg, errat, str, args[kw_highlight], args[kw_order]);
  1005. return str;
  1006. }
  1007. /*
  1008. * call-seq:
  1009. * exception.message -> string
  1010. *
  1011. * Returns the result of invoking <code>exception.to_s</code>.
  1012. * Normally this returns the exception's message or name.
  1013. */
  1014. static VALUE
  1015. exc_message(VALUE exc)
  1016. {
  1017. return rb_funcallv(exc, idTo_s, 0, 0);
  1018. }
  1019. /*
  1020. * call-seq:
  1021. * exception.inspect -> string
  1022. *
  1023. * Return this exception's class name and message.
  1024. */
  1025. static VALUE
  1026. exc_inspect(VALUE exc)
  1027. {
  1028. VALUE str, klass;
  1029. klass = CLASS_OF(exc);
  1030. exc = rb_obj_as_string(exc);
  1031. if (RSTRING_LEN(exc) == 0) {
  1032. return rb_class_name(klass);
  1033. }
  1034. str = rb_str_buf_new2("#<");
  1035. klass = rb_class_name(klass);
  1036. rb_str_buf_append(str, klass);
  1037. rb_str_buf_cat(str, ": ", 2);
  1038. rb_str_buf_append(str, exc);
  1039. rb_str_buf_cat(str, ">", 1);
  1040. return str;
  1041. }
  1042. /*
  1043. * call-seq:
  1044. * exception.backtrace -> array or nil
  1045. *
  1046. * Returns any backtrace associated with the exception. The backtrace
  1047. * is an array of strings, each containing either ``filename:lineNo: in
  1048. * `method''' or ``filename:lineNo.''
  1049. *
  1050. * def a
  1051. * raise "boom"
  1052. * end
  1053. *
  1054. * def b
  1055. * a()
  1056. * end
  1057. *
  1058. * begin
  1059. * b()
  1060. * rescue => detail
  1061. * print detail.backtrace.join("\n")
  1062. * end
  1063. *
  1064. * <em>produces:</em>
  1065. *
  1066. * prog.rb:2:in `a'
  1067. * prog.rb:6:in `b'
  1068. * prog.rb:10
  1069. *
  1070. * In the case no backtrace has been set, +nil+ is returned
  1071. *
  1072. * ex = StandardError.new
  1073. * ex.backtrace
  1074. * #=> nil
  1075. */
  1076. static VALUE
  1077. exc_backtrace(VALUE exc)
  1078. {
  1079. VALUE obj;
  1080. obj = rb_attr_get(exc, id_bt);
  1081. if (rb_backtrace_p(obj)) {
  1082. obj = rb_backtrace_to_str_ary(obj);
  1083. /* rb_ivar_set(exc, id_bt, obj); */
  1084. }
  1085. return obj;
  1086. }
  1087. static VALUE rb_check_backtrace(VALUE);
  1088. VALUE
  1089. rb_get_backtrace(VALUE exc)
  1090. {
  1091. ID mid = id_backtrace;
  1092. VALUE info;
  1093. if (rb_method_basic_definition_p(CLASS_OF(exc), id_backtrace)) {
  1094. VALUE klass = rb_eException;
  1095. rb_execution_context_t *ec = GET_EC();
  1096. if (NIL_P(exc))
  1097. return Qnil;
  1098. EXEC_EVENT_HOOK(ec, RUBY_EVENT_C_CALL, exc, mid, mid, klass, Qundef);
  1099. info = exc_backtrace(exc);
  1100. EXEC_EVENT_HOOK(ec, RUBY_EVENT_C_RETURN, exc, mid, mid, klass, info);
  1101. }
  1102. else {
  1103. info = rb_funcallv(exc, mid, 0, 0);
  1104. }
  1105. if (NIL_P(info)) return Qnil;
  1106. return rb_check_backtrace(info);
  1107. }
  1108. /*
  1109. * call-seq:
  1110. * exception.backtrace_locations -> array or nil
  1111. *
  1112. * Returns any backtrace associated with the exception. This method is
  1113. * similar to Exception#backtrace, but the backtrace is an array of
  1114. * Thread::Backtrace::Location.
  1115. *
  1116. * This method is not affected by Exception#set_backtrace().
  1117. */
  1118. static VALUE
  1119. exc_backtrace_locations(VALUE exc)
  1120. {
  1121. VALUE obj;
  1122. obj = rb_attr_get(exc, id_bt_locations);
  1123. if (!NIL_P(obj)) {
  1124. obj = rb_backtrace_to_location_ary(obj);
  1125. }
  1126. return obj;
  1127. }
  1128. static VALUE
  1129. rb_check_backtrace(VALUE bt)
  1130. {
  1131. long i;
  1132. static const char err[] = "backtrace must be Array of String";
  1133. if (!NIL_P(bt)) {
  1134. if (RB_TYPE_P(bt, T_STRING)) return rb_ary_new3(1, bt);
  1135. if (rb_backtrace_p(bt)) return bt;
  1136. if (!RB_TYPE_P(bt, T_ARRAY)) {
  1137. rb_raise(rb_eTypeError, err);
  1138. }
  1139. for (i=0;i<RARRAY_LEN(bt);i++) {
  1140. VALUE e = RARRAY_AREF(bt, i);
  1141. if (!RB_TYPE_P(e, T_STRING)) {
  1142. rb_raise(rb_eTypeError, err);
  1143. }
  1144. }
  1145. }
  1146. return bt;
  1147. }
  1148. /*
  1149. * call-seq:
  1150. * exc.set_backtrace(backtrace) -> array
  1151. *
  1152. * Sets the backtrace information associated with +exc+. The +backtrace+ must
  1153. * be an array of String objects or a single String in the format described
  1154. * in Exception#backtrace.
  1155. *
  1156. */
  1157. static VALUE
  1158. exc_set_backtrace(VALUE exc, VALUE bt)
  1159. {
  1160. return rb_ivar_set(exc, id_bt, rb_check_backtrace(bt));
  1161. }
  1162. MJIT_FUNC_EXPORTED VALUE
  1163. rb_exc_set_backtrace(VALUE exc, VALUE bt)
  1164. {
  1165. return exc_set_backtrace(exc, bt);
  1166. }
  1167. /*
  1168. * call-seq:
  1169. * exception.cause -> an_exception or nil
  1170. *
  1171. * Returns the previous exception ($!) at the time this exception was raised.
  1172. * This is useful for wrapping exceptions and retaining the original exception
  1173. * information.
  1174. */
  1175. static VALUE
  1176. exc_cause(VALUE exc)
  1177. {
  1178. return rb_attr_get(exc, id_cause);
  1179. }
  1180. static VALUE
  1181. try_convert_to_exception(VALUE obj)
  1182. {
  1183. return rb_check_funcall(obj, idException, 0, 0);
  1184. }
  1185. /*
  1186. * call-seq:
  1187. * exc == obj -> true or false
  1188. *
  1189. * Equality---If <i>obj</i> is not an Exception, returns
  1190. * <code>false</code>. Otherwise, returns <code>true</code> if <i>exc</i> and
  1191. * <i>obj</i> share same class, messages, and backtrace.
  1192. */
  1193. static VALUE
  1194. exc_equal(VALUE exc, VALUE obj)
  1195. {
  1196. VALUE mesg, backtrace;
  1197. if (exc == obj) return Qtrue;
  1198. if (rb_obj_class(exc) != rb_obj_class(obj)) {
  1199. int state;
  1200. obj = rb_protect(try_convert_to_exception, obj, &state);
  1201. if (state || obj == Qundef) {
  1202. rb_set_errinfo(Qnil);
  1203. return Qfalse;
  1204. }
  1205. if (rb_obj_class(exc) != rb_obj_class(obj)) return Qfalse;
  1206. mesg = rb_check_funcall(obj, id_message, 0, 0);
  1207. if (mesg == Qundef) return Qfalse;
  1208. backtrace = rb_check_funcall(obj, id_backtrace, 0, 0);
  1209. if (backtrace == Qundef) return Qfalse;
  1210. }
  1211. else {
  1212. mesg = rb_attr_get(obj, id_mesg);
  1213. backtrace = exc_backtrace(obj);
  1214. }
  1215. if (!rb_equal(rb_attr_get(exc, id_mesg), mesg))
  1216. return Qfalse;
  1217. if (!rb_equal(exc_backtrace(exc), backtrace))
  1218. return Qfalse;
  1219. return Qtrue;
  1220. }
  1221. /*
  1222. * call-seq:
  1223. * SystemExit.new -> system_exit
  1224. * SystemExit.new(status) -> system_exit
  1225. * SystemExit.new(status, msg) -> system_exit
  1226. * SystemExit.new(msg) -> system_exit
  1227. *
  1228. * Create a new +SystemExit+ exception with the given status and message.
  1229. * Status is true, false, or an integer.
  1230. * If status is not given, true is used.
  1231. */
  1232. static VALUE
  1233. exit_initialize(int argc, VALUE *argv, VALUE exc)
  1234. {
  1235. VALUE status;
  1236. if (argc > 0) {
  1237. status = *argv;
  1238. switch (status) {
  1239. case Qtrue:
  1240. status = INT2FIX(EXIT_SUCCESS);
  1241. ++argv;
  1242. --argc;
  1243. break;
  1244. case Qfalse:
  1245. status = INT2FIX(EXIT_FAILURE);
  1246. ++argv;
  1247. --argc;
  1248. break;
  1249. default:
  1250. status = rb_check_to_int(status);
  1251. if (NIL_P(status)) {
  1252. status = INT2FIX(EXIT_SUCCESS);
  1253. }
  1254. else {
  1255. #if EXIT_SUCCESS != 0
  1256. if (status == INT2FIX(0))
  1257. status = INT2FIX(EXIT_SUCCESS);
  1258. #endif
  1259. ++argv;
  1260. --argc;
  1261. }
  1262. break;
  1263. }
  1264. }
  1265. else {
  1266. status = INT2FIX(EXIT_SUCCESS);
  1267. }
  1268. rb_call_super(argc, argv);
  1269. rb_ivar_set(exc, id_status, status);
  1270. return exc;
  1271. }
  1272. /*
  1273. * call-seq:
  1274. * system_exit.status -> integer
  1275. *
  1276. * Return the status value associated with this system exit.
  1277. */
  1278. static VALUE
  1279. exit_status(VALUE exc)
  1280. {
  1281. return rb_attr_get(exc, id_status);
  1282. }
  1283. /*
  1284. * call-seq:
  1285. * system_exit.success? -> true or false
  1286. *
  1287. * Returns +true+ if exiting successful, +false+ if not.
  1288. */
  1289. static VALUE
  1290. exit_success_p(VALUE exc)
  1291. {
  1292. VALUE status_val = rb_attr_get(exc, id_status);
  1293. int status;
  1294. if (NIL_P(status_val))
  1295. return Qtrue;
  1296. status = NUM2INT(status_val);
  1297. if (WIFEXITED(status) && WEXITSTATUS(status) == EXIT_SUCCESS)
  1298. return Qtrue;
  1299. return Qfalse;
  1300. }
  1301. static VALUE
  1302. err_init_recv(VALUE exc, VALUE recv)
  1303. {
  1304. if (recv != Qundef) rb_ivar_set(exc, id_recv, recv);
  1305. return exc;
  1306. }
  1307. /*
  1308. * call-seq:
  1309. * FrozenError.new(msg=nil, receiver: nil) -> frozen_error
  1310. *
  1311. * Construct a new FrozenError exception. If given the <i>receiver</i>
  1312. * parameter may subsequently be examined using the FrozenError#receiver
  1313. * method.
  1314. *
  1315. * a = [].freeze
  1316. * raise FrozenError.new("can't modify frozen array", receiver: a)
  1317. */
  1318. static VALUE
  1319. frozen_err_initialize(int argc, VALUE *argv, VALUE self)
  1320. {
  1321. ID keywords[1];
  1322. VALUE values[numberof(keywords)], options;
  1323. argc = rb_scan_args(argc, argv, "*:", NULL, &options);
  1324. keywords[0] = id_receiver;
  1325. rb_get_kwargs(options, keywords, 0, numberof(values), values);
  1326. rb_call_super(argc, argv);
  1327. err_init_recv(self, values[0]);
  1328. return self;
  1329. }
  1330. /*
  1331. * Document-method: FrozenError#receiver
  1332. * call-seq:
  1333. * frozen_error.receiver -> object
  1334. *
  1335. * Return the receiver associated with this FrozenError exception.
  1336. */
  1337. #define frozen_err_receiver name_err_receiver
  1338. void
  1339. rb_name_error(ID id, const char *fmt, ...)
  1340. {
  1341. VALUE exc, argv[2];
  1342. va_list args;
  1343. va_start(args, fmt);
  1344. argv[0] = rb_vsprintf(fmt, args);
  1345. va_end(args);
  1346. argv[1] = ID2SYM(id);
  1347. exc = rb_class_new_instance(2, argv, rb_eNameError);
  1348. rb_exc_raise(exc);
  1349. }
  1350. void
  1351. rb_name_error_str(VALUE str, const char *fmt, ...)
  1352. {
  1353. VALUE exc, argv[2];
  1354. va_list args;
  1355. va_start(args, fmt);
  1356. argv[0] = rb_vsprintf(fmt, args);
  1357. va_end(args);
  1358. argv[1] = str;
  1359. exc = rb_class_new_instance(2, argv, rb_eNameError);
  1360. rb_exc_raise(exc);
  1361. }
  1362. static VALUE
  1363. name_err_init_attr(VALUE exc, VALUE recv, VALUE method)
  1364. {
  1365. const rb_execution_context_t *ec = GET_EC();
  1366. rb_control_frame_t *cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(ec->cfp);
  1367. cfp = rb_vm_get_ruby_level_next_cfp(ec, cfp);
  1368. rb_ivar_set(exc, id_name, method);
  1369. err_init_recv(exc, recv);
  1370. if (cfp) rb_ivar_set(exc, id_iseq, rb_iseqw_new(cfp->iseq));
  1371. return exc;
  1372. }
  1373. /*
  1374. * call-seq:
  1375. * NameError.new(msg=nil, name=nil, receiver: nil) -> name_error
  1376. *
  1377. * Construct a new NameError exception. If given the <i>name</i>
  1378. * parameter may subsequently be examined using the NameError#name
  1379. * method. <i>receiver</i> parameter allows to pass object in
  1380. * context of which the error happened. Example:
  1381. *
  1382. * [1, 2, 3].method(:rject) # NameError with name "rject" and receiver: Array
  1383. * [1, 2, 3].singleton_method(:rject) # NameError with name "rject" and receiver: [1, 2, 3]
  1384. */
  1385. static VALUE
  1386. name_err_initialize(int argc, VALUE *argv, VALUE self)
  1387. {
  1388. ID keywords[1];
  1389. VALUE values[numberof(keywords)], name, options;
  1390. argc = rb_scan_args(argc, argv, "*:", NULL, &options);
  1391. keywords[0] = id_receiver;
  1392. rb_get_kwargs(options, keywords, 0, numberof(values), values);
  1393. name = (argc > 1) ? argv[--argc] : Qnil;
  1394. rb_call_super(argc, argv);
  1395. name_err_init_attr(self, values[0], name);
  1396. return self;
  1397. }
  1398. static VALUE rb_name_err_mesg_new(VALUE mesg, VALUE recv, VALUE method);
  1399. static VALUE
  1400. name_err_init(VALUE exc, VALUE mesg, VALUE recv, VALUE method)
  1401. {
  1402. exc_init(exc, rb_name_err_mesg_new(mesg, recv, method));
  1403. return name_err_init_attr(exc, recv, method);
  1404. }
  1405. VALUE
  1406. rb_name_err_new(VALUE mesg, VALUE recv, VALUE method)
  1407. {
  1408. VALUE exc = rb_obj_alloc(rb_eNameError);
  1409. return name_err_init(exc, mesg, recv, method);
  1410. }
  1411. /*
  1412. * call-seq:
  1413. * name_error.name -> string or nil
  1414. *
  1415. * Return the name associated with this NameError exception.
  1416. */
  1417. static VALUE
  1418. name_err_name(VALUE self)
  1419. {
  1420. return rb_attr_get(self, id_name);
  1421. }
  1422. /*
  1423. * call-seq:
  1424. * name_error.local_variables -> array
  1425. *
  1426. * Return a list of the local variable names defined where this
  1427. * NameError exception was raised.
  1428. *
  1429. * Internal use only.
  1430. */
  1431. static VALUE
  1432. name_err_local_variables(VALUE self)
  1433. {
  1434. VALUE vars = rb_attr_get(self, id_local_variables);
  1435. if (NIL_P(vars)) {
  1436. VALUE iseqw = rb_attr_get(self, id_iseq);
  1437. if (!NIL_P(iseqw)) vars = rb_iseqw_local_variables(iseqw);
  1438. if (NIL_P(vars)) vars = rb_ary_new();
  1439. rb_ivar_set(self, id_local_variables, vars);
  1440. }
  1441. return vars;
  1442. }
  1443. static VALUE
  1444. nometh_err_init_attr(VALUE exc, VALUE args, int priv)
  1445. {
  1446. rb_ivar_set(exc, id_args, args);
  1447. rb_ivar_set(exc, id_private_call_p, priv ? Qtrue : Qfalse);
  1448. return exc;
  1449. }
  1450. /*
  1451. * call-seq:
  1452. * NoMethodError.new(msg=nil, name=nil, args=nil, private=false, receiver: nil) -> no_method_error
  1453. *
  1454. * Construct a NoMethodError exception for a method of the given name
  1455. * called with the given arguments. The name may be accessed using
  1456. * the <code>#name</code> method on the resulting object, and the
  1457. * arguments using the <code>#args</code> method.
  1458. *
  1459. * If <i>private</i> argument were passed, it designates method was
  1460. * attempted to call in private context, and can be accessed with
  1461. * <code>#private_call?</code> method.
  1462. *
  1463. * <i>receiver</i> argument stores an object whose method was called.
  1464. */
  1465. static VALUE
  1466. nometh_err_initialize(int argc, VALUE *argv, VALUE self)
  1467. {
  1468. int priv;
  1469. VALUE args, options;
  1470. argc = rb_scan_args(argc, argv, "*:", NULL, &options);
  1471. priv = (argc > 3) && (--argc, RTEST(argv[argc]));
  1472. args = (argc > 2) ? argv[--argc] : Qnil;
  1473. if (!NIL_P(options)) argv[argc++] = options;
  1474. rb_call_super_kw(argc, argv, RB_PASS_CALLED_KEYWORDS);
  1475. return nometh_err_init_attr(self, args, priv);
  1476. }
  1477. VALUE
  1478. rb_nomethod_err_new(VALUE mesg, VALUE recv, VALUE method, VALUE args, int priv)
  1479. {
  1480. VALUE exc = rb_obj_alloc(rb_eNoMethodError);
  1481. name_err_init(exc, mesg, recv, method);
  1482. return nometh_err_init_attr(exc, args, priv);
  1483. }
  1484. /* :nodoc: */
  1485. enum {
  1486. NAME_ERR_MESG__MESG,
  1487. NAME_ERR_MESG__RECV,
  1488. NAME_ERR_MESG__NAME,
  1489. NAME_ERR_MESG_COUNT
  1490. };
  1491. static void
  1492. name_err_mesg_mark(void *p)
  1493. {
  1494. VALUE *ptr = p;
  1495. rb_gc_mark_locations(ptr, ptr+NAME_ERR_MESG_COUNT);
  1496. }
  1497. #define name_err_mesg_free RUBY_TYPED_DEFAULT_FREE
  1498. static size_t
  1499. name_err_mesg_memsize(const void *p)
  1500. {
  1501. return NAME_ERR_MESG_COUNT * sizeof(VALUE);
  1502. }
  1503. static const rb_data_type_t name_err_mesg_data_type = {
  1504. "name_err_mesg",
  1505. {
  1506. name_err_mesg_mark,
  1507. name_err_mesg_free,
  1508. name_err_mesg_memsize,
  1509. },
  1510. 0, 0, RUBY_TYPED_FREE_IMMEDIATELY
  1511. };
  1512. /* :nodoc: */
  1513. static VALUE
  1514. rb_name_err_mesg_new(VALUE mesg, VALUE recv, VALUE method)
  1515. {
  1516. VALUE result = TypedData_Wrap_Struct(rb_cNameErrorMesg, &name_err_mesg_data_type, 0);
  1517. VALUE *ptr = ALLOC_N(VALUE, NAME_ERR_MESG_COUNT);
  1518. ptr[NAME_ERR_MESG__MESG] = mesg;
  1519. ptr[NAME_ERR_MESG__RECV] = recv;
  1520. ptr[NAME_ERR_MESG__NAME] = method;
  1521. RTYPEDDATA_DATA(result) = ptr;
  1522. return result;
  1523. }
  1524. /* :nodoc: */
  1525. static VALUE
  1526. name_err_mesg_equal(VALUE obj1, VALUE obj2)
  1527. {
  1528. VALUE *ptr1, *ptr2;
  1529. int i;
  1530. if (obj1 == obj2) return Qtrue;
  1531. if (rb_obj_class(obj2) != rb_cNameErrorMesg)
  1532. return Qfalse;
  1533. TypedData_Get_Struct(obj1, VALUE, &name_err_mesg_data_type, ptr1);
  1534. TypedData_Get_Struct(obj2, VALUE, &name_err_mesg_data_type, ptr2);
  1535. for (i=0; i<NAME_ERR_MESG_COUNT; i++) {
  1536. if (!rb_equal(ptr1[i], ptr2[i]))
  1537. return Qfalse;
  1538. }
  1539. return Qtrue;
  1540. }
  1541. /* :nodoc: */
  1542. static VALUE
  1543. name_err_mesg_to_str(VALUE obj)
  1544. {
  1545. VALUE *ptr, mesg;
  1546. TypedData_Get_Struct(obj, VALUE, &name_err_mesg_data_type, ptr);
  1547. mesg = ptr[NAME_ERR_MESG__MESG];
  1548. if (NIL_P(mesg)) return Qnil;
  1549. else {
  1550. struct RString s_str, d_str;
  1551. VALUE c, s, d = 0, args[4];
  1552. int state = 0, singleton = 0;
  1553. rb_encoding *usascii = rb_usascii_encoding();
  1554. #define FAKE_CSTR(v, str) rb_setup_fake_str((v), (str), rb_strlen_lit(str), usascii)
  1555. obj = ptr[NAME_ERR_MESG__RECV];
  1556. switch (obj) {
  1557. case Qnil:
  1558. d = FAKE_CSTR(&d_str, "nil");
  1559. break;
  1560. case Qtrue:
  1561. d = FAKE_CSTR(&d_str, "true");
  1562. break;
  1563. case Qfalse:
  1564. d = FAKE_CSTR(&d_str, "false");
  1565. break;
  1566. default:
  1567. d = rb_protect(rb_inspect, obj, &state);
  1568. if (state)
  1569. rb_set_errinfo(Qnil);
  1570. if (NIL_P(d)) {
  1571. d = rb_any_to_s(obj);
  1572. }
  1573. singleton = (RSTRING_LEN(d) > 0 && RSTRING_PTR(d)[0] == '#');
  1574. break;
  1575. }
  1576. if (!singleton) {
  1577. s = FAKE_CSTR(&s_str, ":");
  1578. c = rb_class_name(CLASS_OF(obj));
  1579. }
  1580. else {
  1581. c = s = FAKE_CSTR(&s_str, "");
  1582. }
  1583. args[0] = rb_obj_as_string(ptr[NAME_ERR_MESG__NAME]);
  1584. args[1] = d;
  1585. args[2] = s;
  1586. args[3] = c;
  1587. mesg = rb_str_format(4, args, mesg);
  1588. }
  1589. return mesg;
  1590. }
  1591. /* :nodoc: */
  1592. static VALUE
  1593. name_err_mesg_dump(VALUE obj, VALUE limit)
  1594. {
  1595. return name_err_mesg_to_str(obj);
  1596. }
  1597. /* :nodoc: */
  1598. static VALUE
  1599. name_err_mesg_load(VALUE klass, VALUE str)
  1600. {
  1601. return str;
  1602. }
  1603. /*
  1604. * call-seq:
  1605. * name_error.receiver -> object
  1606. *
  1607. * Return the receiver associated with this NameError exception.
  1608. */
  1609. static VALUE
  1610. name_err_receiver(VALUE self)
  1611. {
  1612. VALUE *ptr, recv, mesg;
  1613. recv = rb_ivar_lookup(self, id_recv, Qundef);
  1614. if (recv != Qundef) return recv;
  1615. mesg = rb_attr_get(self, id_mesg);
  1616. if (!rb_typeddata_is_kind_of(mesg, &name_err_mesg_data_type)) {
  1617. rb_raise(rb_eArgError, "no receiver is available");
  1618. }
  1619. ptr = DATA_PTR(mesg);
  1620. return ptr[NAME_ERR_MESG__RECV];
  1621. }
  1622. /*
  1623. * call-seq:
  1624. * no_method_error.args -> obj
  1625. *
  1626. * Return the arguments passed in as the third parameter to
  1627. * the constructor.
  1628. */
  1629. static VALUE
  1630. nometh_err_args(VALUE self)
  1631. {
  1632. return rb_attr_get(self, id_args);
  1633. }
  1634. /*
  1635. * call-seq:
  1636. * no_method_error.private_call? -> true or false
  1637. *
  1638. * Return true if the caused method was called as private.
  1639. */
  1640. static VALUE
  1641. nometh_err_private_call_p(VALUE self)
  1642. {
  1643. return rb_attr_get(self, id_private_call_p);
  1644. }
  1645. void
  1646. rb_invalid_str(const char *str, const char *type)
  1647. {
  1648. VALUE s = rb_str_new2(str);
  1649. rb_raise(rb_eArgError, "invalid value for %s: %+"PRIsVALUE, type, s);
  1650. }
  1651. /*
  1652. * call-seq:
  1653. * key_error.receiver -> object
  1654. *
  1655. * Return the receiver associated with this KeyError exception.
  1656. */
  1657. static VALUE
  1658. key_err_receiver(VALUE self)
  1659. {
  1660. VALUE recv;
  1661. recv = rb_ivar_lookup(self, id_receiver, Qundef);
  1662. if (recv != Qundef) return recv;
  1663. rb_raise(rb_eArgError, "no receiver is available");
  1664. }
  1665. /*
  1666. * call-seq:
  1667. * key_error.key -> object
  1668. *
  1669. * Return the key caused this KeyError exception.
  1670. */
  1671. static VALUE
  1672. key_err_key(VALUE self)
  1673. {
  1674. VALUE key;
  1675. key = rb_ivar_lookup(self, id_key, Qundef);
  1676. if (key != Qundef) return key;
  1677. rb_raise(rb_eArgError, "no key is available");
  1678. }
  1679. VALUE
  1680. rb_key_err_new(VALUE mesg, VALUE recv, VALUE key)
  1681. {
  1682. VALUE exc = rb_obj_alloc(rb_eKeyError);
  1683. rb_ivar_set(exc, id_mesg, mesg);
  1684. rb_ivar_set(exc, id_bt, Qnil);
  1685. rb_ivar_set(exc, id_key, key);
  1686. rb_ivar_set(exc, id_receiver, recv);
  1687. return exc;
  1688. }
  1689. /*
  1690. * call-seq:
  1691. * KeyError.new(message=nil, receiver: nil, key: nil) -> key_error
  1692. *
  1693. * Construct a new +KeyError+ exception with the given message,
  1694. * receiver and key.
  1695. */
  1696. static VALUE
  1697. key_err_initialize(int argc, VALUE *argv, VALUE self)
  1698. {
  1699. VALUE options;
  1700. rb_call_super(rb_scan_args(argc, argv, "01:", NULL, &options), argv);
  1701. if (!NIL_P(options)) {
  1702. ID keywords[2];
  1703. VALUE values[numberof(keywords)];
  1704. int i;
  1705. keywords[0] = id_receiver;
  1706. keywords[1] = id_key;
  1707. rb_get_kwargs(options, keywords, 0, numberof(values), values);
  1708. for (i = 0; i < numberof(values); ++i) {
  1709. if (values[i] != Qundef) {
  1710. rb_ivar_set(self, keywords[i], values[i]);
  1711. }
  1712. }
  1713. }
  1714. return self;
  1715. }
  1716. /*
  1717. * call-seq:
  1718. * SyntaxError.new([msg]) -> syntax_error
  1719. *
  1720. * Construct a SyntaxError exception.
  1721. */
  1722. static VALUE
  1723. syntax_error_initialize(int argc, VALUE *argv, VALUE self)
  1724. {
  1725. VALUE mesg;
  1726. if (argc == 0) {
  1727. mesg = rb_fstring_lit("compile error");
  1728. argc = 1;
  1729. argv = &mesg;
  1730. }
  1731. return rb_call_super(argc, argv);
  1732. }
  1733. /*
  1734. * Document-module: Errno
  1735. *
  1736. * Ruby exception objects are subclasses of Exception. However,
  1737. * operating systems typically report errors using plain
  1738. * integers. Module Errno is created dynamically to map these
  1739. * operating system errors to Ruby classes, with each error number
  1740. * generating its own subclass of SystemCallError. As the subclass
  1741. * is created in module Errno, its name will start
  1742. * <code>Errno::</code>.
  1743. *
  1744. * The names of the <code>Errno::</code> classes depend on the
  1745. * environment in which Ruby runs. On a typical Unix or Windows
  1746. * platform, there are Errno classes such as Errno::EACCES,
  1747. * Errno::EAGAIN, Errno::EINTR, and so on.
  1748. *
  1749. * The integer operating system error number corresponding to a
  1750. * particular error is available as the class constant
  1751. * <code>Errno::</code><em>error</em><code>::Errno</code>.
  1752. *
  1753. * Errno::EACCES::Errno #=> 13
  1754. * Errno::EAGAIN::Errno #=> 11
  1755. * Errno::EINTR::Errno #=> 4
  1756. *
  1757. * The full list of operating system errors on your particular platform
  1758. * are available as the constants of Errno.
  1759. *
  1760. * Errno.constants #=> :E2BIG, :EACCES, :EADDRINUSE, :EADDRNOTAVAIL, ...
  1761. */
  1762. static st_table *syserr_tbl;
  1763. static VALUE
  1764. set_syserr(int n, const char *name)
  1765. {
  1766. st_data_t error;
  1767. if (!st_lookup(syserr_tbl, n, &error)) {
  1768. error = rb_define_class_under(rb_mErrno, name, rb_eSystemCallError);
  1769. /* capture nonblock errnos for WaitReadable/WaitWritable subclasses */
  1770. switch (n) {
  1771. case EAGAIN:
  1772. rb_eEAGAIN = error;
  1773. #if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
  1774. break;
  1775. case EWOULDBLOCK:
  1776. #endif
  1777. rb_eEWOULDBLOCK = error;
  1778. break;
  1779. case EINPROGRESS:
  1780. rb_eEINPROGRESS = error;
  1781. break;
  1782. }
  1783. rb_define_const(error, "Errno", INT2NUM(n));
  1784. st_add_direct(syserr_tbl, n, error);
  1785. }
  1786. else {
  1787. rb_define_const(rb_mErrno, name, error);
  1788. }
  1789. return error;
  1790. }
  1791. static VALUE
  1792. get_syserr(int n)
  1793. {
  1794. st_data_t error;
  1795. if (!st_lookup(syserr_tbl, n, &error)) {
  1796. char name[8]; /* some Windows' errno have 5 digits. */
  1797. snprintf(name, sizeof(name), "E%03d", n);
  1798. error = set_syserr(n, name);
  1799. }
  1800. return error;
  1801. }
  1802. /*
  1803. * call-seq:
  1804. * SystemCallError.new(msg, errno) -> system_call_error_subclass
  1805. *
  1806. * If _errno_ corresponds to a known system error code, constructs the
  1807. * appropriate Errno class for that error, otherwise constructs a
  1808. * generic SystemCallError object. The error number is subsequently
  1809. * available via the #errno method.
  1810. */
  1811. static VALUE
  1812. syserr_initialize(int argc, VALUE *argv, VALUE self)
  1813. {
  1814. #if !defined(_WIN32)
  1815. char *strerror();
  1816. #endif
  1817. const char *err;
  1818. VALUE mesg, error, func, errmsg;
  1819. VALUE klass = rb_obj_class(self);
  1820. if (klass == rb_eSystemCallError) {
  1821. st_data_t data = (st_data_t)klass;
  1822. rb_scan_args(argc, argv, "12", &mesg, &error, &func);
  1823. if (argc == 1 && FIXNUM_P(mesg)) {
  1824. error = mesg; mesg = Qnil;
  1825. }
  1826. if (!NIL_P(error) && st_lookup(syserr_tbl, NUM2LONG(error), &data)) {
  1827. klass = (VALUE)data;
  1828. /* change class */
  1829. if (!RB_TYPE_P(self, T_OBJECT)) { /* insurance to avoid type crash */
  1830. rb_raise(rb_eTypeError, "invalid instance type");
  1831. }
  1832. RBASIC_SET_CLASS(self, klass);
  1833. }
  1834. }
  1835. else {
  1836. rb_scan_args(argc, argv, "02", &mesg, &func);
  1837. error = rb_const_get(klass, id_Errno);
  1838. }
  1839. if (!NIL_P(error)) err = strerror(NUM2INT(error));
  1840. else err = "unknown error";
  1841. errmsg = rb_enc_str_new_cstr(err, rb_locale_encoding());
  1842. if (!NIL_P(mesg)) {
  1843. VALUE str = StringValue(mesg);
  1844. if (!NIL_P(func)) rb_str_catf(errmsg, " @ %"PRIsVALUE, func);
  1845. rb_str_catf(errmsg, " - %"PRIsVALUE, str);
  1846. }
  1847. mesg = errmsg;
  1848. rb_call_super(1, &mesg);
  1849. rb_ivar_set(self, id_errno, error);
  1850. return self;
  1851. }
  1852. /*
  1853. * call-seq:
  1854. * system_call_error.errno -> integer
  1855. *
  1856. * Return this SystemCallError's error number.
  1857. */
  1858. static VALUE
  1859. syserr_errno(VALUE self)
  1860. {
  1861. return rb_attr_get(self, id_errno);
  1862. }
  1863. /*
  1864. * call-seq:
  1865. * system_call_error === other -> true or false
  1866. *
  1867. * Return +true+ if the receiver is a generic +SystemCallError+, or
  1868. * if the error numbers +self+ and _other_ are the same.
  1869. */
  1870. static VALUE
  1871. syserr_eqq(VALUE self, VALUE exc)
  1872. {
  1873. VALUE num, e;
  1874. if (!rb_obj_is_kind_of(exc, rb_eSystemCallError)) {
  1875. if (!rb_respond_to(exc, id_errno)) return Qfalse;
  1876. }
  1877. else if (self == rb_eSystemCallError) return Qtrue;
  1878. num = rb_attr_get(exc, id_errno);
  1879. if (NIL_P(num)) {
  1880. num = rb_funcallv(exc, id_errno, 0, 0);
  1881. }
  1882. e = rb_const_get(self, id_Errno);
  1883. if (FIXNUM_P(num) ? num == e : rb_equal(num, e))
  1884. return Qtrue;
  1885. return Qfalse;
  1886. }
  1887. /*
  1888. * Document-class: StandardError
  1889. *
  1890. * The most standard error types are subclasses of StandardError. A
  1891. * rescue clause without an explicit Exception class will rescue all
  1892. * StandardErrors (and only those).
  1893. *
  1894. * def foo
  1895. * raise "Oups"
  1896. * end
  1897. * foo rescue "Hello" #=> "Hello"
  1898. *
  1899. * On the other hand:
  1900. *
  1901. * require 'does/not/exist' rescue "Hi"
  1902. *
  1903. * <em>raises the exception:</em>
  1904. *
  1905. * LoadError: no such file to load -- does/not/exist
  1906. *
  1907. */
  1908. /*
  1909. * Document-class: SystemExit
  1910. *
  1911. * Raised by +exit+ to initiate the termination of the script.
  1912. */
  1913. /*
  1914. * Document-class: SignalException
  1915. *
  1916. * Raised when a signal is received.
  1917. *
  1918. * begin
  1919. * Process.kill('HUP',Process.pid)
  1920. * sleep # wait for receiver to handle signal sent by Process.kill
  1921. * rescue SignalException => e
  1922. * puts "received Exception #{e}"
  1923. * end
  1924. *
  1925. * <em>produces:</em>
  1926. *
  1927. * received Exception SIGHUP
  1928. */
  1929. /*
  1930. * Document-class: Interrupt
  1931. *
  1932. * Raised when the interrupt signal is received, typically because the
  1933. * user has pressed Control-C (on most posix platforms). As such, it is a
  1934. * subclass of +SignalException+.
  1935. *
  1936. * begin
  1937. * puts "Press ctrl-C when you get bored"
  1938. * loop {}
  1939. * rescue Interrupt => e
  1940. * puts "Note: You will typically use Signal.trap instead."
  1941. * end
  1942. *
  1943. * <em>produces:</em>
  1944. *
  1945. * Press ctrl-C when you get bored
  1946. *
  1947. * <em>then waits until it is interrupted with Control-C and then prints:</em>
  1948. *
  1949. * Note: You will typically use Signal.trap instead.
  1950. */
  1951. /*
  1952. * Document-class: TypeError
  1953. *
  1954. * Raised when encountering an object that is not of the expected type.
  1955. *
  1956. * [1, 2, 3].first("two")
  1957. *
  1958. * <em>raises the exception:</em>
  1959. *
  1960. * TypeError: no implicit conversion of String into Integer
  1961. *
  1962. */
  1963. /*
  1964. * Document-class: ArgumentError
  1965. *
  1966. * Raised when the arguments are wrong and there isn't a more specific
  1967. * Exception class.
  1968. *
  1969. * Ex: passing the wrong number of arguments
  1970. *
  1971. * [1, 2, 3].first(4, 5)
  1972. *
  1973. * <em>raises the exception:</em>
  1974. *
  1975. * ArgumentError: wrong number of arguments (given 2, expected 1)
  1976. *
  1977. * Ex: passing an argument that is not acceptable:
  1978. *
  1979. * [1, 2, 3].first(-4)
  1980. *
  1981. * <em>raises the exception:</em>
  1982. *
  1983. * ArgumentError: negative array size
  1984. */
  1985. /*
  1986. * Document-class: IndexError
  1987. *
  1988. * Raised when the given index is invalid.
  1989. *
  1990. * a = [:foo, :bar]
  1991. * a.fetch(0) #=> :foo
  1992. * a[4] #=> nil
  1993. * a.fetch(4) #=> IndexError: index 4 outside of array bounds: -2...2
  1994. *
  1995. */
  1996. /*
  1997. * Document-class: KeyError
  1998. *
  1999. * Raised when the specified key is not found. It is a subclass of
  2000. * IndexError.
  2001. *
  2002. * h = {"foo" => :bar}
  2003. * h.fetch("foo") #=> :bar
  2004. * h.fetch("baz") #=> KeyError: key not found: "baz"
  2005. *
  2006. */
  2007. /*
  2008. * Document-class: RangeError
  2009. *
  2010. * Raised when a given numerical value is out of range.
  2011. *
  2012. * [1, 2, 3].drop(1 << 100)
  2013. *
  2014. * <em>raises the exception:</em>
  2015. *
  2016. * RangeError: bignum too big to convert into `long'
  2017. */
  2018. /*
  2019. * Document-class: ScriptError
  2020. *
  2021. * ScriptError is the superclass for errors raised when a script
  2022. * can not be executed because of a +LoadError+,
  2023. * +NotImplementedError+ or a +SyntaxError+. Note these type of
  2024. * +ScriptErrors+ are not +StandardError+ and will not be
  2025. * rescued unless it is specified explicitly (or its ancestor
  2026. * +Exception+).
  2027. */
  2028. /*
  2029. * Document-class: SyntaxError
  2030. *
  2031. * Raised when encountering Ruby code with an invalid syntax.
  2032. *
  2033. * eval("1+1=2")
  2034. *
  2035. * <em>raises the exception:</em>
  2036. *
  2037. * SyntaxError: (eval):1: syntax error, unexpected '=', expecting $end
  2038. */
  2039. /*
  2040. * Document-class: LoadError
  2041. *
  2042. * Raised when a file required (a Ruby script, extension library, ...)
  2043. * fails to load.
  2044. *
  2045. * require 'this/file/does/not/exist'
  2046. *
  2047. * <em>raises the exception:</em>
  2048. *
  2049. * LoadError: no such file to load -- this/file/does/not/exist
  2050. */
  2051. /*
  2052. * Document-class: NotImplementedError
  2053. *
  2054. * Raised when a feature is not implemented on the current platform. For
  2055. * example, methods depending on the +fsync+ or +fork+ system calls may
  2056. * raise this exception if the underlying operating system or Ruby
  2057. * runtime does not support them.
  2058. *
  2059. * Note that if +fork+ raises a +NotImplementedError+, then
  2060. * <code>respond_to?(:fork)</code> returns +false+.
  2061. */
  2062. /*
  2063. * Document-class: NameError
  2064. *
  2065. * Raised when a given name is invalid or undefined.
  2066. *
  2067. * puts foo
  2068. *
  2069. * <em>raises the exception:</em>
  2070. *
  2071. * NameError: undefined local variable or method `foo' for main:Object
  2072. *
  2073. * Since constant names must start with a capital:
  2074. *
  2075. * Integer.const_set :answer, 42
  2076. *
  2077. * <em>raises the exception:</em>
  2078. *
  2079. * NameError: wrong constant name answer
  2080. */
  2081. /*
  2082. * Document-class: NoMethodError
  2083. *
  2084. * Raised when a method is called on a receiver which doesn't have it
  2085. * defined and also fails to respond with +method_missing+.
  2086. *
  2087. * "hello".to_ary
  2088. *
  2089. * <em>raises the exception:</em>
  2090. *
  2091. * NoMethodError: undefined method `to_ary' for "hello":String
  2092. */
  2093. /*
  2094. * Document-class: FrozenError
  2095. *
  2096. * Raised when there is an attempt to modify a frozen object.
  2097. *
  2098. * [1, 2, 3].freeze << 4
  2099. *
  2100. * <em>raises the exception:</em>
  2101. *
  2102. * FrozenError: can't modify frozen Array
  2103. */
  2104. /*
  2105. * Document-class: RuntimeError
  2106. *
  2107. * A generic error class raised when an invalid operation is attempted.
  2108. * Kernel#raise will raise a RuntimeError if no Exception class is
  2109. * specified.
  2110. *
  2111. * raise "ouch"
  2112. *
  2113. * <em>raises the exception:</em>
  2114. *
  2115. * RuntimeError: ouch
  2116. */
  2117. /*
  2118. * Document-class: SecurityError
  2119. *
  2120. * No longer used by internal code.
  2121. */
  2122. /*
  2123. * Document-class: NoMemoryError
  2124. *
  2125. * Raised when memory allocation fails.
  2126. */
  2127. /*
  2128. * Document-class: SystemCallError
  2129. *
  2130. * SystemCallError is the base class for all low-level
  2131. * platform-dependent errors.
  2132. *
  2133. * The errors available on the current platform are subclasses of
  2134. * SystemCallError and are defined in the Errno module.
  2135. *
  2136. * File.open("does/not/exist")
  2137. *
  2138. * <em>raises the exception:</em>
  2139. *
  2140. * Errno::ENOENT: No such file or directory - does/not/exist
  2141. */
  2142. /*
  2143. * Document-class: EncodingError
  2144. *
  2145. * EncodingError is the base class for encoding errors.
  2146. */
  2147. /*
  2148. * Document-class: Encoding::CompatibilityError
  2149. *
  2150. * Raised by Encoding and String methods when the source encoding is
  2151. * incompatible with the target encoding.
  2152. */
  2153. /*
  2154. * Document-class: fatal
  2155. *
  2156. * fatal is an Exception that is raised when Ruby has encountered a fatal
  2157. * error and must exit.
  2158. */
  2159. /*
  2160. * Document-class: NameError::message
  2161. * :nodoc:
  2162. */
  2163. /*
  2164. * \Class Exception and its subclasses are used to communicate between
  2165. * Kernel#raise and +rescue+ statements in <code>begin ... end</code> blocks.
  2166. *
  2167. * An Exception object carries information about an exception:
  2168. * - Its type (the exception's class).
  2169. * - An optional descriptive message.
  2170. * - Optional backtrace information.
  2171. *
  2172. * Some built-in subclasses of Exception have additional methods: e.g., NameError#name.
  2173. *
  2174. * == Defaults
  2175. *
  2176. * Two Ruby statements have default exception classes:
  2177. * - +raise+: defaults to RuntimeError.
  2178. * - +rescue+: defaults to StandardError.
  2179. *
  2180. * == Global Variables
  2181. *
  2182. * When an exception has been raised but not yet handled (in +rescue+,
  2183. * +ensure+, +at_exit+ and +END+ blocks), two global variables are set:
  2184. * - <code>$!</code> contains the current exception.
  2185. * - <code>$@</code> contains its backtrace.
  2186. *
  2187. * == Custom Exceptions
  2188. *
  2189. * To provide additional or alternate information,
  2190. * a program may create custom exception classes
  2191. * that derive from the built-in exception classes.
  2192. *
  2193. * A good practice is for a library to create a single "generic" exception class
  2194. * (typically a subclass of StandardError or RuntimeError)
  2195. * and have its other exception classes derive from that class.
  2196. * This allows the user to rescue the generic exception, thus catching all exceptions
  2197. * the library may raise even if future versions of the library add new
  2198. * exception subclasses.
  2199. *
  2200. * For example:
  2201. *
  2202. * class MyLibrary
  2203. * class Error < ::StandardError
  2204. * end
  2205. *
  2206. * class WidgetError < Error
  2207. * end
  2208. *
  2209. * class FrobError < Error
  2210. * end
  2211. *
  2212. * end
  2213. *
  2214. * To handle both MyLibrary::WidgetError and MyLibrary::FrobError the library
  2215. * user can rescue MyLibrary::Error.
  2216. *
  2217. * == Built-In Exception Classes
  2218. *
  2219. * The built-in subclasses of Exception are:
  2220. *
  2221. * * NoMemoryError
  2222. * * ScriptError
  2223. * * LoadError
  2224. * * NotImplementedError
  2225. * * SyntaxError
  2226. * * SecurityError
  2227. * * SignalException
  2228. * * Interrupt
  2229. * * StandardError
  2230. * * ArgumentError
  2231. * * UncaughtThrowError
  2232. * * EncodingError
  2233. * * FiberError
  2234. * * IOError
  2235. * * EOFError
  2236. * * IndexError
  2237. * * KeyError
  2238. * * StopIteration
  2239. * * ClosedQueueError
  2240. * * LocalJumpError
  2241. * * NameError
  2242. * * NoMethodError
  2243. * * RangeError
  2244. * * FloatDomainError
  2245. * * RegexpError
  2246. * * RuntimeError
  2247. * * FrozenError
  2248. * * SystemCallError
  2249. * * Errno::*
  2250. * * ThreadError
  2251. * * TypeError
  2252. * * ZeroDivisionError
  2253. * * SystemExit
  2254. * * SystemStackError
  2255. * * fatal
  2256. */
  2257. void
  2258. Init_Exception(void)
  2259. {
  2260. rb_eException = rb_define_class("Exception", rb_cObject);
  2261. rb_define_singleton_method(rb_eException, "exception", rb_class_new_instance, -1);
  2262. rb_define_singleton_method(rb_eException, "to_tty?", exc_s_to_tty_p, 0);
  2263. rb_define_method(rb_eException, "exception", exc_exception, -1);
  2264. rb_define_method(rb_eException, "initialize", exc_initialize, -1);
  2265. rb_define_method(rb_eException, "==", exc_equal, 1);
  2266. rb_define_method(rb_eException, "to_s", exc_to_s, 0);
  2267. rb_define_method(rb_eException, "message", exc_message, 0);
  2268. rb_define_method(rb_eException, "full_message", exc_full_message, -1);
  2269. rb_define_method(rb_eException, "inspect", exc_inspect, 0);
  2270. rb_define_method(rb_eException, "backtrace", exc_backtrace, 0);
  2271. rb_define_method(rb_eException, "backtrace_locations", exc_backtrace_locations, 0);
  2272. rb_define_method(rb_eException, "set_backtrace", exc_set_backtrace, 1);
  2273. rb_define_method(rb_eException, "cause", exc_cause, 0);
  2274. rb_eSystemExit = rb_define_class("SystemExit", rb_eException);
  2275. rb_define_method(rb_eSystemExit, "initialize", exit_initialize, -1);
  2276. rb_define_method(rb_eSystemExit, "status", exit_status, 0);
  2277. rb_define_method(rb_eSystemExit, "success?", exit_success_p, 0);
  2278. rb_eFatal = rb_define_class("fatal", rb_eException);
  2279. rb_eSignal = rb_define_class("SignalException", rb_eException);
  2280. rb_eInterrupt = rb_define_class("Interrupt", rb_eSignal);
  2281. rb_eStandardError = rb_define_class("StandardError", rb_eException);
  2282. rb_eTypeError = rb_define_class("TypeError", rb_eStandardError);
  2283. rb_eArgError = rb_define_class("ArgumentError", rb_eStandardError);
  2284. rb_eIndexError = rb_define_class("IndexError", rb_eStandardError);
  2285. rb_eKeyError = rb_define_class("KeyError", rb_eIndexError);
  2286. rb_define_method(rb_eKeyError, "initialize", key_err_initialize, -1);
  2287. rb_define_method(rb_eKeyError, "receiver", key_err_receiver, 0);
  2288. rb_define_method(rb_eKeyError, "key", key_err_key, 0);
  2289. rb_eRangeError = rb_define_class("RangeError", rb_eStandardError);
  2290. rb_eScriptError = rb_define_class("ScriptError", rb_eException);
  2291. rb_eSyntaxError = rb_define_class("SyntaxError", rb_eScriptError);
  2292. rb_define_method(rb_eSyntaxError, "initialize", syntax_error_initialize, -1);
  2293. rb_eLoadError = rb_define_class("LoadError", rb_eScriptError);
  2294. /* the path failed to load */
  2295. rb_attr(rb_eLoadError, rb_intern_const("path"), 1, 0, Qfalse);
  2296. rb_eNotImpError = rb_define_class("NotImplementedError", rb_eScriptError);
  2297. rb_eNameError = rb_define_class("NameError", rb_eStandardError);
  2298. rb_define_method(rb_eNameError, "initialize", name_err_initialize, -1);
  2299. rb_define_method(rb_eNameError, "name", name_err_name, 0);
  2300. rb_define_method(rb_eNameError, "receiver", name_err_receiver, 0);
  2301. rb_define_method(rb_eNameError, "local_variables", name_err_local_variables, 0);
  2302. rb_cNameErrorMesg = rb_define_class_under(rb_eNameError, "message", rb_cData);
  2303. rb_define_method(rb_cNameErrorMesg, "==", name_err_mesg_equal, 1);
  2304. rb_define_method(rb_cNameErrorMesg, "to_str", name_err_mesg_to_str, 0);
  2305. rb_define_method(rb_cNameErrorMesg, "_dump", name_err_mesg_dump, 1);
  2306. rb_define_singleton_method(rb_cNameErrorMesg, "_load", name_err_mesg_load, 1);
  2307. rb_eNoMethodError = rb_define_class("NoMethodError", rb_eNameError);
  2308. rb_define_method(rb_eNoMethodError, "initialize", nometh_err_initialize, -1);
  2309. rb_define_method(rb_eNoMethodError, "args", nometh_err_args, 0);
  2310. rb_define_method(rb_eNoMethodError, "private_call?", nometh_err_private_call_p, 0);
  2311. rb_eRuntimeError = rb_define_class("RuntimeError", rb_eStandardError);
  2312. rb_eFrozenError = rb_define_class("FrozenError", rb_eRuntimeError);
  2313. rb_define_method(rb_eFrozenError, "initialize", frozen_err_initialize, -1);
  2314. rb_define_method(rb_eFrozenError, "receiver", frozen_err_receiver, 0);
  2315. rb_eSecurityError = rb_define_class("SecurityError", rb_eException);
  2316. rb_eNoMemError = rb_define_class("NoMemoryError", rb_eException);
  2317. rb_eEncodingError = rb_define_class("EncodingError", rb_eStandardError);
  2318. rb_eEncCompatError = rb_define_class_under(rb_cEncoding, "CompatibilityError", rb_eEncodingError);
  2319. rb_eNoMatchingPatternError = rb_define_class("NoMatchingPatternError", rb_eRuntimeError);
  2320. syserr_tbl = st_init_numtable();
  2321. rb_eSystemCallError = rb_define_class("SystemCallError", rb_eStandardError);
  2322. rb_define_method(rb_eSystemCallError, "initialize", syserr_initialize, -1);
  2323. rb_define_method(rb_eSystemCallError, "errno", syserr_errno, 0);
  2324. rb_define_singleton_method(rb_eSystemCallError, "===", syserr_eqq, 1);
  2325. rb_mErrno = rb_define_module("Errno");
  2326. rb_mWarning = rb_define_module("Warning");
  2327. rb_define_singleton_method(rb_mWarning, "[]", rb_warning_s_aref, 1);
  2328. rb_define_singleton_method(rb_mWarning, "[]=", rb_warning_s_aset, 2);
  2329. rb_define_method(rb_mWarning, "warn", rb_warning_s_warn, 1);
  2330. rb_extend_object(rb_mWarning, rb_mWarning);
  2331. /* :nodoc: */
  2332. rb_cWarningBuffer = rb_define_class_under(rb_mWarning, "buffer", rb_cString);
  2333. rb_define_method(rb_cWarningBuffer, "write", warning_write, -1);
  2334. id_cause = rb_intern_const("cause");
  2335. id_message = rb_intern_const("message");
  2336. id_backtrace = rb_intern_const("backtrace");
  2337. id_key = rb_intern_const("key");
  2338. id_args = rb_intern_const("args");
  2339. id_receiver = rb_intern_const("receiver");
  2340. id_private_call_p = rb_intern_const("private_call?");
  2341. id_local_variables = rb_intern_const("local_variables");
  2342. id_Errno = rb_intern_const("Errno");
  2343. id_errno = rb_intern_const("errno");
  2344. id_i_path = rb_intern_const("@path");
  2345. id_warn = rb_intern_const("warn");
  2346. id_top = rb_intern_const("top");
  2347. id_bottom = rb_intern_const("bottom");
  2348. id_iseq = rb_make_internal_id();
  2349. id_recv = rb_make_internal_id();
  2350. }
  2351. void
  2352. rb_enc_raise(rb_encoding *enc, VALUE exc, const char *fmt, ...)
  2353. {
  2354. va_list args;
  2355. VALUE mesg;
  2356. va_start(args, fmt);
  2357. mesg = rb_enc_vsprintf(enc, fmt, args);
  2358. va_end(args);
  2359. rb_exc_raise(rb_exc_new3(exc, mesg));
  2360. }
  2361. void
  2362. rb_vraise(VALUE exc, const char *fmt, va_list ap)
  2363. {
  2364. rb_exc_raise(rb_exc_new3(exc, rb_vsprintf(fmt, ap)));
  2365. }
  2366. void
  2367. rb_raise(VALUE exc, const char *fmt, ...)
  2368. {
  2369. va_list args;
  2370. va_start(args, fmt);
  2371. rb_vraise(exc, fmt, args);
  2372. va_end(args);
  2373. }
  2374. NORETURN(static void raise_loaderror(VALUE path, VALUE mesg));
  2375. static void
  2376. raise_loaderror(VALUE path, VALUE mesg)
  2377. {
  2378. VALUE err = rb_exc_new3(rb_eLoadError, mesg);
  2379. rb_ivar_set(err, id_i_path, path);
  2380. rb_exc_raise(err);
  2381. }
  2382. void
  2383. rb_loaderror(const char *fmt, ...)
  2384. {
  2385. va_list args;
  2386. VALUE mesg;
  2387. va_start(args, fmt);
  2388. mesg = rb_enc_vsprintf(rb_locale_encoding(), fmt, args);
  2389. va_end(args);
  2390. raise_loaderror(Qnil, mesg);
  2391. }
  2392. void
  2393. rb_loaderror_with_path(VALUE path, const char *fmt, ...)
  2394. {
  2395. va_list args;
  2396. VALUE mesg;
  2397. va_start(args, fmt);
  2398. mesg = rb_enc_vsprintf(rb_locale_encoding(), fmt, args);
  2399. va_end(args);
  2400. raise_loaderror(path, mesg);
  2401. }
  2402. void
  2403. rb_notimplement(void)
  2404. {
  2405. rb_raise(rb_eNotImpError,
  2406. "%"PRIsVALUE"() function is unimplemented on this machine",
  2407. rb_id2str(rb_frame_this_func()));
  2408. }
  2409. void
  2410. rb_fatal(const char *fmt, ...)
  2411. {
  2412. va_list args;
  2413. VALUE mesg;
  2414. if (! ruby_thread_has_gvl_p()) {
  2415. /* The thread has no GVL. Object allocation impossible (cant run GC),
  2416. * thus no message can be printed out. */
  2417. fprintf(stderr, "[FATAL] rb_fatal() outside of GVL\n");
  2418. rb_print_backtrace();
  2419. die();
  2420. }
  2421. va_start(args, fmt);
  2422. mesg = rb_vsprintf(fmt, args);
  2423. va_end(args);
  2424. rb_exc_fatal(rb_exc_new3(rb_eFatal, mesg));
  2425. }
  2426. static VALUE
  2427. make_errno_exc(const char *mesg)
  2428. {
  2429. int n = errno;
  2430. errno = 0;
  2431. if (n == 0) {
  2432. rb_bug("rb_sys_fail(%s) - errno == 0", mesg ? mesg : "");
  2433. }
  2434. return rb_syserr_new(n, mesg);
  2435. }
  2436. static VALUE
  2437. make_errno_exc_str(VALUE mesg)
  2438. {
  2439. int n = errno;
  2440. errno = 0;
  2441. if (!mesg) mesg = Qnil;
  2442. if (n == 0) {
  2443. const char *s = !NIL_P(mesg) ? RSTRING_PTR(mesg) : "";
  2444. rb_bug("rb_sys_fail_str(%s) - errno == 0", s);
  2445. }
  2446. return rb_syserr_new_str(n, mesg);
  2447. }
  2448. VALUE
  2449. rb_syserr_new(int n, const char *mesg)
  2450. {
  2451. VALUE arg;
  2452. arg = mesg ? rb_str_new2(mesg) : Qnil;
  2453. return rb_syserr_new_str(n, arg);
  2454. }
  2455. VALUE
  2456. rb_syserr_new_str(int n, VALUE arg)
  2457. {
  2458. return rb_class_new_instance(1, &arg, get_syserr(n));
  2459. }
  2460. void
  2461. rb_syserr_fail(int e, const char *mesg)
  2462. {
  2463. rb_exc_raise(rb_syserr_new(e, mesg));
  2464. }
  2465. void
  2466. rb_syserr_fail_str(int e, VALUE mesg)
  2467. {
  2468. rb_exc_raise(rb_syserr_new_str(e, mesg));
  2469. }
  2470. void
  2471. rb_sys_fail(const char *mesg)
  2472. {
  2473. rb_exc_raise(make_errno_exc(mesg));
  2474. }
  2475. void
  2476. rb_sys_fail_str(VALUE mesg)
  2477. {
  2478. rb_exc_raise(make_errno_exc_str(mesg));
  2479. }
  2480. #ifdef RUBY_FUNCTION_NAME_STRING
  2481. void
  2482. rb_sys_fail_path_in(const char *func_name, VALUE path)
  2483. {
  2484. int n = errno;
  2485. errno = 0;
  2486. rb_syserr_fail_path_in(func_name, n, path);
  2487. }
  2488. void
  2489. rb_syserr_fail_path_in(const char *func_name, int n, VALUE path)
  2490. {
  2491. rb_exc_raise(rb_syserr_new_path_in(func_name, n, path));
  2492. }
  2493. VALUE
  2494. rb_syserr_new_path_in(const char *func_name, int n, VALUE path)
  2495. {
  2496. VALUE args[2];
  2497. if (!path) path = Qnil;
  2498. if (n == 0) {
  2499. const char *s = !NIL_P(path) ? RSTRING_PTR(path) : "";
  2500. if (!func_name) func_name = "(null)";
  2501. rb_bug("rb_sys_fail_path_in(%s, %s) - errno == 0",
  2502. func_name, s);
  2503. }
  2504. args[0] = path;
  2505. args[1] = rb_str_new_cstr(func_name);
  2506. return rb_class_new_instance(2, args, get_syserr(n));
  2507. }
  2508. #endif
  2509. void
  2510. rb_mod_sys_fail(VALUE mod, const char *mesg)
  2511. {
  2512. VALUE exc = make_errno_exc(mesg);
  2513. rb_extend_object(exc, mod);
  2514. rb_exc_raise(exc);
  2515. }
  2516. void
  2517. rb_mod_sys_fail_str(VALUE mod, VALUE mesg)
  2518. {
  2519. VALUE exc = make_errno_exc_str(mesg);
  2520. rb_extend_object(exc, mod);
  2521. rb_exc_raise(exc);
  2522. }
  2523. void
  2524. rb_mod_syserr_fail(VALUE mod, int e, const char *mesg)
  2525. {
  2526. VALUE exc = rb_syserr_new(e, mesg);
  2527. rb_extend_object(exc, mod);
  2528. rb_exc_raise(exc);
  2529. }
  2530. void
  2531. rb_mod_syserr_fail_str(VALUE mod, int e, VALUE mesg)
  2532. {
  2533. VALUE exc = rb_syserr_new_str(e, mesg);
  2534. rb_extend_object(exc, mod);
  2535. rb_exc_raise(exc);
  2536. }
  2537. static void
  2538. syserr_warning(VALUE mesg, int err)
  2539. {
  2540. rb_str_set_len(mesg, RSTRING_LEN(mesg)-1);
  2541. rb_str_catf(mesg, ": %s\n", strerror(err));
  2542. rb_write_warning_str(mesg);
  2543. }
  2544. #if 0
  2545. void
  2546. rb_sys_warn(const char *fmt, ...)
  2547. {
  2548. if (!NIL_P(ruby_verbose)) {
  2549. int errno_save = errno;
  2550. with_warning_string(mesg, 0, fmt) {
  2551. syserr_warning(mesg, errno_save);
  2552. }
  2553. errno = errno_save;
  2554. }
  2555. }
  2556. void
  2557. rb_syserr_warn(int err, const char *fmt, ...)
  2558. {
  2559. if (!NIL_P(ruby_verbose)) {
  2560. with_warning_string(mesg, 0, fmt) {
  2561. syserr_warning(mesg, err);
  2562. }
  2563. }
  2564. }
  2565. void
  2566. rb_sys_enc_warn(rb_encoding *enc, const char *fmt, ...)
  2567. {
  2568. if (!NIL_P(ruby_verbose)) {
  2569. int errno_save = errno;
  2570. with_warning_string(mesg, enc, fmt) {
  2571. syserr_warning(mesg, errno_save);
  2572. }
  2573. errno = errno_save;
  2574. }
  2575. }
  2576. void
  2577. rb_syserr_enc_warn(int err, rb_encoding *enc, const char *fmt, ...)
  2578. {
  2579. if (!NIL_P(ruby_verbose)) {
  2580. with_warning_string(mesg, enc, fmt) {
  2581. syserr_warning(mesg, err);
  2582. }
  2583. }
  2584. }
  2585. #endif
  2586. void
  2587. rb_sys_warning(const char *fmt, ...)
  2588. {
  2589. if (RTEST(ruby_verbose)) {
  2590. int errno_save = errno;
  2591. with_warning_string(mesg, 0, fmt) {
  2592. syserr_warning(mesg, errno_save);
  2593. }
  2594. errno = errno_save;
  2595. }
  2596. }
  2597. #if 0
  2598. void
  2599. rb_syserr_warning(int err, const char *fmt, ...)
  2600. {
  2601. if (RTEST(ruby_verbose)) {
  2602. with_warning_string(mesg, 0, fmt) {
  2603. syserr_warning(mesg, err);
  2604. }
  2605. }
  2606. }
  2607. #endif
  2608. void
  2609. rb_sys_enc_warning(rb_encoding *enc, const char *fmt, ...)
  2610. {
  2611. if (RTEST(ruby_verbose)) {
  2612. int errno_save = errno;
  2613. with_warning_string(mesg, enc, fmt) {
  2614. syserr_warning(mesg, errno_save);
  2615. }
  2616. errno = errno_save;
  2617. }
  2618. }
  2619. void
  2620. rb_syserr_enc_warning(int err, rb_encoding *enc, const char *fmt, ...)
  2621. {
  2622. if (RTEST(ruby_verbose)) {
  2623. with_warning_string(mesg, enc, fmt) {
  2624. syserr_warning(mesg, err);
  2625. }
  2626. }
  2627. }
  2628. void
  2629. rb_load_fail(VALUE path, const char *err)
  2630. {
  2631. VALUE mesg = rb_str_buf_new_cstr(err);
  2632. rb_str_cat2(mesg, " -- ");
  2633. rb_str_append(mesg, path); /* should be ASCII compatible */
  2634. raise_loaderror(path, mesg);
  2635. }
  2636. void
  2637. rb_error_frozen(const char *what)
  2638. {
  2639. rb_raise(rb_eFrozenError, "can't modify frozen %s", what);
  2640. }
  2641. void
  2642. rb_frozen_error_raise(VALUE frozen_obj, const char *fmt, ...)
  2643. {
  2644. va_list args;
  2645. VALUE exc, mesg;
  2646. va_start(args, fmt);
  2647. mesg = rb_vsprintf(fmt, args);
  2648. va_end(args);
  2649. exc = rb_exc_new3(rb_eFrozenError, mesg);
  2650. rb_ivar_set(exc, id_recv, frozen_obj);
  2651. rb_exc_raise(exc);
  2652. }
  2653. static VALUE
  2654. inspect_frozen_obj(VALUE obj, VALUE mesg, int recur)
  2655. {
  2656. if (recur) {
  2657. rb_str_cat_cstr(mesg, " ...");
  2658. }
  2659. else {
  2660. rb_str_append(mesg, rb_inspect(obj));
  2661. }
  2662. return mesg;
  2663. }
  2664. void
  2665. rb_error_frozen_object(VALUE frozen_obj)
  2666. {
  2667. VALUE debug_info;
  2668. const ID created_info = id_debug_created_info;
  2669. VALUE mesg = rb_sprintf("can't modify frozen %"PRIsVALUE": ",
  2670. CLASS_OF(frozen_obj));
  2671. VALUE exc = rb_exc_new_str(rb_eFrozenError, mesg);
  2672. rb_ivar_set(exc, id_recv, frozen_obj);
  2673. rb_exec_recursive(inspect_frozen_obj, frozen_obj, mesg);
  2674. if (!NIL_P(debug_info = rb_attr_get(frozen_obj, created_info))) {
  2675. VALUE path = rb_ary_entry(debug_info, 0);
  2676. VALUE line = rb_ary_entry(debug_info, 1);
  2677. rb_str_catf(mesg, ", created at %"PRIsVALUE":%"PRIsVALUE, path, line);
  2678. }
  2679. rb_exc_raise(exc);
  2680. }
  2681. #undef rb_check_frozen
  2682. void
  2683. rb_check_frozen(VALUE obj)
  2684. {
  2685. rb_check_frozen_internal(obj);
  2686. }
  2687. void
  2688. rb_error_untrusted(VALUE obj)
  2689. {
  2690. rb_warn_deprecated_to_remove("rb_error_untrusted", "3.2");
  2691. }
  2692. #undef rb_check_trusted
  2693. void
  2694. rb_check_trusted(VALUE obj)
  2695. {
  2696. rb_warn_deprecated_to_remove("rb_check_trusted", "3.2");
  2697. }
  2698. void
  2699. rb_check_copyable(VALUE obj, VALUE orig)
  2700. {
  2701. if (!FL_ABLE(obj)) return;
  2702. rb_check_frozen_internal(obj);
  2703. if (!FL_ABLE(orig)) return;
  2704. }
  2705. void
  2706. Init_syserr(void)
  2707. {
  2708. rb_eNOERROR = set_syserr(0, "NOERROR");
  2709. #define defined_error(name, num) set_syserr((num), (name));
  2710. #define undefined_error(name) set_syserr(0, (name));
  2711. #include "known_errors.inc"
  2712. #undef defined_error
  2713. #undef undefined_error
  2714. }
  2715. #include "warning.rbinc"
  2716. /*!
  2717. * \}
  2718. */