Ruby  3.4.0dev (2024-11-05 revision 348a53415339076afc4a02fcd09f3ae36e9c4c61)
error.c (348a53415339076afc4a02fcd09f3ae36e9c4c61)
1 /**********************************************************************
2 
3  error.c -
4 
5  $Author$
6  created at: Mon Aug 9 16:11:34 JST 1993
7 
8  Copyright (C) 1993-2007 Yukihiro Matsumoto
9 
10 **********************************************************************/
11 
12 #include "ruby/internal/config.h"
13 
14 #include <errno.h>
15 #include <stdarg.h>
16 #include <stdio.h>
17 
18 #ifdef HAVE_STDLIB_H
19 # include <stdlib.h>
20 #endif
21 
22 #ifdef HAVE_UNISTD_H
23 # include <unistd.h>
24 #endif
25 
26 #ifdef HAVE_SYS_WAIT_H
27 # include <sys/wait.h>
28 #endif
29 
30 #if defined __APPLE__
31 # include <AvailabilityMacros.h>
32 #endif
33 
34 #include "internal.h"
35 #include "internal/class.h"
36 #include "internal/error.h"
37 #include "internal/eval.h"
38 #include "internal/hash.h"
39 #include "internal/io.h"
40 #include "internal/load.h"
41 #include "internal/object.h"
42 #include "internal/process.h"
43 #include "internal/string.h"
44 #include "internal/symbol.h"
45 #include "internal/thread.h"
46 #include "internal/variable.h"
47 #include "ruby/encoding.h"
48 #include "ruby/st.h"
49 #include "ruby/util.h"
50 #include "ruby_assert.h"
51 #include "vm_core.h"
52 #include "yjit.h"
53 
54 #include "builtin.h"
55 
61 #ifndef EXIT_SUCCESS
62 #define EXIT_SUCCESS 0
63 #endif
64 
65 #ifndef WIFEXITED
66 #define WIFEXITED(status) 1
67 #endif
68 
69 #ifndef WEXITSTATUS
70 #define WEXITSTATUS(status) (status)
71 #endif
72 
73 VALUE rb_iseqw_local_variables(VALUE iseqval);
74 VALUE rb_iseqw_new(const rb_iseq_t *);
75 int rb_str_end_with_asciichar(VALUE str, int c);
76 
77 long rb_backtrace_length_limit = -1;
78 VALUE rb_eEAGAIN;
79 VALUE rb_eEWOULDBLOCK;
80 VALUE rb_eEINPROGRESS;
81 static VALUE rb_mWarning;
82 static VALUE rb_cWarningBuffer;
83 
84 static ID id_warn;
85 static ID id_category;
86 static ID id_deprecated;
87 static ID id_experimental;
88 static ID id_performance;
89 static VALUE sym_category;
90 static VALUE sym_highlight;
91 static struct {
92  st_table *id2enum, *enum2id;
93 } warning_categories;
94 
95 extern const char *rb_dynamic_description;
96 
97 static const char *
98 rb_strerrno(int err)
99 {
100 #define defined_error(name, num) if (err == (num)) return (name);
101 #define undefined_error(name)
102 #include "known_errors.inc"
103 #undef defined_error
104 #undef undefined_error
105  return NULL;
106 }
107 
108 static int
109 err_position_0(char *buf, long len, const char *file, int line)
110 {
111  if (!file) {
112  return 0;
113  }
114  else if (line == 0) {
115  return snprintf(buf, len, "%s: ", file);
116  }
117  else {
118  return snprintf(buf, len, "%s:%d: ", file, line);
119  }
120 }
121 
122 RBIMPL_ATTR_FORMAT(RBIMPL_PRINTF_FORMAT, 5, 0)
123 static VALUE
124 err_vcatf(VALUE str, const char *pre, const char *file, int line,
125  const char *fmt, va_list args)
126 {
127  if (file) {
128  rb_str_cat2(str, file);
129  if (line) rb_str_catf(str, ":%d", line);
130  rb_str_cat2(str, ": ");
131  }
132  if (pre) rb_str_cat2(str, pre);
133  rb_str_vcatf(str, fmt, args);
134  return str;
135 }
136 
137 static VALUE syntax_error_with_path(VALUE, VALUE, VALUE*, rb_encoding*);
138 
139 VALUE
140 rb_syntax_error_append(VALUE exc, VALUE file, int line, int column,
141  rb_encoding *enc, const char *fmt, va_list args)
142 {
143  const char *fn = NIL_P(file) ? NULL : RSTRING_PTR(file);
144  if (!exc) {
145  VALUE mesg = rb_enc_str_new(0, 0, enc);
146  err_vcatf(mesg, NULL, fn, line, fmt, args);
147  rb_str_cat2(mesg, "\n");
148  rb_write_error_str(mesg);
149  }
150  else {
151  VALUE mesg;
152  exc = syntax_error_with_path(exc, file, &mesg, enc);
153  err_vcatf(mesg, NULL, fn, line, fmt, args);
154  }
155 
156  return exc;
157 }
158 
159 static unsigned int warning_disabled_categories = (
161  ~RB_WARN_CATEGORY_DEFAULT_BITS);
162 
163 static unsigned int
164 rb_warning_category_mask(VALUE category)
165 {
166  return 1U << rb_warning_category_from_name(category);
167 }
168 
170 rb_warning_category_from_name(VALUE category)
171 {
172  st_data_t cat_value;
173  ID cat_id;
174  Check_Type(category, T_SYMBOL);
175  if (!(cat_id = rb_check_id(&category)) ||
176  !st_lookup(warning_categories.id2enum, cat_id, &cat_value)) {
177  rb_raise(rb_eArgError, "unknown category: %"PRIsVALUE, category);
178  }
179  return (rb_warning_category_t)cat_value;
180 }
181 
182 static VALUE
183 rb_warning_category_to_name(rb_warning_category_t category)
184 {
185  st_data_t id;
186  if (!st_lookup(warning_categories.enum2id, category, &id)) {
187  rb_raise(rb_eArgError, "invalid category: %d", (int)category);
188  }
189  return id ? ID2SYM(id) : Qnil;
190 }
191 
192 void
193 rb_warning_category_update(unsigned int mask, unsigned int bits)
194 {
195  warning_disabled_categories &= ~mask;
196  warning_disabled_categories |= mask & ~bits;
197 }
198 
199 bool
200 rb_warning_category_enabled_p(rb_warning_category_t category)
201 {
202  return !(warning_disabled_categories & (1U << category));
203 }
204 
205 /*
206  * call-seq:
207  * Warning[category] -> true or false
208  *
209  * Returns the flag to show the warning messages for +category+.
210  * Supported categories are:
211  *
212  * +:deprecated+ ::
213  * deprecation warnings
214  * * assignment of non-nil value to <code>$,</code> and <code>$;</code>
215  * * keyword arguments
216  * etc.
217  *
218  * +:experimental+ ::
219  * experimental features
220  *
221  * +:performance+ ::
222  * performance hints
223  * * Shape variation limit
224  */
225 
226 static VALUE
227 rb_warning_s_aref(VALUE mod, VALUE category)
228 {
229  rb_warning_category_t cat = rb_warning_category_from_name(category);
230  return RBOOL(rb_warning_category_enabled_p(cat));
231 }
232 
233 /*
234  * call-seq:
235  * Warning[category] = flag -> flag
236  *
237  * Sets the warning flags for +category+.
238  * See Warning.[] for the categories.
239  */
240 
241 static VALUE
242 rb_warning_s_aset(VALUE mod, VALUE category, VALUE flag)
243 {
244  unsigned int mask = rb_warning_category_mask(category);
245  unsigned int disabled = warning_disabled_categories;
246  if (!RTEST(flag))
247  disabled |= mask;
248  else
249  disabled &= ~mask;
250  warning_disabled_categories = disabled;
251  return flag;
252 }
253 
254 /*
255  * call-seq:
256  * categories -> array
257  *
258  * Returns a list of the supported category symbols.
259  */
260 
261 static VALUE
262 rb_warning_s_categories(VALUE mod)
263 {
264  st_index_t num = warning_categories.id2enum->num_entries;
265  ID *ids = ALLOCA_N(ID, num);
266  num = st_keys(warning_categories.id2enum, ids, num);
267  VALUE ary = rb_ary_new_capa(num);
268  for (st_index_t i = 0; i < num; ++i) {
269  rb_ary_push(ary, ID2SYM(ids[i]));
270  }
271  return rb_ary_freeze(ary);
272 }
273 
274 /*
275  * call-seq:
276  * warn(msg, category: nil) -> nil
277  *
278  * Writes warning message +msg+ to $stderr. This method is called by
279  * Ruby for all emitted warnings. A +category+ may be included with
280  * the warning.
281  *
282  * See the documentation of the Warning module for how to customize this.
283  */
284 
285 static VALUE
286 rb_warning_s_warn(int argc, VALUE *argv, VALUE mod)
287 {
288  VALUE str;
289  VALUE opt;
290  VALUE category = Qnil;
291 
292  rb_scan_args(argc, argv, "1:", &str, &opt);
293  if (!NIL_P(opt)) rb_get_kwargs(opt, &id_category, 0, 1, &category);
294 
295  Check_Type(str, T_STRING);
296  rb_must_asciicompat(str);
297  if (!NIL_P(category)) {
298  rb_warning_category_t cat = rb_warning_category_from_name(category);
299  if (!rb_warning_category_enabled_p(cat)) return Qnil;
300  }
301  rb_write_error_str(str);
302  return Qnil;
303 }
304 
305 /*
306  * Document-module: Warning
307  *
308  * The Warning module contains a single method named #warn, and the
309  * module extends itself, making Warning.warn available.
310  * Warning.warn is called for all warnings issued by Ruby.
311  * By default, warnings are printed to $stderr.
312  *
313  * Changing the behavior of Warning.warn is useful to customize how warnings are
314  * handled by Ruby, for instance by filtering some warnings, and/or outputting
315  * warnings somewhere other than <tt>$stderr</tt>.
316  *
317  * If you want to change the behavior of Warning.warn you should use
318  * <tt>Warning.extend(MyNewModuleWithWarnMethod)</tt> and you can use +super+
319  * to get the default behavior of printing the warning to <tt>$stderr</tt>.
320  *
321  * Example:
322  * module MyWarningFilter
323  * def warn(message, category: nil, **kwargs)
324  * if /some warning I want to ignore/.match?(message)
325  * # ignore
326  * else
327  * super
328  * end
329  * end
330  * end
331  * Warning.extend MyWarningFilter
332  *
333  * You should never redefine Warning#warn (the instance method), as that will
334  * then no longer provide a way to use the default behavior.
335  *
336  * The warning[https://rubygems.org/gems/warning] gem provides convenient ways to customize Warning.warn.
337  */
338 
339 static VALUE
340 rb_warning_warn(VALUE mod, VALUE str)
341 {
342  return rb_funcallv(mod, id_warn, 1, &str);
343 }
344 
345 
346 static int
347 rb_warning_warn_arity(void)
348 {
349  const rb_method_entry_t *me = rb_method_entry(rb_singleton_class(rb_mWarning), id_warn);
350  return me ? rb_method_entry_arity(me) : 1;
351 }
352 
353 static VALUE
354 rb_warn_category(VALUE str, VALUE category)
355 {
356  if (RUBY_DEBUG && !NIL_P(category)) {
357  rb_warning_category_from_name(category);
358  }
359 
360  if (rb_warning_warn_arity() == 1) {
361  return rb_warning_warn(rb_mWarning, str);
362  }
363  else {
364  VALUE args[2];
365  args[0] = str;
366  args[1] = rb_hash_new();
367  rb_hash_aset(args[1], sym_category, category);
368  return rb_funcallv_kw(rb_mWarning, id_warn, 2, args, RB_PASS_KEYWORDS);
369  }
370 }
371 
372 static void
373 rb_write_warning_str(VALUE str)
374 {
375  rb_warning_warn(rb_mWarning, str);
376 }
377 
378 RBIMPL_ATTR_FORMAT(RBIMPL_PRINTF_FORMAT, 4, 0)
379 static VALUE
380 warn_vsprintf(rb_encoding *enc, const char *file, int line, const char *fmt, va_list args)
381 {
382  VALUE str = rb_enc_str_new(0, 0, enc);
383 
384  err_vcatf(str, "warning: ", file, line, fmt, args);
385  return rb_str_cat2(str, "\n");
386 }
387 
388 #define with_warn_vsprintf(enc, file, line, fmt) \
389  VALUE str; \
390  va_list args; \
391  va_start(args, fmt); \
392  str = warn_vsprintf(enc, file, line, fmt, args); \
393  va_end(args);
394 
395 void
396 rb_compile_warn(const char *file, int line, const char *fmt, ...)
397 {
398  if (!NIL_P(ruby_verbose)) {
399  with_warn_vsprintf(NULL, file, line, fmt) {
400  rb_write_warning_str(str);
401  }
402  }
403 }
404 
405 void
406 rb_enc_compile_warn(rb_encoding *enc, const char *file, int line, const char *fmt, ...)
407 {
408  if (!NIL_P(ruby_verbose)) {
409  with_warn_vsprintf(enc, file, line, fmt) {
410  rb_write_warning_str(str);
411  }
412  }
413 }
414 
415 /* rb_compile_warning() reports only in verbose mode */
416 void
417 rb_compile_warning(const char *file, int line, const char *fmt, ...)
418 {
419  if (RTEST(ruby_verbose)) {
420  with_warn_vsprintf(NULL, file, line, fmt) {
421  rb_write_warning_str(str);
422  }
423  }
424 }
425 
426 /* rb_enc_compile_warning() reports only in verbose mode */
427 void
428 rb_enc_compile_warning(rb_encoding *enc, const char *file, int line, const char *fmt, ...)
429 {
430  if (RTEST(ruby_verbose)) {
431  with_warn_vsprintf(enc, file, line, fmt) {
432  rb_write_warning_str(str);
433  }
434  }
435 }
436 
437 void
438 rb_category_compile_warn(rb_warning_category_t category, const char *file, int line, const char *fmt, ...)
439 {
440  if (!NIL_P(ruby_verbose)) {
441  with_warn_vsprintf(NULL, file, line, fmt) {
442  rb_warn_category(str, rb_warning_category_to_name(category));
443  }
444  }
445 }
446 
447 RBIMPL_ATTR_FORMAT(RBIMPL_PRINTF_FORMAT, 2, 0)
448 static VALUE
449 warning_string(rb_encoding *enc, const char *fmt, va_list args)
450 {
451  int line;
452  const char *file = rb_source_location_cstr(&line);
453  return warn_vsprintf(enc, file, line, fmt, args);
454 }
455 
456 #define with_warning_string(mesg, enc, fmt) \
457  with_warning_string_from(mesg, enc, fmt, fmt)
458 #define with_warning_string_from(mesg, enc, fmt, last_arg) \
459  VALUE mesg; \
460  va_list args; va_start(args, last_arg); \
461  mesg = warning_string(enc, fmt, args); \
462  va_end(args);
463 
464 void
465 rb_warn(const char *fmt, ...)
466 {
467  if (!NIL_P(ruby_verbose)) {
468  with_warning_string(mesg, 0, fmt) {
469  rb_write_warning_str(mesg);
470  }
471  }
472 }
473 
474 void
475 rb_category_warn(rb_warning_category_t category, const char *fmt, ...)
476 {
477  if (!NIL_P(ruby_verbose) && rb_warning_category_enabled_p(category)) {
478  with_warning_string(mesg, 0, fmt) {
479  rb_warn_category(mesg, rb_warning_category_to_name(category));
480  }
481  }
482 }
483 
484 void
485 rb_enc_warn(rb_encoding *enc, const char *fmt, ...)
486 {
487  if (!NIL_P(ruby_verbose)) {
488  with_warning_string(mesg, enc, fmt) {
489  rb_write_warning_str(mesg);
490  }
491  }
492 }
493 
494 /* rb_warning() reports only in verbose mode */
495 void
496 rb_warning(const char *fmt, ...)
497 {
498  if (RTEST(ruby_verbose)) {
499  with_warning_string(mesg, 0, fmt) {
500  rb_write_warning_str(mesg);
501  }
502  }
503 }
504 
505 /* rb_category_warning() reports only in verbose mode */
506 void
507 rb_category_warning(rb_warning_category_t category, const char *fmt, ...)
508 {
509  if (RTEST(ruby_verbose) && rb_warning_category_enabled_p(category)) {
510  with_warning_string(mesg, 0, fmt) {
511  rb_warn_category(mesg, rb_warning_category_to_name(category));
512  }
513  }
514 }
515 
516 VALUE
517 rb_warning_string(const char *fmt, ...)
518 {
519  with_warning_string(mesg, 0, fmt) {
520  }
521  return mesg;
522 }
523 
524 #if 0
525 void
526 rb_enc_warning(rb_encoding *enc, const char *fmt, ...)
527 {
528  if (RTEST(ruby_verbose)) {
529  with_warning_string(mesg, enc, fmt) {
530  rb_write_warning_str(mesg);
531  }
532  }
533 }
534 #endif
535 
536 static bool
537 deprecation_warning_enabled(void)
538 {
539  if (NIL_P(ruby_verbose)) return false;
540  if (!rb_warning_category_enabled_p(RB_WARN_CATEGORY_DEPRECATED)) return false;
541  return true;
542 }
543 
544 static void
545 warn_deprecated(VALUE mesg, const char *removal, const char *suggest)
546 {
547  rb_str_set_len(mesg, RSTRING_LEN(mesg) - 1);
548  rb_str_cat_cstr(mesg, " is deprecated");
549  if (removal) {
550  rb_str_catf(mesg, " and will be removed in Ruby %s", removal);
551  }
552  if (suggest) rb_str_catf(mesg, "; use %s instead", suggest);
553  rb_str_cat_cstr(mesg, "\n");
554  rb_warn_category(mesg, ID2SYM(id_deprecated));
555 }
556 
557 void
558 rb_warn_deprecated(const char *fmt, const char *suggest, ...)
559 {
560  if (!deprecation_warning_enabled()) return;
561 
562  with_warning_string_from(mesg, 0, fmt, suggest) {
563  warn_deprecated(mesg, NULL, suggest);
564  }
565 }
566 
567 void
568 rb_warn_deprecated_to_remove(const char *removal, const char *fmt, const char *suggest, ...)
569 {
570  if (!deprecation_warning_enabled()) return;
571 
572  with_warning_string_from(mesg, 0, fmt, suggest) {
573  warn_deprecated(mesg, removal, suggest);
574  }
575 }
576 
577 static inline int
578 end_with_asciichar(VALUE str, int c)
579 {
580  return RB_TYPE_P(str, T_STRING) &&
581  rb_str_end_with_asciichar(str, c);
582 }
583 
584 /* :nodoc: */
585 static VALUE
586 warning_write(int argc, VALUE *argv, VALUE buf)
587 {
588  while (argc-- > 0) {
589  rb_str_append(buf, *argv++);
590  }
591  return buf;
592 }
593 
594 VALUE rb_ec_backtrace_location_ary(const rb_execution_context_t *ec, long lev, long n, bool skip_internal);
595 
596 static VALUE
597 rb_warn_m(rb_execution_context_t *ec, VALUE exc, VALUE msgs, VALUE uplevel, VALUE category)
598 {
599  VALUE location = Qnil;
600  int argc = RARRAY_LENINT(msgs);
601  const VALUE *argv = RARRAY_CONST_PTR(msgs);
602 
603  if (!NIL_P(ruby_verbose) && argc > 0) {
604  VALUE str = argv[0];
605  if (!NIL_P(uplevel)) {
606  long lev = NUM2LONG(uplevel);
607  if (lev < 0) {
608  rb_raise(rb_eArgError, "negative level (%ld)", lev);
609  }
610  location = rb_ec_backtrace_location_ary(ec, lev + 1, 1, TRUE);
611  if (!NIL_P(location)) {
612  location = rb_ary_entry(location, 0);
613  }
614  }
615  if (argc > 1 || !NIL_P(uplevel) || !end_with_asciichar(str, '\n')) {
616  VALUE path;
617  if (NIL_P(uplevel)) {
618  str = rb_str_tmp_new(0);
619  }
620  else if (NIL_P(location) ||
621  NIL_P(path = rb_funcall(location, rb_intern("path"), 0))) {
622  str = rb_str_new_cstr("warning: ");
623  }
624  else {
625  str = rb_sprintf("%s:%ld: warning: ",
626  rb_string_value_ptr(&path),
627  NUM2LONG(rb_funcall(location, rb_intern("lineno"), 0)));
628  }
629  RBASIC_SET_CLASS(str, rb_cWarningBuffer);
630  rb_io_puts(argc, argv, str);
631  RBASIC_SET_CLASS(str, rb_cString);
632  }
633 
634  if (!NIL_P(category)) {
635  category = rb_to_symbol_type(category);
636  rb_warning_category_from_name(category);
637  }
638 
639  if (exc == rb_mWarning) {
640  rb_must_asciicompat(str);
641  rb_write_error_str(str);
642  }
643  else {
644  rb_warn_category(str, category);
645  }
646  }
647  return Qnil;
648 }
649 
650 #define MAX_BUG_REPORTERS 0x100
651 
652 static struct bug_reporters {
653  void (*func)(FILE *out, void *data);
654  void *data;
655 } bug_reporters[MAX_BUG_REPORTERS];
656 
657 static int bug_reporters_size;
658 
659 int
660 rb_bug_reporter_add(void (*func)(FILE *, void *), void *data)
661 {
662  struct bug_reporters *reporter;
663  if (bug_reporters_size >= MAX_BUG_REPORTERS) {
664  return 0; /* failed to register */
665  }
666  reporter = &bug_reporters[bug_reporters_size++];
667  reporter->func = func;
668  reporter->data = data;
669 
670  return 1;
671 }
672 
673 /* returns true if x can not be used as file name */
674 static bool
675 path_sep_p(char x)
676 {
677 #if defined __CYGWIN__ || defined DOSISH
678 # define PATH_SEP_ENCODING 1
679  // Assume that "/" is only the first byte in any encoding.
680  if (x == ':') return true; // drive letter or ADS
681  if (x == '\\') return true;
682 #endif
683  return x == '/';
684 }
685 
686 struct path_string {
687  const char *ptr;
688  size_t len;
689 };
690 
691 static const char PATHSEP_REPLACE = '!';
692 
693 static char *
694 append_pathname(char *p, const char *pe, VALUE str)
695 {
696 #ifdef PATH_SEP_ENCODING
697  rb_encoding *enc = rb_enc_get(str);
698 #endif
699  const char *s = RSTRING_PTR(str);
700  const char *const se = s + RSTRING_LEN(str);
701  char c;
702 
703  --pe; // for terminator
704 
705  while (p < pe && s < se && (c = *s) != '\0') {
706  if (c == '.') {
707  if (s == se || !*s) break; // chomp "." basename
708  if (path_sep_p(s[1])) goto skipsep; // skip "./"
709  }
710  else if (path_sep_p(c)) {
711  // squeeze successive separators
712  *p++ = PATHSEP_REPLACE;
713  skipsep:
714  while (++s < se && path_sep_p(*s));
715  continue;
716  }
717  const char *const ss = s;
718  while (p < pe && s < se && *s && !path_sep_p(*s)) {
719 #ifdef PATH_SEP_ENCODING
720  int n = rb_enc_mbclen(s, se, enc);
721 #else
722  const int n = 1;
723 #endif
724  p += n;
725  s += n;
726  }
727  if (s > ss) memcpy(p - (s - ss), ss, s - ss);
728  }
729 
730  return p;
731 }
732 
733 static char *
734 append_basename(char *p, const char *pe, struct path_string *path, VALUE str)
735 {
736  if (!path->ptr) {
737 #ifdef PATH_SEP_ENCODING
738  rb_encoding *enc = rb_enc_get(str);
739 #endif
740  const char *const b = RSTRING_PTR(str), *const e = RSTRING_END(str), *p = e;
741 
742  while (p > b) {
743  if (path_sep_p(p[-1])) {
744 #ifdef PATH_SEP_ENCODING
745  const char *t = rb_enc_prev_char(b, p, e, enc);
746  if (t == p-1) break;
747  p = t;
748 #else
749  break;
750 #endif
751  }
752  else {
753  --p;
754  }
755  }
756 
757  path->ptr = p;
758  path->len = e - p;
759  }
760  size_t n = path->len;
761  if (p + n > pe) n = pe - p;
762  memcpy(p, path->ptr, n);
763  return p + n;
764 }
765 
766 static void
767 finish_report(FILE *out, rb_pid_t pid)
768 {
769  if (out != stdout && out != stderr) fclose(out);
770 #ifdef HAVE_WORKING_FORK
771  if (pid > 0) waitpid(pid, NULL, 0);
772 #endif
773 }
774 
776  struct path_string exe, script;
777  rb_pid_t pid;
778  time_t time;
779 };
780 
781 /*
782  * Open a bug report file to write. The `RUBY_CRASH_REPORT`
783  * environment variable can be set to define a template that is used
784  * to name bug report files. The template can contain % specifiers
785  * which are substituted by the following values when a bug report
786  * file is created:
787  *
788  * %% A single % character.
789  * %e The base name of the executable filename.
790  * %E Pathname of executable, with slashes ('/') replaced by
791  * exclamation marks ('!').
792  * %f Similar to %e with the main script filename.
793  * %F Similar to %E with the main script filename.
794  * %p PID of dumped process in decimal.
795  * %t Time of dump, expressed as seconds since the Epoch,
796  * 1970-01-01 00:00:00 +0000 (UTC).
797  * %NNN Octal char code, upto 3 digits.
798  */
799 static char *
800 expand_report_argument(const char **input_template, struct report_expansion *values,
801  char *buf, size_t size, bool word)
802 {
803  char *p = buf;
804  char *end = buf + size;
805  const char *template = *input_template;
806  bool store = true;
807 
808  if (p >= end-1 || !*template) return NULL;
809  do {
810  char c = *template++;
811  if (word && ISSPACE(c)) break;
812  if (!store) continue;
813  if (c == '%') {
814  size_t n;
815  switch (c = *template++) {
816  case 'e':
817  p = append_basename(p, end, &values->exe, rb_argv0);
818  continue;
819  case 'E':
820  p = append_pathname(p, end, rb_argv0);
821  continue;
822  case 'f':
823  p = append_basename(p, end, &values->script, GET_VM()->orig_progname);
824  continue;
825  case 'F':
826  p = append_pathname(p, end, GET_VM()->orig_progname);
827  continue;
828  case 'p':
829  if (!values->pid) values->pid = getpid();
830  snprintf(p, end-p, "%" PRI_PIDT_PREFIX "d", values->pid);
831  p += strlen(p);
832  continue;
833  case 't':
834  if (!values->time) values->time = time(NULL);
835  snprintf(p, end-p, "%" PRI_TIMET_PREFIX "d", values->time);
836  p += strlen(p);
837  continue;
838  default:
839  if (c >= '0' && c <= '7') {
840  c = (unsigned char)ruby_scan_oct(template-1, 3, &n);
841  template += n - 1;
842  if (!c) store = false;
843  }
844  break;
845  }
846  }
847  if (p < end-1) *p++ = c;
848  } while (*template);
849  *input_template = template;
850  *p = '\0';
851  return ++p;
852 }
853 
854 FILE *ruby_popen_writer(char *const *argv, rb_pid_t *pid);
855 
856 static FILE *
857 open_report_path(const char *template, char *buf, size_t size, rb_pid_t *pid)
858 {
859  struct report_expansion values = {{0}};
860 
861  if (!template) return NULL;
862  if (0) fprintf(stderr, "RUBY_CRASH_REPORT=%s\n", buf);
863  if (*template == '|') {
864  char *argv[16], *bufend = buf + size, *p;
865  int argc;
866  template++;
867  for (argc = 0; argc < numberof(argv) - 1; ++argc) {
868  while (*template && ISSPACE(*template)) template++;
869  p = expand_report_argument(&template, &values, buf, bufend-buf, true);
870  if (!p) break;
871  argv[argc] = buf;
872  buf = p;
873  }
874  argv[argc] = NULL;
875  if (!p) return ruby_popen_writer(argv, pid);
876  }
877  else if (*template) {
878  expand_report_argument(&template, &values, buf, size, false);
879  return fopen(buf, "w");
880  }
881  return NULL;
882 }
883 
884 static const char *crash_report;
885 
886 /* SIGSEGV handler might have a very small stack. Thus we need to use it carefully. */
887 #define REPORT_BUG_BUFSIZ 256
888 static FILE *
889 bug_report_file(const char *file, int line, rb_pid_t *pid)
890 {
891  char buf[REPORT_BUG_BUFSIZ];
892  const char *report = crash_report;
893  if (!report) report = getenv("RUBY_CRASH_REPORT");
894  FILE *out = open_report_path(report, buf, sizeof(buf), pid);
895  int len = err_position_0(buf, sizeof(buf), file, line);
896 
897  if (out) {
898  if ((ssize_t)fwrite(buf, 1, len, out) == (ssize_t)len) return out;
899  fclose(out);
900  }
901  if ((ssize_t)fwrite(buf, 1, len, stderr) == (ssize_t)len) {
902  return stderr;
903  }
904  if ((ssize_t)fwrite(buf, 1, len, stdout) == (ssize_t)len) {
905  return stdout;
906  }
907 
908  return NULL;
909 }
910 
911 FUNC_MINIMIZED(static void bug_important_message(FILE *out, const char *const msg, size_t len));
912 
913 static void
914 bug_important_message(FILE *out, const char *const msg, size_t len)
915 {
916  const char *const endmsg = msg + len;
917  const char *p = msg;
918 
919  if (!len) return;
920  if (isatty(fileno(out))) {
921  static const char red[] = "\033[;31;1;7m";
922  static const char green[] = "\033[;32;7m";
923  static const char reset[] = "\033[m";
924  const char *e = strchr(p, '\n');
925  const int w = (int)(e - p);
926  do {
927  int i = (int)(e - p);
928  fputs(*p == ' ' ? green : red, out);
929  fwrite(p, 1, e - p, out);
930  for (; i < w; ++i) fputc(' ', out);
931  fputs(reset, out);
932  fputc('\n', out);
933  } while ((p = e + 1) < endmsg && (e = strchr(p, '\n')) != 0 && e > p + 1);
934  }
935  fwrite(p, 1, endmsg - p, out);
936 }
937 
938 #undef CRASH_REPORTER_MAY_BE_CREATED
939 #if defined(__APPLE__) && \
940  (!defined(MAC_OS_X_VERSION_10_6) || MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_6 || defined(__POWERPC__)) /* 10.6 PPC case */
941 # define CRASH_REPORTER_MAY_BE_CREATED
942 #endif
943 static void
944 preface_dump(FILE *out)
945 {
946 #if defined __APPLE__
947  static const char msg[] = ""
948  "-- Crash Report log information "
949  "--------------------------------------------\n"
950  " See Crash Report log file in one of the following locations:\n"
951 # ifdef CRASH_REPORTER_MAY_BE_CREATED
952  " * ~/Library/Logs/CrashReporter\n"
953  " * /Library/Logs/CrashReporter\n"
954 # endif
955  " * ~/Library/Logs/DiagnosticReports\n"
956  " * /Library/Logs/DiagnosticReports\n"
957  " for more details.\n"
958  "Don't forget to include the above Crash Report log file in bug reports.\n"
959  "\n";
960  const size_t msglen = sizeof(msg) - 1;
961 #else
962  const char *msg = NULL;
963  const size_t msglen = 0;
964 #endif
965  bug_important_message(out, msg, msglen);
966 }
967 
968 static void
969 postscript_dump(FILE *out)
970 {
971 #if defined __APPLE__
972  static const char msg[] = ""
973  "[IMPORTANT]"
974  /*" ------------------------------------------------"*/
975  "\n""Don't forget to include the Crash Report log file under\n"
976 # ifdef CRASH_REPORTER_MAY_BE_CREATED
977  "CrashReporter or "
978 # endif
979  "DiagnosticReports directory in bug reports.\n"
980  /*"------------------------------------------------------------\n"*/
981  "\n";
982  const size_t msglen = sizeof(msg) - 1;
983 #else
984  const char *msg = NULL;
985  const size_t msglen = 0;
986 #endif
987  bug_important_message(out, msg, msglen);
988 }
989 
990 RBIMPL_ATTR_FORMAT(RBIMPL_PRINTF_FORMAT, 2, 0)
991 static void
992 bug_report_begin_valist(FILE *out, const char *fmt, va_list args)
993 {
994  char buf[REPORT_BUG_BUFSIZ];
995 
996  fputs("[BUG] ", out);
997  vsnprintf(buf, sizeof(buf), fmt, args);
998  fputs(buf, out);
999  snprintf(buf, sizeof(buf), "\n%s\n\n", rb_dynamic_description);
1000  fputs(buf, out);
1001  preface_dump(out);
1002 }
1003 
1004 #define bug_report_begin(out, fmt) do { \
1005  va_list args; \
1006  va_start(args, fmt); \
1007  bug_report_begin_valist(out, fmt, args); \
1008  va_end(args); \
1009 } while (0)
1010 
1011 static void
1012 bug_report_end(FILE *out, rb_pid_t pid)
1013 {
1014  /* call additional bug reporters */
1015  {
1016  int i;
1017  for (i=0; i<bug_reporters_size; i++) {
1018  struct bug_reporters *reporter = &bug_reporters[i];
1019  (*reporter->func)(out, reporter->data);
1020  }
1021  }
1022  postscript_dump(out);
1023  finish_report(out, pid);
1024 }
1025 
1026 #define report_bug(file, line, fmt, ctx) do { \
1027  rb_pid_t pid = -1; \
1028  FILE *out = bug_report_file(file, line, &pid); \
1029  if (out) { \
1030  bug_report_begin(out, fmt); \
1031  rb_vm_bugreport(ctx, out); \
1032  bug_report_end(out, pid); \
1033  } \
1034 } while (0) \
1035 
1036 #define report_bug_valist(file, line, fmt, ctx, args) do { \
1037  rb_pid_t pid = -1; \
1038  FILE *out = bug_report_file(file, line, &pid); \
1039  if (out) { \
1040  bug_report_begin_valist(out, fmt, args); \
1041  rb_vm_bugreport(ctx, out); \
1042  bug_report_end(out, pid); \
1043  } \
1044 } while (0) \
1045 
1046 void
1047 ruby_set_crash_report(const char *template)
1048 {
1049  crash_report = template;
1050 #if RUBY_DEBUG
1051  rb_pid_t pid = -1;
1052  char buf[REPORT_BUG_BUFSIZ];
1053  FILE *out = open_report_path(template, buf, sizeof(buf), &pid);
1054  if (out) {
1055  time_t t = time(NULL);
1056  fprintf(out, "ruby_test_bug_report: %s", ctime(&t));
1057  finish_report(out, pid);
1058  }
1059 #endif
1060 }
1061 
1062 NORETURN(static void die(void));
1063 static void
1064 die(void)
1065 {
1066 #if defined(_WIN32) && defined(RUBY_MSVCRT_VERSION) && RUBY_MSVCRT_VERSION >= 80
1067  _set_abort_behavior( 0, _CALL_REPORTFAULT);
1068 #endif
1069 
1070  abort();
1071 }
1072 
1073 RBIMPL_ATTR_FORMAT(RBIMPL_PRINTF_FORMAT, 1, 0)
1074 void
1075 rb_bug_without_die(const char *fmt, va_list args)
1076 {
1077  const char *file = NULL;
1078  int line = 0;
1079 
1080  if (GET_EC()) {
1081  file = rb_source_location_cstr(&line);
1082  }
1083 
1084  report_bug_valist(file, line, fmt, NULL, args);
1085 }
1086 
1087 void
1088 rb_bug(const char *fmt, ...)
1089 {
1090  va_list args;
1091  va_start(args, fmt);
1092  rb_bug_without_die(fmt, args);
1093  va_end(args);
1094  die();
1095 }
1096 
1097 void
1098 rb_bug_for_fatal_signal(ruby_sighandler_t default_sighandler, int sig, const void *ctx, const char *fmt, ...)
1099 {
1100  const char *file = NULL;
1101  int line = 0;
1102 
1103  if (GET_EC()) {
1104  file = rb_source_location_cstr(&line);
1105  }
1106 
1107  report_bug(file, line, fmt, ctx);
1108 
1109  if (default_sighandler) default_sighandler(sig);
1110 
1111  ruby_default_signal(sig);
1112  die();
1113 }
1114 
1115 
1116 void
1117 rb_bug_errno(const char *mesg, int errno_arg)
1118 {
1119  if (errno_arg == 0)
1120  rb_bug("%s: errno == 0 (NOERROR)", mesg);
1121  else {
1122  const char *errno_str = rb_strerrno(errno_arg);
1123  if (errno_str)
1124  rb_bug("%s: %s (%s)", mesg, strerror(errno_arg), errno_str);
1125  else
1126  rb_bug("%s: %s (%d)", mesg, strerror(errno_arg), errno_arg);
1127  }
1128 }
1129 
1130 /*
1131  * this is safe to call inside signal handler and timer thread
1132  * (which isn't a Ruby Thread object)
1133  */
1134 #define write_or_abort(fd, str, len) (write((fd), (str), (len)) < 0 ? abort() : (void)0)
1135 #define WRITE_CONST(fd,str) write_or_abort((fd),(str),sizeof(str) - 1)
1136 
1137 void
1138 rb_async_bug_errno(const char *mesg, int errno_arg)
1139 {
1140  WRITE_CONST(2, "[ASYNC BUG] ");
1141  write_or_abort(2, mesg, strlen(mesg));
1142  WRITE_CONST(2, "\n");
1143 
1144  if (errno_arg == 0) {
1145  WRITE_CONST(2, "errno == 0 (NOERROR)\n");
1146  }
1147  else {
1148  const char *errno_str = rb_strerrno(errno_arg);
1149 
1150  if (!errno_str)
1151  errno_str = "undefined errno";
1152  write_or_abort(2, errno_str, strlen(errno_str));
1153  }
1154  WRITE_CONST(2, "\n\n");
1155  write_or_abort(2, rb_dynamic_description, strlen(rb_dynamic_description));
1156  abort();
1157 }
1158 
1159 void
1160 rb_report_bug_valist(VALUE file, int line, const char *fmt, va_list args)
1161 {
1162  report_bug_valist(RSTRING_PTR(file), line, fmt, NULL, args);
1163 }
1164 
1165 void
1166 rb_assert_failure(const char *file, int line, const char *name, const char *expr)
1167 {
1168  rb_assert_failure_detail(file, line, name, expr, NULL);
1169 }
1170 
1171 void
1172 rb_assert_failure_detail(const char *file, int line, const char *name, const char *expr,
1173  const char *fmt, ...)
1174 {
1175  FILE *out = stderr;
1176  fprintf(out, "Assertion Failed: %s:%d:", file, line);
1177  if (name) fprintf(out, "%s:", name);
1178  fputs(expr, out);
1179 
1180  if (fmt && *fmt) {
1181  va_list args;
1182  va_start(args, fmt);
1183  fputs(": ", out);
1184  vfprintf(out, fmt, args);
1185  va_end(args);
1186  }
1187  fprintf(out, "\n%s\n\n", rb_dynamic_description);
1188 
1189  preface_dump(out);
1190  rb_vm_bugreport(NULL, out);
1191  bug_report_end(out, -1);
1192  die();
1193 }
1194 
1195 static const char builtin_types[][10] = {
1196  "", /* 0x00, */
1197  "Object",
1198  "Class",
1199  "Module",
1200  "Float",
1201  "String",
1202  "Regexp",
1203  "Array",
1204  "Hash",
1205  "Struct",
1206  "Integer",
1207  "File",
1208  "Data", /* internal use: wrapped C pointers */
1209  "MatchData", /* data of $~ */
1210  "Complex",
1211  "Rational",
1212  "", /* 0x10 */
1213  "nil",
1214  "true",
1215  "false",
1216  "Symbol", /* :symbol */
1217  "Integer",
1218  "undef", /* internal use: #undef; should not happen */
1219  "", /* 0x17 */
1220  "", /* 0x18 */
1221  "", /* 0x19 */
1222  "<Memo>", /* internal use: general memo */
1223  "<Node>", /* internal use: syntax tree node */
1224  "<iClass>", /* internal use: mixed-in module holder */
1225 };
1226 
1227 const char *
1228 rb_builtin_type_name(int t)
1229 {
1230  const char *name;
1231  if ((unsigned int)t >= numberof(builtin_types)) return 0;
1232  name = builtin_types[t];
1233  if (*name) return name;
1234  return 0;
1235 }
1236 
1237 static VALUE
1238 displaying_class_of(VALUE x)
1239 {
1240  switch (x) {
1241  case Qfalse: return rb_fstring_cstr("false");
1242  case Qnil: return rb_fstring_cstr("nil");
1243  case Qtrue: return rb_fstring_cstr("true");
1244  default: return rb_obj_class(x);
1245  }
1246 }
1247 
1248 static const char *
1249 builtin_class_name(VALUE x)
1250 {
1251  const char *etype;
1252 
1253  if (NIL_P(x)) {
1254  etype = "nil";
1255  }
1256  else if (FIXNUM_P(x)) {
1257  etype = "Integer";
1258  }
1259  else if (SYMBOL_P(x)) {
1260  etype = "Symbol";
1261  }
1262  else if (RB_TYPE_P(x, T_TRUE)) {
1263  etype = "true";
1264  }
1265  else if (RB_TYPE_P(x, T_FALSE)) {
1266  etype = "false";
1267  }
1268  else {
1269  etype = NULL;
1270  }
1271  return etype;
1272 }
1273 
1274 const char *
1275 rb_builtin_class_name(VALUE x)
1276 {
1277  const char *etype = builtin_class_name(x);
1278 
1279  if (!etype) {
1280  etype = rb_obj_classname(x);
1281  }
1282  return etype;
1283 }
1284 
1285 COLDFUNC NORETURN(static void unexpected_type(VALUE, int, int));
1286 #define UNDEF_LEAKED "undef leaked to the Ruby space"
1287 
1288 static void
1289 unexpected_type(VALUE x, int xt, int t)
1290 {
1291  const char *tname = rb_builtin_type_name(t);
1292  VALUE mesg, exc = rb_eFatal;
1293 
1294  if (tname) {
1295  mesg = rb_sprintf("wrong argument type %"PRIsVALUE" (expected %s)",
1296  displaying_class_of(x), tname);
1297  exc = rb_eTypeError;
1298  }
1299  else if (xt > T_MASK && xt <= 0x3f) {
1300  mesg = rb_sprintf("unknown type 0x%x (0x%x given, probably comes"
1301  " from extension library for ruby 1.8)", t, xt);
1302  }
1303  else {
1304  mesg = rb_sprintf("unknown type 0x%x (0x%x given)", t, xt);
1305  }
1306  rb_exc_raise(rb_exc_new_str(exc, mesg));
1307 }
1308 
1309 void
1311 {
1312  int xt;
1313 
1314  if (RB_UNLIKELY(UNDEF_P(x))) {
1315  rb_bug(UNDEF_LEAKED);
1316  }
1317 
1318  xt = TYPE(x);
1319  if (xt != t || (xt == T_DATA && rbimpl_rtypeddata_p(x))) {
1320  /*
1321  * Typed data is not simple `T_DATA`, but in a sense an
1322  * extension of `struct RVALUE`, which are incompatible with
1323  * each other except when inherited.
1324  *
1325  * So it is not enough to just check `T_DATA`, it must be
1326  * identified by its `type` using `Check_TypedStruct` instead.
1327  */
1328  unexpected_type(x, xt, t);
1329  }
1330 }
1331 
1332 void
1334 {
1335  if (RB_UNLIKELY(UNDEF_P(x))) {
1336  rb_bug(UNDEF_LEAKED);
1337  }
1338 
1339  unexpected_type(x, TYPE(x), t);
1340 }
1341 
1342 int
1344 {
1345  while (child) {
1346  if (child == parent) return 1;
1347  child = child->parent;
1348  }
1349  return 0;
1350 }
1351 
1352 int
1354 {
1355  if (!RB_TYPE_P(obj, T_DATA) ||
1356  !RTYPEDDATA_P(obj) || !rb_typeddata_inherited_p(RTYPEDDATA_TYPE(obj), data_type)) {
1357  return 0;
1358  }
1359  return 1;
1360 }
1361 
1362 #undef rb_typeddata_is_instance_of
1363 int
1364 rb_typeddata_is_instance_of(VALUE obj, const rb_data_type_t *data_type)
1365 {
1366  return rb_typeddata_is_instance_of_inline(obj, data_type);
1367 }
1368 
1369 void *
1371 {
1372  VALUE actual;
1373 
1374  if (!RB_TYPE_P(obj, T_DATA)) {
1375  actual = displaying_class_of(obj);
1376  }
1377  else if (!RTYPEDDATA_P(obj)) {
1378  actual = displaying_class_of(obj);
1379  }
1380  else if (!rb_typeddata_inherited_p(RTYPEDDATA_TYPE(obj), data_type)) {
1381  const char *name = RTYPEDDATA_TYPE(obj)->wrap_struct_name;
1382  actual = rb_str_new_cstr(name); /* or rb_fstring_cstr? not sure... */
1383  }
1384  else {
1385  return RTYPEDDATA_GET_DATA(obj);
1386  }
1387 
1388  const char *expected = data_type->wrap_struct_name;
1389  rb_raise(rb_eTypeError, "wrong argument type %"PRIsVALUE" (expected %s)",
1390  actual, expected);
1391  UNREACHABLE_RETURN(NULL);
1392 }
1393 
1394 /* exception classes */
1418 
1422 
1425 static VALUE rb_eNOERROR;
1426 
1427 ID ruby_static_id_cause;
1428 #define id_cause ruby_static_id_cause
1429 static ID id_message, id_detailed_message, id_backtrace;
1430 static ID id_key, id_matchee, id_args, id_Errno, id_errno, id_i_path;
1431 static ID id_receiver, id_recv, id_iseq, id_local_variables;
1432 static ID id_private_call_p, id_top, id_bottom;
1433 #define id_bt idBt
1434 #define id_bt_locations idBt_locations
1435 #define id_mesg idMesg
1436 #define id_name idName
1437 
1438 #undef rb_exc_new_cstr
1439 
1440 VALUE
1441 rb_exc_new(VALUE etype, const char *ptr, long len)
1442 {
1443  VALUE mesg = rb_str_new(ptr, len);
1444  return rb_class_new_instance(1, &mesg, etype);
1445 }
1446 
1447 VALUE
1448 rb_exc_new_cstr(VALUE etype, const char *s)
1449 {
1450  return rb_exc_new(etype, s, strlen(s));
1451 }
1452 
1453 VALUE
1455 {
1456  rb_yjit_lazy_push_frame(GET_EC()->cfp->pc);
1457  StringValue(str);
1458  return rb_class_new_instance(1, &str, etype);
1459 }
1460 
1461 static VALUE
1462 exc_init(VALUE exc, VALUE mesg)
1463 {
1464  rb_ivar_set(exc, id_mesg, mesg);
1465  rb_ivar_set(exc, id_bt, Qnil);
1466 
1467  return exc;
1468 }
1469 
1470 /*
1471  * call-seq:
1472  * Exception.new(message = nil) -> exception
1473  *
1474  * Returns a new exception object.
1475  *
1476  * The given +message+ should be
1477  * a {string-convertible object}[rdoc-ref:implicit_conversion.rdoc@String-Convertible+Objects];
1478  * see method #message;
1479  * if not given, the message is the class name of the new instance
1480  * (which may be the name of a subclass):
1481  *
1482  * Examples:
1483  *
1484  * Exception.new # => #<Exception: Exception>
1485  * LoadError.new # => #<LoadError: LoadError> # Subclass of Exception.
1486  * Exception.new('Boom') # => #<Exception: Boom>
1487  *
1488  */
1489 
1490 static VALUE
1491 exc_initialize(int argc, VALUE *argv, VALUE exc)
1492 {
1493  VALUE arg;
1494 
1495  arg = (!rb_check_arity(argc, 0, 1) ? Qnil : argv[0]);
1496  return exc_init(exc, arg);
1497 }
1498 
1499 /*
1500  * Document-method: exception
1501  *
1502  * call-seq:
1503  * exception(message = nil) -> self or new_exception
1504  *
1505  * Returns an exception object of the same class as +self+;
1506  * useful for creating a similar exception, but with a different message.
1507  *
1508  * With +message+ +nil+, returns +self+:
1509  *
1510  * x0 = StandardError.new('Boom') # => #<StandardError: Boom>
1511  * x1 = x0.exception # => #<StandardError: Boom>
1512  * x0.__id__ == x1.__id__ # => true
1513  *
1514  * With {string-convertible object}[rdoc-ref:implicit_conversion.rdoc@String-Convertible+Objects]
1515  * +message+ (even the same as the original message),
1516  * returns a new exception object whose class is the same as +self+,
1517  * and whose message is the given +message+:
1518  *
1519  * x1 = x0.exception('Boom') # => #<StandardError: Boom>
1520  * x0..equal?(x1) # => false
1521  *
1522  */
1523 
1524 static VALUE
1525 exc_exception(int argc, VALUE *argv, VALUE self)
1526 {
1527  VALUE exc;
1528 
1529  argc = rb_check_arity(argc, 0, 1);
1530  if (argc == 0) return self;
1531  if (argc == 1 && self == argv[0]) return self;
1532  exc = rb_obj_clone(self);
1533  rb_ivar_set(exc, id_mesg, argv[0]);
1534  return exc;
1535 }
1536 
1537 /*
1538  * call-seq:
1539  * to_s -> string
1540  *
1541  * Returns a string representation of +self+:
1542  *
1543  * x = RuntimeError.new('Boom')
1544  * x.to_s # => "Boom"
1545  * x = RuntimeError.new
1546  * x.to_s # => "RuntimeError"
1547  *
1548  */
1549 
1550 static VALUE
1551 exc_to_s(VALUE exc)
1552 {
1553  VALUE mesg = rb_attr_get(exc, idMesg);
1554 
1555  if (NIL_P(mesg)) return rb_class_name(CLASS_OF(exc));
1556  return rb_String(mesg);
1557 }
1558 
1559 /* FIXME: Include eval_error.c */
1560 void rb_error_write(VALUE errinfo, VALUE emesg, VALUE errat, VALUE str, VALUE opt, VALUE highlight, VALUE reverse);
1561 
1562 VALUE
1563 rb_get_message(VALUE exc)
1564 {
1565  VALUE e = rb_check_funcall(exc, id_message, 0, 0);
1566  if (UNDEF_P(e)) return Qnil;
1567  if (!RB_TYPE_P(e, T_STRING)) e = rb_check_string_type(e);
1568  return e;
1569 }
1570 
1571 VALUE
1572 rb_get_detailed_message(VALUE exc, VALUE opt)
1573 {
1574  VALUE e;
1575  if (NIL_P(opt)) {
1576  e = rb_check_funcall(exc, id_detailed_message, 0, 0);
1577  }
1578  else {
1579  e = rb_check_funcall_kw(exc, id_detailed_message, 1, &opt, 1);
1580  }
1581  if (UNDEF_P(e)) return Qnil;
1582  if (!RB_TYPE_P(e, T_STRING)) e = rb_check_string_type(e);
1583  return e;
1584 }
1585 
1586 /*
1587  * call-seq:
1588  * Exception.to_tty? -> true or false
1589  *
1590  * Returns +true+ if exception messages will be sent to a terminal device.
1591  */
1592 static VALUE
1593 exc_s_to_tty_p(VALUE self)
1594 {
1595  return RBOOL(rb_stderr_tty_p());
1596 }
1597 
1598 static VALUE
1599 check_highlight_keyword(VALUE opt, int auto_tty_detect)
1600 {
1601  VALUE highlight = Qnil;
1602 
1603  if (!NIL_P(opt)) {
1604  highlight = rb_hash_lookup(opt, sym_highlight);
1605 
1606  switch (highlight) {
1607  default:
1608  rb_bool_expected(highlight, "highlight", TRUE);
1609  UNREACHABLE;
1610  case Qtrue: case Qfalse: case Qnil: break;
1611  }
1612  }
1613 
1614  if (NIL_P(highlight)) {
1615  highlight = RBOOL(auto_tty_detect && rb_stderr_tty_p());
1616  }
1617 
1618  return highlight;
1619 }
1620 
1621 static VALUE
1622 check_order_keyword(VALUE opt)
1623 {
1624  VALUE order = Qnil;
1625 
1626  if (!NIL_P(opt)) {
1627  static VALUE kw_order;
1628  if (!kw_order) kw_order = ID2SYM(rb_intern_const("order"));
1629 
1630  order = rb_hash_lookup(opt, kw_order);
1631 
1632  if (order != Qnil) {
1633  ID id = rb_check_id(&order);
1634  if (id == id_bottom) order = Qtrue;
1635  else if (id == id_top) order = Qfalse;
1636  else {
1637  rb_raise(rb_eArgError, "expected :top or :bottom as "
1638  "order: %+"PRIsVALUE, order);
1639  }
1640  }
1641  }
1642 
1643  if (NIL_P(order)) order = Qfalse;
1644 
1645  return order;
1646 }
1647 
1648 /*
1649  * call-seq:
1650  * full_message(highlight: true, order: :top) -> string
1651  *
1652  * Returns an enhanced message string:
1653  *
1654  * - Includes the exception class name.
1655  * - If the value of keyword +highlight+ is true (not +nil+ or +false+),
1656  * includes bolding ANSI codes (see below) to enhance the appearance of the message.
1657  * - Includes the {backtrace}[rdoc-ref:exceptions.md@Backtraces]:
1658  *
1659  * - If the value of keyword +order+ is +:top+ (the default),
1660  * lists the error message and the innermost backtrace entry first.
1661  * - If the value of keyword +order+ is +:bottom+,
1662  * lists the error message the the innermost entry last.
1663  *
1664  * Example:
1665  *
1666  * def baz
1667  * begin
1668  * 1 / 0
1669  * rescue => x
1670  * pp x.message
1671  * pp x.full_message(highlight: false).split("\n")
1672  * pp x.full_message.split("\n")
1673  * end
1674  * end
1675  * def bar; baz; end
1676  * def foo; bar; end
1677  * foo
1678  *
1679  * Output:
1680  *
1681  * "divided by 0"
1682  * ["t.rb:3:in `/': divided by 0 (ZeroDivisionError)",
1683  * "\tfrom t.rb:3:in `baz'",
1684  * "\tfrom t.rb:10:in `bar'",
1685  * "\tfrom t.rb:11:in `foo'",
1686  * "\tfrom t.rb:12:in `<main>'"]
1687  * ["t.rb:3:in `/': \e[1mdivided by 0 (\e[1;4mZeroDivisionError\e[m\e[1m)\e[m",
1688  * "\tfrom t.rb:3:in `baz'",
1689  * "\tfrom t.rb:10:in `bar'",
1690  * "\tfrom t.rb:11:in `foo'",
1691  * "\tfrom t.rb:12:in `<main>'"]
1692  *
1693  * An overriding method should be careful with ANSI code enhancements;
1694  * see {Messages}[rdoc-ref:exceptions.md@Messages].
1695  */
1696 
1697 static VALUE
1698 exc_full_message(int argc, VALUE *argv, VALUE exc)
1699 {
1700  VALUE opt, str, emesg, errat;
1701  VALUE highlight, order;
1702 
1703  rb_scan_args(argc, argv, "0:", &opt);
1704 
1705  highlight = check_highlight_keyword(opt, 1);
1706  order = check_order_keyword(opt);
1707 
1708  {
1709  if (NIL_P(opt)) opt = rb_hash_new();
1710  rb_hash_aset(opt, sym_highlight, highlight);
1711  }
1712 
1713  str = rb_str_new2("");
1714  errat = rb_get_backtrace(exc);
1715  emesg = rb_get_detailed_message(exc, opt);
1716 
1717  rb_error_write(exc, emesg, errat, str, opt, highlight, order);
1718  return str;
1719 }
1720 
1721 /*
1722  * call-seq:
1723  * message -> string
1724  *
1725  * Returns #to_s.
1726  *
1727  * See {Messages}[rdoc-ref:exceptions.md@Messages].
1728  */
1729 
1730 static VALUE
1731 exc_message(VALUE exc)
1732 {
1733  return rb_funcallv(exc, idTo_s, 0, 0);
1734 }
1735 
1736 /*
1737  * call-seq:
1738  * detailed_message(highlight: false, **kwargs) -> string
1739  *
1740  * Returns the message string with enhancements:
1741  *
1742  * - Includes the exception class name in the first line.
1743  * - If the value of keyword +highlight+ is +true+,
1744  * includes bolding and underlining ANSI codes (see below)
1745  * to enhance the appearance of the message.
1746  *
1747  * Examples:
1748  *
1749  * begin
1750  * 1 / 0
1751  * rescue => x
1752  * p x.message
1753  * p x.detailed_message # Class name added.
1754  * p x.detailed_message(highlight: true) # Class name, bolding, and underlining added.
1755  * end
1756  *
1757  * Output:
1758  *
1759  * "divided by 0"
1760  * "divided by 0 (ZeroDivisionError)"
1761  * "\e[1mdivided by 0 (\e[1;4mZeroDivisionError\e[m\e[1m)\e[m"
1762  *
1763  * This method is overridden by some gems in the Ruby standard library to add information:
1764  *
1765  * - DidYouMean::Correctable#detailed_message.
1766  * - ErrorHighlight::CoreExt#detailed_message.
1767  * - SyntaxSuggest#detailed_message.
1768  *
1769  * An overriding method must be tolerant of passed keyword arguments,
1770  * which may include (but may not be limited to):
1771  *
1772  * - +:highlight+.
1773  * - +:did_you_mean+.
1774  * - +:error_highlight+.
1775  * - +:syntax_suggest+.
1776  *
1777  * An overriding method should also be careful with ANSI code enhancements;
1778  * see {Messages}[rdoc-ref:exceptions.md@Messages].
1779  */
1780 
1781 static VALUE
1782 exc_detailed_message(int argc, VALUE *argv, VALUE exc)
1783 {
1784  VALUE opt;
1785 
1786  rb_scan_args(argc, argv, "0:", &opt);
1787 
1788  VALUE highlight = check_highlight_keyword(opt, 0);
1789 
1790  extern VALUE rb_decorate_message(const VALUE eclass, VALUE emesg, int highlight);
1791 
1792  return rb_decorate_message(CLASS_OF(exc), rb_get_message(exc), RTEST(highlight));
1793 }
1794 
1795 /*
1796  * call-seq:
1797  * inspect -> string
1798  *
1799  * Returns a string representation of +self+:
1800  *
1801  * x = RuntimeError.new('Boom')
1802  * x.inspect # => "#<RuntimeError: Boom>"
1803  * x = RuntimeError.new
1804  * x.inspect # => "#<RuntimeError: RuntimeError>"
1805  *
1806  */
1807 
1808 static VALUE
1809 exc_inspect(VALUE exc)
1810 {
1811  VALUE str, klass;
1812 
1813  klass = CLASS_OF(exc);
1814  exc = rb_obj_as_string(exc);
1815  if (RSTRING_LEN(exc) == 0) {
1816  return rb_class_name(klass);
1817  }
1818 
1819  str = rb_str_buf_new2("#<");
1820  klass = rb_class_name(klass);
1821  rb_str_buf_append(str, klass);
1822 
1823  if (RTEST(rb_str_include(exc, rb_str_new2("\n")))) {
1824  rb_str_catf(str, ":%+"PRIsVALUE, exc);
1825  }
1826  else {
1827  rb_str_buf_cat(str, ": ", 2);
1828  rb_str_buf_append(str, exc);
1829  }
1830 
1831  rb_str_buf_cat(str, ">", 1);
1832 
1833  return str;
1834 }
1835 
1836 /*
1837  * call-seq:
1838  * backtrace -> array or nil
1839  *
1840  * Returns a backtrace value for +self+;
1841  * the returned value depends on the form of the stored backtrace value:
1842  *
1843  * - \Array of Thread::Backtrace::Location objects:
1844  * returns the array of strings given by
1845  * <tt>Exception#backtrace_locations.map {|loc| loc.to_s }</tt>.
1846  * This is the normal case, where the backtrace value was stored by Kernel#raise.
1847  * - \Array of strings: returns that array.
1848  * This is the unusual case, where the backtrace value was explicitly
1849  * stored as an array of strings.
1850  * - +nil+: returns +nil+.
1851  *
1852  * Example:
1853  *
1854  * begin
1855  * 1 / 0
1856  * rescue => x
1857  * x.backtrace.take(2)
1858  * end
1859  * # => ["(irb):132:in `/'", "(irb):132:in `<top (required)>'"]
1860  *
1861  * see {Backtraces}[rdoc-ref:exceptions.md@Backtraces].
1862  */
1863 
1864 static VALUE
1865 exc_backtrace(VALUE exc)
1866 {
1867  VALUE obj;
1868 
1869  obj = rb_attr_get(exc, id_bt);
1870 
1871  if (rb_backtrace_p(obj)) {
1872  obj = rb_backtrace_to_str_ary(obj);
1873  /* rb_ivar_set(exc, id_bt, obj); */
1874  }
1875 
1876  return obj;
1877 }
1878 
1879 static VALUE rb_check_backtrace(VALUE);
1880 
1881 VALUE
1882 rb_get_backtrace(VALUE exc)
1883 {
1884  ID mid = id_backtrace;
1885  VALUE info;
1886  if (rb_method_basic_definition_p(CLASS_OF(exc), id_backtrace)) {
1887  VALUE klass = rb_eException;
1888  rb_execution_context_t *ec = GET_EC();
1889  if (NIL_P(exc))
1890  return Qnil;
1891  EXEC_EVENT_HOOK(ec, RUBY_EVENT_C_CALL, exc, mid, mid, klass, Qundef);
1892  info = exc_backtrace(exc);
1893  EXEC_EVENT_HOOK(ec, RUBY_EVENT_C_RETURN, exc, mid, mid, klass, info);
1894  }
1895  else {
1896  info = rb_funcallv(exc, mid, 0, 0);
1897  }
1898  if (NIL_P(info)) return Qnil;
1899  return rb_check_backtrace(info);
1900 }
1901 
1902 /*
1903  * call-seq:
1904  * backtrace_locations -> array or nil
1905  *
1906  * Returns a backtrace value for +self+;
1907  * the returned value depends on the form of the stored backtrace value:
1908  *
1909  * - \Array of Thread::Backtrace::Location objects: returns that array.
1910  * - \Array of strings or +nil+: returns +nil+.
1911  *
1912  * Example:
1913  *
1914  * begin
1915  * 1 / 0
1916  * rescue => x
1917  * x.backtrace_locations.take(2)
1918  * end
1919  * # => ["(irb):150:in `/'", "(irb):150:in `<top (required)>'"]
1920  *
1921  * See {Backtraces}[rdoc-ref:exceptions.md@Backtraces].
1922  */
1923 static VALUE
1924 exc_backtrace_locations(VALUE exc)
1925 {
1926  VALUE obj;
1927 
1928  obj = rb_attr_get(exc, id_bt_locations);
1929  if (!NIL_P(obj)) {
1930  obj = rb_backtrace_to_location_ary(obj);
1931  }
1932  return obj;
1933 }
1934 
1935 static VALUE
1936 rb_check_backtrace(VALUE bt)
1937 {
1938  long i;
1939  static const char err[] = "backtrace must be an Array of String or an Array of Thread::Backtrace::Location";
1940 
1941  if (!NIL_P(bt)) {
1942  if (RB_TYPE_P(bt, T_STRING)) return rb_ary_new3(1, bt);
1943  if (rb_backtrace_p(bt)) return bt;
1944  if (!RB_TYPE_P(bt, T_ARRAY)) {
1945  rb_raise(rb_eTypeError, err);
1946  }
1947  for (i=0;i<RARRAY_LEN(bt);i++) {
1948  VALUE e = RARRAY_AREF(bt, i);
1949  if (!RB_TYPE_P(e, T_STRING)) {
1950  rb_raise(rb_eTypeError, err);
1951  }
1952  }
1953  }
1954  return bt;
1955 }
1956 
1957 /*
1958  * call-seq:
1959  * set_backtrace(value) -> value
1960  *
1961  * Sets the backtrace value for +self+; returns the given +value:
1962  *
1963  * x = RuntimeError.new('Boom')
1964  * x.set_backtrace(%w[foo bar baz]) # => ["foo", "bar", "baz"]
1965  * x.backtrace # => ["foo", "bar", "baz"]
1966  *
1967  * The given +value+ must be an array of strings, a single string, or +nil+.
1968  *
1969  * Does not affect the value returned by #backtrace_locations.
1970  *
1971  * See {Backtraces}[rdoc-ref:exceptions.md@Backtraces].
1972  */
1973 
1974 static VALUE
1975 exc_set_backtrace(VALUE exc, VALUE bt)
1976 {
1977  VALUE btobj = rb_location_ary_to_backtrace(bt);
1978  if (RTEST(btobj)) {
1979  rb_ivar_set(exc, id_bt, btobj);
1980  rb_ivar_set(exc, id_bt_locations, btobj);
1981  return bt;
1982  }
1983  else {
1984  return rb_ivar_set(exc, id_bt, rb_check_backtrace(bt));
1985  }
1986 }
1987 
1988 VALUE
1989 rb_exc_set_backtrace(VALUE exc, VALUE bt)
1990 {
1991  return exc_set_backtrace(exc, bt);
1992 }
1993 
1994 /*
1995  * call-seq:
1996  * cause -> exception or nil
1997  *
1998  * Returns the previous value of global variable <tt>$!</tt>,
1999  * which may be +nil+
2000  * (see {Global Variables}[rdoc-ref:exceptions.md@Global+Variables]):
2001  *
2002  * begin
2003  * raise('Boom 0')
2004  * rescue => x0
2005  * puts "Exception: #{x0}; $!: #{$!}; cause: #{x0.cause.inspect}."
2006  * begin
2007  * raise('Boom 1')
2008  * rescue => x1
2009  * puts "Exception: #{x1}; $!: #{$!}; cause: #{x1.cause}."
2010  * begin
2011  * raise('Boom 2')
2012  * rescue => x2
2013  * puts "Exception: #{x2}; $!: #{$!}; cause: #{x2.cause}."
2014  * end
2015  * end
2016  * end
2017  *
2018  * Output:
2019  *
2020  * Exception: Boom 0; $!: Boom 0; cause: nil.
2021  * Exception: Boom 1; $!: Boom 1; cause: Boom 0.
2022  * Exception: Boom 2; $!: Boom 2; cause: Boom 1.
2023  *
2024  */
2025 
2026 static VALUE
2027 exc_cause(VALUE exc)
2028 {
2029  return rb_attr_get(exc, id_cause);
2030 }
2031 
2032 static VALUE
2033 try_convert_to_exception(VALUE obj)
2034 {
2035  return rb_check_funcall(obj, idException, 0, 0);
2036 }
2037 
2038 /*
2039  * call-seq:
2040  * self == object -> true or false
2041  *
2042  * Returns whether +object+ is the same class as +self+
2043  * and its #message and #backtrace are equal to those of +self+.
2044  *
2045  */
2046 
2047 static VALUE
2048 exc_equal(VALUE exc, VALUE obj)
2049 {
2050  VALUE mesg, backtrace;
2051 
2052  if (exc == obj) return Qtrue;
2053 
2054  if (rb_obj_class(exc) != rb_obj_class(obj)) {
2055  int state;
2056 
2057  obj = rb_protect(try_convert_to_exception, obj, &state);
2058  if (state || UNDEF_P(obj)) {
2060  return Qfalse;
2061  }
2062  if (rb_obj_class(exc) != rb_obj_class(obj)) return Qfalse;
2063  mesg = rb_check_funcall(obj, id_message, 0, 0);
2064  if (UNDEF_P(mesg)) return Qfalse;
2065  backtrace = rb_check_funcall(obj, id_backtrace, 0, 0);
2066  if (UNDEF_P(backtrace)) return Qfalse;
2067  }
2068  else {
2069  mesg = rb_attr_get(obj, id_mesg);
2070  backtrace = exc_backtrace(obj);
2071  }
2072 
2073  if (!rb_equal(rb_attr_get(exc, id_mesg), mesg))
2074  return Qfalse;
2075  return rb_equal(exc_backtrace(exc), backtrace);
2076 }
2077 
2078 /*
2079  * call-seq:
2080  * SystemExit.new -> system_exit
2081  * SystemExit.new(status) -> system_exit
2082  * SystemExit.new(status, msg) -> system_exit
2083  * SystemExit.new(msg) -> system_exit
2084  *
2085  * Create a new +SystemExit+ exception with the given status and message.
2086  * Status is true, false, or an integer.
2087  * If status is not given, true is used.
2088  */
2089 
2090 static VALUE
2091 exit_initialize(int argc, VALUE *argv, VALUE exc)
2092 {
2093  VALUE status;
2094  if (argc > 0) {
2095  status = *argv;
2096 
2097  switch (status) {
2098  case Qtrue:
2099  status = INT2FIX(EXIT_SUCCESS);
2100  ++argv;
2101  --argc;
2102  break;
2103  case Qfalse:
2104  status = INT2FIX(EXIT_FAILURE);
2105  ++argv;
2106  --argc;
2107  break;
2108  default:
2109  status = rb_check_to_int(status);
2110  if (NIL_P(status)) {
2111  status = INT2FIX(EXIT_SUCCESS);
2112  }
2113  else {
2114 #if EXIT_SUCCESS != 0
2115  if (status == INT2FIX(0))
2116  status = INT2FIX(EXIT_SUCCESS);
2117 #endif
2118  ++argv;
2119  --argc;
2120  }
2121  break;
2122  }
2123  }
2124  else {
2125  status = INT2FIX(EXIT_SUCCESS);
2126  }
2127  rb_call_super(argc, argv);
2128  rb_ivar_set(exc, id_status, status);
2129  return exc;
2130 }
2131 
2132 
2133 /*
2134  * call-seq:
2135  * system_exit.status -> integer
2136  *
2137  * Return the status value associated with this system exit.
2138  */
2139 
2140 static VALUE
2141 exit_status(VALUE exc)
2142 {
2143  return rb_attr_get(exc, id_status);
2144 }
2145 
2146 
2147 /*
2148  * call-seq:
2149  * system_exit.success? -> true or false
2150  *
2151  * Returns +true+ if exiting successful, +false+ if not.
2152  */
2153 
2154 static VALUE
2155 exit_success_p(VALUE exc)
2156 {
2157  VALUE status_val = rb_attr_get(exc, id_status);
2158  int status;
2159 
2160  if (NIL_P(status_val))
2161  return Qtrue;
2162  status = NUM2INT(status_val);
2163  return RBOOL(WIFEXITED(status) && WEXITSTATUS(status) == EXIT_SUCCESS);
2164 }
2165 
2166 static VALUE
2167 err_init_recv(VALUE exc, VALUE recv)
2168 {
2169  if (!UNDEF_P(recv)) rb_ivar_set(exc, id_recv, recv);
2170  return exc;
2171 }
2172 
2173 /*
2174  * call-seq:
2175  * FrozenError.new(msg=nil, receiver: nil) -> frozen_error
2176  *
2177  * Construct a new FrozenError exception. If given the <i>receiver</i>
2178  * parameter may subsequently be examined using the FrozenError#receiver
2179  * method.
2180  *
2181  * a = [].freeze
2182  * raise FrozenError.new("can't modify frozen array", receiver: a)
2183  */
2184 
2185 static VALUE
2186 frozen_err_initialize(int argc, VALUE *argv, VALUE self)
2187 {
2188  ID keywords[1];
2189  VALUE values[numberof(keywords)], options;
2190 
2191  argc = rb_scan_args(argc, argv, "*:", NULL, &options);
2192  keywords[0] = id_receiver;
2193  rb_get_kwargs(options, keywords, 0, numberof(values), values);
2194  rb_call_super(argc, argv);
2195  err_init_recv(self, values[0]);
2196  return self;
2197 }
2198 
2199 /*
2200  * Document-method: FrozenError#receiver
2201  * call-seq:
2202  * frozen_error.receiver -> object
2203  *
2204  * Return the receiver associated with this FrozenError exception.
2205  */
2206 
2207 #define frozen_err_receiver name_err_receiver
2208 
2209 void
2210 rb_name_error(ID id, const char *fmt, ...)
2211 {
2212  VALUE exc, argv[2];
2213  va_list args;
2214 
2215  va_start(args, fmt);
2216  argv[0] = rb_vsprintf(fmt, args);
2217  va_end(args);
2218 
2219  argv[1] = ID2SYM(id);
2220  exc = rb_class_new_instance(2, argv, rb_eNameError);
2221  rb_exc_raise(exc);
2222 }
2223 
2224 void
2225 rb_name_error_str(VALUE str, const char *fmt, ...)
2226 {
2227  VALUE exc, argv[2];
2228  va_list args;
2229 
2230  va_start(args, fmt);
2231  argv[0] = rb_vsprintf(fmt, args);
2232  va_end(args);
2233 
2234  argv[1] = str;
2235  exc = rb_class_new_instance(2, argv, rb_eNameError);
2236  rb_exc_raise(exc);
2237 }
2238 
2239 static VALUE
2240 name_err_init_attr(VALUE exc, VALUE recv, VALUE method)
2241 {
2242  const rb_execution_context_t *ec = GET_EC();
2243  rb_control_frame_t *cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(ec->cfp);
2244  cfp = rb_vm_get_ruby_level_next_cfp(ec, cfp);
2245  rb_ivar_set(exc, id_name, method);
2246  err_init_recv(exc, recv);
2247  if (cfp && VM_FRAME_TYPE(cfp) != VM_FRAME_MAGIC_DUMMY) {
2248  rb_ivar_set(exc, id_iseq, rb_iseqw_new(cfp->iseq));
2249  }
2250  return exc;
2251 }
2252 
2253 /*
2254  * call-seq:
2255  * NameError.new(msg=nil, name=nil, receiver: nil) -> name_error
2256  *
2257  * Construct a new NameError exception. If given the <i>name</i>
2258  * parameter may subsequently be examined using the NameError#name
2259  * method. <i>receiver</i> parameter allows to pass object in
2260  * context of which the error happened. Example:
2261  *
2262  * [1, 2, 3].method(:rject) # NameError with name "rject" and receiver: Array
2263  * [1, 2, 3].singleton_method(:rject) # NameError with name "rject" and receiver: [1, 2, 3]
2264  */
2265 
2266 static VALUE
2267 name_err_initialize(int argc, VALUE *argv, VALUE self)
2268 {
2269  ID keywords[1];
2270  VALUE values[numberof(keywords)], name, options;
2271 
2272  argc = rb_scan_args(argc, argv, "*:", NULL, &options);
2273  keywords[0] = id_receiver;
2274  rb_get_kwargs(options, keywords, 0, numberof(values), values);
2275  name = (argc > 1) ? argv[--argc] : Qnil;
2276  rb_call_super(argc, argv);
2277  name_err_init_attr(self, values[0], name);
2278  return self;
2279 }
2280 
2281 static VALUE rb_name_err_mesg_new(VALUE mesg, VALUE recv, VALUE method);
2282 
2283 static VALUE
2284 name_err_init(VALUE exc, VALUE mesg, VALUE recv, VALUE method)
2285 {
2286  exc_init(exc, rb_name_err_mesg_new(mesg, recv, method));
2287  return name_err_init_attr(exc, recv, method);
2288 }
2289 
2290 VALUE
2291 rb_name_err_new(VALUE mesg, VALUE recv, VALUE method)
2292 {
2294  return name_err_init(exc, mesg, recv, method);
2295 }
2296 
2297 /*
2298  * call-seq:
2299  * name_error.name -> string or nil
2300  *
2301  * Return the name associated with this NameError exception.
2302  */
2303 
2304 static VALUE
2305 name_err_name(VALUE self)
2306 {
2307  return rb_attr_get(self, id_name);
2308 }
2309 
2310 /*
2311  * call-seq:
2312  * name_error.local_variables -> array
2313  *
2314  * Return a list of the local variable names defined where this
2315  * NameError exception was raised.
2316  *
2317  * Internal use only.
2318  */
2319 
2320 static VALUE
2321 name_err_local_variables(VALUE self)
2322 {
2323  VALUE vars = rb_attr_get(self, id_local_variables);
2324 
2325  if (NIL_P(vars)) {
2326  VALUE iseqw = rb_attr_get(self, id_iseq);
2327  if (!NIL_P(iseqw)) vars = rb_iseqw_local_variables(iseqw);
2328  if (NIL_P(vars)) vars = rb_ary_new();
2329  rb_ivar_set(self, id_local_variables, vars);
2330  }
2331  return vars;
2332 }
2333 
2334 static VALUE
2335 nometh_err_init_attr(VALUE exc, VALUE args, int priv)
2336 {
2337  rb_ivar_set(exc, id_args, args);
2338  rb_ivar_set(exc, id_private_call_p, RBOOL(priv));
2339  return exc;
2340 }
2341 
2342 /*
2343  * call-seq:
2344  * NoMethodError.new(msg=nil, name=nil, args=nil, private=false, receiver: nil) -> no_method_error
2345  *
2346  * Construct a NoMethodError exception for a method of the given name
2347  * called with the given arguments. The name may be accessed using
2348  * the <code>#name</code> method on the resulting object, and the
2349  * arguments using the <code>#args</code> method.
2350  *
2351  * If <i>private</i> argument were passed, it designates method was
2352  * attempted to call in private context, and can be accessed with
2353  * <code>#private_call?</code> method.
2354  *
2355  * <i>receiver</i> argument stores an object whose method was called.
2356  */
2357 
2358 static VALUE
2359 nometh_err_initialize(int argc, VALUE *argv, VALUE self)
2360 {
2361  int priv;
2362  VALUE args, options;
2363  argc = rb_scan_args(argc, argv, "*:", NULL, &options);
2364  priv = (argc > 3) && (--argc, RTEST(argv[argc]));
2365  args = (argc > 2) ? argv[--argc] : Qnil;
2366  if (!NIL_P(options)) argv[argc++] = options;
2368  return nometh_err_init_attr(self, args, priv);
2369 }
2370 
2371 VALUE
2372 rb_nomethod_err_new(VALUE mesg, VALUE recv, VALUE method, VALUE args, int priv)
2373 {
2375  name_err_init(exc, mesg, recv, method);
2376  return nometh_err_init_attr(exc, args, priv);
2377 }
2378 
2380  VALUE mesg;
2381  VALUE recv;
2382  VALUE name;
2384 
2385 static void
2386 name_err_mesg_mark(void *p)
2387 {
2389  rb_gc_mark_movable(ptr->mesg);
2390  rb_gc_mark_movable(ptr->recv);
2391  rb_gc_mark_movable(ptr->name);
2392 }
2393 
2394 static void
2395 name_err_mesg_update(void *p)
2396 {
2398  ptr->mesg = rb_gc_location(ptr->mesg);
2399  ptr->recv = rb_gc_location(ptr->recv);
2400  ptr->name = rb_gc_location(ptr->name);
2401 }
2402 
2403 static const rb_data_type_t name_err_mesg_data_type = {
2404  "name_err_mesg",
2405  {
2406  name_err_mesg_mark,
2408  NULL, // No external memory to report,
2409  name_err_mesg_update,
2410  },
2411  0, 0, RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_EMBEDDABLE
2412 };
2413 
2414 /* :nodoc: */
2415 static VALUE
2416 rb_name_err_mesg_init(VALUE klass, VALUE mesg, VALUE recv, VALUE name)
2417 {
2418  name_error_message_t *message;
2419  VALUE result = TypedData_Make_Struct(klass, name_error_message_t, &name_err_mesg_data_type, message);
2420  RB_OBJ_WRITE(result, &message->mesg, mesg);
2421  RB_OBJ_WRITE(result, &message->recv, recv);
2422  RB_OBJ_WRITE(result, &message->name, name);
2423  return result;
2424 }
2425 
2426 /* :nodoc: */
2427 static VALUE
2428 rb_name_err_mesg_new(VALUE mesg, VALUE recv, VALUE method)
2429 {
2430  return rb_name_err_mesg_init(rb_cNameErrorMesg, mesg, recv, method);
2431 }
2432 
2433 /* :nodoc: */
2434 static VALUE
2435 name_err_mesg_alloc(VALUE klass)
2436 {
2437  return rb_name_err_mesg_init(klass, Qnil, Qnil, Qnil);
2438 }
2439 
2440 /* :nodoc: */
2441 static VALUE
2442 name_err_mesg_init_copy(VALUE obj1, VALUE obj2)
2443 {
2444  if (obj1 == obj2) return obj1;
2445  rb_obj_init_copy(obj1, obj2);
2446 
2447  name_error_message_t *ptr1, *ptr2;
2448  TypedData_Get_Struct(obj1, name_error_message_t, &name_err_mesg_data_type, ptr1);
2449  TypedData_Get_Struct(obj2, name_error_message_t, &name_err_mesg_data_type, ptr2);
2450 
2451  RB_OBJ_WRITE(obj1, &ptr1->mesg, ptr2->mesg);
2452  RB_OBJ_WRITE(obj1, &ptr1->recv, ptr2->recv);
2453  RB_OBJ_WRITE(obj1, &ptr1->name, ptr2->name);
2454  return obj1;
2455 }
2456 
2457 /* :nodoc: */
2458 static VALUE
2459 name_err_mesg_equal(VALUE obj1, VALUE obj2)
2460 {
2461  if (obj1 == obj2) return Qtrue;
2462 
2463  if (rb_obj_class(obj2) != rb_cNameErrorMesg)
2464  return Qfalse;
2465 
2466  name_error_message_t *ptr1, *ptr2;
2467  TypedData_Get_Struct(obj1, name_error_message_t, &name_err_mesg_data_type, ptr1);
2468  TypedData_Get_Struct(obj2, name_error_message_t, &name_err_mesg_data_type, ptr2);
2469 
2470  if (!rb_equal(ptr1->mesg, ptr2->mesg)) return Qfalse;
2471  if (!rb_equal(ptr1->recv, ptr2->recv)) return Qfalse;
2472  if (!rb_equal(ptr1->name, ptr2->name)) return Qfalse;
2473  return Qtrue;
2474 }
2475 
2476 /* :nodoc: */
2477 static VALUE
2478 name_err_mesg_receiver_name(VALUE obj)
2479 {
2480  if (RB_SPECIAL_CONST_P(obj)) return Qundef;
2481  if (RB_BUILTIN_TYPE(obj) == T_MODULE || RB_BUILTIN_TYPE(obj) == T_CLASS) {
2482  return rb_check_funcall(obj, rb_intern("name"), 0, 0);
2483  }
2484  return Qundef;
2485 }
2486 
2487 /* :nodoc: */
2488 static VALUE
2489 name_err_mesg_to_str(VALUE obj)
2490 {
2492  TypedData_Get_Struct(obj, name_error_message_t, &name_err_mesg_data_type, ptr);
2493 
2494  VALUE mesg = ptr->mesg;
2495  if (NIL_P(mesg)) return Qnil;
2496  else {
2497  struct RString s_str, c_str, d_str;
2498  VALUE c, s, d = 0, args[4], c2;
2499  int state = 0;
2500  rb_encoding *usascii = rb_usascii_encoding();
2501 
2502 #define FAKE_CSTR(v, str) rb_setup_fake_str((v), (str), rb_strlen_lit(str), usascii)
2503  c = s = FAKE_CSTR(&s_str, "");
2504  obj = ptr->recv;
2505  switch (obj) {
2506  case Qnil:
2507  c = d = FAKE_CSTR(&d_str, "nil");
2508  break;
2509  case Qtrue:
2510  c = d = FAKE_CSTR(&d_str, "true");
2511  break;
2512  case Qfalse:
2513  c = d = FAKE_CSTR(&d_str, "false");
2514  break;
2515  default:
2516  if (strstr(RSTRING_PTR(mesg), "%2$s")) {
2517  d = rb_protect(name_err_mesg_receiver_name, obj, &state);
2518  if (state || NIL_OR_UNDEF_P(d))
2519  d = rb_protect(rb_inspect, obj, &state);
2520  if (state) {
2522  }
2523  d = rb_check_string_type(d);
2524  if (NIL_P(d)) {
2525  d = rb_any_to_s(obj);
2526  }
2527  }
2528 
2529  if (!RB_SPECIAL_CONST_P(obj)) {
2530  switch (RB_BUILTIN_TYPE(obj)) {
2531  case T_MODULE:
2532  s = FAKE_CSTR(&s_str, "module ");
2533  c = obj;
2534  break;
2535  case T_CLASS:
2536  s = FAKE_CSTR(&s_str, "class ");
2537  c = obj;
2538  break;
2539  default:
2540  goto object;
2541  }
2542  }
2543  else {
2544  VALUE klass;
2545  object:
2546  klass = CLASS_OF(obj);
2547  if (RB_TYPE_P(klass, T_CLASS) && RCLASS_SINGLETON_P(klass)) {
2548  s = FAKE_CSTR(&s_str, "");
2549  if (obj == rb_vm_top_self()) {
2550  c = FAKE_CSTR(&c_str, "main");
2551  }
2552  else {
2553  c = rb_any_to_s(obj);
2554  }
2555  break;
2556  }
2557  else {
2558  s = FAKE_CSTR(&s_str, "an instance of ");
2559  c = rb_class_real(klass);
2560  }
2561  }
2562  c2 = rb_protect(name_err_mesg_receiver_name, c, &state);
2563  if (state || NIL_OR_UNDEF_P(c2))
2564  c2 = rb_protect(rb_inspect, c, &state);
2565  if (state) {
2567  }
2568  c2 = rb_check_string_type(c2);
2569  if (NIL_P(c2)) {
2570  c2 = rb_any_to_s(c);
2571  }
2572  c = c2;
2573  break;
2574  }
2575  args[0] = rb_obj_as_string(ptr->name);
2576  args[1] = d;
2577  args[2] = s;
2578  args[3] = c;
2579  mesg = rb_str_format(4, args, mesg);
2580  }
2581  return mesg;
2582 }
2583 
2584 /* :nodoc: */
2585 static VALUE
2586 name_err_mesg_dump(VALUE obj, VALUE limit)
2587 {
2588  return name_err_mesg_to_str(obj);
2589 }
2590 
2591 /* :nodoc: */
2592 static VALUE
2593 name_err_mesg_load(VALUE klass, VALUE str)
2594 {
2595  return str;
2596 }
2597 
2598 /*
2599  * call-seq:
2600  * name_error.receiver -> object
2601  *
2602  * Return the receiver associated with this NameError exception.
2603  */
2604 
2605 static VALUE
2606 name_err_receiver(VALUE self)
2607 {
2608  VALUE recv = rb_ivar_lookup(self, id_recv, Qundef);
2609  if (!UNDEF_P(recv)) return recv;
2610 
2611  VALUE mesg = rb_attr_get(self, id_mesg);
2612  if (!rb_typeddata_is_kind_of(mesg, &name_err_mesg_data_type)) {
2613  rb_raise(rb_eArgError, "no receiver is available");
2614  }
2615 
2617  TypedData_Get_Struct(mesg, name_error_message_t, &name_err_mesg_data_type, ptr);
2618  return ptr->recv;
2619 }
2620 
2621 /*
2622  * call-seq:
2623  * no_method_error.args -> obj
2624  *
2625  * Return the arguments passed in as the third parameter to
2626  * the constructor.
2627  */
2628 
2629 static VALUE
2630 nometh_err_args(VALUE self)
2631 {
2632  return rb_attr_get(self, id_args);
2633 }
2634 
2635 /*
2636  * call-seq:
2637  * no_method_error.private_call? -> true or false
2638  *
2639  * Return true if the caused method was called as private.
2640  */
2641 
2642 static VALUE
2643 nometh_err_private_call_p(VALUE self)
2644 {
2645  return rb_attr_get(self, id_private_call_p);
2646 }
2647 
2648 void
2649 rb_invalid_str(const char *str, const char *type)
2650 {
2651  VALUE s = rb_str_new2(str);
2652 
2653  rb_raise(rb_eArgError, "invalid value for %s: %+"PRIsVALUE, type, s);
2654 }
2655 
2656 /*
2657  * call-seq:
2658  * key_error.receiver -> object
2659  *
2660  * Return the receiver associated with this KeyError exception.
2661  */
2662 
2663 static VALUE
2664 key_err_receiver(VALUE self)
2665 {
2666  VALUE recv;
2667 
2668  recv = rb_ivar_lookup(self, id_receiver, Qundef);
2669  if (!UNDEF_P(recv)) return recv;
2670  rb_raise(rb_eArgError, "no receiver is available");
2671 }
2672 
2673 /*
2674  * call-seq:
2675  * key_error.key -> object
2676  *
2677  * Return the key caused this KeyError exception.
2678  */
2679 
2680 static VALUE
2681 key_err_key(VALUE self)
2682 {
2683  VALUE key;
2684 
2685  key = rb_ivar_lookup(self, id_key, Qundef);
2686  if (!UNDEF_P(key)) return key;
2687  rb_raise(rb_eArgError, "no key is available");
2688 }
2689 
2690 VALUE
2691 rb_key_err_new(VALUE mesg, VALUE recv, VALUE key)
2692 {
2694  rb_ivar_set(exc, id_mesg, mesg);
2695  rb_ivar_set(exc, id_bt, Qnil);
2696  rb_ivar_set(exc, id_key, key);
2697  rb_ivar_set(exc, id_receiver, recv);
2698  return exc;
2699 }
2700 
2701 /*
2702  * call-seq:
2703  * KeyError.new(message=nil, receiver: nil, key: nil) -> key_error
2704  *
2705  * Construct a new +KeyError+ exception with the given message,
2706  * receiver and key.
2707  */
2708 
2709 static VALUE
2710 key_err_initialize(int argc, VALUE *argv, VALUE self)
2711 {
2712  VALUE options;
2713 
2714  rb_call_super(rb_scan_args(argc, argv, "01:", NULL, &options), argv);
2715 
2716  if (!NIL_P(options)) {
2717  ID keywords[2];
2718  VALUE values[numberof(keywords)];
2719  int i;
2720  keywords[0] = id_receiver;
2721  keywords[1] = id_key;
2722  rb_get_kwargs(options, keywords, 0, numberof(values), values);
2723  for (i = 0; i < numberof(values); ++i) {
2724  if (!UNDEF_P(values[i])) {
2725  rb_ivar_set(self, keywords[i], values[i]);
2726  }
2727  }
2728  }
2729 
2730  return self;
2731 }
2732 
2733 /*
2734  * call-seq:
2735  * no_matching_pattern_key_error.matchee -> object
2736  *
2737  * Return the matchee associated with this NoMatchingPatternKeyError exception.
2738  */
2739 
2740 static VALUE
2741 no_matching_pattern_key_err_matchee(VALUE self)
2742 {
2743  VALUE matchee;
2744 
2745  matchee = rb_ivar_lookup(self, id_matchee, Qundef);
2746  if (!UNDEF_P(matchee)) return matchee;
2747  rb_raise(rb_eArgError, "no matchee is available");
2748 }
2749 
2750 /*
2751  * call-seq:
2752  * no_matching_pattern_key_error.key -> object
2753  *
2754  * Return the key caused this NoMatchingPatternKeyError exception.
2755  */
2756 
2757 static VALUE
2758 no_matching_pattern_key_err_key(VALUE self)
2759 {
2760  VALUE key;
2761 
2762  key = rb_ivar_lookup(self, id_key, Qundef);
2763  if (!UNDEF_P(key)) return key;
2764  rb_raise(rb_eArgError, "no key is available");
2765 }
2766 
2767 /*
2768  * call-seq:
2769  * NoMatchingPatternKeyError.new(message=nil, matchee: nil, key: nil) -> no_matching_pattern_key_error
2770  *
2771  * Construct a new +NoMatchingPatternKeyError+ exception with the given message,
2772  * matchee and key.
2773  */
2774 
2775 static VALUE
2776 no_matching_pattern_key_err_initialize(int argc, VALUE *argv, VALUE self)
2777 {
2778  VALUE options;
2779 
2780  rb_call_super(rb_scan_args(argc, argv, "01:", NULL, &options), argv);
2781 
2782  if (!NIL_P(options)) {
2783  ID keywords[2];
2784  VALUE values[numberof(keywords)];
2785  int i;
2786  keywords[0] = id_matchee;
2787  keywords[1] = id_key;
2788  rb_get_kwargs(options, keywords, 0, numberof(values), values);
2789  for (i = 0; i < numberof(values); ++i) {
2790  if (!UNDEF_P(values[i])) {
2791  rb_ivar_set(self, keywords[i], values[i]);
2792  }
2793  }
2794  }
2795 
2796  return self;
2797 }
2798 
2799 
2800 /*
2801  * call-seq:
2802  * SyntaxError.new([msg]) -> syntax_error
2803  *
2804  * Construct a SyntaxError exception.
2805  */
2806 
2807 static VALUE
2808 syntax_error_initialize(int argc, VALUE *argv, VALUE self)
2809 {
2810  VALUE mesg;
2811  if (argc == 0) {
2812  mesg = rb_fstring_lit("compile error");
2813  argc = 1;
2814  argv = &mesg;
2815  }
2816  return rb_call_super(argc, argv);
2817 }
2818 
2819 static VALUE
2820 syntax_error_with_path(VALUE exc, VALUE path, VALUE *mesg, rb_encoding *enc)
2821 {
2822  if (NIL_P(exc)) {
2823  *mesg = rb_enc_str_new(0, 0, enc);
2824  exc = rb_class_new_instance(1, mesg, rb_eSyntaxError);
2825  rb_ivar_set(exc, id_i_path, path);
2826  }
2827  else {
2828  VALUE old_path = rb_attr_get(exc, id_i_path);
2829  if (old_path != path) {
2830  if (rb_str_equal(path, old_path)) {
2831  rb_raise(rb_eArgError, "SyntaxError#path changed: %+"PRIsVALUE" (%p->%p)",
2832  old_path, (void *)old_path, (void *)path);
2833  }
2834  else {
2835  rb_raise(rb_eArgError, "SyntaxError#path changed: %+"PRIsVALUE"(%s%s)->%+"PRIsVALUE"(%s)",
2836  old_path, rb_enc_name(rb_enc_get(old_path)),
2837  (FL_TEST(old_path, RSTRING_FSTR) ? ":FSTR" : ""),
2838  path, rb_enc_name(rb_enc_get(path)));
2839  }
2840  }
2841  VALUE s = *mesg = rb_attr_get(exc, idMesg);
2842  if (RSTRING_LEN(s) > 0 && *(RSTRING_END(s)-1) != '\n')
2843  rb_str_cat_cstr(s, "\n");
2844  }
2845  return exc;
2846 }
2847 
2848 /*
2849  * Document-module: Errno
2850 
2851  * When an operating system encounters an error,
2852  * it typically reports the error as an integer error code:
2853  *
2854  * $ ls nosuch.txt
2855  * ls: cannot access 'nosuch.txt': No such file or directory
2856  * $ echo $? # Code for last error.
2857  * 2
2858  *
2859  * When the Ruby interpreter interacts with the operating system
2860  * and receives such an error code (e.g., +2+),
2861  * it maps the code to a particular Ruby exception class (e.g., +Errno::ENOENT+):
2862  *
2863  * File.open('nosuch.txt')
2864  * # => No such file or directory @ rb_sysopen - nosuch.txt (Errno::ENOENT)
2865  *
2866  * Each such class is:
2867  *
2868  * - A nested class in this module, +Errno+.
2869  * - A subclass of class SystemCallError.
2870  * - Associated with an error code.
2871  *
2872  * Thus:
2873  *
2874  * Errno::ENOENT.superclass # => SystemCallError
2875  * Errno::ENOENT::Errno # => 2
2876  *
2877  * The names of nested classes are returned by method +Errno.constants+:
2878  *
2879  * Errno.constants.size # => 158
2880  * Errno.constants.sort.take(5) # => [:E2BIG, :EACCES, :EADDRINUSE, :EADDRNOTAVAIL, :EADV]
2881  *
2882  * As seen above, the error code associated with each class
2883  * is available as the value of a constant;
2884  * the value for a particular class may vary among operating systems.
2885  * If the class is not needed for the particular operating system,
2886  * the value is zero:
2887  *
2888  * Errno::ENOENT::Errno # => 2
2889  * Errno::ENOTCAPABLE::Errno # => 0
2890  *
2891  */
2892 
2893 static st_table *syserr_tbl;
2894 
2895 void
2896 rb_free_warning(void)
2897 {
2898  st_free_table(warning_categories.id2enum);
2899  st_free_table(warning_categories.enum2id);
2900  st_free_table(syserr_tbl);
2901 }
2902 
2903 static VALUE
2904 setup_syserr(int n, const char *name)
2905 {
2907 
2908  /* capture nonblock errnos for WaitReadable/WaitWritable subclasses */
2909  switch (n) {
2910  case EAGAIN:
2911  rb_eEAGAIN = error;
2912 
2913 #if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
2914  break;
2915  case EWOULDBLOCK:
2916 #endif
2917 
2918  rb_eEWOULDBLOCK = error;
2919  break;
2920  case EINPROGRESS:
2921  rb_eEINPROGRESS = error;
2922  break;
2923  }
2924 
2925  rb_define_const(error, "Errno", INT2NUM(n));
2926  st_add_direct(syserr_tbl, n, (st_data_t)error);
2927  return error;
2928 }
2929 
2930 static VALUE
2931 set_syserr(int n, const char *name)
2932 {
2933  st_data_t error;
2934 
2935  if (!st_lookup(syserr_tbl, n, &error)) {
2936  return setup_syserr(n, name);
2937  }
2938  else {
2939  VALUE errclass = (VALUE)error;
2940  rb_define_const(rb_mErrno, name, errclass);
2941  return errclass;
2942  }
2943 }
2944 
2945 static VALUE
2946 get_syserr(int n)
2947 {
2948  st_data_t error;
2949 
2950  if (!st_lookup(syserr_tbl, n, &error)) {
2951  char name[DECIMAL_SIZE_OF(n) + sizeof("E-")];
2952 
2953  snprintf(name, sizeof(name), "E%03d", n);
2954  return setup_syserr(n, name);
2955  }
2956  return (VALUE)error;
2957 }
2958 
2959 /*
2960  * call-seq:
2961  * SystemCallError.new(msg, errno) -> system_call_error_subclass
2962  *
2963  * If _errno_ corresponds to a known system error code, constructs the
2964  * appropriate Errno class for that error, otherwise constructs a
2965  * generic SystemCallError object. The error number is subsequently
2966  * available via the #errno method.
2967  */
2968 
2969 static VALUE
2970 syserr_initialize(int argc, VALUE *argv, VALUE self)
2971 {
2972  const char *err;
2973  VALUE mesg, error, func, errmsg;
2974  VALUE klass = rb_obj_class(self);
2975 
2976  if (klass == rb_eSystemCallError) {
2977  st_data_t data = (st_data_t)klass;
2978  rb_scan_args(argc, argv, "12", &mesg, &error, &func);
2979  if (argc == 1 && FIXNUM_P(mesg)) {
2980  error = mesg; mesg = Qnil;
2981  }
2982  if (!NIL_P(error) && st_lookup(syserr_tbl, NUM2LONG(error), &data)) {
2983  klass = (VALUE)data;
2984  /* change class */
2985  if (!RB_TYPE_P(self, T_OBJECT)) { /* insurance to avoid type crash */
2986  rb_raise(rb_eTypeError, "invalid instance type");
2987  }
2988  RBASIC_SET_CLASS(self, klass);
2989  }
2990  }
2991  else {
2992  rb_scan_args(argc, argv, "02", &mesg, &func);
2993  error = rb_const_get(klass, id_Errno);
2994  }
2995  if (!NIL_P(error)) err = strerror(NUM2INT(error));
2996  else err = "unknown error";
2997 
2998  errmsg = rb_enc_str_new_cstr(err, rb_locale_encoding());
2999  if (!NIL_P(mesg)) {
3000  VALUE str = StringValue(mesg);
3001 
3002  if (!NIL_P(func)) rb_str_catf(errmsg, " @ %"PRIsVALUE, func);
3003  rb_str_catf(errmsg, " - %"PRIsVALUE, str);
3004  }
3005  mesg = errmsg;
3006 
3007  rb_call_super(1, &mesg);
3008  rb_ivar_set(self, id_errno, error);
3009  return self;
3010 }
3011 
3012 /*
3013  * call-seq:
3014  * system_call_error.errno -> integer
3015  *
3016  * Return this SystemCallError's error number.
3017  */
3018 
3019 static VALUE
3020 syserr_errno(VALUE self)
3021 {
3022  return rb_attr_get(self, id_errno);
3023 }
3024 
3025 /*
3026  * call-seq:
3027  * system_call_error === other -> true or false
3028  *
3029  * Return +true+ if the receiver is a generic +SystemCallError+, or
3030  * if the error numbers +self+ and _other_ are the same.
3031  */
3032 
3033 static VALUE
3034 syserr_eqq(VALUE self, VALUE exc)
3035 {
3036  VALUE num, e;
3037 
3039  if (!rb_respond_to(exc, id_errno)) return Qfalse;
3040  }
3041  else if (self == rb_eSystemCallError) return Qtrue;
3042 
3043  num = rb_attr_get(exc, id_errno);
3044  if (NIL_P(num)) {
3045  num = rb_funcallv(exc, id_errno, 0, 0);
3046  }
3047  e = rb_const_get(self, id_Errno);
3048  return RBOOL(FIXNUM_P(num) ? num == e : rb_equal(num, e));
3049 }
3050 
3051 
3052 /*
3053  * Document-class: StandardError
3054  *
3055  * The most standard error types are subclasses of StandardError. A
3056  * rescue clause without an explicit Exception class will rescue all
3057  * StandardErrors (and only those).
3058  *
3059  * def foo
3060  * raise "Oups"
3061  * end
3062  * foo rescue "Hello" #=> "Hello"
3063  *
3064  * On the other hand:
3065  *
3066  * require 'does/not/exist' rescue "Hi"
3067  *
3068  * <em>raises the exception:</em>
3069  *
3070  * LoadError: no such file to load -- does/not/exist
3071  *
3072  */
3073 
3074 /*
3075  * Document-class: SystemExit
3076  *
3077  * Raised by +exit+ to initiate the termination of the script.
3078  */
3079 
3080 /*
3081  * Document-class: SignalException
3082  *
3083  * Raised when a signal is received.
3084  *
3085  * begin
3086  * Process.kill('HUP',Process.pid)
3087  * sleep # wait for receiver to handle signal sent by Process.kill
3088  * rescue SignalException => e
3089  * puts "received Exception #{e}"
3090  * end
3091  *
3092  * <em>produces:</em>
3093  *
3094  * received Exception SIGHUP
3095  */
3096 
3097 /*
3098  * Document-class: Interrupt
3099  *
3100  * Raised when the interrupt signal is received, typically because the
3101  * user has pressed Control-C (on most posix platforms). As such, it is a
3102  * subclass of +SignalException+.
3103  *
3104  * begin
3105  * puts "Press ctrl-C when you get bored"
3106  * loop {}
3107  * rescue Interrupt => e
3108  * puts "Note: You will typically use Signal.trap instead."
3109  * end
3110  *
3111  * <em>produces:</em>
3112  *
3113  * Press ctrl-C when you get bored
3114  *
3115  * <em>then waits until it is interrupted with Control-C and then prints:</em>
3116  *
3117  * Note: You will typically use Signal.trap instead.
3118  */
3119 
3120 /*
3121  * Document-class: TypeError
3122  *
3123  * Raised when encountering an object that is not of the expected type.
3124  *
3125  * [1, 2, 3].first("two")
3126  *
3127  * <em>raises the exception:</em>
3128  *
3129  * TypeError: no implicit conversion of String into Integer
3130  *
3131  */
3132 
3133 /*
3134  * Document-class: ArgumentError
3135  *
3136  * Raised when the arguments are wrong and there isn't a more specific
3137  * Exception class.
3138  *
3139  * Ex: passing the wrong number of arguments
3140  *
3141  * [1, 2, 3].first(4, 5)
3142  *
3143  * <em>raises the exception:</em>
3144  *
3145  * ArgumentError: wrong number of arguments (given 2, expected 1)
3146  *
3147  * Ex: passing an argument that is not acceptable:
3148  *
3149  * [1, 2, 3].first(-4)
3150  *
3151  * <em>raises the exception:</em>
3152  *
3153  * ArgumentError: negative array size
3154  */
3155 
3156 /*
3157  * Document-class: IndexError
3158  *
3159  * Raised when the given index is invalid.
3160  *
3161  * a = [:foo, :bar]
3162  * a.fetch(0) #=> :foo
3163  * a[4] #=> nil
3164  * a.fetch(4) #=> IndexError: index 4 outside of array bounds: -2...2
3165  *
3166  */
3167 
3168 /*
3169  * Document-class: KeyError
3170  *
3171  * Raised when the specified key is not found. It is a subclass of
3172  * IndexError.
3173  *
3174  * h = {"foo" => :bar}
3175  * h.fetch("foo") #=> :bar
3176  * h.fetch("baz") #=> KeyError: key not found: "baz"
3177  *
3178  */
3179 
3180 /*
3181  * Document-class: RangeError
3182  *
3183  * Raised when a given numerical value is out of range.
3184  *
3185  * [1, 2, 3].drop(1 << 100)
3186  *
3187  * <em>raises the exception:</em>
3188  *
3189  * RangeError: bignum too big to convert into `long'
3190  */
3191 
3192 /*
3193  * Document-class: ScriptError
3194  *
3195  * ScriptError is the superclass for errors raised when a script
3196  * can not be executed because of a +LoadError+,
3197  * +NotImplementedError+ or a +SyntaxError+. Note these type of
3198  * +ScriptErrors+ are not +StandardError+ and will not be
3199  * rescued unless it is specified explicitly (or its ancestor
3200  * +Exception+).
3201  */
3202 
3203 /*
3204  * Document-class: SyntaxError
3205  *
3206  * Raised when encountering Ruby code with an invalid syntax.
3207  *
3208  * eval("1+1=2")
3209  *
3210  * <em>raises the exception:</em>
3211  *
3212  * SyntaxError: (eval):1: syntax error, unexpected '=', expecting $end
3213  */
3214 
3215 /*
3216  * Document-class: LoadError
3217  *
3218  * Raised when a file required (a Ruby script, extension library, ...)
3219  * fails to load.
3220  *
3221  * require 'this/file/does/not/exist'
3222  *
3223  * <em>raises the exception:</em>
3224  *
3225  * LoadError: no such file to load -- this/file/does/not/exist
3226  */
3227 
3228 /*
3229  * Document-class: NotImplementedError
3230  *
3231  * Raised when a feature is not implemented on the current platform. For
3232  * example, methods depending on the +fsync+ or +fork+ system calls may
3233  * raise this exception if the underlying operating system or Ruby
3234  * runtime does not support them.
3235  *
3236  * Note that if +fork+ raises a +NotImplementedError+, then
3237  * <code>respond_to?(:fork)</code> returns +false+.
3238  */
3239 
3240 /*
3241  * Document-class: NameError
3242  *
3243  * Raised when a given name is invalid or undefined.
3244  *
3245  * puts foo
3246  *
3247  * <em>raises the exception:</em>
3248  *
3249  * NameError: undefined local variable or method `foo' for main:Object
3250  *
3251  * Since constant names must start with a capital:
3252  *
3253  * Integer.const_set :answer, 42
3254  *
3255  * <em>raises the exception:</em>
3256  *
3257  * NameError: wrong constant name answer
3258  */
3259 
3260 /*
3261  * Document-class: NoMethodError
3262  *
3263  * Raised when a method is called on a receiver which doesn't have it
3264  * defined and also fails to respond with +method_missing+.
3265  *
3266  * "hello".to_ary
3267  *
3268  * <em>raises the exception:</em>
3269  *
3270  * NoMethodError: undefined method `to_ary' for an instance of String
3271  */
3272 
3273 /*
3274  * Document-class: FrozenError
3275  *
3276  * Raised when there is an attempt to modify a frozen object.
3277  *
3278  * [1, 2, 3].freeze << 4
3279  *
3280  * <em>raises the exception:</em>
3281  *
3282  * FrozenError: can't modify frozen Array
3283  */
3284 
3285 /*
3286  * Document-class: RuntimeError
3287  *
3288  * A generic error class raised when an invalid operation is attempted.
3289  * Kernel#raise will raise a RuntimeError if no Exception class is
3290  * specified.
3291  *
3292  * raise "ouch"
3293  *
3294  * <em>raises the exception:</em>
3295  *
3296  * RuntimeError: ouch
3297  */
3298 
3299 /*
3300  * Document-class: SecurityError
3301  *
3302  * No longer used by internal code.
3303  */
3304 
3305 /*
3306  * Document-class: NoMemoryError
3307  *
3308  * Raised when memory allocation fails.
3309  */
3310 
3311 /*
3312  * Document-class: SystemCallError
3313  *
3314  * SystemCallError is the base class for all low-level
3315  * platform-dependent errors.
3316  *
3317  * The errors available on the current platform are subclasses of
3318  * SystemCallError and are defined in the Errno module.
3319  *
3320  * File.open("does/not/exist")
3321  *
3322  * <em>raises the exception:</em>
3323  *
3324  * Errno::ENOENT: No such file or directory - does/not/exist
3325  */
3326 
3327 /*
3328  * Document-class: EncodingError
3329  *
3330  * EncodingError is the base class for encoding errors.
3331  */
3332 
3333 /*
3334  * Document-class: Encoding::CompatibilityError
3335  *
3336  * Raised by Encoding and String methods when the source encoding is
3337  * incompatible with the target encoding.
3338  */
3339 
3340 /*
3341  * Document-class: fatal
3342  *
3343  * +fatal+ is an Exception that is raised when Ruby has encountered a fatal
3344  * error and must exit.
3345  */
3346 
3347 /*
3348  * Document-class: NameError::message
3349  * :nodoc:
3350  */
3351 
3352 /*
3353  * Document-class: Exception
3354  *
3355  * \Class +Exception+ and its subclasses are used to indicate that an error
3356  * or other problem has occurred,
3357  * and may need to be handled.
3358  * See {Exceptions}[rdoc-ref:exceptions.md].
3359  *
3360  * An +Exception+ object carries certain information:
3361  *
3362  * - The type (the exception's class),
3363  * commonly StandardError, RuntimeError, or a subclass of one or the other;
3364  * see {Built-In Exception Class Hierarchy}[rdoc-ref:Exception@Built-In+Exception+Class+Hierarchy].
3365  * - An optional descriptive message;
3366  * see methods ::new, #message.
3367  * - Optional backtrace information;
3368  * see methods #backtrace, #backtrace_locations, #set_backtrace.
3369  * - An optional cause;
3370  * see method #cause.
3371  *
3372  * == Built-In \Exception \Class Hierarchy
3373  *
3374  * The hierarchy of built-in subclasses of class +Exception+:
3375  *
3376  * * NoMemoryError
3377  * * ScriptError
3378  * * {LoadError}[https://docs.ruby-lang.org/en/master/LoadError.html]
3379  * * NotImplementedError
3380  * * SyntaxError
3381  * * SecurityError
3382  * * SignalException
3383  * * Interrupt
3384  * * StandardError
3385  * * ArgumentError
3386  * * UncaughtThrowError
3387  * * EncodingError
3388  * * FiberError
3389  * * IOError
3390  * * EOFError
3391  * * IndexError
3392  * * KeyError
3393  * * StopIteration
3394  * * ClosedQueueError
3395  * * LocalJumpError
3396  * * NameError
3397  * * NoMethodError
3398  * * RangeError
3399  * * FloatDomainError
3400  * * RegexpError
3401  * * RuntimeError
3402  * * FrozenError
3403  * * SystemCallError
3404  * * Errno (and its subclasses, representing system errors)
3405  * * ThreadError
3406  * * TypeError
3407  * * ZeroDivisionError
3408  * * SystemExit
3409  * * SystemStackError
3410  * * {fatal}[https://docs.ruby-lang.org/en/master/fatal.html]
3411  *
3412  */
3413 
3414 static VALUE
3415 exception_alloc(VALUE klass)
3416 {
3417  return rb_class_allocate_instance(klass);
3418 }
3419 
3420 static VALUE
3421 exception_dumper(VALUE exc)
3422 {
3423  // TODO: Currently, the instance variables "bt" and "bt_locations"
3424  // refers to the same object (Array of String). But "bt_locations"
3425  // should have an Array of Thread::Backtrace::Locations.
3426 
3427  return exc;
3428 }
3429 
3430 static int
3431 ivar_copy_i(ID key, VALUE val, st_data_t exc)
3432 {
3433  rb_ivar_set((VALUE)exc, key, val);
3434  return ST_CONTINUE;
3435 }
3436 
3437 void rb_exc_check_circular_cause(VALUE exc);
3438 
3439 static VALUE
3440 exception_loader(VALUE exc, VALUE obj)
3441 {
3442  // The loader function of rb_marshal_define_compat seems to be called for two events:
3443  // one is for fixup (r_fixup_compat), the other is for TYPE_USERDEF.
3444  // In the former case, the first argument is an instance of Exception (because
3445  // we pass rb_eException to rb_marshal_define_compat). In the latter case, the first
3446  // argument is a class object (see TYPE_USERDEF case in r_object0).
3447  // We want to copy all instance variables (but "bt_locations") from obj to exc.
3448  // But we do not want to do so in the second case, so the following branch is for that.
3449  if (RB_TYPE_P(exc, T_CLASS)) return obj; // maybe called from Marshal's TYPE_USERDEF
3450 
3451  rb_ivar_foreach(obj, ivar_copy_i, exc);
3452 
3453  rb_exc_check_circular_cause(exc);
3454 
3455  if (rb_attr_get(exc, id_bt) == rb_attr_get(exc, id_bt_locations)) {
3456  rb_ivar_set(exc, id_bt_locations, Qnil);
3457  }
3458 
3459  return exc;
3460 }
3461 
3462 void
3463 Init_Exception(void)
3464 {
3465  rb_eException = rb_define_class("Exception", rb_cObject);
3466  rb_define_alloc_func(rb_eException, exception_alloc);
3467  rb_marshal_define_compat(rb_eException, rb_eException, exception_dumper, exception_loader);
3469  rb_define_singleton_method(rb_eException, "to_tty?", exc_s_to_tty_p, 0);
3470  rb_define_method(rb_eException, "exception", exc_exception, -1);
3471  rb_define_method(rb_eException, "initialize", exc_initialize, -1);
3472  rb_define_method(rb_eException, "==", exc_equal, 1);
3473  rb_define_method(rb_eException, "to_s", exc_to_s, 0);
3474  rb_define_method(rb_eException, "message", exc_message, 0);
3475  rb_define_method(rb_eException, "detailed_message", exc_detailed_message, -1);
3476  rb_define_method(rb_eException, "full_message", exc_full_message, -1);
3477  rb_define_method(rb_eException, "inspect", exc_inspect, 0);
3478  rb_define_method(rb_eException, "backtrace", exc_backtrace, 0);
3479  rb_define_method(rb_eException, "backtrace_locations", exc_backtrace_locations, 0);
3480  rb_define_method(rb_eException, "set_backtrace", exc_set_backtrace, 1);
3481  rb_define_method(rb_eException, "cause", exc_cause, 0);
3482 
3483  rb_eSystemExit = rb_define_class("SystemExit", rb_eException);
3484  rb_define_method(rb_eSystemExit, "initialize", exit_initialize, -1);
3485  rb_define_method(rb_eSystemExit, "status", exit_status, 0);
3486  rb_define_method(rb_eSystemExit, "success?", exit_success_p, 0);
3487 
3489  rb_eSignal = rb_define_class("SignalException", rb_eException);
3490  rb_eInterrupt = rb_define_class("Interrupt", rb_eSignal);
3491 
3492  rb_eStandardError = rb_define_class("StandardError", rb_eException);
3494  rb_eArgError = rb_define_class("ArgumentError", rb_eStandardError);
3497  rb_define_method(rb_eKeyError, "initialize", key_err_initialize, -1);
3498  rb_define_method(rb_eKeyError, "receiver", key_err_receiver, 0);
3499  rb_define_method(rb_eKeyError, "key", key_err_key, 0);
3501 
3502  rb_eScriptError = rb_define_class("ScriptError", rb_eException);
3504  rb_define_method(rb_eSyntaxError, "initialize", syntax_error_initialize, -1);
3505 
3506  /* RDoc will use literal name value while parsing rb_attr,
3507  * and will render `idPath` as an attribute name without this trick */
3508  ID path = idPath;
3509 
3510  /* the path that failed to parse */
3511  rb_attr(rb_eSyntaxError, path, TRUE, FALSE, FALSE);
3512 
3514  /* the path that failed to load */
3515  rb_attr(rb_eLoadError, path, TRUE, FALSE, FALSE);
3516 
3517  rb_eNotImpError = rb_define_class("NotImplementedError", rb_eScriptError);
3518 
3520  rb_define_method(rb_eNameError, "initialize", name_err_initialize, -1);
3521  rb_define_method(rb_eNameError, "name", name_err_name, 0);
3522  rb_define_method(rb_eNameError, "receiver", name_err_receiver, 0);
3523  rb_define_method(rb_eNameError, "local_variables", name_err_local_variables, 0);
3524  rb_cNameErrorMesg = rb_define_class_under(rb_eNameError, "message", rb_cObject);
3525  rb_define_alloc_func(rb_cNameErrorMesg, name_err_mesg_alloc);
3526  rb_define_method(rb_cNameErrorMesg, "initialize_copy", name_err_mesg_init_copy, 1);
3527  rb_define_method(rb_cNameErrorMesg, "==", name_err_mesg_equal, 1);
3528  rb_define_method(rb_cNameErrorMesg, "to_str", name_err_mesg_to_str, 0);
3529  rb_define_method(rb_cNameErrorMesg, "_dump", name_err_mesg_dump, 1);
3530  rb_define_singleton_method(rb_cNameErrorMesg, "_load", name_err_mesg_load, 1);
3531  rb_eNoMethodError = rb_define_class("NoMethodError", rb_eNameError);
3532  rb_define_method(rb_eNoMethodError, "initialize", nometh_err_initialize, -1);
3533  rb_define_method(rb_eNoMethodError, "args", nometh_err_args, 0);
3534  rb_define_method(rb_eNoMethodError, "private_call?", nometh_err_private_call_p, 0);
3535 
3538  rb_define_method(rb_eFrozenError, "initialize", frozen_err_initialize, -1);
3539  rb_define_method(rb_eFrozenError, "receiver", frozen_err_receiver, 0);
3540  rb_eSecurityError = rb_define_class("SecurityError", rb_eException);
3541  rb_eNoMemError = rb_define_class("NoMemoryError", rb_eException);
3544  rb_eNoMatchingPatternError = rb_define_class("NoMatchingPatternError", rb_eStandardError);
3546  rb_define_method(rb_eNoMatchingPatternKeyError, "initialize", no_matching_pattern_key_err_initialize, -1);
3547  rb_define_method(rb_eNoMatchingPatternKeyError, "matchee", no_matching_pattern_key_err_matchee, 0);
3548  rb_define_method(rb_eNoMatchingPatternKeyError, "key", no_matching_pattern_key_err_key, 0);
3549 
3550  syserr_tbl = st_init_numtable();
3552  rb_define_method(rb_eSystemCallError, "initialize", syserr_initialize, -1);
3553  rb_define_method(rb_eSystemCallError, "errno", syserr_errno, 0);
3554  rb_define_singleton_method(rb_eSystemCallError, "===", syserr_eqq, 1);
3555 
3556  rb_mErrno = rb_define_module("Errno");
3557 
3558  rb_mWarning = rb_define_module("Warning");
3559  rb_define_singleton_method(rb_mWarning, "[]", rb_warning_s_aref, 1);
3560  rb_define_singleton_method(rb_mWarning, "[]=", rb_warning_s_aset, 2);
3561  rb_define_singleton_method(rb_mWarning, "categories", rb_warning_s_categories, 0);
3562  rb_define_method(rb_mWarning, "warn", rb_warning_s_warn, -1);
3563  rb_extend_object(rb_mWarning, rb_mWarning);
3564 
3565  /* :nodoc: */
3566  rb_cWarningBuffer = rb_define_class_under(rb_mWarning, "buffer", rb_cString);
3567  rb_define_method(rb_cWarningBuffer, "write", warning_write, -1);
3568 
3569  id_cause = rb_intern_const("cause");
3570  id_message = rb_intern_const("message");
3571  id_detailed_message = rb_intern_const("detailed_message");
3572  id_backtrace = rb_intern_const("backtrace");
3573  id_key = rb_intern_const("key");
3574  id_matchee = rb_intern_const("matchee");
3575  id_args = rb_intern_const("args");
3576  id_receiver = rb_intern_const("receiver");
3577  id_private_call_p = rb_intern_const("private_call?");
3578  id_local_variables = rb_intern_const("local_variables");
3579  id_Errno = rb_intern_const("Errno");
3580  id_errno = rb_intern_const("errno");
3581  id_i_path = rb_intern_const("@path");
3582  id_warn = rb_intern_const("warn");
3583  id_category = rb_intern_const("category");
3584  id_deprecated = rb_intern_const("deprecated");
3585  id_experimental = rb_intern_const("experimental");
3586  id_performance = rb_intern_const("performance");
3587  id_top = rb_intern_const("top");
3588  id_bottom = rb_intern_const("bottom");
3589  id_iseq = rb_make_internal_id();
3590  id_recv = rb_make_internal_id();
3591 
3592  sym_category = ID2SYM(id_category);
3593  sym_highlight = ID2SYM(rb_intern_const("highlight"));
3594 
3595  warning_categories.id2enum = rb_init_identtable();
3596  st_add_direct(warning_categories.id2enum, id_deprecated, RB_WARN_CATEGORY_DEPRECATED);
3597  st_add_direct(warning_categories.id2enum, id_experimental, RB_WARN_CATEGORY_EXPERIMENTAL);
3598  st_add_direct(warning_categories.id2enum, id_performance, RB_WARN_CATEGORY_PERFORMANCE);
3599 
3600  warning_categories.enum2id = rb_init_identtable();
3601  st_add_direct(warning_categories.enum2id, RB_WARN_CATEGORY_NONE, 0);
3602  st_add_direct(warning_categories.enum2id, RB_WARN_CATEGORY_DEPRECATED, id_deprecated);
3603  st_add_direct(warning_categories.enum2id, RB_WARN_CATEGORY_EXPERIMENTAL, id_experimental);
3604  st_add_direct(warning_categories.enum2id, RB_WARN_CATEGORY_PERFORMANCE, id_performance);
3605 }
3606 
3607 void
3608 rb_enc_raise(rb_encoding *enc, VALUE exc, const char *fmt, ...)
3609 {
3610  va_list args;
3611  VALUE mesg;
3612 
3613  va_start(args, fmt);
3614  mesg = rb_enc_vsprintf(enc, fmt, args);
3615  va_end(args);
3616 
3617  rb_exc_raise(rb_exc_new3(exc, mesg));
3618 }
3619 
3620 void
3621 rb_vraise(VALUE exc, const char *fmt, va_list ap)
3622 {
3623  rb_exc_raise(rb_exc_new3(exc, rb_vsprintf(fmt, ap)));
3624 }
3625 
3626 void
3627 rb_raise(VALUE exc, const char *fmt, ...)
3628 {
3629  va_list args;
3630  va_start(args, fmt);
3631  rb_vraise(exc, fmt, args);
3632  va_end(args);
3633 }
3634 
3635 NORETURN(static void raise_loaderror(VALUE path, VALUE mesg));
3636 
3637 static void
3638 raise_loaderror(VALUE path, VALUE mesg)
3639 {
3640  VALUE err = rb_exc_new3(rb_eLoadError, mesg);
3641  rb_ivar_set(err, id_i_path, path);
3642  rb_exc_raise(err);
3643 }
3644 
3645 void
3646 rb_loaderror(const char *fmt, ...)
3647 {
3648  va_list args;
3649  VALUE mesg;
3650 
3651  va_start(args, fmt);
3652  mesg = rb_enc_vsprintf(rb_locale_encoding(), fmt, args);
3653  va_end(args);
3654  raise_loaderror(Qnil, mesg);
3655 }
3656 
3657 void
3658 rb_loaderror_with_path(VALUE path, const char *fmt, ...)
3659 {
3660  va_list args;
3661  VALUE mesg;
3662 
3663  va_start(args, fmt);
3664  mesg = rb_enc_vsprintf(rb_locale_encoding(), fmt, args);
3665  va_end(args);
3666  raise_loaderror(path, mesg);
3667 }
3668 
3669 void
3671 {
3673  "%"PRIsVALUE"() function is unimplemented on this machine",
3675 }
3676 
3677 void
3678 rb_fatal(const char *fmt, ...)
3679 {
3680  va_list args;
3681  VALUE mesg;
3682 
3683  if (! ruby_thread_has_gvl_p()) {
3684  /* The thread has no GVL. Object allocation impossible (cant run GC),
3685  * thus no message can be printed out. */
3686  fprintf(stderr, "[FATAL] rb_fatal() outside of GVL\n");
3687  rb_print_backtrace(stderr);
3688  die();
3689  }
3690 
3691  va_start(args, fmt);
3692  mesg = rb_vsprintf(fmt, args);
3693  va_end(args);
3694 
3696 }
3697 
3698 static VALUE
3699 make_errno_exc(const char *mesg)
3700 {
3701  int n = errno;
3702 
3703  errno = 0;
3704  if (n == 0) {
3705  rb_bug("rb_sys_fail(%s) - errno == 0", mesg ? mesg : "");
3706  }
3707  return rb_syserr_new(n, mesg);
3708 }
3709 
3710 static VALUE
3711 make_errno_exc_str(VALUE mesg)
3712 {
3713  int n = errno;
3714 
3715  errno = 0;
3716  if (!mesg) mesg = Qnil;
3717  if (n == 0) {
3718  const char *s = !NIL_P(mesg) ? RSTRING_PTR(mesg) : "";
3719  rb_bug("rb_sys_fail_str(%s) - errno == 0", s);
3720  }
3721  return rb_syserr_new_str(n, mesg);
3722 }
3723 
3724 VALUE
3725 rb_syserr_new(int n, const char *mesg)
3726 {
3727  VALUE arg;
3728  arg = mesg ? rb_str_new2(mesg) : Qnil;
3729  return rb_syserr_new_str(n, arg);
3730 }
3731 
3732 VALUE
3734 {
3735  return rb_class_new_instance(1, &arg, get_syserr(n));
3736 }
3737 
3738 void
3739 rb_syserr_fail(int e, const char *mesg)
3740 {
3741  rb_exc_raise(rb_syserr_new(e, mesg));
3742 }
3743 
3744 void
3746 {
3747  rb_exc_raise(rb_syserr_new_str(e, mesg));
3748 }
3749 
3750 #undef rb_sys_fail
3751 void
3752 rb_sys_fail(const char *mesg)
3753 {
3754  rb_exc_raise(make_errno_exc(mesg));
3755 }
3756 
3757 #undef rb_sys_fail_str
3758 void
3760 {
3761  rb_exc_raise(make_errno_exc_str(mesg));
3762 }
3763 
3764 #ifdef RUBY_FUNCTION_NAME_STRING
3765 void
3766 rb_sys_fail_path_in(const char *func_name, VALUE path)
3767 {
3768  int n = errno;
3769 
3770  errno = 0;
3771  rb_syserr_fail_path_in(func_name, n, path);
3772 }
3773 
3774 void
3775 rb_syserr_fail_path_in(const char *func_name, int n, VALUE path)
3776 {
3777  rb_exc_raise(rb_syserr_new_path_in(func_name, n, path));
3778 }
3779 
3780 VALUE
3781 rb_syserr_new_path_in(const char *func_name, int n, VALUE path)
3782 {
3783  VALUE args[2];
3784 
3785  if (!path) path = Qnil;
3786  if (n == 0) {
3787  const char *s = !NIL_P(path) ? RSTRING_PTR(path) : "";
3788  if (!func_name) func_name = "(null)";
3789  rb_bug("rb_sys_fail_path_in(%s, %s) - errno == 0",
3790  func_name, s);
3791  }
3792  args[0] = path;
3793  args[1] = rb_str_new_cstr(func_name);
3794  return rb_class_new_instance(2, args, get_syserr(n));
3795 }
3796 #endif
3797 
3798 NORETURN(static void rb_mod_exc_raise(VALUE exc, VALUE mod));
3799 
3800 static void
3801 rb_mod_exc_raise(VALUE exc, VALUE mod)
3802 {
3803  rb_extend_object(exc, mod);
3804  rb_exc_raise(exc);
3805 }
3806 
3807 void
3808 rb_mod_sys_fail(VALUE mod, const char *mesg)
3809 {
3810  VALUE exc = make_errno_exc(mesg);
3811  rb_mod_exc_raise(exc, mod);
3812 }
3813 
3814 void
3816 {
3817  VALUE exc = make_errno_exc_str(mesg);
3818  rb_mod_exc_raise(exc, mod);
3819 }
3820 
3821 void
3822 rb_mod_syserr_fail(VALUE mod, int e, const char *mesg)
3823 {
3824  VALUE exc = rb_syserr_new(e, mesg);
3825  rb_mod_exc_raise(exc, mod);
3826 }
3827 
3828 void
3830 {
3831  VALUE exc = rb_syserr_new_str(e, mesg);
3832  rb_mod_exc_raise(exc, mod);
3833 }
3834 
3835 static void
3836 syserr_warning(VALUE mesg, int err)
3837 {
3838  rb_str_set_len(mesg, RSTRING_LEN(mesg)-1);
3839  rb_str_catf(mesg, ": %s\n", strerror(err));
3840  rb_write_warning_str(mesg);
3841 }
3842 
3843 #if 0
3844 void
3845 rb_sys_warn(const char *fmt, ...)
3846 {
3847  if (!NIL_P(ruby_verbose)) {
3848  int errno_save = errno;
3849  with_warning_string(mesg, 0, fmt) {
3850  syserr_warning(mesg, errno_save);
3851  }
3852  errno = errno_save;
3853  }
3854 }
3855 
3856 void
3857 rb_syserr_warn(int err, const char *fmt, ...)
3858 {
3859  if (!NIL_P(ruby_verbose)) {
3860  with_warning_string(mesg, 0, fmt) {
3861  syserr_warning(mesg, err);
3862  }
3863  }
3864 }
3865 
3866 void
3867 rb_sys_enc_warn(rb_encoding *enc, const char *fmt, ...)
3868 {
3869  if (!NIL_P(ruby_verbose)) {
3870  int errno_save = errno;
3871  with_warning_string(mesg, enc, fmt) {
3872  syserr_warning(mesg, errno_save);
3873  }
3874  errno = errno_save;
3875  }
3876 }
3877 
3878 void
3879 rb_syserr_enc_warn(int err, rb_encoding *enc, const char *fmt, ...)
3880 {
3881  if (!NIL_P(ruby_verbose)) {
3882  with_warning_string(mesg, enc, fmt) {
3883  syserr_warning(mesg, err);
3884  }
3885  }
3886 }
3887 #endif
3888 
3889 void
3890 rb_sys_warning(const char *fmt, ...)
3891 {
3892  if (RTEST(ruby_verbose)) {
3893  int errno_save = errno;
3894  with_warning_string(mesg, 0, fmt) {
3895  syserr_warning(mesg, errno_save);
3896  }
3897  errno = errno_save;
3898  }
3899 }
3900 
3901 #if 0
3902 void
3903 rb_syserr_warning(int err, const char *fmt, ...)
3904 {
3905  if (RTEST(ruby_verbose)) {
3906  with_warning_string(mesg, 0, fmt) {
3907  syserr_warning(mesg, err);
3908  }
3909  }
3910 }
3911 #endif
3912 
3913 void
3914 rb_sys_enc_warning(rb_encoding *enc, const char *fmt, ...)
3915 {
3916  if (RTEST(ruby_verbose)) {
3917  int errno_save = errno;
3918  with_warning_string(mesg, enc, fmt) {
3919  syserr_warning(mesg, errno_save);
3920  }
3921  errno = errno_save;
3922  }
3923 }
3924 
3925 void
3926 rb_syserr_enc_warning(int err, rb_encoding *enc, const char *fmt, ...)
3927 {
3928  if (RTEST(ruby_verbose)) {
3929  with_warning_string(mesg, enc, fmt) {
3930  syserr_warning(mesg, err);
3931  }
3932  }
3933 }
3934 
3935 void
3936 rb_load_fail(VALUE path, const char *err)
3937 {
3938  VALUE mesg = rb_str_buf_new_cstr(err);
3939  rb_str_cat2(mesg, " -- ");
3940  rb_str_append(mesg, path); /* should be ASCII compatible */
3941  raise_loaderror(path, mesg);
3942 }
3943 
3944 void
3945 rb_error_frozen(const char *what)
3946 {
3947  rb_raise(rb_eFrozenError, "can't modify frozen %s", what);
3948 }
3949 
3950 void
3951 rb_frozen_error_raise(VALUE frozen_obj, const char *fmt, ...)
3952 {
3953  va_list args;
3954  VALUE exc, mesg;
3955 
3956  va_start(args, fmt);
3957  mesg = rb_vsprintf(fmt, args);
3958  va_end(args);
3959  exc = rb_exc_new3(rb_eFrozenError, mesg);
3960  rb_ivar_set(exc, id_recv, frozen_obj);
3961  rb_exc_raise(exc);
3962 }
3963 
3964 static VALUE
3965 inspect_frozen_obj(VALUE obj, VALUE mesg, int recur)
3966 {
3967  if (recur) {
3968  rb_str_cat_cstr(mesg, " ...");
3969  }
3970  else {
3971  rb_str_append(mesg, rb_inspect(obj));
3972  }
3973  return mesg;
3974 }
3975 
3976 static VALUE
3977 get_created_info(VALUE obj, int *pline)
3978 {
3979  VALUE info = rb_attr_get(obj, id_debug_created_info);
3980 
3981  if (NIL_P(info)) return Qnil;
3982 
3983  VALUE path = rb_ary_entry(info, 0);
3984  VALUE line = rb_ary_entry(info, 1);
3985  if (NIL_P(path)) return Qnil;
3986  *pline = NUM2INT(line);
3987  return StringValue(path);
3988 }
3989 
3990 void
3992 {
3993  rb_yjit_lazy_push_frame(GET_EC()->cfp->pc);
3994 
3995  VALUE mesg = rb_sprintf("can't modify frozen %"PRIsVALUE": ",
3996  CLASS_OF(frozen_obj));
3997  VALUE exc = rb_exc_new_str(rb_eFrozenError, mesg);
3998 
3999  rb_ivar_set(exc, id_recv, frozen_obj);
4000  rb_exec_recursive(inspect_frozen_obj, frozen_obj, mesg);
4001 
4002  int created_line;
4003  VALUE created_path = get_created_info(frozen_obj, &created_line);
4004  if (!NIL_P(created_path)) {
4005  rb_str_catf(mesg, ", created at %"PRIsVALUE":%d", created_path, created_line);
4006  }
4007  rb_exc_raise(exc);
4008 }
4009 
4010 void
4011 rb_warn_unchilled(VALUE obj)
4012 {
4014  if (!NIL_P(ruby_verbose) && rb_warning_category_enabled_p(category)) {
4015  int line;
4016  VALUE file = rb_source_location(&line);
4017  VALUE mesg = NIL_P(file) ? rb_str_new(0, 0) : rb_str_dup(file);
4018 
4019  if (!NIL_P(file)) {
4020  if (line) rb_str_catf(mesg, ":%d", line);
4021  rb_str_cat2(mesg, ": ");
4022  }
4023  rb_str_cat2(mesg, "warning: literal string will be frozen in the future");
4024 
4025  VALUE str = obj;
4026  if (STR_SHARED_P(str)) {
4027  str = RSTRING(obj)->as.heap.aux.shared;
4028  }
4029  VALUE created = get_created_info(str, &line);
4030  if (NIL_P(created)) {
4031  rb_str_cat2(mesg, " (run with --debug-frozen-string-literal for more information)\n");
4032  } else {
4033  rb_str_cat2(mesg, "\n");
4034  rb_str_append(mesg, created);
4035  if (line) rb_str_catf(mesg, ":%d", line);
4036  rb_str_cat2(mesg, ": info: the string was created here\n");
4037  }
4038  rb_warn_category(mesg, rb_warning_category_to_name(category));
4039  }
4040 }
4041 
4042 #undef rb_check_frozen
4043 void
4045 {
4047 }
4048 
4049 void
4051 {
4052  if (!FL_ABLE(obj)) return;
4053  rb_check_frozen(obj);
4054  if (!FL_ABLE(orig)) return;
4055 }
4056 
4057 void
4058 Init_syserr(void)
4059 {
4060  rb_eNOERROR = setup_syserr(0, "NOERROR");
4061 #if 0
4062  /* No error */
4063  rb_define_const(rb_mErrno, "NOERROR", rb_eNOERROR);
4064 #endif
4065 #define defined_error(name, num) set_syserr((num), (name));
4066 #define undefined_error(name) rb_define_const(rb_mErrno, (name), rb_eNOERROR);
4067 #include "known_errors.inc"
4068 #undef defined_error
4069 #undef undefined_error
4070 }
4071 
4072 #include "warning.rbinc"
4073 
#define RUBY_DEBUG
Define this macro when you want assertions.
Definition: assert.h:88
#define RB_UNLIKELY(x)
Asserts that the given Boolean expression likely doesn't hold.
Definition: assume.h:50
#define rb_define_singleton_method(klass, mid, func, arity)
Defines klass.mid.
Definition: cxxanyargs.hpp:685
VALUE rb_enc_vsprintf(rb_encoding *enc, const char *fmt, va_list ap)
Identical to rb_enc_sprintf(), except it takes a va_list instead of variadic arguments.
Definition: sprintf.c:1179
#define RUBY_EVENT_C_CALL
A method, written in C, is called.
Definition: event.h:43
#define RUBY_EVENT_C_RETURN
Return from a method, written in C.
Definition: event.h:44
#define RBIMPL_ATTR_FORMAT(x, y, z)
Wraps (or simulates) __attribute__((format))
Definition: format.h:27
VALUE rb_define_class(const char *name, VALUE super)
Defines a top-level class.
Definition: class.c:980
void rb_extend_object(VALUE obj, VALUE module)
Extend the object with the module.
Definition: eval.c:1750
VALUE rb_singleton_class(VALUE obj)
Finds or creates the singleton class of the passed object.
Definition: class.c:2297
VALUE rb_define_class_under(VALUE outer, const char *name, VALUE super)
Defines a class under the namespace of outer.
Definition: class.c:1012
VALUE rb_define_module(const char *name)
Defines a top-level module.
Definition: class.c:1095
int rb_scan_args(int argc, const VALUE *argv, const char *fmt,...)
Retrieves argument from argc and argv to given VALUE references according to the format string.
Definition: class.c:2635
void rb_define_method(VALUE klass, const char *name, VALUE(*func)(ANYARGS), int argc)
Defines a method.
Definition: class.c:2142
int rb_get_kwargs(VALUE keyword_hash, const ID *table, int required, int optional, VALUE *values)
Keyword argument deconstructor.
Definition: class.c:2424
#define rb_str_new2
Old name of rb_str_new_cstr.
Definition: string.h:1675
#define TYPE(_)
Old name of rb_type.
Definition: value_type.h:108
#define ISSPACE
Old name of rb_isspace.
Definition: ctype.h:88
#define T_STRING
Old name of RUBY_T_STRING.
Definition: value_type.h:78
#define T_MASK
Old name of RUBY_T_MASK.
Definition: value_type.h:68
#define Qundef
Old name of RUBY_Qundef.
#define INT2FIX
Old name of RB_INT2FIX.
Definition: long.h:48
#define UNREACHABLE
Old name of RBIMPL_UNREACHABLE.
Definition: assume.h:28
#define ID2SYM
Old name of RB_ID2SYM.
Definition: symbol.h:44
#define rb_str_buf_new2
Old name of rb_str_buf_new_cstr.
Definition: string.h:1679
#define UNREACHABLE_RETURN
Old name of RBIMPL_UNREACHABLE_RETURN.
Definition: assume.h:29
#define T_DATA
Old name of RUBY_T_DATA.
Definition: value_type.h:60
#define CLASS_OF
Old name of rb_class_of.
Definition: globals.h:203
#define T_MODULE
Old name of RUBY_T_MODULE.
Definition: value_type.h:70
#define T_TRUE
Old name of RUBY_T_TRUE.
Definition: value_type.h:81
#define FL_ABLE
Old name of RB_FL_ABLE.
Definition: fl_type.h:122
#define rb_ary_new3
Old name of rb_ary_new_from_args.
Definition: array.h:658
#define rb_exc_new3
Old name of rb_exc_new_str.
Definition: error.h:38
#define T_FALSE
Old name of RUBY_T_FALSE.
Definition: value_type.h:61
#define Qtrue
Old name of RUBY_Qtrue.
#define NUM2INT
Old name of RB_NUM2INT.
Definition: int.h:44
#define INT2NUM
Old name of RB_INT2NUM.
Definition: int.h:43
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#define T_ARRAY
Old name of RUBY_T_ARRAY.
Definition: value_type.h:56
#define T_OBJECT
Old name of RUBY_T_OBJECT.
Definition: value_type.h:75
#define NIL_P
Old name of RB_NIL_P.
#define T_SYMBOL
Old name of RUBY_T_SYMBOL.
Definition: value_type.h:80
#define T_CLASS
Old name of RUBY_T_CLASS.
Definition: value_type.h:58
#define FL_TEST
Old name of RB_FL_TEST.
Definition: fl_type.h:131
#define NUM2LONG
Old name of RB_NUM2LONG.
Definition: long.h:51
#define FIXNUM_P
Old name of RB_FIXNUM_P.
#define SYMBOL_P
Old name of RB_SYMBOL_P.
Definition: value_type.h:88
void rb_notimplement(void)
Definition: error.c:3670
void rb_mod_sys_fail(VALUE mod, const char *mesg)
Identical to rb_sys_fail(), except it takes additional module to extend the exception object before r...
Definition: error.c:3808
void * rb_check_typeddata(VALUE obj, const rb_data_type_t *data_type)
Identical to rb_typeddata_is_kind_of(), except it raises exceptions instead of returning false.
Definition: error.c:1370
rb_warning_category_t
Warning categories.
Definition: error.h:43
void rb_category_warn(rb_warning_category_t category, const char *fmt,...)
Identical to rb_category_warning(), except it reports unless $VERBOSE is nil.
Definition: error.c:475
void rb_raise(VALUE exc, const char *fmt,...)
Exception entry point.
Definition: error.c:3627
int rb_typeddata_inherited_p(const rb_data_type_t *child, const rb_data_type_t *parent)
Checks for the domestic relationship between the two.
Definition: error.c:1343
void rb_compile_warn(const char *file, int line, const char *fmt,...)
Identical to rb_compile_warning(), except it reports unless $VERBOSE is nil.
Definition: error.c:396
void rb_category_warning(rb_warning_category_t category, const char *fmt,...)
Identical to rb_warning(), except it takes additional "category" parameter.
Definition: error.c:507
void rb_mod_syserr_fail(VALUE mod, int e, const char *mesg)
Identical to rb_mod_sys_fail(), except it does not depend on C global variable errno.
Definition: error.c:3822
void rb_check_frozen(VALUE obj)
Queries if the passed object is frozen.
Definition: error.c:4044
VALUE rb_eNotImpError
NotImplementedError exception.
Definition: error.c:1413
VALUE rb_eScriptError
ScriptError exception.
Definition: error.c:1419
void rb_exc_raise(VALUE mesg)
Raises an exception in the current thread.
Definition: eval.c:676
int rb_typeddata_is_kind_of(VALUE obj, const rb_data_type_t *data_type)
Checks if the given object is of given kind.
Definition: error.c:1353
void rb_syserr_fail(int e, const char *mesg)
Raises appropriate exception that represents a C errno.
Definition: error.c:3739
VALUE rb_eKeyError
KeyError exception.
Definition: error.c:1406
void rb_bug(const char *fmt,...)
Interpreter panic switch.
Definition: error.c:1088
VALUE rb_cNameErrorMesg
NameError::Message class.
Definition: error.c:1415
VALUE rb_eSystemExit
SystemExit exception.
Definition: error.c:1396
void rb_sys_fail(const char *mesg)
Converts a C errno into a Ruby exception, then raises it.
Definition: error.c:3752
void rb_name_error(ID id, const char *fmt,...)
Raises an instance of rb_eNameError.
Definition: error.c:2210
void rb_sys_warning(const char *fmt,...)
Identical to rb_sys_fail(), except it does not raise an exception to render a warning instead.
Definition: error.c:3890
void rb_check_copyable(VALUE obj, VALUE orig)
Ensures that the passed object can be initialize_copy relationship.
Definition: error.c:4050
VALUE rb_eStandardError
StandardError exception.
Definition: error.c:1400
VALUE rb_mErrno
Errno module.
Definition: error.c:1424
VALUE rb_syserr_new_str(int n, VALUE arg)
Identical to rb_syserr_new(), except it takes the message in Ruby's String instead of C's.
Definition: error.c:3733
void rb_mod_syserr_fail_str(VALUE mod, int e, VALUE mesg)
Identical to rb_mod_syserr_fail(), except it takes the message in Ruby's String instead of C's.
Definition: error.c:3829
void rb_error_frozen(const char *what)
Identical to rb_frozen_error_raise(), except its raising exception has a message like "can't modify f...
Definition: error.c:3945
void rb_set_errinfo(VALUE err)
Sets the current exception ($!) to the given value.
Definition: eval.c:1941
VALUE rb_eFrozenError
FrozenError exception.
Definition: error.c:1402
VALUE rb_eNoMemError
NoMemoryError exception.
Definition: error.c:1414
VALUE rb_eRangeError
RangeError exception.
Definition: error.c:1407
VALUE rb_eLoadError
LoadError exception.
Definition: error.c:1421
void rb_syserr_fail_str(int e, VALUE mesg)
Identical to rb_syserr_fail(), except it takes the message in Ruby's String instead of C's.
Definition: error.c:3745
#define ruby_verbose
This variable controls whether the interpreter is in debug mode.
Definition: error.h:471
VALUE rb_eTypeError
TypeError exception.
Definition: error.c:1403
VALUE rb_eNoMatchingPatternError
NoMatchingPatternError exception.
Definition: error.c:1416
void rb_name_error_str(VALUE str, const char *fmt,...)
Identical to rb_name_error(), except it takes a VALUE instead of ID.
Definition: error.c:2225
void rb_fatal(const char *fmt,...)
Raises the unsung "fatal" exception.
Definition: error.c:3678
void rb_frozen_error_raise(VALUE frozen_obj, const char *fmt,...)
Raises an instance of rb_eFrozenError.
Definition: error.c:3951
VALUE rb_eEncCompatError
Encoding::CompatibilityError exception.
Definition: error.c:1410
void rb_category_compile_warn(rb_warning_category_t category, const char *file, int line, const char *fmt,...)
Identical to rb_compile_warn(), except it also accepts category.
Definition: error.c:438
VALUE rb_eFatal
fatal exception.
Definition: error.c:1399
void rb_invalid_str(const char *str, const char *type)
Honestly I don't understand the name, but it raises an instance of rb_eArgError.
Definition: error.c:2649
VALUE rb_eInterrupt
Interrupt exception.
Definition: error.c:1397
VALUE rb_eNameError
NameError exception.
Definition: error.c:1408
VALUE rb_eNoMethodError
NoMethodError exception.
Definition: error.c:1411
void rb_exc_fatal(VALUE mesg)
Raises a fatal error in the current thread.
Definition: eval.c:689
VALUE rb_eRuntimeError
RuntimeError exception.
Definition: error.c:1401
VALUE rb_exc_new_cstr(VALUE etype, const char *s)
Identical to rb_exc_new(), except it assumes the passed pointer is a pointer to a C string.
Definition: error.c:1448
void rb_warn(const char *fmt,...)
Identical to rb_warning(), except it reports unless $VERBOSE is nil.
Definition: error.c:465
VALUE rb_exc_new(VALUE etype, const char *ptr, long len)
Creates an instance of the passed exception class.
Definition: error.c:1441
VALUE rb_eNoMatchingPatternKeyError
NoMatchingPatternKeyError exception.
Definition: error.c:1417
void rb_error_frozen_object(VALUE frozen_obj)
Identical to rb_error_frozen(), except it takes arbitrary Ruby object instead of C's string.
Definition: error.c:3991
VALUE rb_exc_new_str(VALUE etype, VALUE str)
Identical to rb_exc_new_cstr(), except it takes a Ruby's string instead of C's.
Definition: error.c:1454
VALUE rb_eArgError
ArgumentError exception.
Definition: error.c:1404
void rb_bug_errno(const char *mesg, int errno_arg)
This is a wrapper of rb_bug() which automatically constructs appropriate message from the passed errn...
Definition: error.c:1117
void rb_enc_raise(rb_encoding *enc, VALUE exc, const char *fmt,...)
Identical to rb_raise(), except it additionally takes an encoding.
Definition: error.c:3608
void rb_compile_warning(const char *file, int line, const char *fmt,...)
Issues a compile-time warning that happens at __file__:__line__.
Definition: error.c:417
void rb_loaderror(const char *fmt,...)
Raises an instance of rb_eLoadError.
Definition: error.c:3646
VALUE rb_eException
Mother of all exceptions.
Definition: error.c:1395
VALUE rb_eIndexError
IndexError exception.
Definition: error.c:1405
void rb_loaderror_with_path(VALUE path, const char *fmt,...)
Identical to rb_loaderror(), except it additionally takes which file is unable to load.
Definition: error.c:3658
VALUE rb_eSyntaxError
SyntaxError exception.
Definition: error.c:1420
VALUE rb_eEncodingError
EncodingError exception.
Definition: error.c:1409
VALUE rb_syserr_new(int n, const char *mesg)
Creates an exception object that represents the given C errno.
Definition: error.c:3725
VALUE rb_eSecurityError
SecurityError exception.
Definition: error.c:1412
void rb_sys_fail_str(VALUE mesg)
Identical to rb_sys_fail(), except it takes the message in Ruby's String instead of C's.
Definition: error.c:3759
void rb_unexpected_type(VALUE x, int t)
Fails with the given object's type incompatibility to the type.
Definition: error.c:1333
void rb_mod_sys_fail_str(VALUE mod, VALUE mesg)
Identical to rb_mod_sys_fail(), except it takes the message in Ruby's String instead of C's.
Definition: error.c:3815
void rb_check_type(VALUE x, int t)
This was the old implementation of Check_Type(), but they diverged.
Definition: error.c:1310
VALUE rb_eSystemCallError
SystemCallError exception.
Definition: error.c:1423
void rb_warning(const char *fmt,...)
Issues a warning.
Definition: error.c:496
VALUE rb_eSignal
SignalException exception.
Definition: error.c:1398
@ RB_WARN_CATEGORY_DEPRECATED
Warning is for deprecated features.
Definition: error.h:48
@ RB_WARN_CATEGORY_EXPERIMENTAL
Warning is for experimental features.
Definition: error.h:51
@ RB_WARN_CATEGORY_PERFORMANCE
Warning is for performance issues (not enabled by -w).
Definition: error.h:54
@ RB_WARN_CATEGORY_NONE
Category unspecified.
Definition: error.h:45
VALUE rb_check_to_int(VALUE val)
Identical to rb_check_to_integer(), except it uses #to_int for conversion.
Definition: object.c:3192
VALUE rb_any_to_s(VALUE obj)
Generates a textual representation of the given object.
Definition: object.c:667
VALUE rb_obj_alloc(VALUE klass)
Allocates an instance of the given class.
Definition: object.c:2091
VALUE rb_class_new_instance(int argc, const VALUE *argv, VALUE klass)
Allocates, then initialises an instance of the given class.
Definition: object.c:2132
VALUE rb_obj_init_copy(VALUE src, VALUE dst)
Default implementation of #initialize_copy, #initialize_dup and #initialize_clone.
Definition: object.c:614
VALUE rb_obj_class(VALUE obj)
Queries the class of an object.
Definition: object.c:247
VALUE rb_cEncoding
Encoding class.
Definition: encoding.c:57
VALUE rb_inspect(VALUE obj)
Generates a human-readable textual representation of the given object.
Definition: object.c:678
VALUE rb_class_real(VALUE klass)
Finds a "real" class.
Definition: object.c:237
VALUE rb_equal(VALUE lhs, VALUE rhs)
This function is an optimised version of calling #==.
Definition: object.c:179
VALUE rb_obj_clone(VALUE obj)
Produces a shallow copy of the given object.
Definition: object.c:519
VALUE rb_obj_is_kind_of(VALUE obj, VALUE klass)
Queries if the given object is an instance (of possibly descendants) of the given class.
Definition: object.c:863
VALUE rb_String(VALUE val)
This is the logic behind Kernel#String.
Definition: object.c:3716
VALUE rb_cString
String class.
Definition: string.c:78
#define RB_OBJ_WRITE(old, slot, young)
Declaration of a "back" pointer.
Definition: gc.h:603
Encoding relates APIs.
rb_encoding * rb_locale_encoding(void)
Queries the encoding that represents the current locale.
Definition: encoding.c:1508
rb_encoding * rb_usascii_encoding(void)
Queries the encoding that represents US-ASCII.
Definition: encoding.c:1472
static char * rb_enc_prev_char(const char *s, const char *p, const char *e, rb_encoding *enc)
Queries the previous (left) character.
Definition: encoding.h:662
int rb_enc_mbclen(const char *p, const char *e, rb_encoding *enc)
Queries the number of bytes of the character at the passed pointer.
Definition: encoding.c:1164
rb_encoding * rb_enc_get(VALUE obj)
Identical to rb_enc_get_index(), except the return type.
Definition: encoding.c:1013
static const char * rb_enc_name(rb_encoding *enc)
Queries the (canonical) name of the passed encoding.
Definition: encoding.h:417
VALUE rb_enc_str_new_cstr(const char *ptr, rb_encoding *enc)
Identical to rb_enc_str_new(), except it assumes the passed pointer is a pointer to a C string.
Definition: string.c:1082
VALUE rb_enc_str_new(const char *ptr, long len, rb_encoding *enc)
Identical to rb_str_new(), except it additionally takes an encoding.
Definition: string.c:1042
VALUE rb_funcall(VALUE recv, ID mid, int n,...)
Calls a method.
Definition: vm_eval.c:1099
VALUE rb_funcallv_kw(VALUE recv, ID mid, int argc, const VALUE *argv, int kw_splat)
Identical to rb_funcallv(), except you can specify how to handle the last element of the given array.
Definition: vm_eval.c:1066
VALUE rb_funcallv(VALUE recv, ID mid, int argc, const VALUE *argv)
Identical to rb_funcall(), except it takes the method arguments as a C array.
Definition: vm_eval.c:1058
VALUE rb_call_super_kw(int argc, const VALUE *argv, int kw_splat)
Identical to rb_call_super(), except you can specify how to handle the last element of the given arra...
Definition: vm_eval.c:354
VALUE rb_call_super(int argc, const VALUE *argv)
This resembles ruby's super.
Definition: vm_eval.c:362
void rb_gc_mark_movable(VALUE obj)
Maybe this is the only function provided for C extensions to control the pinning of objects,...
Definition: gc.c:2076
VALUE rb_gc_location(VALUE obj)
Finds a new "location" of an object.
Definition: gc.c:3004
Defines RBIMPL_HAS_BUILTIN.
VALUE rb_ary_new(void)
Allocates a new, empty array.
Definition: array.c:747
VALUE rb_ary_new_capa(long capa)
Identical to rb_ary_new(), except it additionally specifies how many rooms of objects it should alloc...
Definition: array.c:741
VALUE rb_ary_push(VALUE ary, VALUE elem)
Special case of rb_ary_cat() that it adds only one element.
Definition: array.c:1384
VALUE rb_ary_freeze(VALUE obj)
Freeze an array, preventing further modifications.
Definition: array.c:648
VALUE rb_ary_entry(VALUE ary, long off)
Queries an element of an array.
Definition: array.c:1737
static void rb_check_frozen_inline(VALUE obj)
Just another name of rb_check_frozen.
Definition: error.h:253
static int rb_check_arity(int argc, int min, int max)
Ensures that the passed integer is in the passed range.
Definition: error.h:284
ID rb_frame_this_func(void)
Queries the name of the Ruby level method that is calling this function.
Definition: eval.c:1094
VALUE rb_hash_aset(VALUE hash, VALUE key, VALUE val)
Inserts or replaces ("upsert"s) the objects into the given hash table.
Definition: hash.c:2893
VALUE rb_hash_lookup(VALUE hash, VALUE key)
Identical to rb_hash_aref(), except it always returns RUBY_Qnil for misshits.
Definition: hash.c:2099
VALUE rb_hash_new(void)
Creates a new, empty hash object.
Definition: hash.c:1475
VALUE rb_io_puts(int argc, const VALUE *argv, VALUE io)
Iterates over the passed array to apply rb_io_write() individually.
Definition: io.c:8922
VALUE rb_protect(VALUE(*func)(VALUE args), VALUE args, int *state)
Protects a function call from potential global escapes from the function.
void ruby_default_signal(int sig)
Pretends as if there was no custom signal handler.
Definition: signal.c:411
VALUE rb_str_append(VALUE dst, VALUE src)
Identical to rb_str_buf_append(), except it converts the right hand side before concatenating.
Definition: string.c:3662
VALUE rb_str_tmp_new(long len)
Allocates a "temporary" string.
Definition: string.c:1655
VALUE rb_str_buf_cat(VALUE, const char *, long)
Just another name of rb_str_cat.
VALUE rb_str_cat2(VALUE, const char *)
Just another name of rb_str_cat_cstr.
VALUE rb_str_dup(VALUE str)
Duplicates a string.
Definition: string.c:1911
VALUE rb_str_buf_append(VALUE dst, VALUE src)
Identical to rb_str_cat_cstr(), except it takes Ruby's string instead of C's.
Definition: string.c:3628
VALUE rb_str_equal(VALUE str1, VALUE str2)
Equality of two strings.
Definition: string.c:4133
void rb_str_set_len(VALUE str, long len)
Overwrites the length of the string.
Definition: string.c:3254
void rb_must_asciicompat(VALUE obj)
Asserts that the given string's encoding is (Ruby's definition of) ASCII compatible.
Definition: string.c:2694
VALUE rb_str_buf_new_cstr(const char *ptr)
This is a rb_str_buf_new() + rb_str_buf_cat() combo.
Definition: string.c:1643
VALUE rb_str_new(const char *ptr, long len)
Allocates an instance of rb_cString.
Definition: string.c:1020
VALUE rb_check_string_type(VALUE obj)
Try converting an object to its stringised representation using its to_str method,...
Definition: string.c:2845
VALUE rb_str_new_cstr(const char *ptr)
Identical to rb_str_new(), except it assumes the passed pointer is a pointer to a C string.
Definition: string.c:1054
VALUE rb_str_cat_cstr(VALUE dst, const char *src)
Identical to rb_str_cat(), except it assumes the passed pointer is a pointer to a C string.
Definition: string.c:3440
VALUE rb_obj_as_string(VALUE obj)
Try converting an object to its stringised representation using its to_s method, if any.
Definition: string.c:1770
VALUE rb_exec_recursive(VALUE(*f)(VALUE g, VALUE h, int r), VALUE g, VALUE h)
"Recursion" API entry point.
VALUE rb_const_get(VALUE space, ID name)
Identical to rb_const_defined(), except it returns the actual defined value.
Definition: variable.c:3151
VALUE rb_attr_get(VALUE obj, ID name)
Identical to rb_ivar_get()
Definition: variable.c:1358
VALUE rb_ivar_set(VALUE obj, ID name, VALUE val)
Identical to rb_iv_set(), except it accepts the name as an ID instead of a C string.
Definition: variable.c:1859
void rb_ivar_foreach(VALUE obj, int(*func)(ID name, VALUE val, st_data_t arg), st_data_t arg)
Iterates over an object's instance variables.
VALUE rb_class_name(VALUE obj)
Queries the name of the given object's class.
Definition: variable.c:412
int rb_respond_to(VALUE obj, ID mid)
Queries if the object responds to the method.
Definition: vm_method.c:2955
int rb_method_basic_definition_p(VALUE klass, ID mid)
Well...
Definition: vm_method.c:2833
void rb_attr(VALUE klass, ID name, int need_reader, int need_writer, int honour_visibility)
This function resembles now-deprecated Module#attr.
Definition: vm_method.c:1864
VALUE rb_check_funcall(VALUE recv, ID mid, int argc, const VALUE *argv)
Identical to rb_funcallv(), except it returns RUBY_Qundef instead of raising rb_eNoMethodError.
Definition: vm_eval.c:668
VALUE rb_check_funcall_kw(VALUE recv, ID mid, int argc, const VALUE *argv, int kw_splat)
Identical to rb_check_funcall(), except you can specify how to handle the last element of the given a...
Definition: vm_eval.c:662
void rb_define_alloc_func(VALUE klass, rb_alloc_func_t func)
Sets the allocator function of a class.
static ID rb_intern_const(const char *str)
This is a "tiny optimisation" over rb_intern().
Definition: symbol.h:276
ID rb_check_id(volatile VALUE *namep)
Detects if the given name is already interned or not.
Definition: symbol.c:1117
ID rb_intern(const char *name)
Finds or creates a symbol of the given name.
Definition: symbol.c:823
VALUE rb_id2str(ID id)
Identical to rb_id2name(), except it returns a Ruby's String instead of C's.
Definition: symbol.c:986
void rb_define_const(VALUE klass, const char *name, VALUE val)
Defines a Ruby level constant under a namespace.
Definition: variable.c:3713
char * ptr
Pointer to the underlying memory region, of at least capa bytes.
Definition: io.h:2
int len
Length of the buffer.
Definition: io.h:8
#define DECIMAL_SIZE_OF(expr)
An approximation of decimal representation size.
Definition: util.h:48
unsigned long ruby_scan_oct(const char *str, size_t len, size_t *consumed)
Interprets the passed string as an octal unsigned integer.
Definition: util.c:43
VALUE rb_str_format(int argc, const VALUE *argv, VALUE fmt)
Formats a string.
Definition: sprintf.c:214
VALUE rb_sprintf(const char *fmt,...)
Ruby's extended sprintf(3).
Definition: sprintf.c:1217
VALUE rb_str_vcatf(VALUE dst, const char *fmt, va_list ap)
Identical to rb_str_catf(), except it takes a va_list.
Definition: sprintf.c:1230
VALUE rb_vsprintf(const char *fmt, va_list ap)
Identical to rb_sprintf(), except it takes a va_list.
Definition: sprintf.c:1211
VALUE rb_str_catf(VALUE dst, const char *fmt,...)
Identical to rb_sprintf(), except it renders the output to the specified object rather than creating ...
Definition: sprintf.c:1240
void rb_marshal_define_compat(VALUE newclass, VALUE oldclass, VALUE(*dumper)(VALUE), VALUE(*loader)(VALUE, VALUE))
Marshal format compatibility layer.
Definition: marshal.c:134
#define ALLOCA_N(type, n)
Definition: memory.h:287
VALUE type(ANYARGS)
ANYARGS-ed function type.
Definition: cxxanyargs.hpp:56
#define PRI_PIDT_PREFIX
A rb_sprintf() format prefix to be used for a pid_t parameter.
Definition: pid_t.h:38
#define RARRAY_LEN
Just another name of rb_array_len.
Definition: rarray.h:51
static int RARRAY_LENINT(VALUE ary)
Identical to rb_array_len(), except it differs for the return type.
Definition: rarray.h:281
#define RARRAY_AREF(a, i)
Definition: rarray.h:403
#define RARRAY_CONST_PTR
Just another name of rb_array_const_ptr.
Definition: rarray.h:52
#define StringValue(v)
Ensures that the parameter object is a String.
Definition: rstring.h:66
static char * RSTRING_END(VALUE str)
Queries the end of the contents pointer of the string.
Definition: rstring.h:442
static char * RSTRING_PTR(VALUE str)
Queries the contents pointer of the string.
Definition: rstring.h:416
char * rb_string_value_ptr(volatile VALUE *ptr)
Identical to rb_str_to_str(), except it returns the converted string's backend memory region.
Definition: string.c:2717
static long RSTRING_LEN(VALUE str)
Queries the length of the string.
Definition: rstring.h:367
#define RSTRING(obj)
Convenient casting macro.
Definition: rstring.h:41
static bool RTYPEDDATA_P(VALUE obj)
Checks whether the passed object is RTypedData or RData.
Definition: rtypeddata.h:579
#define RUBY_TYPED_DEFAULT_FREE
This is a value you can set to rb_data_type_struct::dfree.
Definition: rtypeddata.h:79
#define TypedData_Get_Struct(obj, type, data_type, sval)
Obtains a C struct from inside of a wrapper Ruby object.
Definition: rtypeddata.h:515
static const struct rb_data_type_struct * RTYPEDDATA_TYPE(VALUE obj)
Queries for the type of given object.
Definition: rtypeddata.h:602
#define TypedData_Make_Struct(klass, type, data_type, sval)
Identical to TypedData_Wrap_Struct, except it allocates a new data region internally instead of takin...
Definition: rtypeddata.h:497
VALUE rb_argv0
The value of $0 at process bootup.
Definition: ruby.c:1844
const char * rb_obj_classname(VALUE obj)
Queries the name of the class of the passed object.
Definition: variable.c:427
#define errno
Ractor-aware version of errno.
Definition: ruby.h:388
#define RB_PASS_KEYWORDS
Pass keywords, final argument should be a hash of keywords.
Definition: scan_args.h:72
#define RB_PASS_CALLED_KEYWORDS
Pass keywords if current method is called with keywords, useful for argument delegation.
Definition: scan_args.h:78
static bool RB_SPECIAL_CONST_P(VALUE obj)
Checks if the given object is of enum ruby_special_consts.
#define RTEST
This is an old name of RB_TEST.
Defines old _.
Ruby's String.
Definition: rstring.h:196
This is the struct that holds necessary info for a struct.
Definition: rtypeddata.h:200
const rb_data_type_t * parent
Parent of this class.
Definition: rtypeddata.h:290
const char * wrap_struct_name
Name of structs of this kind.
Definition: rtypeddata.h:207
Definition: method.h:54
Definition: st.h:79
uintptr_t ID
Type that represents a Ruby identifier such as a variable name.
Definition: value.h:52
uintptr_t VALUE
Type that represents a Ruby object.
Definition: value.h:40
static enum ruby_value_type RB_BUILTIN_TYPE(VALUE obj)
Queries the type of the object.
Definition: value_type.h:182
static void Check_Type(VALUE v, enum ruby_value_type t)
Identical to RB_TYPE_P(), except it raises exceptions on predication failure.
Definition: value_type.h:433
static bool RB_TYPE_P(VALUE obj, enum ruby_value_type t)
Queries if the given object is of given type.
Definition: value_type.h:376