2024-08-05 00:59:07 +02:00
|
|
|
#include <stdint.h>
|
|
|
|
|
2024-08-10 03:49:28 +02:00
|
|
|
#include <kernel/heap.h>
|
|
|
|
#include <debugging.h>
|
|
|
|
|
2024-08-10 18:08:17 +02:00
|
|
|
#define HEAP_SIZE (4096)
|
2024-08-10 03:49:28 +02:00
|
|
|
|
2024-08-10 14:37:31 +02:00
|
|
|
uint8_t* global_heap_data[HEAP_SIZE + sizeof(struct Heap_Block)];
|
2024-08-10 03:49:28 +02:00
|
|
|
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;
|
2024-08-12 16:27:53 +02:00
|
|
|
|
|
|
|
struct Heap_Block* first_unused;
|
|
|
|
bool found_unused = false;
|
|
|
|
|
2024-08-10 14:37:31 +02:00
|
|
|
while (current->data != ptr) {
|
2024-08-12 16:27:53 +02:00
|
|
|
if (!current->used && !found_unused) {
|
|
|
|
first_unused = current;
|
|
|
|
found_unused = true;
|
|
|
|
} else {
|
|
|
|
found_unused = false;
|
|
|
|
}
|
|
|
|
current = current->next;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!found_unused) {
|
|
|
|
first_unused = current;
|
2024-08-10 14:37:31 +02:00
|
|
|
}
|
2024-08-10 03:49:28 +02:00
|
|
|
|
|
|
|
current->used = false;
|
|
|
|
|
2024-08-10 14:37:31 +02:00
|
|
|
if (current->next == 0) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2024-08-12 16:27:53 +02:00
|
|
|
struct Heap_Block* start = first_unused;
|
|
|
|
current = start;
|
2024-08-10 14:37:31 +02:00
|
|
|
|
2024-08-12 16:27:53 +02:00
|
|
|
while (current->used == false && current->next != 0) {
|
2024-08-10 03:49:28 +02:00
|
|
|
current = current->next;
|
|
|
|
}
|
2024-08-10 14:37:31 +02:00
|
|
|
|
2024-08-10 03:49:28 +02:00
|
|
|
start->next = current;
|
|
|
|
start->size = (uint32_t)start->next - (uint32_t)start->data;
|
|
|
|
}
|
|
|
|
|