From 79ebcacce291c9ec28a23464377a651765289808 Mon Sep 17 00:00:00 2001 From: Andreas Kling Date: Fri, 9 Apr 2021 09:08:23 +0200 Subject: [PATCH] Kernel: Add some basic double-kfree() detection Double kfree() is exceedingly rare in our kernel since we use automatic memory management and smart pointers for almost all code. However, it doesn't hurt to do some basic checking that might one day catch bugs. This patch makes us VERIFY that we don't already consider the first chunk of a kmalloc() allocation free when kfree()'ing it. --- Kernel/Heap/Heap.h | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Kernel/Heap/Heap.h b/Kernel/Heap/Heap.h index f5c82f402c..88db1e57e9 100644 --- a/Kernel/Heap/Heap.h +++ b/Kernel/Heap/Heap.h @@ -107,9 +107,12 @@ public: return; auto* a = (AllocationHeader*)((((u8*)ptr) - sizeof(AllocationHeader))); VERIFY((u8*)a >= m_chunks && (u8*)ptr < m_chunks + m_total_chunks * CHUNK_SIZE); - VERIFY((u8*)a + a->allocation_size_in_chunks * CHUNK_SIZE <= m_chunks + m_total_chunks * CHUNK_SIZE); FlatPtr start = ((FlatPtr)a - (FlatPtr)m_chunks) / CHUNK_SIZE; + // First, verify that the start of the allocation at `ptr` is actually allocated. + VERIFY(m_bitmap.get(start)); + + VERIFY((u8*)a + a->allocation_size_in_chunks * CHUNK_SIZE <= m_chunks + m_total_chunks * CHUNK_SIZE); m_bitmap.set_range(start, a->allocation_size_in_chunks, false); VERIFY(m_allocated_chunks >= a->allocation_size_in_chunks);