From fba5d6fbb285bde53a3d9bbd62355bf4f96d6ab5 Mon Sep 17 00:00:00 2001 From: Matthew Sotoudeh Date: Fri, 17 May 2024 16:21:50 -0700 Subject: fix growing allocator other libc functions call malloc which would call sbrk --- lua_benchmark/main.c | 39 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 38 insertions(+), 1 deletion(-) (limited to 'lua_benchmark') diff --git a/lua_benchmark/main.c b/lua_benchmark/main.c index a05c744..4f1eb04 100644 --- a/lua_benchmark/main.c +++ b/lua_benchmark/main.c @@ -45,6 +45,7 @@ static void *allocator_fn(void *ud, void *ptr, size_t osize, size_t nsize) { #include "magic_buddy/magic_buddy.h" static size_t POOL_SIZE; static void *POOL; +static void *END_POOL; static struct buddy BUDDY; static void init_allocator() { @@ -58,7 +59,10 @@ static void init_allocator() { } static int grow_pool() { - if (sbrk(POOL_SIZE) == (void *)-1) return 0; + if (sbrk(POOL_SIZE) != (void*)((uint8_t*)POOL + POOL_SIZE)) { + printf("sbrk failure!\n"); + return 0; + } POOL_SIZE *= 2; grow_buddy(POOL, POOL_SIZE, &BUDDY); return 1; @@ -83,6 +87,39 @@ static void *allocator_fn(void *ud, void *ptr, size_t osize, size_t nsize) { return result; } +// custom malloc/free/calloc/realloc +void *malloc(size_t s) { + if (!POOL) init_allocator(); + size_t *block = allocator_fn((void*)1, 0, 0, s + sizeof(size_t)); + *block = s + sizeof(size_t); + return (void*)((uint8_t*)block + sizeof(size_t)); +} +void free(void *ptr) { + if (!ptr) return; + if (!POOL) init_allocator(); + ptr = (uint8_t*)ptr - sizeof(size_t); + size_t size = *(size_t*)ptr; + allocator_fn((void*)1, ptr, size, 0); +} +void *realloc(void *ptr, size_t nsize) { + if (!POOL) init_allocator(); + if (nsize == 0) { + free(ptr); + return 0; + } + ptr = (uint8_t*)ptr - sizeof(size_t); + size_t osize = *(size_t*)ptr; + void *res = allocator_fn((void*)1, ptr, osize, nsize + sizeof(size_t)); + *(size_t*)res = nsize + sizeof(size_t); + return (void*)((uint8_t*)res + sizeof(size_t)); +} +void *calloc(size_t cnt, size_t size) { + if (!POOL) init_allocator(); + uint8_t *data = malloc(cnt * size); + for (size_t i = 0; i < cnt * size; i++) data[i] = 0; + return (void*)data; +} + #elif defined(ALLOC_SYSTEM) static void init_allocator() { } -- cgit v1.2.3