aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMarvin Borner2020-11-26 14:04:50 +0100
committerMarvin Borner2020-11-28 16:12:59 +0100
commitdc661fee8168ed46b06b682f80f1dcab9e69e7be (patch)
tree833fac7874cfd3c53b86f5f90a0bb8172486ff2c
parentcc7b4983c07a00ab721bd5b4a533f3078c871530 (diff)
Added userspace heap
-rw-r--r--libc/inc/mem.h5
-rw-r--r--libc/mem.c45
2 files changed, 45 insertions, 5 deletions
diff --git a/libc/inc/mem.h b/libc/inc/mem.h
index 964b24b..15505fd 100644
--- a/libc/inc/mem.h
+++ b/libc/inc/mem.h
@@ -13,9 +13,8 @@ void heap_init(u32 start);
void *malloc(u32 size);
void free(void *ptr);
#elif defined(userspace)
-#include <sys.h>
-#define malloc(n) (void *)sys1(SYS_MALLOC, n)
-#define free(ptr) (void)(sys1(SYS_FREE, (int)ptr))
+void *malloc(u32 size);
+void free(void *ptr);
#else
#error "No lib target specified. Please use -Dkernel or -Duserspace"
#endif
diff --git a/libc/mem.c b/libc/mem.c
index c81a13f..fab91f8 100644
--- a/libc/mem.c
+++ b/libc/mem.c
@@ -68,8 +68,6 @@ int memcmp(const void *s1, const void *s2, u32 n)
return 0;
}
-#ifdef kernel
-
#define ALIGNMENT 16ul
#define ALIGN_TYPE char
#define ALIGN_INFO sizeof(ALIGN_TYPE) * 16
@@ -94,6 +92,8 @@ int memcmp(const void *s1, const void *s2, u32 n)
} \
}
+#ifdef kernel
+
static u32 *heap;
static u32 index;
@@ -117,6 +117,7 @@ int count()
return i;
}
+// TODO: Identify by pid (for freeing)
void *malloc(u32 size)
{
if (size < 1)
@@ -146,4 +147,44 @@ void *realloc(void *ptr, u32 size)
return ptr;
}
+#elif defined(userspace)
+
+#define HEAP_SIZE 100000
+
+#define kmalloc(n) (void *)sys1(SYS_MALLOC, n)
+#define kfree(ptr) (void)(sys1(SYS_FREE, (int)ptr))
+
+static u32 *heap = NULL;
+static u32 index = 0;
+static u32 malloced = 0;
+
+void *malloc(u32 size)
+{
+ if (size < 1)
+ return NULL;
+
+ size = size + ALIGNMENT + ALIGN_INFO;
+
+ if (!malloced || size > malloced) {
+ heap = kmalloc(HEAP_SIZE);
+ malloced = HEAP_SIZE;
+ }
+ malloced -= size;
+
+ heap[index] = size;
+ index += size + 1;
+
+ void *p = (void *)(heap + index - size);
+ ALIGN(p);
+
+ return p;
+}
+
+// TODO: Implement free, realloc and find_smallest_hole
+void free(void *ptr)
+{
+ (void)ptr;
+ /* UNALIGN(ptr); */
+}
+
#endif