platformMemory.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  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. #include <string>
  40. // If profile paths are enabled, disable profiling of the
  41. // memory manager as that would cause a cyclic dependency
  42. // through the string table's allocation stuff used by the
  43. // profiler (talk about a long sentence...)
  44. #ifdef TORQUE_ENABLE_PROFILE_PATH
  45. # undef PROFILE_START
  46. # undef PROFILE_END
  47. # undef PROFILE_SCOPE
  48. # define PROFILE_START( x )
  49. # define PROFILE_END()
  50. # define PROFILE_SCOPE( x )
  51. #endif
  52. #ifdef TORQUE_MULTITHREAD
  53. void* gMemMutex = NULL;
  54. #endif
  55. //-------------------------------------- Make sure we don't have the define set
  56. #ifdef new
  57. #undef new
  58. #endif
  59. //---------------------------------------------------------------------------
  60. namespace Memory
  61. {
  62. #if !defined(TORQUE_DISABLE_MEMORY_MANAGER)
  63. static const U32 MaxAllocs = 10240;
  64. static MemInfo allocList[MaxAllocs];
  65. static U32 allocCount = 0;
  66. static U32 currentAllocId = 0;
  67. static bool initialized = false;
  68. char gLogFilename[256] = { 0 };
  69. bool gStackTrace = true;
  70. bool gFromScript = false;
  71. struct memReport
  72. {
  73. std::string report;
  74. bool skip;
  75. U32 count = 1;
  76. U32 total = 0;
  77. } memLog[MaxAllocs];
  78. void init()
  79. {
  80. if (initialized) return;
  81. std::memset(allocList, 0, sizeof(allocList));
  82. allocCount = 0;
  83. currentAllocId = 0;
  84. initialized = true;
  85. // Generate timestamped log filename
  86. std::time_t now = std::time(nullptr);
  87. std::tm* localTime = std::localtime(&now);
  88. std::strftime(gLogFilename, sizeof(gLogFilename), "memlog_%Y-%m-%d_%H-%M-%S.txt", localTime);
  89. //std::atexit(shutdown);
  90. }
  91. void shutdown()
  92. {
  93. if (!initialized) return;
  94. FILE* log = std::fopen(gLogFilename, "w");
  95. if (!log)
  96. return;
  97. std::fprintf(log, "\n--- Memory Leak Report ---\n");
  98. U32 start = 0;
  99. U32 stop = allocCount;
  100. if (gFromScript) //filter out the bits from console
  101. {
  102. start = 6;
  103. stop = allocCount - 8;
  104. }
  105. for (U32 curRep = start; curRep < stop; ++curRep)
  106. {
  107. if (allocList[curRep].ptr != nullptr)
  108. {
  109. char entry[512] = "";
  110. std::sprintf(entry, "from %s:%u\n", allocList[curRep].file ? allocList[curRep].file : "(null)", allocList[curRep].line);
  111. memLog[curRep].skip = false;
  112. std::string report = entry;
  113. if (gStackTrace)
  114. {
  115. char stack[512] = "";
  116. #ifdef _WIN32
  117. SYMBOL_INFO* symbol = (SYMBOL_INFO*)malloc(sizeof(SYMBOL_INFO) + 256);
  118. symbol->MaxNameLen = 255;
  119. symbol->SizeOfStruct = sizeof(SYMBOL_INFO);
  120. HANDLE process = GetCurrentProcess();
  121. SymInitialize(process, NULL, TRUE);
  122. for (int curStack = 0; curStack < allocList[curRep].backtraceSize; ++curStack)
  123. {
  124. DWORD64 addr = (DWORD64)(allocList[curRep].backtracePtrs[curStack]);
  125. DWORD displacement = 0;
  126. IMAGEHLP_LINE64 line;
  127. std::memset(&line, 0, sizeof(IMAGEHLP_LINE64));
  128. line.SizeOfStruct = sizeof(IMAGEHLP_LINE64);
  129. if (SymFromAddr(process, addr, 0, symbol)) {
  130. if (SymGetLineFromAddr64(process, addr, &displacement, &line)) {
  131. std::sprintf(stack, " [%d] %s - %s:%lu (0x%0llX)\n",
  132. curStack, symbol->Name, line.FileName, line.LineNumber, symbol->Address);
  133. }
  134. else {
  135. std::sprintf(stack, " [%d] %s - ???:??? (0x%0llX)\n",
  136. curStack, symbol->Name, symbol->Address);
  137. }
  138. }
  139. else {
  140. std::sprintf(stack, " [%d] ??? - 0x%0llX\n", curStack, addr);
  141. }
  142. report += stack;
  143. }
  144. std::free(symbol);
  145. #else
  146. char** symbols = backtrace_symbols(allocList[curRep].backtracePtrs, allocList[i].backtraceSize);
  147. for (int curStack = 0; curStack < allocList[curRep].backtraceSize; ++curStack)
  148. {
  149. std::sprintf(stack, " [%d] %s\n", curStack, symbols[curStack]);
  150. report += stack;
  151. }
  152. std::free(symbols);
  153. #endif
  154. }
  155. //if (report.find("getDocsLink") != std::string::npos)
  156. //{
  157. // //known issue. one off allocation
  158. // memLog[curRep].skip = true;
  159. //}
  160. for (U32 oldRep = start; oldRep < curRep; ++oldRep)
  161. {
  162. if (!memLog[oldRep].skip && (memLog[oldRep].report.find(report) != std::string::npos))
  163. {
  164. //inc origional
  165. memLog[oldRep].count++;
  166. memLog[oldRep].total += allocList[curRep].size;
  167. //skip dupe report
  168. memLog[curRep].skip = true;
  169. }
  170. }
  171. if (!memLog[curRep].skip)
  172. {
  173. memLog[curRep].report = report;
  174. memLog[curRep].count = 1;
  175. memLog[curRep].total = allocList[curRep].size;
  176. }
  177. }
  178. }
  179. for (U32 ntry = start; ntry < stop; ++ntry)
  180. {
  181. if (!memLog[ntry].skip)
  182. {
  183. std::fprintf(log, "Leak-count[%i]total[%i]:%s", memLog[ntry].count, memLog[ntry].total, memLog[ntry].report.c_str());
  184. memLog[ntry].report.clear();
  185. }
  186. }
  187. std::fclose(log);
  188. std::memset(allocList, 0, sizeof(allocList));
  189. allocCount = 0;
  190. currentAllocId = 0;
  191. initialized = false;
  192. }
  193. void checkPtr(void* ptr)
  194. {
  195. for (U32 i = 0; i < allocCount; ++i)
  196. if (allocList[i].ptr == ptr)
  197. return;
  198. Platform::debugBreak();
  199. }
  200. static void* alloc(dsize_t size, bool array, const char* fileName, U32 line)
  201. {
  202. if (size == 0)
  203. return nullptr;
  204. void* ptr = std::malloc(size);
  205. if (!ptr)
  206. return nullptr;
  207. if (!initialized || allocCount >= MaxAllocs)
  208. return ptr;
  209. MemInfo& info = allocList[allocCount++];
  210. info.ptr = ptr;
  211. info.size = size;
  212. info.file = fileName ? fileName : "unknown";
  213. info.line = line;
  214. info.allocId = currentAllocId++;
  215. info.flagged = false;
  216. if (gStackTrace)
  217. {
  218. #ifdef _WIN32
  219. info.backtraceSize = CaptureStackBackTrace(0, 16, info.backtracePtrs, nullptr);
  220. #else
  221. info.backtraceSize = backtrace(info.backtracePtrs, MaxBacktraceDepth);
  222. #endif
  223. }
  224. return ptr;
  225. }
  226. static void free(void* ptr, bool array)
  227. {
  228. if (!ptr)
  229. return;
  230. if (!initialized)
  231. {
  232. std::free(ptr);
  233. return;
  234. }
  235. for (U32 i = 0; i < allocCount; ++i)
  236. {
  237. if (allocList[i].ptr == ptr)
  238. {
  239. std::free(ptr);
  240. allocList[i] = allocList[allocCount - 1];
  241. allocList[--allocCount] = {};
  242. return;
  243. }
  244. }
  245. // Unknown pointer, still free it.
  246. std::free(ptr);
  247. }
  248. void getMemoryInfo(void* ptr, MemInfo& info)
  249. {
  250. if (!ptr || !initialized)
  251. return;
  252. for (U32 i = 0; i < allocCount; ++i)
  253. {
  254. if (allocList[i].ptr == ptr)
  255. {
  256. info = allocList[i];
  257. return;
  258. }
  259. }
  260. }
  261. static void* realloc(void* oldPtr, dsize_t newSize, const char* fileName, U32 line)
  262. {
  263. if (!initialized)
  264. return std::realloc(oldPtr, newSize); // fallback if not tracking
  265. if (newSize == 0)
  266. {
  267. free(oldPtr, false);
  268. return nullptr;
  269. }
  270. if (oldPtr == nullptr)
  271. return alloc(newSize, false, fileName, line);
  272. void* newPtr = std::realloc(oldPtr, newSize);
  273. if (!newPtr)
  274. return nullptr;
  275. // Update existing record
  276. for (U32 i = 0; i < allocCount; ++i)
  277. {
  278. if (allocList[i].ptr == oldPtr)
  279. {
  280. allocList[i].ptr = newPtr;
  281. allocList[i].size = newSize;
  282. allocList[i].file = fileName;
  283. allocList[i].line = line;
  284. allocList[i].allocId = currentAllocId++;
  285. return newPtr;
  286. }
  287. }
  288. // Not found — see if newPtr is already being tracked
  289. for (U32 i = 0; i < allocCount; ++i)
  290. {
  291. if (allocList[i].ptr == newPtr)
  292. {
  293. allocList[i].size = newSize;
  294. allocList[i].file = fileName;
  295. allocList[i].line = line;
  296. allocList[i].allocId = currentAllocId++;
  297. return newPtr;
  298. }
  299. }
  300. // Still not found — treat as a new allocation
  301. if (allocCount < MaxAllocs)
  302. {
  303. MemInfo& info = allocList[allocCount++];
  304. info = {};
  305. info.ptr = newPtr;
  306. info.size = newSize;
  307. info.file = fileName;
  308. info.line = line;
  309. info.allocId = currentAllocId++;
  310. }
  311. return newPtr;
  312. }
  313. #endif
  314. }
  315. //---------------------------------------------------------------------------
  316. //---------------------------------------------------------------------------
  317. #if !defined(TORQUE_DISABLE_MEMORY_MANAGER)
  318. // Manage our own memory, add overloaded memory operators and functions
  319. void* FN_CDECL operator new(dsize_t size, const char* fileName, const U32 line)
  320. {
  321. return Memory::alloc(size, false, fileName, line);
  322. }
  323. void* FN_CDECL operator new[](dsize_t size, const char* fileName, const U32 line)
  324. {
  325. return Memory::alloc(size, true, fileName, line);
  326. }
  327. void* FN_CDECL operator new(dsize_t size)
  328. {
  329. return Memory::alloc(size, false, NULL, 0);
  330. }
  331. void* FN_CDECL operator new[](dsize_t size)
  332. {
  333. return Memory::alloc(size, true, NULL, 0);
  334. }
  335. void FN_CDECL operator delete(void* mem)
  336. {
  337. Memory::free(mem, false);
  338. }
  339. void FN_CDECL operator delete[](void* mem)
  340. {
  341. Memory::free(mem, true);
  342. }
  343. void* dMalloc_r(dsize_t in_size, const char* fileName, const dsize_t line)
  344. {
  345. return Memory::alloc(in_size, false, fileName, line);
  346. }
  347. void dFree(void* in_pFree)
  348. {
  349. Memory::free(in_pFree, false);
  350. }
  351. void* dRealloc_r(void* in_pResize, dsize_t in_size, const char* fileName, const dsize_t line)
  352. {
  353. return Memory::realloc(in_pResize, in_size, fileName, line);
  354. }
  355. DefineEngineFunction(LeakTrace, void, (bool start, bool stackTrace), (true, true), "start/stop tracing leaks")
  356. {
  357. if (Memory::initialized) Memory::shutdown();
  358. if (start) Memory::init();
  359. Memory::gFromScript = true;
  360. Memory::gStackTrace = stackTrace;
  361. }
  362. #else
  363. // Don't manage our own memory
  364. void* dMalloc_r(dsize_t in_size, const char* fileName, const dsize_t line)
  365. {
  366. return malloc(in_size);
  367. }
  368. void dFree(void* in_pFree)
  369. {
  370. free(in_pFree);
  371. }
  372. void* dRealloc_r(void* in_pResize, dsize_t in_size, const char* fileName, const dsize_t line)
  373. {
  374. return realloc(in_pResize,in_size);
  375. }
  376. #endif