From 8befa72f595bfef57592d12cd2321b310961ba4a Mon Sep 17 00:00:00 2001 From: Jakob Kaivo Date: Tue, 30 Jun 2020 10:24:06 -0400 Subject: basic malloc() implementation --- src/mapalloc.c | 69 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 68 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/mapalloc.c b/src/mapalloc.c index bde39f9..00af064 100644 --- a/src/mapalloc.c +++ b/src/mapalloc.c @@ -1,9 +1,37 @@ #define _POSIX_C_SOURCE 200809L -#include +#include +#include +#include #include +#include +#include #include "mapalloc.h" +#ifndef PAGESIZE +static size_t get_pagesize(void) +{ + static size_t pagesize = 0; + if (pagesize == 0) { + pagesize = (size_t)sysconf(_SC_PAGESIZE); + } + return pagesize; +} + +#define PAGESIZE get_pagesize() +#endif + +struct bucket { + size_t used; + size_t allocated; +}; + +static struct bucket *get_bucket(void *ptr) +{ + uintptr_t addr = (uintptr_t)ptr; + return NULL; +} + void *map_calloc(size_t nelem, size_t elsize) { size_t n = nelem * elsize; @@ -18,6 +46,39 @@ void *map_calloc(size_t nelem, size_t elsize) void *map_malloc(size_t n) { + int fd = -1; + int prot = PROT_READ | PROT_WRITE; + int flags = MAP_PRIVATE; + + /* round up to PAGESIZE, add 2 * PAGESIZE */ + size_t alloc = n; + if (n % PAGESIZE != 0) { + alloc += n % PAGESIZE; + } + alloc += 2 * PAGESIZE; + + #ifdef MAP_ANONYMOUS + flags = MAP_ANONYMOUS; + #else + fd = open("/dev/null", O_RDONLY); + #endif + + void *ptr = mmap(NULL, alloc, prot, flags, fd, 0); + + if (fd != -1) { + close(fd); + } + + mprotect(ptr, PAGESIZE, PROT_NONE); + mprotect((char*)ptr + alloc - (2 * PAGESIZE), PAGESIZE, PROT_NONE); + + /* + struct bucket *b = get_bucket(ptr); + b->used = n; + b->allocated = alloc; + */ + + return ptr; } void *map_realloc(void *ptr, size_t n) @@ -25,6 +86,7 @@ void *map_realloc(void *ptr, size_t n) if (ptr == NULL) { return map_malloc(n); } + return NULL; } void map_free(void *ptr) @@ -32,4 +94,9 @@ void map_free(void *ptr) if (ptr == NULL) { return; } + + struct bucket *b = get_bucket(ptr); + if (b == NULL) { + /* attempting to free() an invalid pointer */ + } } -- cgit v1.2.1