lib/malloc: Implement a simple free() only for last malloc()

Implement a free() that supports only the last malloc(). Rewind
the heap to the last allocation point if the ptr to be freed is
matching the end of heap before last malloc(). With current situation,
since free() is no-op, every call to malloc() is a memory leak.

BUG=b:140124451
TEST=Wrote a test function to do malloc and free operations.

Change-Id: I6d43cf54b79e6897cf6882335730b2310e4eae45
Signed-off-by: Bora Guvendik <bora.guvendik@intel.com>
Reviewed-on: https://review.coreboot.org/c/coreboot/+/37919
Tested-by: build bot (Jenkins) <no-reply@coreboot.org>
Reviewed-by: Aaron Durbin <adurbin@chromium.org>
This commit is contained in:
Bora Guvendik 2019-12-23 16:44:06 -08:00 committed by Aaron Durbin
parent 320d6e88af
commit a347ea3787
2 changed files with 30 additions and 2 deletions

View File

@ -5,7 +5,6 @@
void *memalign(size_t boundary, size_t size); void *memalign(size_t boundary, size_t size);
void *malloc(size_t size); void *malloc(size_t size);
/* We never free memory */ void free(void *ptr);
static inline void free(void *ptr) {}
#endif /* STDLIB_H */ #endif /* STDLIB_H */

View File

@ -11,6 +11,8 @@
extern unsigned char _heap, _eheap; extern unsigned char _heap, _eheap;
static void *free_mem_ptr = &_heap; /* Start of heap */ static void *free_mem_ptr = &_heap; /* Start of heap */
static void *free_mem_end_ptr = &_eheap; /* End of heap */ static void *free_mem_end_ptr = &_eheap; /* End of heap */
static void *free_last_alloc_ptr = &_heap; /* End of heap before
last allocation */
/* We don't restrict the boundary. This is firmware, /* We don't restrict the boundary. This is firmware,
* you are supposed to know what you are doing. * you are supposed to know what you are doing.
@ -26,6 +28,12 @@ void *memalign(size_t boundary, size_t size)
p = free_mem_ptr; p = free_mem_ptr;
free_mem_ptr += size; free_mem_ptr += size;
/*
* Store last allocation pointer after ALIGN, as malloc() will
* return it. This may cause n bytes of gap between allocations
* where n < boundary.
*/
free_last_alloc_ptr = p;
if (free_mem_ptr >= free_mem_end_ptr) { if (free_mem_ptr >= free_mem_end_ptr) {
printk(BIOS_ERR, "memalign(boundary=%zu, size=%zu): failed: ", printk(BIOS_ERR, "memalign(boundary=%zu, size=%zu): failed: ",
@ -46,3 +54,24 @@ void *malloc(size_t size)
{ {
return memalign(sizeof(u64), size); return memalign(sizeof(u64), size);
} }
void free(void *ptr)
{
if (ptr == NULL)
return;
if (ptr < (void *)&_heap || ptr >= free_mem_end_ptr) {
printk(BIOS_WARNING, "Warning - Pointer passed to %s is not "
"pointing to the heap\n", __func__);
return;
}
/*
* Rewind the heap pointer to the end of heap
* before the last successful malloc().
*/
if (ptr == free_last_alloc_ptr) {
free_mem_ptr = free_last_alloc_ptr;
free_last_alloc_ptr = NULL;
}
}