From 76bceb9ed29d669be978cef7c85b5864f73fbd33 Mon Sep 17 00:00:00 2001 From: Corey Wharton Date: Wed, 23 Oct 2024 14:36:25 -0700 Subject: [PATCH] kernel: mem_slab: always validate memory address on free Allowing an invalid address to be "freed" when asserts are disabled is dangerous and can lead to a very hard class of bugs (and potential security issues) to troubleshoot. This change always validates the address before adding it to the free list and calls k_panic() if asserts are not enabled. Signed-off-by: Corey Wharton --- kernel/mem_slab.c | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/kernel/mem_slab.c b/kernel/mem_slab.c index 80710d063d9..e64359174c5 100644 --- a/kernel/mem_slab.c +++ b/kernel/mem_slab.c @@ -204,7 +204,6 @@ out: return rc; } -#if __ASSERT_ON static bool slab_ptr_is_good(struct k_mem_slab *slab, const void *ptr) { const char *p = ptr; @@ -214,7 +213,6 @@ static bool slab_ptr_is_good(struct k_mem_slab *slab, const void *ptr) (offset < (slab->info.block_size * slab->info.num_blocks)) && ((offset % slab->info.block_size) == 0); } -#endif int k_mem_slab_alloc(struct k_mem_slab *slab, void **mem, k_timeout_t timeout) { @@ -267,9 +265,13 @@ int k_mem_slab_alloc(struct k_mem_slab *slab, void **mem, k_timeout_t timeout) void k_mem_slab_free(struct k_mem_slab *slab, void *mem) { - k_spinlock_key_t key = k_spin_lock(&slab->lock); + if (!slab_ptr_is_good(slab, mem)) { + __ASSERT(false, "Invalid memory pointer provided"); + k_panic(); + return; + } - __ASSERT(slab_ptr_is_good(slab, mem), "Invalid memory pointer provided"); + k_spinlock_key_t key = k_spin_lock(&slab->lock); SYS_PORT_TRACING_OBJ_FUNC_ENTER(k_mem_slab, free, slab); if ((slab->free_list == NULL) && IS_ENABLED(CONFIG_MULTITHREADING)) {