Add realloc func argument for memory allocator (#191)

This commit is contained in:
wenyongh
2020-03-08 21:18:18 +08:00
committed by GitHub
parent 057c849fc0
commit 180ee4c78a
12 changed files with 213 additions and 42 deletions

View File

@ -48,6 +48,7 @@ static Memory_Mode memory_mode = MEMORY_MODE_UNKNOWN;
static mem_allocator_t pool_allocator = NULL;
static void *(*malloc_func)(unsigned int size) = NULL;
static void *(*realloc_func)(void *ptr, unsigned int size) = NULL;
static void (*free_func)(void *ptr) = NULL;
static unsigned int global_pool_size;
@ -69,11 +70,14 @@ int bh_memory_init_with_pool(void *mem, unsigned int bytes)
return -1;
}
int bh_memory_init_with_allocator(void *_malloc_func, void *_free_func)
int bh_memory_init_with_allocator_internal(void *_malloc_func,
void *_realloc_func,
void *_free_func)
{
if (_malloc_func && _free_func && _malloc_func != _free_func) {
memory_mode = MEMORY_MODE_ALLOCATOR;
malloc_func = _malloc_func;
realloc_func = _realloc_func;
free_func = _free_func;
#if BEIHAI_ENABLE_MEMORY_PROFILING != 0
vm_mutex_init(&profile_lock);
@ -85,6 +89,12 @@ int bh_memory_init_with_allocator(void *_malloc_func, void *_free_func)
return -1;
}
int bh_memory_init_with_allocator(void *_malloc_func, void *_free_func)
{
return bh_memory_init_with_allocator_internal(_malloc_func,
NULL, _free_func);
}
void bh_memory_destroy()
{
#if BEIHAI_ENABLE_MEMORY_PROFILING != 0
@ -115,6 +125,21 @@ void* bh_malloc_internal(unsigned int size)
}
}
void* bh_realloc_internal(void *ptr, unsigned int size)
{
if (memory_mode == MEMORY_MODE_UNKNOWN) {
bh_printf("bh_realloc failed: memory hasn't been initialize.\n");
return NULL;
} else if (memory_mode == MEMORY_MODE_POOL) {
return mem_allocator_realloc(pool_allocator, ptr, size);
} else {
if (realloc_func)
return realloc_func(ptr, size);
else
return NULL;
}
}
void bh_free_internal(void *ptr)
{
if (memory_mode == MEMORY_MODE_UNKNOWN) {
@ -267,6 +292,11 @@ void* bh_malloc(unsigned int size)
return bh_malloc_internal(size);
}
void* bh_realloc(void *ptr, unsigned int size)
{
return bh_realloc_internal(ptr, size);
}
void bh_free(void *ptr)
{
bh_free_internal(ptr);
@ -282,6 +312,11 @@ void* bh_malloc(unsigned int size)
return malloc(size);
}
void* bh_realloc(void *ptr, unsigned int size)
{
return realloc(ptr, size);
}
void bh_free(void *ptr)
{
if (ptr)
@ -306,6 +341,23 @@ void* bh_malloc_profile(const char *file,
return malloc(size);
}
void* bh_realloc_profile(const char *file,
int line,
const char *func,
void *ptr,
unsigned int size)
{
(void)file;
(void)line;
(void)func;
(void)memory_profiles_list;
(void)profile_lock;
(void)memory_in_use;
return realloc(ptr, size);
}
void bh_free_profile(const char *file, int line, const char *func, void *ptr)
{
(void)file;