stacktrace.h 1002 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. #ifndef STACKTRACE_H_
  2. #define STACKTRACE_H_
  3. #include <stdlib.h>
  4. #include <stdio.h>
  5. #if defined(__GNUC__) && defined(__linux__)
  6. #include <execinfo.h>
  7. #include <unistd.h>
  8. #define N 100
  9. #endif
  10. #ifndef NDEBUG
  11. #define trace_assert(condition) (void)((condition) || (__trace_assert(__FILE__, __LINE__, __func__, #condition), 0))
  12. #else
  13. #define trace_assert(condition) (void)(condition)
  14. #endif
  15. static inline
  16. void print_stacktrace(void)
  17. {
  18. #if defined(__GNUC__) && defined(__linux__)
  19. void *array[N];
  20. int size;
  21. size = backtrace(array, N);
  22. if (size <= 0) {
  23. return;
  24. }
  25. fprintf(stderr, "Stacktrace: \n");
  26. backtrace_symbols_fd(array + 1, size - 1, STDERR_FILENO);
  27. #endif
  28. }
  29. static inline
  30. void __trace_assert(const char *file, int line, const char *function, const char *message)
  31. {
  32. fprintf(
  33. stderr,
  34. "%s:%d: %s: Assertion `%s' failed\n",
  35. file, line,
  36. function,
  37. message);
  38. print_stacktrace();
  39. abort();
  40. }
  41. #endif // STACKTRACE_H_