SDL_test_memory.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 1997-2023 Sam Lantinga <slouken@libsdl.org>
  4. This software is provided 'as-is', without any express or implied
  5. warranty. In no event will the authors be held liable for any damages
  6. arising from the use of this software.
  7. Permission is granted to anyone to use this software for any purpose,
  8. including commercial applications, and to alter it and redistribute it
  9. freely, subject to the following restrictions:
  10. 1. The origin of this software must not be misrepresented; you must not
  11. claim that you wrote the original software. If you use this software
  12. in a product, an acknowledgment in the product documentation would be
  13. appreciated but is not required.
  14. 2. Altered source versions must be plainly marked as such, and must not be
  15. misrepresented as being the original software.
  16. 3. This notice may not be removed or altered from any source distribution.
  17. */
  18. #include <SDL3/SDL_test.h>
  19. #ifdef HAVE_LIBUNWIND_H
  20. #define UNW_LOCAL_ONLY
  21. #include <libunwind.h>
  22. #endif
  23. #ifdef __WINDOWS__
  24. #include <windows.h>
  25. #include <dbghelp.h>
  26. static void *s_dbghelp;
  27. typedef BOOL (__stdcall *dbghelp_SymInitialize_fn)(HANDLE hProcess, PCSTR UserSearchPath, BOOL fInvadeProcess);
  28. typedef BOOL (__stdcall *dbghelp_SymFromAddr_fn)(HANDLE hProcess, DWORD64 Address, PDWORD64 Displacement, PSYMBOL_INFO Symbol);
  29. static dbghelp_SymFromAddr_fn dbghelp_SymFromAddr;
  30. #ifdef _WIN64
  31. typedef BOOL (__stdcall *dbghelp_SymGetLineFromAddr_fn)(HANDLE hProcess, DWORD64 qwAddr, PDWORD pdwDisplacement, PIMAGEHLP_LINE64 Line);
  32. #else
  33. typedef BOOL (__stdcall *dbghelp_SymGetLineFromAddr_fn)(HANDLE hProcess, DWORD qwAddr, PDWORD pdwDisplacement, PIMAGEHLP_LINE Line);
  34. #endif
  35. static dbghelp_SymGetLineFromAddr_fn dbghelp_SymGetLineFromAddr;
  36. #endif
  37. /* This is a simple tracking allocator to demonstrate the use of SDL's
  38. memory allocation replacement functionality.
  39. It gets slow with large numbers of allocations and shouldn't be used
  40. for production code.
  41. */
  42. #define MAXIMUM_TRACKED_STACK_DEPTH 32
  43. typedef struct SDL_tracked_allocation
  44. {
  45. void *mem;
  46. size_t size;
  47. Uint64 stack[MAXIMUM_TRACKED_STACK_DEPTH];
  48. char stack_names[MAXIMUM_TRACKED_STACK_DEPTH][256];
  49. struct SDL_tracked_allocation *next;
  50. } SDL_tracked_allocation;
  51. static SDLTest_Crc32Context s_crc32_context;
  52. static SDL_malloc_func SDL_malloc_orig = NULL;
  53. static SDL_calloc_func SDL_calloc_orig = NULL;
  54. static SDL_realloc_func SDL_realloc_orig = NULL;
  55. static SDL_free_func SDL_free_orig = NULL;
  56. static int s_previous_allocations = 0;
  57. static SDL_tracked_allocation *s_tracked_allocations[256];
  58. static SDL_bool s_randfill_allocations = SDL_FALSE;
  59. static unsigned int get_allocation_bucket(void *mem)
  60. {
  61. CrcUint32 crc_value;
  62. unsigned int index;
  63. SDLTest_Crc32Calc(&s_crc32_context, (CrcUint8 *)&mem, sizeof(mem), &crc_value);
  64. index = (crc_value & (SDL_arraysize(s_tracked_allocations) - 1));
  65. return index;
  66. }
  67. static SDL_tracked_allocation* SDL_GetTrackedAllocation(void *mem)
  68. {
  69. SDL_tracked_allocation *entry;
  70. int index = get_allocation_bucket(mem);
  71. for (entry = s_tracked_allocations[index]; entry; entry = entry->next) {
  72. if (mem == entry->mem) {
  73. return entry;
  74. }
  75. }
  76. return NULL;
  77. }
  78. static size_t SDL_GetTrackedAllocationSize(void *mem)
  79. {
  80. SDL_tracked_allocation *entry = SDL_GetTrackedAllocation(mem);
  81. return entry ? entry->size : SIZE_MAX;
  82. }
  83. static SDL_bool SDL_IsAllocationTracked(void *mem)
  84. {
  85. return SDL_GetTrackedAllocation(mem) != NULL;
  86. }
  87. static void SDL_TrackAllocation(void *mem, size_t size)
  88. {
  89. SDL_tracked_allocation *entry;
  90. int index = get_allocation_bucket(mem);
  91. if (SDL_IsAllocationTracked(mem)) {
  92. return;
  93. }
  94. entry = (SDL_tracked_allocation *)SDL_malloc_orig(sizeof(*entry));
  95. if (entry == NULL) {
  96. return;
  97. }
  98. entry->mem = mem;
  99. entry->size = size;
  100. /* Generate the stack trace for the allocation */
  101. SDL_zeroa(entry->stack);
  102. #ifdef HAVE_LIBUNWIND_H
  103. {
  104. int stack_index;
  105. unw_cursor_t cursor;
  106. unw_context_t context;
  107. unw_getcontext(&context);
  108. unw_init_local(&cursor, &context);
  109. stack_index = 0;
  110. while (unw_step(&cursor) > 0) {
  111. unw_word_t offset, pc;
  112. char sym[236];
  113. unw_get_reg(&cursor, UNW_REG_IP, &pc);
  114. entry->stack[stack_index] = pc;
  115. if (unw_get_proc_name(&cursor, sym, sizeof(sym), &offset) == 0) {
  116. SDL_snprintf(entry->stack_names[stack_index], sizeof(entry->stack_names[stack_index]), "%s+0x%llx", sym, (unsigned long long)offset);
  117. }
  118. ++stack_index;
  119. if (stack_index == SDL_arraysize(entry->stack)) {
  120. break;
  121. }
  122. }
  123. }
  124. #elif defined(__WINDOWS__)
  125. {
  126. Uint32 count;
  127. PVOID frames[63];
  128. Uint32 i;
  129. count = CaptureStackBackTrace(1, SDL_arraysize(frames), frames, NULL);
  130. entry->size = SDL_min(count, MAXIMUM_TRACKED_STACK_DEPTH);
  131. for (i = 0; i < entry->size; i++) {
  132. char symbol_buffer[sizeof(SYMBOL_INFO) + MAX_SYM_NAME * sizeof(TCHAR)];
  133. PSYMBOL_INFO pSymbol = (PSYMBOL_INFO)symbol_buffer;
  134. DWORD64 dwDisplacement = 0;
  135. DWORD lineColumn = 0;
  136. pSymbol->SizeOfStruct = sizeof(SYMBOL_INFO);
  137. pSymbol->MaxNameLen = MAX_SYM_NAME;
  138. IMAGEHLP_LINE line;
  139. line.SizeOfStruct = sizeof(line);
  140. entry->stack[i] = (Uint64)(uintptr_t)frames[i];
  141. if (s_dbghelp) {
  142. if (!dbghelp_SymFromAddr(GetCurrentProcess(), (DWORD64)(uintptr_t)frames[i], &dwDisplacement, pSymbol)) {
  143. SDL_strlcpy(pSymbol->Name, "???", MAX_SYM_NAME);
  144. dwDisplacement = 0;
  145. }
  146. if (!dbghelp_SymGetLineFromAddr(GetCurrentProcess(), (DWORD64)(uintptr_t)frames[i], &lineColumn, &line)) {
  147. line.FileName = "";
  148. line.LineNumber = 0;
  149. }
  150. SDL_snprintf(entry->stack_names[i], sizeof(entry->stack_names[i]), "%s+0x%llx %s:%u", pSymbol->Name, (unsigned long long)dwDisplacement, line.FileName, (Uint32)line.LineNumber);
  151. }
  152. }
  153. }
  154. #endif /* HAVE_LIBUNWIND_H */
  155. entry->next = s_tracked_allocations[index];
  156. s_tracked_allocations[index] = entry;
  157. }
  158. static void SDL_UntrackAllocation(void *mem)
  159. {
  160. SDL_tracked_allocation *entry, *prev;
  161. int index = get_allocation_bucket(mem);
  162. prev = NULL;
  163. for (entry = s_tracked_allocations[index]; entry; entry = entry->next) {
  164. if (mem == entry->mem) {
  165. if (prev) {
  166. prev->next = entry->next;
  167. } else {
  168. s_tracked_allocations[index] = entry->next;
  169. }
  170. SDL_free_orig(entry);
  171. return;
  172. }
  173. prev = entry;
  174. }
  175. }
  176. static void rand_fill_memory(void* ptr, size_t start, size_t end)
  177. {
  178. Uint8* mem = (Uint8*) ptr;
  179. size_t i;
  180. if (!s_randfill_allocations)
  181. return;
  182. for (i = start; i < end; ++i) {
  183. mem[i] = SDLTest_RandomUint8();
  184. }
  185. }
  186. static void *SDLCALL SDLTest_TrackedMalloc(size_t size)
  187. {
  188. void *mem;
  189. mem = SDL_malloc_orig(size);
  190. if (mem) {
  191. SDL_TrackAllocation(mem, size);
  192. rand_fill_memory(mem, 0, size);
  193. }
  194. return mem;
  195. }
  196. static void *SDLCALL SDLTest_TrackedCalloc(size_t nmemb, size_t size)
  197. {
  198. void *mem;
  199. mem = SDL_calloc_orig(nmemb, size);
  200. if (mem) {
  201. SDL_TrackAllocation(mem, nmemb * size);
  202. }
  203. return mem;
  204. }
  205. static void *SDLCALL SDLTest_TrackedRealloc(void *ptr, size_t size)
  206. {
  207. void *mem;
  208. size_t old_size = 0;
  209. if (ptr) {
  210. old_size = SDL_GetTrackedAllocationSize(ptr);
  211. SDL_assert(old_size != SIZE_MAX);
  212. }
  213. mem = SDL_realloc_orig(ptr, size);
  214. if (ptr) {
  215. SDL_UntrackAllocation(ptr);
  216. }
  217. if (mem) {
  218. SDL_TrackAllocation(mem, size);
  219. if (size > old_size) {
  220. rand_fill_memory(mem, old_size, size);
  221. }
  222. }
  223. return mem;
  224. }
  225. static void SDLCALL SDLTest_TrackedFree(void *ptr)
  226. {
  227. if (ptr == NULL) {
  228. return;
  229. }
  230. if (!s_previous_allocations) {
  231. SDL_assert(SDL_IsAllocationTracked(ptr));
  232. }
  233. SDL_UntrackAllocation(ptr);
  234. SDL_free_orig(ptr);
  235. }
  236. void SDLTest_TrackAllocations(void)
  237. {
  238. if (SDL_malloc_orig) {
  239. return;
  240. }
  241. SDLTest_Crc32Init(&s_crc32_context);
  242. s_previous_allocations = SDL_GetNumAllocations();
  243. if (s_previous_allocations != 0) {
  244. SDL_Log("SDLTest_TrackAllocations(): There are %d previous allocations, disabling free() validation", s_previous_allocations);
  245. }
  246. #ifdef __WINDOWS__
  247. {
  248. s_dbghelp = SDL_LoadObject("dbghelp.dll");
  249. if (s_dbghelp) {
  250. dbghelp_SymInitialize_fn dbghelp_SymInitialize;
  251. dbghelp_SymInitialize = (dbghelp_SymInitialize_fn)SDL_LoadFunction(s_dbghelp, "SymInitialize");
  252. dbghelp_SymFromAddr = (dbghelp_SymFromAddr_fn)SDL_LoadFunction(s_dbghelp, "SymFromAddr");
  253. #ifdef _WIN64
  254. dbghelp_SymGetLineFromAddr = (dbghelp_SymGetLineFromAddr_fn)SDL_LoadFunction(s_dbghelp, "SymGetLineFromAddr64");
  255. #else
  256. dbghelp_SymGetLineFromAddr = (dbghelp_SymGetLineFromAddr_fn)SDL_LoadFunction(s_dbghelp, "SymGetLineFromAddr");
  257. #endif
  258. if (!dbghelp_SymFromAddr || !dbghelp_SymFromAddr || !dbghelp_SymGetLineFromAddr) {
  259. SDL_UnloadObject(s_dbghelp);
  260. s_dbghelp = NULL;
  261. } else {
  262. if (!dbghelp_SymInitialize(GetCurrentProcess(), NULL, TRUE)) {
  263. SDL_UnloadObject(s_dbghelp);
  264. s_dbghelp = NULL;
  265. }
  266. }
  267. }
  268. }
  269. #endif
  270. SDL_GetMemoryFunctions(&SDL_malloc_orig,
  271. &SDL_calloc_orig,
  272. &SDL_realloc_orig,
  273. &SDL_free_orig);
  274. SDL_SetMemoryFunctions(SDLTest_TrackedMalloc,
  275. SDLTest_TrackedCalloc,
  276. SDLTest_TrackedRealloc,
  277. SDLTest_TrackedFree);
  278. }
  279. void SDLTest_RandFillAllocations()
  280. {
  281. SDLTest_TrackAllocations();
  282. s_randfill_allocations = SDL_TRUE;
  283. }
  284. void SDLTest_LogAllocations(void)
  285. {
  286. char *message = NULL;
  287. size_t message_size = 0;
  288. char line[128], *tmp;
  289. SDL_tracked_allocation *entry;
  290. int index, count, stack_index;
  291. Uint64 total_allocated;
  292. if (!SDL_malloc_orig) {
  293. return;
  294. }
  295. message = SDL_realloc_orig(NULL, 1);
  296. if (!message) {
  297. return;
  298. }
  299. *message = 0;
  300. #define ADD_LINE() \
  301. message_size += (SDL_strlen(line) + 1); \
  302. tmp = (char *)SDL_realloc_orig(message, message_size); \
  303. if (!tmp) { \
  304. return; \
  305. } \
  306. message = tmp; \
  307. SDL_strlcat(message, line, message_size)
  308. SDL_strlcpy(line, "Memory allocations:\n", sizeof(line));
  309. ADD_LINE();
  310. count = 0;
  311. total_allocated = 0;
  312. for (index = 0; index < SDL_arraysize(s_tracked_allocations); ++index) {
  313. for (entry = s_tracked_allocations[index]; entry; entry = entry->next) {
  314. (void)SDL_snprintf(line, sizeof(line), "Allocation %d: %d bytes\n", count, (int)entry->size);
  315. ADD_LINE();
  316. /* Start at stack index 1 to skip our tracking functions */
  317. for (stack_index = 1; stack_index < SDL_arraysize(entry->stack); ++stack_index) {
  318. if (!entry->stack[stack_index]) {
  319. break;
  320. }
  321. (void)SDL_snprintf(line, sizeof(line), "\t0x%" SDL_PRIx64 ": %s\n", entry->stack[stack_index], entry->stack_names[stack_index]);
  322. ADD_LINE();
  323. }
  324. total_allocated += entry->size;
  325. ++count;
  326. }
  327. }
  328. (void)SDL_snprintf(line, sizeof(line), "Total: %.2f Kb in %d allocations\n", total_allocated / 1024.0, count);
  329. ADD_LINE();
  330. #undef ADD_LINE
  331. SDL_Log("%s", message);
  332. }