forked from lda/telodendria
Add hook functionality so we can log allocations and deallocations.
This commit is contained in:
parent
2d49ac78b8
commit
8ae86b18fe
2 changed files with 35 additions and 0 deletions
26
src/Memory.c
26
src/Memory.c
|
@ -18,6 +18,8 @@ struct MemoryInfo
|
|||
|
||||
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
|
||||
static MemoryInfo *lastAllocation = NULL;
|
||||
static void (*hook)(MemoryAction, MemoryInfo *, void *) = NULL;
|
||||
static void *hookArgs = NULL;
|
||||
|
||||
void *
|
||||
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;
|
||||
|
||||
if (hook)
|
||||
{
|
||||
hook(MEMORY_ALLOCATE, a, hookArgs);
|
||||
}
|
||||
|
||||
pthread_mutex_unlock(&lock);
|
||||
return p;
|
||||
}
|
||||
|
@ -79,6 +86,11 @@ MemoryReallocate(void *p, size_t size)
|
|||
{
|
||||
a->pointer = new;
|
||||
a->size = size;
|
||||
|
||||
if (hook)
|
||||
{
|
||||
hook(MEMORY_REALLOCATE, a, hookArgs);
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
|
@ -123,6 +135,11 @@ MemoryFree(void *p)
|
|||
lastAllocation = a->prev;
|
||||
}
|
||||
|
||||
if (hook)
|
||||
{
|
||||
hook(MEMORY_FREE, a, hookArgs);
|
||||
}
|
||||
|
||||
free(a);
|
||||
free(p);
|
||||
|
||||
|
@ -270,3 +287,12 @@ MemoryIterate(void (*iterFunc)(MemoryInfo *, void *), void *args)
|
|||
|
||||
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);
|
||||
}
|
||||
|
|
|
@ -3,6 +3,13 @@
|
|||
|
||||
#include <stddef.h>
|
||||
|
||||
typedef enum MemoryAction
|
||||
{
|
||||
MEMORY_ALLOCATE,
|
||||
MEMORY_REALLOCATE,
|
||||
MEMORY_FREE
|
||||
} MemoryAction;
|
||||
|
||||
#define Malloc(x) MemoryAllocate(x, __FILE__, __LINE__, __FUNCTION__)
|
||||
#define Realloc(x, s) MemoryReallocate(x, s)
|
||||
#define Free(x) MemoryFree(x)
|
||||
|
@ -26,4 +33,6 @@ extern void * MemoryInfoGetPointer(MemoryInfo *);
|
|||
|
||||
extern void MemoryIterate(void (*)(MemoryInfo *, void *), void *);
|
||||
|
||||
extern void MemoryHook(void (*)(MemoryAction, MemoryInfo *, void *), void *);
|
||||
|
||||
#endif
|
||||
|
|
Loading…
Reference in a new issue