summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMatthew Sotoudeh <matthew@masot.net>2024-05-17 16:21:50 -0700
committerMatthew Sotoudeh <matthew@masot.net>2024-05-17 16:21:50 -0700
commitfba5d6fbb285bde53a3d9bbd62355bf4f96d6ab5 (patch)
tree9a881c8c3bfe8d3b82684770c1ff042007bcaeb5
parentd068f0b3c11348a50c18af1ee3b0d2e5f38c4faf (diff)
fix growing allocator
other libc functions call malloc which would call sbrk
-rw-r--r--lua_benchmark/main.c39
1 files changed, 38 insertions, 1 deletions
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() { }
generated by cgit on debian on lair
contact matthew@masot.net with questions or feedback