Heap: SCRUB IT ALL
All checks were successful
continuous-integration/drone/push Build is passing

If your memory is all 0xacacacac there is a big probability you haven't initialized it.
This commit is contained in:
apio 2022-12-19 13:20:38 +01:00
parent a11a5dec1f
commit 042f999677
Signed by: apio
GPG Key ID: B8A7D06E42258954
2 changed files with 17 additions and 5 deletions

View File

@ -24,6 +24,9 @@ static constexpr int BLOCK_END_MEM = 1 << 2;
static constexpr usize BLOCK_MAGIC = 0x6d616c6c6f63210a; // echo 'malloc!' | hexdump -C (includes a newline)
static constexpr usize BLOCK_DEAD = 0xdeaddeaddeaddead;
static constexpr u8 KMALLOC_SCRUB_BYTE = 0xac;
static constexpr u8 KFREE_SCRUB_BYTE = 0xde;
static constexpr usize MINIMUM_PAGES_PER_ALLOCATION = 4;
struct HeapBlock : LinkedListNode<HeapBlock>
@ -166,7 +169,7 @@ static Result<HeapBlock*> combine_backward(HeapBlock* block)
return last;
}
Result<void*> kmalloc(usize size)
Result<void*> kmalloc(usize size, bool should_scrub)
{
if (!size) return (void*)BLOCK_MAGIC;
@ -219,6 +222,8 @@ Result<void*> kmalloc(usize size)
block->req_size = size;
block->status |= BLOCK_USED;
if (should_scrub) { memset(get_pointer_from_heap_block(block), KMALLOC_SCRUB_BYTE, size); }
return get_pointer_from_heap_block(block);
}
@ -249,6 +254,8 @@ Result<void> kfree(void* ptr)
else
block->status &= ~BLOCK_USED;
memset(ptr, KFREE_SCRUB_BYTE, block->req_size);
auto maybe_next = heap.next(block);
if (maybe_next.has_value() && is_block_free(maybe_next.value()))
{
@ -307,21 +314,26 @@ Result<void*> krealloc(void* ptr, usize size)
if (block->full_size >= size)
{
// This block is already large enough!
// FIXME: Scrub this if necessary.
block->req_size = size;
return ptr;
}
void* const new_ptr = TRY(kmalloc(size));
memcpy(new_ptr, ptr, block->req_size > size ? size : block->req_size);
usize old_size = block->req_size;
void* const new_ptr = TRY(kmalloc(size, false));
memcpy(new_ptr, ptr, old_size > size ? size : old_size);
TRY(kfree(ptr));
if (old_size < size) { memset(offset_ptr(new_ptr, old_size), KMALLOC_SCRUB_BYTE, size - old_size); }
return new_ptr;
}
Result<void*> kcalloc(usize nmemb, usize size)
{
const usize realsize = TRY(safe_mul(nmemb, size));
void* const ptr = TRY(kmalloc(realsize));
void* const ptr = TRY(kmalloc(realsize, false));
return memset(ptr, 0, realsize);
}

View File

@ -2,7 +2,7 @@
#include <luna/PlacementNew.h>
#include <luna/Result.h>
Result<void*> kmalloc(usize size);
Result<void*> kmalloc(usize size, bool should_scrub = true);
Result<void*> kcalloc(usize nmemb, usize size);
Result<void*> krealloc(void* ptr, usize size);
Result<void> kfree(void* ptr);