platformMemory.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  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. bool sortMemReports(memReport const& lhs, memReport const& rhs)
  79. {
  80. if (lhs.total != rhs.total)
  81. return lhs.total > rhs.total;
  82. return lhs.count > rhs.count;
  83. }
  84. void init()
  85. {
  86. if (initialized) return;
  87. std::memset(allocList, 0, sizeof(allocList));
  88. std::memset(memLog, 0, sizeof(memLog));
  89. allocCount = 0;
  90. currentAllocId = 0;
  91. initialized = true;
  92. // Generate timestamped log filename
  93. std::time_t now = std::time(nullptr);
  94. std::tm* localTime = std::localtime(&now);
  95. std::strftime(gLogFilename, sizeof(gLogFilename), "memlog_%Y-%m-%d_%H-%M-%S.txt", localTime);
  96. std::atexit(shutdown);
  97. }
  98. void shutdown()
  99. {
  100. if (!initialized) return;
  101. FILE* log = std::fopen(gLogFilename, "w");
  102. if (!log)
  103. return;
  104. std::fprintf(log, "\n--- Memory Leak Report ---\n");
  105. for (U32 curRep = 0; curRep < allocCount; ++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\n",
  132. curStack, symbol->Name, line.FileName, line.LineNumber);
  133. }
  134. else {
  135. std::sprintf(stack, " [%d] %s - ???:???\n",
  136. curStack, symbol->Name);
  137. }
  138. }
  139. else {
  140. std::sprintf(stack, " [%d] ???\n", curStack);
  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. for (U32 oldRep = 0; oldRep < curRep; ++oldRep)
  156. {
  157. if (!memLog[oldRep].skip && (memLog[oldRep].report.find(report) != std::string::npos))
  158. {
  159. //inc origional
  160. memLog[oldRep].count++;
  161. memLog[oldRep].total += allocList[curRep].size;
  162. //skip dupe report
  163. memLog[curRep].skip = true;
  164. }
  165. }
  166. if (!memLog[curRep].skip)
  167. {
  168. memLog[curRep].report = report;
  169. memLog[curRep].count = 1;
  170. memLog[curRep].total = allocList[curRep].size;
  171. }
  172. }
  173. }
  174. std::sort(memLog, memLog + allocCount, &sortMemReports);
  175. for (U32 ntry = 0; ntry < allocCount; ++ntry)
  176. {
  177. if (!memLog[ntry].skip /* && (memLog[ntry].count>9 || memLog[ntry].total >1023)*/) //unrem to focus on large leaks only -BJR
  178. {
  179. std::fprintf(log, "Leak-count[%i]total[%i]:%s", memLog[ntry].count, memLog[ntry].total, memLog[ntry].report.c_str());
  180. memLog[ntry].report.clear();
  181. }
  182. }
  183. std::fclose(log);
  184. std::memset(allocList, 0, sizeof(allocList));
  185. std::memset(memLog, 0, sizeof(memLog));
  186. allocCount = 0;
  187. currentAllocId = 0;
  188. initialized = false;
  189. }
  190. void checkPtr(void* ptr)
  191. {
  192. for (U32 i = 0; i < allocCount; ++i)
  193. if (allocList[i].ptr == ptr)
  194. return;
  195. Platform::debugBreak();
  196. }
  197. static void* alloc(dsize_t size, bool array, const char* fileName, U32 line)
  198. {
  199. if (size == 0)
  200. return nullptr;
  201. void* ptr = std::malloc(size);
  202. if (!ptr)
  203. return nullptr;
  204. if (!initialized || allocCount >= MaxAllocs)
  205. return ptr;
  206. MemInfo& info = allocList[allocCount++];
  207. info.ptr = ptr;
  208. info.size = size;
  209. info.file = fileName ? fileName : "unknown";
  210. info.line = line;
  211. info.allocId = currentAllocId++;
  212. info.flagged = false;
  213. if (gStackTrace)
  214. {
  215. #ifdef _WIN32
  216. info.backtraceSize = CaptureStackBackTrace(0, 16, info.backtracePtrs, nullptr);
  217. #else
  218. info.backtraceSize = backtrace(info.backtracePtrs, MaxBacktraceDepth);
  219. #endif
  220. }
  221. return ptr;
  222. }
  223. static void free(void* ptr, bool array)
  224. {
  225. if (!ptr)
  226. return;
  227. if (!initialized)
  228. {
  229. std::free(ptr);
  230. return;
  231. }
  232. for (U32 i = 0; i < allocCount; ++i)
  233. {
  234. if (allocList[i].ptr == ptr)
  235. {
  236. std::free(ptr);
  237. allocList[i] = allocList[allocCount - 1];
  238. allocList[--allocCount] = {};
  239. return;
  240. }
  241. }
  242. // Unknown pointer, still free it.
  243. std::free(ptr);
  244. }
  245. void getMemoryInfo(void* ptr, MemInfo& info)
  246. {
  247. if (!ptr || !initialized)
  248. return;
  249. for (U32 i = 0; i < allocCount; ++i)
  250. {
  251. if (allocList[i].ptr == ptr)
  252. {
  253. info = allocList[i];
  254. return;
  255. }
  256. }
  257. }
  258. static void* realloc(void* oldPtr, dsize_t newSize, const char* fileName, U32 line)
  259. {
  260. if (!initialized)
  261. return std::realloc(oldPtr, newSize); // fallback if not tracking
  262. if (newSize == 0)
  263. {
  264. free(oldPtr, false);
  265. return nullptr;
  266. }
  267. if (oldPtr == nullptr)
  268. return alloc(newSize, false, fileName, line);
  269. void* newPtr = std::realloc(oldPtr, newSize);
  270. if (!newPtr)
  271. return nullptr;
  272. // Update existing record
  273. for (U32 i = 0; i < allocCount; ++i)
  274. {
  275. if (allocList[i].ptr == oldPtr)
  276. {
  277. allocList[i].ptr = newPtr;
  278. allocList[i].size = newSize;
  279. allocList[i].file = fileName;
  280. allocList[i].line = line;
  281. allocList[i].allocId = currentAllocId++;
  282. return newPtr;
  283. }
  284. }
  285. // Not found — see if newPtr is already being tracked
  286. for (U32 i = 0; i < allocCount; ++i)
  287. {
  288. if (allocList[i].ptr == newPtr)
  289. {
  290. allocList[i].size = newSize;
  291. allocList[i].file = fileName;
  292. allocList[i].line = line;
  293. allocList[i].allocId = currentAllocId++;
  294. return newPtr;
  295. }
  296. }
  297. // Still not found — treat as a new allocation
  298. if (allocCount < MaxAllocs)
  299. {
  300. MemInfo& info = allocList[allocCount++];
  301. info = {};
  302. info.ptr = newPtr;
  303. info.size = newSize;
  304. info.file = fileName;
  305. info.line = line;
  306. info.allocId = currentAllocId++;
  307. }
  308. return newPtr;
  309. }
  310. #endif
  311. }
  312. //---------------------------------------------------------------------------
  313. //---------------------------------------------------------------------------
  314. #if !defined(TORQUE_DISABLE_MEMORY_MANAGER)
  315. // Manage our own memory, add overloaded memory operators and functions
  316. void* FN_CDECL operator new(dsize_t size, const char* fileName, const U32 line)
  317. {
  318. return Memory::alloc(size, false, fileName, line);
  319. }
  320. void* FN_CDECL operator new[](dsize_t size, const char* fileName, const U32 line)
  321. {
  322. return Memory::alloc(size, true, fileName, line);
  323. }
  324. void* FN_CDECL operator new(dsize_t size)
  325. {
  326. return Memory::alloc(size, false, NULL, 0);
  327. }
  328. void* FN_CDECL operator new[](dsize_t size)
  329. {
  330. return Memory::alloc(size, true, NULL, 0);
  331. }
  332. void FN_CDECL operator delete(void* mem)
  333. {
  334. Memory::free(mem, false);
  335. }
  336. void FN_CDECL operator delete[](void* mem)
  337. {
  338. Memory::free(mem, true);
  339. }
  340. void* dMalloc_r(dsize_t in_size, const char* fileName, const dsize_t line)
  341. {
  342. return Memory::alloc(in_size, false, fileName, line);
  343. }
  344. void dFree(void* in_pFree)
  345. {
  346. Memory::free(in_pFree, false);
  347. }
  348. void* dRealloc_r(void* in_pResize, dsize_t in_size, const char* fileName, const dsize_t line)
  349. {
  350. return Memory::realloc(in_pResize, in_size, fileName, line);
  351. }
  352. DefineEngineFunction(LeakTrace, void, (bool start, bool stackTrace), (true, true), "start/stop tracing leaks")
  353. {
  354. if (Memory::initialized) Memory::shutdown();
  355. if (start) Memory::init();
  356. Memory::gFromScript = true;
  357. Memory::gStackTrace = stackTrace;
  358. }
  359. #else
  360. // Don't manage our own memory
  361. void* dMalloc_r(dsize_t in_size, const char* fileName, const dsize_t line)
  362. {
  363. return malloc(in_size);
  364. }
  365. void dFree(void* in_pFree)
  366. {
  367. free(in_pFree);
  368. }
  369. void* dRealloc_r(void* in_pResize, dsize_t in_size, const char* fileName, const dsize_t line)
  370. {
  371. return realloc(in_pResize, in_size);
  372. }
  373. #endif