From b141582f40c91cdd59af0e852ac12ed578c52d3a Mon Sep 17 00:00:00 2001 From: ngiddings Date: Sat, 17 Apr 2021 01:18:14 -0500 Subject: [PATCH] Added very simple kernel memory allocator --- include/allocator.h | 9 +++++++++ src/Makefile.am | 2 +- src/allocator.c | 34 ++++++++++++++++++++++++++++++++++ 3 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 include/allocator.h create mode 100644 src/allocator.c diff --git a/include/allocator.h b/include/allocator.h new file mode 100644 index 0000000..a9c0699 --- /dev/null +++ b/include/allocator.h @@ -0,0 +1,9 @@ +#pragma once + +#include + +void initialize_allocator(void *bottom, void *top); + +void *allocate_from_bottom(size_t size); + +void *allocate_from_top(size_t size); \ No newline at end of file diff --git a/src/Makefile.am b/src/Makefile.am index ca01154..e55eca4 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -1,5 +1,5 @@ noinst_PROGRAMS = quark-kernel -quark_kernel_SOURCES = kernel.c memorymap.c pageallocator.c priorityqueue.c stdio.c string.c elf.c resource.c +quark_kernel_SOURCES = kernel.c memorymap.c pageallocator.c priorityqueue.c stdio.c string.c elf.c resource.c allocator.c quark_kernel_LDADD = -lgcc quark_kernel_CFLAGS = -I$(top_srcdir)/include -ffreestanding -mgeneral-regs-only -O0 -Wall -ggdb quark_kernel_LDFLAGS = -nostdlib diff --git a/src/allocator.c b/src/allocator.c new file mode 100644 index 0000000..574b195 --- /dev/null +++ b/src/allocator.c @@ -0,0 +1,34 @@ +#include "allocator.h" + +struct linear_allocator_t +{ + void *bottom; + void *top; +} allocator; + +void initialize_allocator(void *bottom, void *top) +{ + allocator.bottom = bottom; + allocator.top = top; +} + +void *allocate_from_bottom(size_t size) +{ + if((size_t)allocator.bottom + size <= (size_t)allocator.top) + { + void *ptr = allocator.bottom; + allocator.bottom += size; + return ptr; + } + return (void*)NULL; +} + +void *allocate_from_top(size_t size) +{ + if((size_t)allocator.top - size >= (size_t)allocator.bottom) + { + allocator.top -= size; + return allocator.top; + } + return (void*)NULL; +}