DebugNew.cpp 9.1 KB

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