Add a function hook called in tlsf_check() on every free block of memory

In this commit:
- We add a weak delcaration of tlsf_check_hook() in tlsf.h.
- We call tlsf_check_hook() in tlsf_check() if the function has a defintion

This hook function allows the user to implement application specific checks on
the memory of every free blocks (e.g. check for memory corruption).
This commit is contained in:
Guillaume Souchere
2022-08-09 13:10:44 +02:00
parent ff11688f24
commit 9393b12cac
2 changed files with 22 additions and 1 deletions

21
tlsf.c
View File

@@ -673,7 +673,8 @@ int tlsf_check(tlsf_t tlsf)
while (block != &control->block_null)
{
int fli, sli;
tlsf_insist(block_is_free(block) && "block should be free");
const bool is_block_free = block_is_free(block);
tlsf_insist(is_block_free && "block should be free");
tlsf_insist(!block_is_prev_free(block) && "blocks should have coalesced");
tlsf_insist(!block_is_free(block_next(block)) && "blocks should have coalesced");
tlsf_insist(block_is_prev_free(block_next(block)) && "block should be free");
@@ -681,6 +682,24 @@ int tlsf_check(tlsf_t tlsf)
mapping_insert(block_size(block), &fli, &sli);
tlsf_insist(fli == i && sli == j && "block size indexed in wrong list");
if (tlsf_check_hook != NULL)
{
/* block_size(block) returns the size of the usable memory when the block is allocated.
* As the block under test is free, we need to subtract to the block size the next_free
* and prev_free fields of the block header as they are not a part of the usable memory
* when the block is free. In addition, we also need to subtract the size of prev_phys_block
* as this field is in fact part of the current free block and not part of the next (allocated)
* block. Check the comments in block_split function for more details.
*/
const size_t actual_free_block_size = block_size(block)
- offsetof(block_header_t, next_free)
- block_header_overhead;
tlsf_insist(tlsf_check_hook((void*)block + sizeof(block_header_t),
actual_free_block_size, is_block_free));
}
block = block->next_free;
}
}

2
tlsf.h
View File

@@ -64,6 +64,8 @@ int tlsf_check_pool(pool_t pool);
*/
__attribute__((weak)) void block_absorb_post_hook(void *start, size_t size, bool is_free);
__attribute__((weak)) bool tlsf_check_hook(void *start, size_t size, bool is_free);
#if defined(__cplusplus)
};
#endif