From 042f9996770174dbb4ccc4eaa4053b561ea8f8fa Mon Sep 17 00:00:00 2001 From: apio Date: Mon, 19 Dec 2022 13:20:38 +0100 Subject: [PATCH] Heap: SCRUB IT ALL If your memory is all 0xacacacac there is a big probability you haven't initialized it. --- kernel/src/memory/Heap.cpp | 20 ++++++++++++++++---- kernel/src/memory/Heap.h | 2 +- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/kernel/src/memory/Heap.cpp b/kernel/src/memory/Heap.cpp index e0abe5c8..ec590d74 100644 --- a/kernel/src/memory/Heap.cpp +++ b/kernel/src/memory/Heap.cpp @@ -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 @@ -166,7 +169,7 @@ static Result combine_backward(HeapBlock* block) return last; } -Result kmalloc(usize size) +Result kmalloc(usize size, bool should_scrub) { if (!size) return (void*)BLOCK_MAGIC; @@ -219,6 +222,8 @@ Result 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 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 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 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); } diff --git a/kernel/src/memory/Heap.h b/kernel/src/memory/Heap.h index 6e57f744..7d13d69a 100644 --- a/kernel/src/memory/Heap.h +++ b/kernel/src/memory/Heap.h @@ -2,7 +2,7 @@ #include #include -Result kmalloc(usize size); +Result kmalloc(usize size, bool should_scrub = true); Result kcalloc(usize nmemb, usize size); Result krealloc(void* ptr, usize size); Result kfree(void* ptr);