AmendHub

jcs

/

subtext

/

amendments

/

227

util: Support malloc map compaction by toggling a variable


jcs made amendment 227 2 months ago
--- util.c Sun Jul 31 18:05:42 2022 +++ util.c Wed Aug 3 14:00:06 2022 @@ -79,11 +79,11 @@ enum { * List of allocations, updated at xmalloc() and xfree(). If an address * passed to xfree() isn't in the list, it indicates a double-free. */ -#define MALLOC_MAP_SIZE 1024 +#define MALLOC_MAP_SIZE 512 struct malloc_map_e { unsigned long addr; unsigned long size; - char note[16]; + char note[MALLOC_NOTE_SIZE]; } malloc_map[MALLOC_MAP_SIZE]; /* @@ -95,6 +95,8 @@ struct malloc_map_e { static const char malloc_uaf_zero[MALLOC_UAF_SIZE] = { 0 }; static char malloc_uaf[MALLOC_UAF_SIZE]; +static bool malloc_map_compact = false; + #endif void vwarn(short alert_func, const char *format, va_list ap); @@ -129,7 +131,7 @@ xmalloc(size_t size, char *note) { void *ptr; #ifdef MALLOC_DEBUG - unsigned short n; + unsigned short n, j; #endif if (size == 0) @@ -140,15 +142,35 @@ xmalloc(size_t size, char *note) panic("xmalloc(%lu) failed", size); #ifdef MALLOC_DEBUG + if (malloc_map_compact) { + for (n = 0; n < MALLOC_MAP_SIZE; n++) { + if (malloc_map[n].addr != 0) + continue; + + for (j = n + 1; j < MALLOC_MAP_SIZE; j++) { + if (malloc_map[j].addr == 0) + continue; + + malloc_map[n] = malloc_map[j]; + memset(&malloc_map[j], 0, sizeof(malloc_map[j])); + break; + } + } + + malloc_map_compact = false; + } + for (n = 0; n <= MALLOC_MAP_SIZE; n++) { if (n == MALLOC_MAP_SIZE) - panic("xmalloc(%lu): out of malloc map entries", size); + panic("xmalloc(%lu): out of malloc map entries, likely a " + "memory leak", size); if (malloc_map[n].addr == 0) { malloc_map[n].addr = (unsigned long)ptr; malloc_map[n].size = size; strlcpy(malloc_map[n].note, note, sizeof(malloc_map[n].note)); break; } + n = n; } #endif @@ -225,7 +247,7 @@ xrealloc(void *src, size_t size) { void *ptr, *tsrc; unsigned long n; - char note[16] = { 0 }; + char note[MALLOC_NOTE_SIZE] = "realloc from null"; #ifdef MALLOC_DEBUG if (src != NULL) { --- util.h Sat Jul 30 22:35:23 2022 +++ util.h Mon Aug 1 15:38:41 2022 @@ -22,6 +22,7 @@ #include <time.h> #define MALLOC_DEBUG +#define MALLOC_NOTE_SIZE 32 #ifndef SIZE_MAX #define SIZE_MAX ULONG_MAX