Debug.cpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #include "Debug.h"
  2. #ifdef __linux__
  3. #include <sys/types.h>
  4. #include <sys/syscall.h>
  5. #include <signal.h>
  6. #include <stdlib.h>
  7. #include <stdio.h>
  8. #endif
  9. // Some private global variables.
  10. volatile const char *FileName;
  11. volatile int LineNumber;
  12. const char *Debug::GetFileName()
  13. {
  14. return (const char *)FileName;
  15. }
  16. int Debug::GetLineNumber()
  17. {
  18. return (int)LineNumber;
  19. }
  20. void Debug::SetFileAndLine(const char *file,int lineNumber)
  21. {
  22. FileName = file;
  23. LineNumber = lineNumber;
  24. }
  25. // Display an error from a segmentation fault.
  26. void Debug::ErrorHandler(int signum)
  27. {
  28. #ifdef __linux__
  29. const char *errorType = "Segmentation fault";
  30. switch (signum) {
  31. case SIGFPE:
  32. {
  33. errorType = "Division by zero";
  34. break;
  35. }
  36. case SIGILL:
  37. {
  38. errorType = "Illegal instruction";
  39. break;
  40. }
  41. case SIGSEGV:
  42. {
  43. errorType = "Bad memory read/write";
  44. break;
  45. }
  46. case SIGBUS:
  47. {
  48. errorType = "Access misalligned memory or non-existent memory";
  49. break;
  50. }
  51. }
  52. printf("%s after %s line %d.\n",errorType,FileName,LineNumber);
  53. exit(signum);
  54. #endif
  55. return;
  56. }
  57. // Add error handlers for segmenation faults not caught with try/catch.
  58. void Debug::AddErrorHandler()
  59. {
  60. #ifdef __linux__
  61. signal (SIGFPE, ErrorHandler); // division by 0
  62. signal (SIGILL, ErrorHandler); // illegal instruction
  63. signal (SIGSEGV, ErrorHandler); // bad memory read/write
  64. signal (SIGBUS, ErrorHandler); // access misalligned memory or non-existent memory
  65. #endif
  66. }
  67. // Make sure the signals don't point to some function that might not exist in the future.
  68. void Debug::RemoveErrorHandler()
  69. {
  70. #ifdef __linux__
  71. signal (SIGFPE, SIG_DFL); // division by 0
  72. signal (SIGILL, SIG_DFL); // illegal instruction
  73. signal (SIGSEGV, SIG_DFL); // bad memory read/write
  74. signal (SIGBUS, SIG_DFL); // access misalligned memory or non-existent memory
  75. #endif
  76. return;
  77. }