Implement kernel memory allocator (kmalloc/kfree) and freestanding string library (AI)

- Added first-fit free-list allocator with block splitting and coalescing.
  Provides kmalloc(), kfree(), and kcalloc() for kernel-space dynamic memory.
- Each block carries an inline header with a magic value (0xCAFEBABE) for
  heap corruption detection, plus double-free checking.
- Memory is obtained from the paging subsystem in 4 KiB page increments.
  All allocations are 8-byte aligned with a 16-byte minimum block size.
- Created freestanding string.c with memset, memcpy, memmove, memcmp,
  strlen, strcmp, strncmp, strcpy, strncpy — replacing the unavailable
  libc implementations.
- Added documentation in docs/kmalloc.md.

Tested: kmalloc(64) returns 0xD0001010 (in kernel heap) and kfree succeeds.
Works with both 4 MiB and 128 MiB RAM.
This commit is contained in:
AI
2026-02-23 11:06:52 +00:00
parent fb61ab7c15
commit f63cd9eb3f
7 changed files with 551 additions and 1 deletions

View File

@@ -7,6 +7,7 @@
#include "port_io.h"
#include "pmm.h"
#include "paging.h"
#include "kmalloc.h"
void offset_print(const char *str)
{
@@ -63,6 +64,21 @@ void kernel_main(uint32_t magic, uint32_t addr) {
offset_print("FAILED to allocate virtual page\n");
}
init_kmalloc();
offset_print("Memory allocator initialized\n");
/* Test kmalloc/kfree */
uint32_t *test_alloc = (uint32_t *)kmalloc(64);
if (test_alloc) {
*test_alloc = 42;
offset_print("kmalloc(64) = ");
print_hex((uint32_t)test_alloc);
kfree(test_alloc);
offset_print("kfree OK\n");
} else {
offset_print("FAILED to kmalloc\n");
}
/* Enable interrupts */
asm volatile("sti");
offset_print("Interrupts enabled\n");