SDL_test_memory.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 1997-2025 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. #ifndef unw_get_proc_name_by_ip
  23. #define SDLTEST_UNWIND_NO_PROC_NAME_BY_IP
  24. static bool s_unwind_symbol_names = true;
  25. #endif
  26. #endif
  27. #ifdef SDL_PLATFORM_WIN32
  28. #include <windows.h>
  29. #include <dbghelp.h>
  30. static struct {
  31. SDL_SharedObject *module;
  32. BOOL (WINAPI *pSymInitialize)(HANDLE hProcess, PCSTR UserSearchPath, BOOL fInvadeProcess);
  33. BOOL (WINAPI *pSymFromAddr)(HANDLE hProcess, DWORD64 Address, PDWORD64 Displacement, PSYMBOL_INFO Symbol);
  34. BOOL (WINAPI *pSymGetLineFromAddr64)(HANDLE hProcess, DWORD64 qwAddr, PDWORD pdwDisplacement, PIMAGEHLP_LINE64 Line);
  35. } dyn_dbghelp;
  36. /* older SDKs might not have this: */
  37. __declspec(dllimport) USHORT WINAPI RtlCaptureStackBackTrace(ULONG FramesToSkip, ULONG FramesToCapture, PVOID* BackTrace, PULONG BackTraceHash);
  38. #define CaptureStackBackTrace RtlCaptureStackBackTrace
  39. #endif
  40. /* This is a simple tracking allocator to demonstrate the use of SDL's
  41. memory allocation replacement functionality.
  42. It gets slow with large numbers of allocations and shouldn't be used
  43. for production code.
  44. */
  45. #define MAXIMUM_TRACKED_STACK_DEPTH 32
  46. typedef struct SDL_tracked_allocation
  47. {
  48. void *mem;
  49. size_t size;
  50. Uint64 stack[MAXIMUM_TRACKED_STACK_DEPTH];
  51. struct SDL_tracked_allocation *next;
  52. #ifdef SDLTEST_UNWIND_NO_PROC_NAME_BY_IP
  53. char stack_names[MAXIMUM_TRACKED_STACK_DEPTH][256];
  54. #endif
  55. } SDL_tracked_allocation;
  56. static SDLTest_Crc32Context s_crc32_context;
  57. static SDL_malloc_func SDL_malloc_orig = NULL;
  58. static SDL_calloc_func SDL_calloc_orig = NULL;
  59. static SDL_realloc_func SDL_realloc_orig = NULL;
  60. static SDL_free_func SDL_free_orig = NULL;
  61. static int s_previous_allocations = 0;
  62. static int s_unknown_frees = 0;
  63. static SDL_tracked_allocation *s_tracked_allocations[256];
  64. static bool s_randfill_allocations = false;
  65. static SDL_AtomicInt s_lock;
  66. #define LOCK_ALLOCATOR() \
  67. do { \
  68. if (SDL_CompareAndSwapAtomicInt(&s_lock, 0, 1)) { \
  69. break; \
  70. } \
  71. SDL_CPUPauseInstruction(); \
  72. } while (true)
  73. #define UNLOCK_ALLOCATOR() do { SDL_SetAtomicInt(&s_lock, 0); } while (0)
  74. static unsigned int get_allocation_bucket(void *mem)
  75. {
  76. CrcUint32 crc_value;
  77. unsigned int index;
  78. SDLTest_Crc32Calc(&s_crc32_context, (CrcUint8 *)&mem, sizeof(mem), &crc_value);
  79. index = (crc_value & (SDL_arraysize(s_tracked_allocations) - 1));
  80. return index;
  81. }
  82. static SDL_tracked_allocation* SDL_GetTrackedAllocation(void *mem)
  83. {
  84. SDL_tracked_allocation *entry;
  85. LOCK_ALLOCATOR();
  86. int index = get_allocation_bucket(mem);
  87. for (entry = s_tracked_allocations[index]; entry; entry = entry->next) {
  88. if (mem == entry->mem) {
  89. UNLOCK_ALLOCATOR();
  90. return entry;
  91. }
  92. }
  93. UNLOCK_ALLOCATOR();
  94. return NULL;
  95. }
  96. static size_t SDL_GetTrackedAllocationSize(void *mem)
  97. {
  98. SDL_tracked_allocation *entry = SDL_GetTrackedAllocation(mem);
  99. return entry ? entry->size : SIZE_MAX;
  100. }
  101. static bool SDL_IsAllocationTracked(void *mem)
  102. {
  103. return SDL_GetTrackedAllocation(mem) != NULL;
  104. }
  105. static void SDL_TrackAllocation(void *mem, size_t size)
  106. {
  107. SDL_tracked_allocation *entry;
  108. int index = get_allocation_bucket(mem);
  109. if (SDL_IsAllocationTracked(mem)) {
  110. return;
  111. }
  112. entry = (SDL_tracked_allocation *)SDL_malloc_orig(sizeof(*entry));
  113. if (!entry) {
  114. return;
  115. }
  116. LOCK_ALLOCATOR();
  117. entry->mem = mem;
  118. entry->size = size;
  119. /* Generate the stack trace for the allocation */
  120. SDL_zeroa(entry->stack);
  121. #ifdef HAVE_LIBUNWIND_H
  122. {
  123. int stack_index;
  124. unw_cursor_t cursor;
  125. unw_context_t context;
  126. unw_getcontext(&context);
  127. unw_init_local(&cursor, &context);
  128. stack_index = 0;
  129. while (unw_step(&cursor) > 0) {
  130. unw_word_t pc;
  131. #ifdef SDLTEST_UNWIND_NO_PROC_NAME_BY_IP
  132. unw_word_t offset;
  133. char sym[236];
  134. #endif
  135. unw_get_reg(&cursor, UNW_REG_IP, &pc);
  136. entry->stack[stack_index] = pc;
  137. #ifdef SDLTEST_UNWIND_NO_PROC_NAME_BY_IP
  138. if (s_unwind_symbol_names && unw_get_proc_name(&cursor, sym, sizeof(sym), &offset) == 0) {
  139. SDL_snprintf(entry->stack_names[stack_index], sizeof(entry->stack_names[stack_index]), "%s+0x%llx", sym, (unsigned long long)offset);
  140. }
  141. #endif
  142. ++stack_index;
  143. if (stack_index == SDL_arraysize(entry->stack)) {
  144. break;
  145. }
  146. }
  147. }
  148. #elif defined(SDL_PLATFORM_WIN32)
  149. {
  150. Uint32 count;
  151. PVOID frames[63];
  152. Uint32 i;
  153. count = CaptureStackBackTrace(1, SDL_arraysize(frames), frames, NULL);
  154. count = SDL_min(count, MAXIMUM_TRACKED_STACK_DEPTH);
  155. for (i = 0; i < count; i++) {
  156. entry->stack[i] = (Uint64)(uintptr_t)frames[i];
  157. }
  158. }
  159. #endif /* HAVE_LIBUNWIND_H */
  160. entry->next = s_tracked_allocations[index];
  161. s_tracked_allocations[index] = entry;
  162. UNLOCK_ALLOCATOR();
  163. }
  164. static void SDL_UntrackAllocation(void *mem)
  165. {
  166. SDL_tracked_allocation *entry, *prev;
  167. int index = get_allocation_bucket(mem);
  168. LOCK_ALLOCATOR();
  169. prev = NULL;
  170. for (entry = s_tracked_allocations[index]; entry; entry = entry->next) {
  171. if (mem == entry->mem) {
  172. if (prev) {
  173. prev->next = entry->next;
  174. } else {
  175. s_tracked_allocations[index] = entry->next;
  176. }
  177. SDL_free_orig(entry);
  178. UNLOCK_ALLOCATOR();
  179. return;
  180. }
  181. prev = entry;
  182. }
  183. s_unknown_frees += 1;
  184. UNLOCK_ALLOCATOR();
  185. }
  186. static void rand_fill_memory(void* ptr, size_t start, size_t end)
  187. {
  188. Uint8* mem = (Uint8*) ptr;
  189. size_t i;
  190. if (!s_randfill_allocations)
  191. return;
  192. for (i = start; i < end; ++i) {
  193. mem[i] = SDLTest_RandomUint8();
  194. }
  195. }
  196. static void * SDLCALL SDLTest_TrackedMalloc(size_t size)
  197. {
  198. void *mem;
  199. mem = SDL_malloc_orig(size);
  200. if (mem) {
  201. SDL_TrackAllocation(mem, size);
  202. rand_fill_memory(mem, 0, size);
  203. }
  204. return mem;
  205. }
  206. static void * SDLCALL SDLTest_TrackedCalloc(size_t nmemb, size_t size)
  207. {
  208. void *mem;
  209. mem = SDL_calloc_orig(nmemb, size);
  210. if (mem) {
  211. SDL_TrackAllocation(mem, nmemb * size);
  212. }
  213. return mem;
  214. }
  215. static void * SDLCALL SDLTest_TrackedRealloc(void *ptr, size_t size)
  216. {
  217. void *mem;
  218. size_t old_size = 0;
  219. if (ptr) {
  220. old_size = SDL_GetTrackedAllocationSize(ptr);
  221. SDL_assert(old_size != SIZE_MAX);
  222. }
  223. mem = SDL_realloc_orig(ptr, size);
  224. if (ptr) {
  225. SDL_UntrackAllocation(ptr);
  226. }
  227. if (mem) {
  228. SDL_TrackAllocation(mem, size);
  229. if (size > old_size) {
  230. rand_fill_memory(mem, old_size, size);
  231. }
  232. }
  233. return mem;
  234. }
  235. static void SDLCALL SDLTest_TrackedFree(void *ptr)
  236. {
  237. if (!ptr) {
  238. return;
  239. }
  240. if (s_previous_allocations == 0) {
  241. SDL_assert(SDL_IsAllocationTracked(ptr));
  242. }
  243. SDL_UntrackAllocation(ptr);
  244. SDL_free_orig(ptr);
  245. }
  246. void SDLTest_TrackAllocations(void)
  247. {
  248. if (SDL_malloc_orig) {
  249. return;
  250. }
  251. SDLTest_Crc32Init(&s_crc32_context);
  252. s_previous_allocations = SDL_GetNumAllocations();
  253. if (s_previous_allocations < 0) {
  254. SDL_Log("SDL was built without allocation count support, disabling free() validation");
  255. } else if (s_previous_allocations != 0) {
  256. SDL_Log("SDLTest_TrackAllocations(): There are %d previous allocations, disabling free() validation", s_previous_allocations);
  257. }
  258. #ifdef SDLTEST_UNWIND_NO_PROC_NAME_BY_IP
  259. do {
  260. /* Don't use SDL_GetHint: SDL_malloc is off limits. */
  261. const char *env_trackmem = SDL_getenv_unsafe("SDL_TRACKMEM_SYMBOL_NAMES");
  262. if (env_trackmem) {
  263. if (SDL_strcasecmp(env_trackmem, "1") == 0 || SDL_strcasecmp(env_trackmem, "yes") == 0 || SDL_strcasecmp(env_trackmem, "true") == 0) {
  264. s_unwind_symbol_names = true;
  265. } else if (SDL_strcasecmp(env_trackmem, "0") == 0 || SDL_strcasecmp(env_trackmem, "no") == 0 || SDL_strcasecmp(env_trackmem, "false") == 0) {
  266. s_unwind_symbol_names = false;
  267. }
  268. }
  269. } while (0);
  270. #elif defined(SDL_PLATFORM_WIN32)
  271. do {
  272. dyn_dbghelp.module = SDL_LoadObject("dbghelp.dll");
  273. if (!dyn_dbghelp.module) {
  274. goto dbghelp_failed;
  275. }
  276. dyn_dbghelp.pSymInitialize = (void *)SDL_LoadFunction(dyn_dbghelp.module, "SymInitialize");
  277. dyn_dbghelp.pSymFromAddr = (void *)SDL_LoadFunction(dyn_dbghelp.module, "SymFromAddr");
  278. dyn_dbghelp.pSymGetLineFromAddr64 = (void *)SDL_LoadFunction(dyn_dbghelp.module, "SymGetLineFromAddr64");
  279. if (!dyn_dbghelp.pSymInitialize || !dyn_dbghelp.pSymFromAddr || !dyn_dbghelp.pSymGetLineFromAddr64) {
  280. goto dbghelp_failed;
  281. }
  282. if (!dyn_dbghelp.pSymInitialize(GetCurrentProcess(), NULL, TRUE)) {
  283. goto dbghelp_failed;
  284. }
  285. break;
  286. dbghelp_failed:
  287. if (dyn_dbghelp.module) {
  288. SDL_UnloadObject(dyn_dbghelp.module);
  289. dyn_dbghelp.module = NULL;
  290. }
  291. } while (0);
  292. #endif
  293. SDL_GetMemoryFunctions(&SDL_malloc_orig,
  294. &SDL_calloc_orig,
  295. &SDL_realloc_orig,
  296. &SDL_free_orig);
  297. SDL_SetMemoryFunctions(SDLTest_TrackedMalloc,
  298. SDLTest_TrackedCalloc,
  299. SDLTest_TrackedRealloc,
  300. SDLTest_TrackedFree);
  301. }
  302. void SDLTest_RandFillAllocations(void)
  303. {
  304. SDLTest_TrackAllocations();
  305. s_randfill_allocations = true;
  306. }
  307. void SDLTest_LogAllocations(void)
  308. {
  309. char *message = NULL;
  310. size_t message_size = 0;
  311. char line[256], *tmp;
  312. SDL_tracked_allocation *entry;
  313. int index, count, stack_index;
  314. Uint64 total_allocated;
  315. if (!SDL_malloc_orig) {
  316. return;
  317. }
  318. message = SDL_realloc_orig(NULL, 1);
  319. if (!message) {
  320. return;
  321. }
  322. *message = 0;
  323. #define ADD_LINE() \
  324. message_size += (SDL_strlen(line) + 1); \
  325. tmp = (char *)SDL_realloc_orig(message, message_size); \
  326. if (!tmp) { \
  327. return; \
  328. } \
  329. message = tmp; \
  330. SDL_strlcat(message, line, message_size)
  331. SDL_strlcpy(line, "Memory allocations:\n", sizeof(line));
  332. ADD_LINE();
  333. count = 0;
  334. total_allocated = 0;
  335. for (index = 0; index < SDL_arraysize(s_tracked_allocations); ++index) {
  336. for (entry = s_tracked_allocations[index]; entry; entry = entry->next) {
  337. (void)SDL_snprintf(line, sizeof(line), "Allocation %d: %d bytes\n", count, (int)entry->size);
  338. ADD_LINE();
  339. /* Start at stack index 1 to skip our tracking functions */
  340. for (stack_index = 1; stack_index < SDL_arraysize(entry->stack); ++stack_index) {
  341. char stack_entry_description[256] = "???";
  342. if (!entry->stack[stack_index]) {
  343. break;
  344. }
  345. #ifdef HAVE_LIBUNWIND_H
  346. {
  347. #ifdef SDLTEST_UNWIND_NO_PROC_NAME_BY_IP
  348. if (s_unwind_symbol_names) {
  349. (void)SDL_snprintf(stack_entry_description, sizeof(stack_entry_description), "%s", entry->stack_names[stack_index]);
  350. }
  351. #else
  352. char name[256] = "???";
  353. unw_word_t offset = 0;
  354. unw_get_proc_name_by_ip(unw_local_addr_space, entry->stack[stack_index], name, sizeof(name), &offset, NULL);
  355. (void)SDL_snprintf(stack_entry_description, sizeof(stack_entry_description), "%s+0x%llx", name, (long long unsigned int)offset);
  356. #endif
  357. }
  358. #elif defined(SDL_PLATFORM_WIN32)
  359. {
  360. DWORD64 dwDisplacement = 0;
  361. char symbol_buffer[sizeof(SYMBOL_INFO) + MAX_SYM_NAME * sizeof(TCHAR)];
  362. PSYMBOL_INFO pSymbol = (PSYMBOL_INFO)symbol_buffer;
  363. DWORD lineColumn = 0;
  364. pSymbol->SizeOfStruct = sizeof(SYMBOL_INFO);
  365. pSymbol->MaxNameLen = MAX_SYM_NAME;
  366. IMAGEHLP_LINE64 dbg_line;
  367. dbg_line.SizeOfStruct = sizeof(dbg_line);
  368. dbg_line.FileName = "";
  369. dbg_line.LineNumber = 0;
  370. if (dyn_dbghelp.module) {
  371. if (!dyn_dbghelp.pSymFromAddr(GetCurrentProcess(), entry->stack[stack_index], &dwDisplacement, pSymbol)) {
  372. SDL_strlcpy(pSymbol->Name, "???", MAX_SYM_NAME);
  373. dwDisplacement = 0;
  374. }
  375. dyn_dbghelp.pSymGetLineFromAddr64(GetCurrentProcess(), (DWORD64)entry->stack[stack_index], &lineColumn, &dbg_line);
  376. }
  377. SDL_snprintf(stack_entry_description, sizeof(stack_entry_description), "%s+0x%I64x %s:%u", pSymbol->Name, dwDisplacement, dbg_line.FileName, (Uint32)dbg_line.LineNumber);
  378. }
  379. #endif
  380. (void)SDL_snprintf(line, sizeof(line), "\t0x%" SDL_PRIx64 ": %s\n", entry->stack[stack_index], stack_entry_description);
  381. ADD_LINE();
  382. }
  383. total_allocated += entry->size;
  384. ++count;
  385. }
  386. }
  387. (void)SDL_snprintf(line, sizeof(line), "Total: %.2f Kb in %d allocations", total_allocated / 1024.0, count);
  388. ADD_LINE();
  389. if (s_unknown_frees != 0) {
  390. (void)SDL_snprintf(line, sizeof(line), ", %d unknown frees", s_unknown_frees);
  391. ADD_LINE();
  392. }
  393. (void)SDL_snprintf(line, sizeof(line), "\n");
  394. ADD_LINE();
  395. #undef ADD_LINE
  396. SDL_Log("%s", message);
  397. }