From d0f42d43ae9afe9ea4084afd030045a3b6484cc4 Mon Sep 17 00:00:00 2001 From: Matte23 Date: Sun, 3 Nov 2024 19:41:58 +0100 Subject: [PATCH] Define heap in linker and place other sections correctly --- linker.ld | 45 +++++++++++++++++++++++++++++++++++---------- os/alloc.c | 10 ++++++---- os/alloc.h | 5 +++++ 3 files changed, 46 insertions(+), 14 deletions(-) diff --git a/linker.ld b/linker.ld index 8b92698..de6a3a2 100644 --- a/linker.ld +++ b/linker.ld @@ -1,15 +1,40 @@ ENTRY(_start) +MEMORY +{ + FLASH (rx) : ORIGIN = 0x00000000, LENGTH = 1M + RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 128K +} + +_Min_Heap_Size = 0x200 ; +_Min_Stack_Size = 0x200 ; /* Required amount of stack. Used by main(), then re-used as the interrupt stack after the kernel starts. */ +_estack = ORIGIN(RAM) + LENGTH(RAM); + + SECTIONS { - /* text section (code)*/ - .text : { *(.text*) } - /* data section, initialized variables */ - .data : { *(.data) } - ram_start = 0x20000000; - /* bss section, uninitialized variables */ - .bss : { *(.bss*) } - /* stack section */ - /* The stack is placed at the end of the RAM */ - stack_top = 0x2001ffff; + .text : { *(.text*) } > FLASH + .rodata : { *(.rodata*) } > FLASH + .bss : { *(.bss*) } > RAM + .data : { *(.data*) } > RAM + .heap : { + . = ALIGN(8); + PROVIDE ( end = . ); + PROVIDE ( _end = . ); + _heap_bottom = .; + . = . + _Min_Heap_Size; + _heap_top = .; + . = . + _Min_Stack_Size; + . = ALIGN(8); + } >RAM + + .stack (NOLOAD) : { + . = ORIGIN(RAM) + LENGTH(RAM); + stack_top = .; + } > RAM + + __StackLimit = stack_top - _Min_Stack_Size; + + /* Check if data + heap + stack exceeds RAM limit */ + ASSERT(__StackLimit >= _heap_top, "region RAM overflowed with stack") } diff --git a/os/alloc.c b/os/alloc.c index c2af1b5..b874543 100644 --- a/os/alloc.c +++ b/os/alloc.c @@ -1,14 +1,16 @@ #include "alloc.h" #include "stdint.h" -void* *first_mem_avail = (void*) 0x20000000; +HeapArena heap_arena; + +extern void * _heap_top; void init_allocator() { - *first_mem_avail = (void*) 0x20000000 +sizeof(void*); + heap_arena.wilderness = &_heap_top; } void* malloc(size_t size) { - void* block = *first_mem_avail; - *first_mem_avail += size; + void* block = heap_arena.wilderness; + heap_arena.wilderness += size; return block; } diff --git a/os/alloc.h b/os/alloc.h index bfe4861..9b29577 100644 --- a/os/alloc.h +++ b/os/alloc.h @@ -1,4 +1,9 @@ #include +#include + +typedef struct { + void * wilderness; +} HeapArena; void init_allocator(); void* malloc (size_t size);