From aa4de534ec7bf0b609aff032c4649484aa49823c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matteo=20Gm=C3=BCr?= Date: Mon, 2 Dec 2024 11:14:43 +0000 Subject: Add check to detect double free in linked list allocator --- arch/x86_64/src/kernel/main.cpp | 3 ++- arch/x86_64/src/memory/heap/linked_list_allocator.cpp | 7 +++++++ 2 files changed, 9 insertions(+), 1 deletion(-) (limited to 'arch/x86_64') diff --git a/arch/x86_64/src/kernel/main.cpp b/arch/x86_64/src/kernel/main.cpp index 7992b34..e68f0fe 100644 --- a/arch/x86_64/src/kernel/main.cpp +++ b/arch/x86_64/src/kernel/main.cpp @@ -42,9 +42,10 @@ namespace teachos::arch::kernel heap_allocator.deallocate(test, 1024); - heap_allocator.allocate(1024); // test 9 + auto test9 = heap_allocator.allocate(1024); auto test10 = heap_allocator.allocate(1024); auto test11 = heap_allocator.allocate(1024); + heap_allocator.deallocate(test9, 1024); auto test12 = heap_allocator.allocate(1024); heap_allocator.allocate(1024); // test 13 heap_allocator.deallocate(test11, 1024); diff --git a/arch/x86_64/src/memory/heap/linked_list_allocator.cpp b/arch/x86_64/src/memory/heap/linked_list_allocator.cpp index 706f43e..f596f27 100644 --- a/arch/x86_64/src/memory/heap/linked_list_allocator.cpp +++ b/arch/x86_64/src/memory/heap/linked_list_allocator.cpp @@ -126,6 +126,13 @@ namespace teachos::arch::memory::heap return; } + // Check if the block we want to deallocate is contained in the previous block, because if it is it can only mean + // that the block has already been deallocated and we therefore attempted a double free. + exception_handling::assert(previous_block == nullptr || + start_address >= + (reinterpret_cast(previous_block) + previous_block->size), + "[Linked List Allocator] Attempted double free detected"); + auto const new_block = new (pointer) memory_block(block_size, next_block); // If we want to deallocate the first block that is before any other free block, then there exists no previous free // block (nullptr). Therefore we have to overwrite the first block instead of overwriting its -- cgit v1.2.3