From 0d73795fc9eeedaa8187abf9cbd88ff1275d2eca Mon Sep 17 00:00:00 2001 From: Augustin Cavalier Date: Wed, 12 Mar 2025 18:37:40 -0400 Subject: [PATCH] libroot/malloc: Make the guarded heap handle bogus pointers better. * Check if the area is a stack, and panic() if so. * Check names before accessing any area, and don't try to do anything with areas that we didn't create. Makes frees pointing to stack data have much more useful diagnostics than just "generic segfault". --- src/system/libroot/posix/malloc/debug/guarded_heap.cpp | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/system/libroot/posix/malloc/debug/guarded_heap.cpp b/src/system/libroot/posix/malloc/debug/guarded_heap.cpp index 60bf15f66c..6fe9f74ba0 100644 --- a/src/system/libroot/posix/malloc/debug/guarded_heap.cpp +++ b/src/system/libroot/posix/malloc/debug/guarded_heap.cpp @@ -714,6 +714,15 @@ guarded_heap_area_allocation_for(void* address, area_id& allocationArea) if (get_area_info(allocationArea, &areaInfo) != B_OK) return NULL; + if ((areaInfo.protection & B_STACK_AREA) != 0) { + panic("tried to free %p which is in a stack area (%d)", + address, allocationArea); + return NULL; + } + + if (strncmp(areaInfo.name, "guarded_heap", strlen("guarded_heap")) != 0) + return NULL; + guarded_heap_page* page = (guarded_heap_page*)areaInfo.address; if (page->flags != (GUARDED_HEAP_PAGE_FLAG_USED | GUARDED_HEAP_PAGE_FLAG_FIRST | GUARDED_HEAP_PAGE_FLAG_AREA)) {