From 320f600cd980230b2b2e34c7256c9564af6afae9 Mon Sep 17 00:00:00 2001 From: David Härdeman Date: Wed, 10 Jun 2020 19:01:39 +0200 Subject: Add some basic memory tracking infrastructure while hacking --- utils.c | 95 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 95 insertions(+) (limited to 'utils.c') diff --git a/utils.c b/utils.c index 87ed0fe..b9a4bed 100644 --- a/utils.c +++ b/utils.c @@ -3,10 +3,105 @@ #include #include #include +#include #include "main.h" #include "utils.h" +static unsigned total_malloc_count = 0; +static int malloc_count = 0; + +LIST_HEAD(malloc_list); + +struct allocation { + void *caller; + void *ptr; + size_t size; + struct list_head list; +}; + +static void +__add_allocation(void *caller, void *ptr, size_t size) +{ + struct allocation *a = malloc(sizeof(*a)); + + a->caller = caller; + a->ptr = ptr; + a->size = size; + list_add(&a->list, &malloc_list); +} + +#define add_allocation(p, s) __add_allocation(__builtin_extract_return_addr(__builtin_return_address(0)), p, s) + +void * +__zmalloc(size_t size) +{ + void *ptr; + + fprintf(stderr, "zmalloc: Allocation size %zi\n", size); + ptr = calloc(1, size); + if (ptr) { + add_allocation(ptr, size); + total_malloc_count++; + malloc_count++; + } + return ptr; +} + +char * +__xstrdup(const char *s) +{ + char *r; + + fprintf(stderr, "xstrdup: Allocation size %zi\n", strlen(s) + 1); + r = strdup(s); + if (r) { + add_allocation(r, strlen(s) + 1); + total_malloc_count++; + malloc_count++; + } + return r; +} + +void +xfree(void *ptr) +{ + struct allocation *a, *tmp; + unsigned delete_count = 0; + + if (!ptr) + return; + free(ptr); + malloc_count--; + + list_for_each_entry_safe(a, tmp, &malloc_list, list) { + if (a->ptr == ptr) { + list_del(&a->list); + free(a); + delete_count++; + } + } + + if (delete_count != 1) { + error("Delete count is %u for ptr 0x%p\n", delete_count, ptr); + exit(EXIT_FAILURE); + } +} + +void +debug_resource_usage() +{ + struct allocation *a; + + fprintf(stderr, "Still malloced %i (total %u)\n", + malloc_count, total_malloc_count); + + list_for_each_entry(a, &malloc_list, list) { + fprintf(stderr, "* Allocation - caller: 0x%p, ptr: 0x%p, size %zu\n", + a->caller, a->ptr, a->size); + } +} + uint16_t sockaddr_port(struct sockaddr_in46 *addr) { switch (addr->storage.ss_family) { -- cgit v1.2.3