platformMemory.cpp 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "platform/platformMemory.h"
  23. #include "console/dynamicTypes.h"
  24. #include "console/engineAPI.h"
  25. #include "core/stream/fileStream.h"
  26. #include "core/strings/stringFunctions.h"
  27. #include "console/console.h"
  28. #include "platform/profiler.h"
  29. #include "platform/threads/mutex.h"
  30. #include "core/module.h"
  31. #ifdef _WIN32
  32. #include <windows.h>
  33. #include <dbghelp.h>
  34. #pragma comment(lib, "Dbghelp.lib")
  35. #else
  36. #include <execinfo.h>
  37. #endif
  38. #include <ctime>
  39. // If profile paths are enabled, disable profiling of the
  40. // memory manager as that would cause a cyclic dependency
  41. // through the string table's allocation stuff used by the
  42. // profiler (talk about a long sentence...)
  43. #ifdef TORQUE_ENABLE_PROFILE_PATH
  44. # undef PROFILE_START
  45. # undef PROFILE_END
  46. # undef PROFILE_SCOPE
  47. # define PROFILE_START( x )
  48. # define PROFILE_END()
  49. # define PROFILE_SCOPE( x )
  50. #endif
  51. #ifdef TORQUE_MULTITHREAD
  52. void* gMemMutex = NULL;
  53. #endif
  54. //-------------------------------------- Make sure we don't have the define set
  55. #ifdef new
  56. #undef new
  57. #endif
  58. //---------------------------------------------------------------------------
  59. namespace Memory
  60. {
  61. #if !defined(TORQUE_DISABLE_MEMORY_MANAGER)
  62. static const U32 MaxAllocs = 10240;
  63. static MemInfo allocList[MaxAllocs];
  64. static U32 allocCount = 0;
  65. static U32 currentAllocId = 0;
  66. static bool initialized = false;
  67. char gLogFilename[256] = { 0 };
  68. bool gStackTrace = false;
  69. void init()
  70. {
  71. if (initialized) return;
  72. std::memset(allocList, 0, sizeof(allocList));
  73. allocCount = 0;
  74. currentAllocId = 0;
  75. initialized = true;
  76. // Generate timestamped log filename
  77. std::time_t now = std::time(nullptr);
  78. std::tm* localTime = std::localtime(&now);
  79. std::strftime(gLogFilename, sizeof(gLogFilename), "memlog_%Y-%m-%d_%H-%M-%S.txt", localTime);
  80. }
  81. void shutdown()
  82. {
  83. if (!initialized) return;
  84. FILE* log = std::fopen(gLogFilename, "w");
  85. if (!log)
  86. return;
  87. std::fprintf(log, "\n--- Memory Leak Report ---\n");
  88. for (U32 i = 0; i < allocCount; ++i)
  89. {
  90. if (allocList[i].ptr != nullptr)
  91. {
  92. std::fprintf(log, "Leak: %p (%zu bytes) from %s:%u [id=%u]\n",
  93. allocList[i].ptr, allocList[i].size,
  94. allocList[i].file ? allocList[i].file : "(null)", allocList[i].line,
  95. allocList[i].allocId);
  96. if (gStackTrace)
  97. {
  98. #ifdef _WIN32
  99. SYMBOL_INFO* symbol = (SYMBOL_INFO*)malloc(sizeof(SYMBOL_INFO) + 256);
  100. symbol->MaxNameLen = 255;
  101. symbol->SizeOfStruct = sizeof(SYMBOL_INFO);
  102. HANDLE process = GetCurrentProcess();
  103. SymInitialize(process, NULL, TRUE);
  104. for (int j = 0; j < allocList[i].backtraceSize; ++j)
  105. {
  106. DWORD64 addr = (DWORD64)(allocList[i].backtracePtrs[j]);
  107. if (SymFromAddr(process, addr, 0, symbol))
  108. {
  109. std::fprintf(log, " [%d] %s - 0x%0llX\n", j, symbol->Name, symbol->Address);
  110. }
  111. else
  112. {
  113. std::fprintf(log, " [%d] ??? - 0x%0llX\n", j, addr);
  114. }
  115. }
  116. std::free(symbol);
  117. #else
  118. char** symbols = backtrace_symbols(allocList[i].backtracePtrs, allocList[i].backtraceSize);
  119. for (int j = 0; j < allocList[i].backtraceSize; ++j)
  120. {
  121. std::fprintf(log, " [%d] %s\n", j, symbols[j]);
  122. }
  123. std::free(symbols);
  124. #endif
  125. }
  126. }
  127. }
  128. std::fclose(log);
  129. initialized = false;
  130. }
  131. void checkPtr(void* ptr)
  132. {
  133. for (U32 i = 0; i < allocCount; ++i)
  134. if (allocList[i].ptr == ptr)
  135. return;
  136. Platform::debugBreak();
  137. }
  138. static void* alloc(dsize_t size, bool array, const char* fileName, U32 line)
  139. {
  140. if (size == 0)
  141. return nullptr;
  142. void* ptr = std::malloc(size);
  143. if (!ptr)
  144. return nullptr;
  145. if (!initialized || allocCount >= MaxAllocs)
  146. return ptr;
  147. MemInfo& info = allocList[allocCount++];
  148. info.ptr = ptr;
  149. info.size = size;
  150. info.file = fileName ? fileName : "unknown";
  151. info.line = line;
  152. info.allocId = currentAllocId++;
  153. info.flagged = false;
  154. if (gStackTrace)
  155. {
  156. #ifdef _WIN32
  157. info.backtraceSize = CaptureStackBackTrace(0, 16, info.backtracePtrs, nullptr);
  158. #else
  159. info.backtraceSize = backtrace(info.backtracePtrs, MaxBacktraceDepth);
  160. #endif
  161. }
  162. return ptr;
  163. }
  164. static void free(void* ptr, bool array)
  165. {
  166. if (!ptr || !initialized)
  167. return;
  168. for (U32 i = 0; i < allocCount; ++i)
  169. {
  170. if (allocList[i].ptr == ptr)
  171. {
  172. std::free(ptr);
  173. allocList[i] = allocList[allocCount - 1];
  174. allocList[--allocCount] = {};
  175. return;
  176. }
  177. }
  178. // Unknown pointer, still free it.
  179. std::free(ptr);
  180. }
  181. void getMemoryInfo(void* ptr, MemInfo& info)
  182. {
  183. if (!ptr || !initialized)
  184. return;
  185. for (U32 i = 0; i < allocCount; ++i)
  186. {
  187. if (allocList[i].ptr == ptr)
  188. {
  189. info = allocList[i];
  190. return;
  191. }
  192. }
  193. }
  194. static void* realloc(void* oldPtr, dsize_t newSize, const char* fileName, U32 line)
  195. {
  196. if (!initialized)
  197. return std::realloc(oldPtr, newSize); // fallback if not tracking
  198. if (newSize == 0)
  199. {
  200. free(oldPtr, false);
  201. return nullptr;
  202. }
  203. if (oldPtr == nullptr)
  204. return alloc(newSize, false, fileName, line);
  205. void* newPtr = std::realloc(oldPtr, newSize);
  206. if (!newPtr)
  207. return nullptr;
  208. // Update existing record
  209. for (U32 i = 0; i < allocCount; ++i)
  210. {
  211. if (allocList[i].ptr == oldPtr)
  212. {
  213. allocList[i].ptr = newPtr;
  214. allocList[i].size = newSize;
  215. allocList[i].file = fileName;
  216. allocList[i].line = line;
  217. allocList[i].allocId = currentAllocId++;
  218. return newPtr;
  219. }
  220. }
  221. // Not found — see if newPtr is already being tracked
  222. for (U32 i = 0; i < allocCount; ++i)
  223. {
  224. if (allocList[i].ptr == newPtr)
  225. {
  226. allocList[i].size = newSize;
  227. allocList[i].file = fileName;
  228. allocList[i].line = line;
  229. allocList[i].allocId = currentAllocId++;
  230. return newPtr;
  231. }
  232. }
  233. // Still not found — treat as a new allocation
  234. if (allocCount < MaxAllocs)
  235. {
  236. MemInfo& info = allocList[allocCount++];
  237. info = {};
  238. info.ptr = newPtr;
  239. info.size = newSize;
  240. info.file = fileName;
  241. info.line = line;
  242. info.allocId = currentAllocId++;
  243. }
  244. return newPtr;
  245. }
  246. #endif
  247. }
  248. //---------------------------------------------------------------------------
  249. //---------------------------------------------------------------------------
  250. #if !defined(TORQUE_DISABLE_MEMORY_MANAGER)
  251. // Manage our own memory, add overloaded memory operators and functions
  252. void* FN_CDECL operator new(dsize_t size, const char* fileName, const U32 line)
  253. {
  254. return Memory::alloc(size, false, fileName, line);
  255. }
  256. void* FN_CDECL operator new[](dsize_t size, const char* fileName, const U32 line)
  257. {
  258. return Memory::alloc(size, true, fileName, line);
  259. }
  260. void* FN_CDECL operator new(dsize_t size)
  261. {
  262. return Memory::alloc(size, false, NULL, 0);
  263. }
  264. void* FN_CDECL operator new[](dsize_t size)
  265. {
  266. return Memory::alloc(size, true, NULL, 0);
  267. }
  268. void FN_CDECL operator delete(void* mem)
  269. {
  270. Memory::free(mem, false);
  271. }
  272. void FN_CDECL operator delete[](void* mem)
  273. {
  274. Memory::free(mem, true);
  275. }
  276. void* dMalloc_r(dsize_t in_size, const char* fileName, const dsize_t line)
  277. {
  278. return Memory::alloc(in_size, false, fileName, line);
  279. }
  280. void dFree(void* in_pFree)
  281. {
  282. Memory::free(in_pFree, false);
  283. }
  284. void* dRealloc_r(void* in_pResize, dsize_t in_size, const char* fileName, const dsize_t line)
  285. {
  286. return Memory::realloc(in_pResize, in_size, fileName, line);
  287. }
  288. #else
  289. // Don't manage our own memory
  290. void* dMalloc_r(dsize_t in_size, const char* fileName, const dsize_t line)
  291. {
  292. return malloc(in_size);
  293. }
  294. void dFree(void* in_pFree)
  295. {
  296. free(in_pFree);
  297. }
  298. void* dRealloc_r(void* in_pResize, dsize_t in_size, const char* fileName, const dsize_t line)
  299. {
  300. return realloc(in_pResize,in_size);
  301. }
  302. #endif