Add hook functionality so we can log allocations and deallocations.

This commit is contained in:
Jordan Bancino 2022-10-13 08:50:27 -04:00
parent 2d49ac78b8
commit 8ae86b18fe
2 changed files with 35 additions and 0 deletions

View file

@ -18,6 +18,8 @@ struct MemoryInfo
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
static MemoryInfo *lastAllocation = NULL; static MemoryInfo *lastAllocation = NULL;
static void (*hook)(MemoryAction, MemoryInfo *, void *) = NULL;
static void *hookArgs = NULL;
void * void *
MemoryAllocate(size_t size, const char *file, int line, const char *func) MemoryAllocate(size_t size, const char *file, int line, const char *func)
@ -57,6 +59,11 @@ MemoryAllocate(size_t size, const char *file, int line, const char *func)
lastAllocation = a; lastAllocation = a;
if (hook)
{
hook(MEMORY_ALLOCATE, a, hookArgs);
}
pthread_mutex_unlock(&lock); pthread_mutex_unlock(&lock);
return p; return p;
} }
@ -79,6 +86,11 @@ MemoryReallocate(void *p, size_t size)
{ {
a->pointer = new; a->pointer = new;
a->size = size; a->size = size;
if (hook)
{
hook(MEMORY_REALLOCATE, a, hookArgs);
}
} }
break; break;
@ -123,6 +135,11 @@ MemoryFree(void *p)
lastAllocation = a->prev; lastAllocation = a->prev;
} }
if (hook)
{
hook(MEMORY_FREE, a, hookArgs);
}
free(a); free(a);
free(p); free(p);
@ -270,3 +287,12 @@ MemoryIterate(void (*iterFunc)(MemoryInfo *, void *), void *args)
pthread_mutex_unlock(&lock); pthread_mutex_unlock(&lock);
} }
void
MemoryHook(void (*memHook)(MemoryAction, MemoryInfo *, void *), void *args)
{
pthread_mutex_lock(&lock);
hook = memHook;
hookArgs = args;
pthread_mutex_unlock(&lock);
}

View file

@ -3,6 +3,13 @@
#include <stddef.h> #include <stddef.h>
typedef enum MemoryAction
{
MEMORY_ALLOCATE,
MEMORY_REALLOCATE,
MEMORY_FREE
} MemoryAction;
#define Malloc(x) MemoryAllocate(x, __FILE__, __LINE__, __FUNCTION__) #define Malloc(x) MemoryAllocate(x, __FILE__, __LINE__, __FUNCTION__)
#define Realloc(x, s) MemoryReallocate(x, s) #define Realloc(x, s) MemoryReallocate(x, s)
#define Free(x) MemoryFree(x) #define Free(x) MemoryFree(x)
@ -26,4 +33,6 @@ extern void * MemoryInfoGetPointer(MemoryInfo *);
extern void MemoryIterate(void (*)(MemoryInfo *, void *), void *); extern void MemoryIterate(void (*)(MemoryInfo *, void *), void *);
extern void MemoryHook(void (*)(MemoryAction, MemoryInfo *, void *), void *);
#endif #endif