PageRenderTime 41ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/error.c

https://github.com/rui314/8cc-old
C | 93 lines | 70 code | 14 blank | 9 comment | 4 complexity | 74101d0813f94eba7054af46d1242719 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. /*
  2. * error.c - error handlers
  3. *
  4. * Copyright 2010 Rui Ueyama <rui314@gmail.com>. All rights reserved.
  5. * This code is available under the simplified BSD license. See LICENSE for details.
  6. */
  7. #include "8cc.h"
  8. #include <execinfo.h>
  9. Exception *current_handler;
  10. Exception *make_exception(void) {
  11. Exception *e = malloc(sizeof(Exception));
  12. e->msg = NULL;
  13. return e;
  14. }
  15. static void print(char *pre, char *format, va_list ap) {
  16. fprintf(stderr, "%s", pre);
  17. vfprintf(stderr, format, ap);
  18. fprintf(stderr, "\n");
  19. }
  20. void debug(char *format, ...) {
  21. va_list ap;
  22. va_start(ap, format);
  23. vfprintf(stderr, format, ap);
  24. va_end(ap);
  25. }
  26. static NORETURN void verror(char *format, va_list ap) {
  27. if (current_handler) {
  28. Exception *e = current_handler;
  29. current_handler = NULL;
  30. e->msg = to_string("ERROR: ");
  31. string_vprintf(e->msg, format, ap);
  32. longjmp(e->jmpbuf, 1);
  33. }
  34. print("ERROR: ", format, ap);
  35. exit(-1);
  36. }
  37. static void vwarn(char *format, va_list ap) {
  38. print("WARN: ", format, ap);
  39. }
  40. NORETURN void error(char *format, ...) {
  41. va_list ap;
  42. va_start(ap, format);
  43. verror(format, ap);
  44. va_end(ap);
  45. }
  46. void warn(char *format, ...) {
  47. va_list ap;
  48. va_start(ap, format);
  49. vwarn(format, ap);
  50. va_end(ap);
  51. }
  52. NORETURN void print_parse_error(int line, int column, char *msg, va_list ap) {
  53. String *b = make_string_printf("Line %d:%d: ", line, column);
  54. string_append(b, msg);
  55. verror(STRING_BODY(b), ap);
  56. }
  57. static void print_stack_trace_int(bool safe) {
  58. void *buf[20];
  59. int size = backtrace(buf, sizeof(buf));
  60. fprintf(stderr, "Stack trace:\n");
  61. fflush(stderr);
  62. if (safe)
  63. backtrace_symbols_fd(buf, size, STDERR_FILENO);
  64. else {
  65. char **strs = backtrace_symbols(buf, size);
  66. for (int i = 0; i < size; i++)
  67. fprintf(stderr, " %s\n", strs[i]);
  68. free(strs);
  69. }
  70. }
  71. void print_stack_trace(void) {
  72. print_stack_trace_int(false);
  73. }
  74. /*
  75. * print_stack_trace() that don't call malloc().
  76. */
  77. void print_stack_trace_safe(void) {
  78. print_stack_trace_int(true);
  79. }