DebugNew.cpp 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. #include <new>
  2. #include <exception>
  3. #include <cstdio>
  4. #include <cstdarg>
  5. #ifdef WIN32
  6. #include <windows.h>
  7. #include <dbghelp.h>
  8. #pragma comment(lib,"dbghelp.lib")
  9. #define MAX_STACK_FRAMES 16
  10. bool __trackStackTrace = false;
  11. #endif
  12. struct MemoryAllocationRecord
  13. {
  14. unsigned long address; // address returned to the caller after allocation
  15. unsigned int size; // size of the allocation request
  16. const char* file; // source file of allocation request
  17. int line; // source line of the allocation request
  18. MemoryAllocationRecord* next;
  19. MemoryAllocationRecord* prev;
  20. #ifdef WIN32
  21. bool trackStackTrace;
  22. unsigned int pc[MAX_STACK_FRAMES];
  23. #endif
  24. };
  25. MemoryAllocationRecord* __memoryAllocations = 0;
  26. int __memoryAllocationCount = 0;
  27. void* debugAlloc(std::size_t size, const char* file, int line);
  28. void debugFree(void* p);
  29. #ifdef _MSC_VER
  30. #pragma warning( disable : 4290 )
  31. #endif
  32. void* operator new (std::size_t size, const char* file, int line)
  33. {
  34. return debugAlloc(size, file, line);
  35. }
  36. void* operator new[] (std::size_t size, const char* file, int line)
  37. {
  38. return operator new (size, file, line);
  39. }
  40. void* operator new (std::size_t size) throw(std::bad_alloc)
  41. {
  42. return operator new (size, "", 0);
  43. }
  44. void* operator new[] (std::size_t size) throw(std::bad_alloc)
  45. {
  46. return operator new (size, "", 0);
  47. }
  48. void* operator new (std::size_t size, const std::nothrow_t&) throw()
  49. {
  50. return operator new (size, "", 0);
  51. }
  52. void* operator new[] (std::size_t size, const std::nothrow_t&) throw()
  53. {
  54. return operator new (size, "", 0);
  55. }
  56. void operator delete (void* p) throw()
  57. {
  58. debugFree(p);
  59. }
  60. void operator delete[] (void* p) throw()
  61. {
  62. operator delete (p);
  63. }
  64. void operator delete (void* p, const char* file, int line) throw()
  65. {
  66. operator delete (p);
  67. }
  68. void operator delete[] (void* p, const char* file, int line) throw()
  69. {
  70. operator delete (p);
  71. }
  72. #ifdef _MSC_VER
  73. #pragma warning( default : 4290 )
  74. #endif
  75. // Include Base.h (needed for logging macros) AFTER new operator impls
  76. #include "Base.h"
  77. void* debugAlloc(std::size_t size, const char* file, int line)
  78. {
  79. // Allocate memory + size for a MemoryAlloctionRecord
  80. unsigned char* mem = (unsigned char*)malloc(size + sizeof(MemoryAllocationRecord));
  81. MemoryAllocationRecord* rec = (MemoryAllocationRecord*)mem;
  82. // Move memory pointer past record
  83. mem += sizeof(MemoryAllocationRecord);
  84. rec->address = (unsigned long)mem;
  85. rec->size = size;
  86. rec->file = file;
  87. rec->line = line;
  88. rec->next = __memoryAllocations;
  89. rec->prev = 0;
  90. // Capture the stack frame (up to MAX_STACK_FRAMES) if we
  91. // are running on Windows and the user has enabled it.
  92. #if defined(WIN32)
  93. rec->trackStackTrace = __trackStackTrace;
  94. if (rec->trackStackTrace)
  95. {
  96. static bool initialized = false;
  97. if (!initialized)
  98. {
  99. if (!SymInitialize(GetCurrentProcess(), NULL, true))
  100. printError("Stack trace tracking will not work.\n");
  101. initialized = true;
  102. }
  103. // Get the current context (state of EBP, EIP, ESP registers).
  104. static CONTEXT context;
  105. RtlCaptureContext(&context);
  106. static STACKFRAME64 stackFrame;
  107. memset(&stackFrame, 0, sizeof(STACKFRAME64));
  108. // Initialize the stack frame based on the machine architecture.
  109. #ifdef _M_IX86
  110. static const DWORD machineType = IMAGE_FILE_MACHINE_I386;
  111. stackFrame.AddrPC.Offset = context.Eip;
  112. stackFrame.AddrPC.Mode = AddrModeFlat;
  113. stackFrame.AddrFrame.Offset = context.Ebp;
  114. stackFrame.AddrFrame.Mode = AddrModeFlat;
  115. stackFrame.AddrStack.Offset = context.Esp;
  116. stackFrame.AddrStack.Mode = AddrModeFlat;
  117. #else
  118. #error "Machine architecture not supported!"
  119. #endif
  120. // Walk up the stack and store the program counters.
  121. memset(rec->pc, 0, sizeof(rec->pc));
  122. for (int i = 0; i < MAX_STACK_FRAMES; i++)
  123. {
  124. rec->pc[i] = stackFrame.AddrPC.Offset;
  125. if (!StackWalk64(machineType, GetCurrentProcess(), GetCurrentThread(), &stackFrame,
  126. &context, NULL, SymFunctionTableAccess64, SymGetModuleBase64, NULL))
  127. {
  128. break;
  129. }
  130. }
  131. }
  132. #endif
  133. if (__memoryAllocations)
  134. __memoryAllocations->prev = rec;
  135. __memoryAllocations = rec;
  136. ++__memoryAllocationCount;
  137. return mem;
  138. }
  139. void debugFree(void* p)
  140. {
  141. if (p == 0)
  142. return;
  143. // Backup passed in pointer to access memory allocation record
  144. void* mem = ((unsigned char*)p) - sizeof(MemoryAllocationRecord);
  145. MemoryAllocationRecord* rec = (MemoryAllocationRecord*)mem;
  146. // Sanity check: ensure that address in record matches passed in address
  147. if (rec->address != (unsigned long)p)
  148. {
  149. printError("[memory] CORRUPTION: Attempting to free memory address with invalid memory allocation record.\n");
  150. return;
  151. }
  152. // Link this item out
  153. if (__memoryAllocations == rec)
  154. __memoryAllocations = rec->next;
  155. if (rec->prev)
  156. rec->prev->next = rec->next;
  157. if (rec->next)
  158. rec->next->prev = rec->prev;
  159. --__memoryAllocationCount;
  160. // Free the address from the original alloc location (before mem allocation record)
  161. free(mem);
  162. }
  163. #ifdef WIN32
  164. void printStackTrace(MemoryAllocationRecord* rec)
  165. {
  166. const unsigned int bufferSize = 512;
  167. // Resolve the program counter to the corresponding function names.
  168. unsigned int pc;
  169. for (int i = 0; i < MAX_STACK_FRAMES; i++)
  170. {
  171. // Check to see if we are at the end of the stack trace.
  172. pc = rec->pc[i];
  173. if (pc == 0)
  174. break;
  175. // Get the function name.
  176. unsigned char buffer[sizeof(IMAGEHLP_SYMBOL64) + bufferSize];
  177. IMAGEHLP_SYMBOL64* symbol = (IMAGEHLP_SYMBOL64*)buffer;
  178. DWORD64 displacement;
  179. memset(symbol, 0, sizeof(IMAGEHLP_SYMBOL64) + bufferSize);
  180. symbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL64);
  181. symbol->MaxNameLength = bufferSize;
  182. if (!SymGetSymFromAddr64(GetCurrentProcess(), pc, &displacement, symbol))
  183. {
  184. printError("[memory] STACK TRACE: <unknown location>\n");
  185. }
  186. else
  187. {
  188. symbol->Name[bufferSize - 1] = '\0';
  189. // Check if we need to go further up the stack.
  190. if (strncmp(symbol->Name, "operator new", 12) == 0)
  191. {
  192. // In operator new or new[], keep going...
  193. }
  194. else
  195. {
  196. // Get the file and line number.
  197. if (pc != 0)
  198. {
  199. IMAGEHLP_LINE64 line;
  200. DWORD displacement;
  201. memset(&line, 0, sizeof(line));
  202. line.SizeOfStruct = sizeof(line);
  203. if (!SymGetLineFromAddr64(GetCurrentProcess(), pc, &displacement, &line))
  204. {
  205. printError("[memory] STACK TRACE: %s - <unknown file>:<unknown line number>\n", symbol->Name);
  206. }
  207. else
  208. {
  209. const char* file = strrchr(line.FileName, '\\');
  210. if(!file)
  211. file = line.FileName;
  212. else
  213. file++;
  214. printError("[memory] STACK TRACE: %s - %s:%d\n", symbol->Name, file, line.LineNumber);
  215. }
  216. }
  217. }
  218. }
  219. }
  220. }
  221. #endif
  222. extern void printMemoryLeaks()
  223. {
  224. // Dump general heap memory leaks
  225. if (__memoryAllocationCount == 0)
  226. {
  227. printError("[memory] All HEAP allocations successfully cleaned up (no leaks detected).\n");
  228. }
  229. else
  230. {
  231. printError("[memory] WARNING: %d HEAP allocations still active in memory.\n", __memoryAllocationCount);
  232. MemoryAllocationRecord* rec = __memoryAllocations;
  233. while (rec)
  234. {
  235. #ifdef WIN32
  236. if (rec->trackStackTrace)
  237. {
  238. printError("[memory] LEAK: HEAP allocation leak at address %#x of size %d:\n", rec->address, rec->size);
  239. printStackTrace(rec);
  240. }
  241. else
  242. printError("[memory] LEAK: HEAP allocation leak at address %#x of size %d from line %d in file '%s'.\n", rec->address, rec->size, rec->line, rec->file);
  243. #else
  244. printError("[memory] LEAK: HEAP allocation leak at address %#x of size %d from line %d in file '%s'.\n", rec->address, rec->size, rec->line, rec->file);
  245. #endif
  246. rec = rec->next;
  247. }
  248. }
  249. }
  250. #if defined(WIN32)
  251. void setTrackStackTrace(bool trackStackTrace)
  252. {
  253. __trackStackTrace = trackStackTrace;
  254. }
  255. void toggleTrackStackTrace()
  256. {
  257. __trackStackTrace = !__trackStackTrace;
  258. }
  259. #endif