diff --git a/luna/src/Heap.cpp b/luna/src/Heap.cpp index 2e9b686f..25623a71 100644 --- a/luna/src/Heap.cpp +++ b/luna/src/Heap.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #ifdef USE_FREESTANDING @@ -45,9 +46,10 @@ static_assert(sizeof(HeapBlock) == 48UL); static const isize HEAP_BLOCK_SIZE = 48; static LinkedList heap; +static Spinlock g_heap_lock; -// If we're allocating a large amount of memory, map enough pages for it, but otherwise just use the default amount of -// pages. +// If we're allocating a large amount of memory, map enough pages for it, but otherwise just use the default amount +// of pages. static usize get_pages_for_allocation(usize bytes) { usize pages = get_blocks_from_size(bytes, PAGE_SIZE); @@ -178,6 +180,8 @@ Result malloc_impl(usize size, bool should_scrub) { if (!size) return (void*)BLOCK_MAGIC; + ScopeLock lock(g_heap_lock); + size = align_up<16>(size); Option block = heap.first(); @@ -231,6 +235,8 @@ Result free_impl(void* ptr) if (ptr == (void*)BLOCK_MAGIC) return {}; // This pointer was returned from a call to malloc(0) if (!ptr) return {}; + ScopeLock lock(g_heap_lock); + HeapBlock* block = get_heap_block_for_pointer(ptr); if (block->magic != BLOCK_MAGIC) @@ -286,6 +292,8 @@ Result realloc_impl(void* ptr, usize size) return (void*)BLOCK_MAGIC; } + ScopeLock lock(g_heap_lock); + HeapBlock* const block = get_heap_block_for_pointer(ptr); if (block->magic != BLOCK_MAGIC) @@ -327,6 +335,8 @@ Result realloc_impl(void* ptr, usize size) usize old_size = block->req_size; + lock.take_over().unlock(); + void* const new_ptr = TRY(malloc_impl(size, false)); memcpy(new_ptr, ptr, old_size > size ? size : old_size); TRY(free_impl(ptr));