From e67fbecfc88b7a54d0f1fc7d0c06c9e2eeee8f96 Mon Sep 17 00:00:00 2001 From: John Hodge Date: Mon, 18 Aug 2014 18:26:20 +0800 Subject: [PATCH] Usermode/libc - Move free logic to another method, allowing libraries to catch and pass failures --- Usermode/Libraries/libc.so_src/heap.c | 27 ++++++++++++++++++--------- 1 file changed, 18 insertions(+), 9 deletions(-) diff --git a/Usermode/Libraries/libc.so_src/heap.c b/Usermode/Libraries/libc.so_src/heap.c index 53460326..d65fc33f 100644 --- a/Usermode/Libraries/libc.so_src/heap.c +++ b/Usermode/Libraries/libc.so_src/heap.c @@ -9,6 +9,7 @@ #include #include #include +#include #include "lib.h" #if 0 @@ -72,6 +73,7 @@ static const heap_head _heap_zero_allocation; EXPORT void *malloc(size_t bytes); void *_malloc(size_t bytes, void *owner); EXPORT void *calloc(size_t bytes, size_t count); +bool _libc_free(void *mem); EXPORT void free(void *mem); EXPORT void *realloc(void *mem, size_t bytes); EXPORT void *sbrk(int increment); @@ -222,26 +224,30 @@ EXPORT void *calloc(size_t __nmemb, size_t __size) \param mem Pointer - Memory to free */ EXPORT void free(void *mem) +{ + if( !_libc_free(mem) ) { + Heap_Validate(1); + exit(0); + } +} + +bool _libc_free(void *mem) { heap_head *head = (heap_head*)mem - 1; // Free of NULL or the zero allocation does nothing if(!mem || mem == _heap_zero_allocation.data) - return ; + return true; // Sanity check the head address if(head->magic != MAGIC) { if( head->magic != MAGIC_FREE ) { - _SysDebug("Double free of %p", mem); - Heap_Validate(1); - exit(0); + _SysDebug("Double free of %p by %p", mem, __builtin_return_address(0)); } else { - _SysDebug("Free of invalid pointer %p", mem); - Heap_Validate(1); - exit(0); + _SysDebug("Free of invalid pointer %p by ", mem, __builtin_return_address(0)); } - return; + return false; } head->magic = MAGIC_FREE; @@ -266,8 +272,9 @@ EXPORT void free(void *mem) heap_foot *prevFoot = PREV_FOOT(head); if( prevFoot->magic != MAGIC ) { + _SysDebug("Heap corruption, previous foot magic invalid"); Heap_Validate(1); - exit(1); + return false; } heap_head *prevHead = prevFoot->header; @@ -282,6 +289,8 @@ EXPORT void free(void *mem) prevFoot->header = NULL; } } + + return true; } /** -- 2.20.1