Added a simple malloc/free

This commit is contained in:
vanten-s 2024-08-10 03:49:28 +02:00
parent 66b966d584
commit 1376ad96d4
Signed by: vanten-s
GPG key ID: DE3060396884D3F2
4 changed files with 89 additions and 2 deletions

View file

@ -24,6 +24,7 @@ kernel/debugging.o \
kernel/elf.o \ kernel/elf.o \
kernel/syscall.o \ kernel/syscall.o \
kernel/keyboard.o \ kernel/keyboard.o \
kernel/heap.o \
LIB_OBJS=\ LIB_OBJS=\
$(ARCHDIR)/bootstrap.o \ $(ARCHDIR)/bootstrap.o \

19
include/kernel/heap.h Normal file
View file

@ -0,0 +1,19 @@
#include <stddef.h>
#include <stdbool.h>
#include <stdint.h>
struct Heap_Metadata {
struct Heap_Block* start;
size_t size;
};
struct Heap_Block {
struct Heap_Block* next;
size_t size;
bool used;
void* data;
};
void heap_init();
void* malloc(size_t size);
void free(void *ptr);

View file

@ -1,3 +1,66 @@
#include <stdint.h> #include <stdint.h>
uint8_t heap[2000]; #include <kernel/heap.h>
#include <debugging.h>
#define HEAP_SIZE (256 * 4096)
uint8_t* global_heap_data[HEAP_SIZE];
struct Heap_Metadata global_heap;
void heap_init()
{
global_heap.size = HEAP_SIZE;
global_heap.start = (struct Heap_Block*) global_heap_data;
struct Heap_Block* start = global_heap.start;
start->size = HEAP_SIZE;
start->used = false;
start->data = start + 1;
start->next = 0;
}
void* malloc(size_t size)
{
struct Heap_Block* current = global_heap.start;
while (true) {
if (current->used || current->size < size) {
current = current->next;
continue;
}
if (current == 0) {
return 0;
}
struct Heap_Block* next = current->data + size;
next->next = current->next;
next->size = current->size - size - sizeof(struct Heap_Block);
next->data = next + 1;
current->next = next;
current->size = size;
current->used = true;
return current->data;
}
}
void free(void *ptr)
{
struct Heap_Block* current = global_heap.start;
while (current->data != ptr) { current = current->next; }
struct Heap_Block* start = current;
current->used = false;
while (current->used == false) {
current = current->next;
}
start->next = current;
start->size = (uint32_t)start->next - (uint32_t)start->data;
}

View file

@ -1,8 +1,10 @@
#include <kernel/tty.h> #include <kernel/tty.h>
#include <kernel/idt.h> #include <kernel/idt.h>
#include <debugging.h>
#include <kernel/elf.h> #include <kernel/elf.h>
#include <kernel/pic.h> #include <kernel/pic.h>
#include <kernel/heap.h>
#include <debugging.h>
/* Check if the compiler thinks you are targeting the wrong operating system. */ /* Check if the compiler thinks you are targeting the wrong operating system. */
#if defined(__linux__) #if defined(__linux__)
@ -25,5 +27,7 @@ void kernel_main(void)
init_pic(); init_pic();
idt_init(); idt_init();
heap_init();
run_program(program, sizeof(program)); run_program(program, sizeof(program));
} }