assert_checkpoint.h 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #ifndef SUPPORT_ASSERT_CHECKPOINT_H
  2. #define SUPPORT_ASSERT_CHECKPOINT_H
  3. #include <csignal>
  4. #include <iostream>
  5. #include <cstdlib>
  6. struct Checkpoint {
  7. const char* file;
  8. const char* func;
  9. int line;
  10. const char* msg;
  11. Checkpoint() : file(nullptr), func(nullptr), line(-1), msg(nullptr) {}
  12. Checkpoint(const char* xfile, const char* xfunc, int xline, const char* xmsg)
  13. : file(xfile), func(xfunc), line(xline), msg(xmsg)
  14. {}
  15. template <class Stream>
  16. void print(Stream& s) const {
  17. if (!file) {
  18. s << "NO CHECKPOINT\n";
  19. return;
  20. }
  21. s << file << ":" << line << " " << func << ": Checkpoint";
  22. if (msg)
  23. s << " '" << msg << "'";
  24. s << std::endl;
  25. }
  26. };
  27. inline Checkpoint& globalCheckpoint() {
  28. static Checkpoint C;
  29. return C;
  30. }
  31. inline void clearCheckpoint() {
  32. globalCheckpoint() = Checkpoint();
  33. }
  34. #if defined(__GNUC__)
  35. #define CHECKPOINT_FUNCTION_NAME __PRETTY_FUNCTION__
  36. #else
  37. #define CHECKPOINT_FUNCTION_NAME __func__
  38. #endif
  39. #define CHECKPOINT(msg) globalCheckpoint() = Checkpoint(__FILE__, CHECKPOINT_FUNCTION_NAME, __LINE__, msg);
  40. inline void checkpointSignalHandler(int signal) {
  41. if (signal == SIGABRT) {
  42. globalCheckpoint().print(std::cerr);
  43. } else {
  44. std::cerr << "Unexpected signal " << signal << " received\n";
  45. }
  46. std::_Exit(EXIT_FAILURE);
  47. }
  48. inline bool initCheckpointHandler() {
  49. typedef void(*HandlerT)(int);
  50. static bool isInit = false;
  51. if (isInit) return true;
  52. HandlerT prev_h = std::signal(SIGABRT, checkpointSignalHandler);
  53. if (prev_h == SIG_ERR) {
  54. std::cerr << "Setup failed.\n";
  55. std::_Exit(EXIT_FAILURE);
  56. }
  57. isInit = true;
  58. return false;
  59. }
  60. static bool initDummy = initCheckpointHandler();
  61. #endif