Skip to content

Commit 76bceb9

Browse files
xodus7nashif
authored andcommitted
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 <[email protected]>
1 parent e330b55 commit 76bceb9

File tree

1 file changed

+6
-4
lines changed

1 file changed

+6
-4
lines changed

kernel/mem_slab.c

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -204,7 +204,6 @@ int k_mem_slab_init(struct k_mem_slab *slab, void *buffer,
204204
return rc;
205205
}
206206

207-
#if __ASSERT_ON
208207
static bool slab_ptr_is_good(struct k_mem_slab *slab, const void *ptr)
209208
{
210209
const char *p = ptr;
@@ -214,7 +213,6 @@ static bool slab_ptr_is_good(struct k_mem_slab *slab, const void *ptr)
214213
(offset < (slab->info.block_size * slab->info.num_blocks)) &&
215214
((offset % slab->info.block_size) == 0);
216215
}
217-
#endif
218216

219217
int k_mem_slab_alloc(struct k_mem_slab *slab, void **mem, k_timeout_t timeout)
220218
{
@@ -267,9 +265,13 @@ int k_mem_slab_alloc(struct k_mem_slab *slab, void **mem, k_timeout_t timeout)
267265

268266
void k_mem_slab_free(struct k_mem_slab *slab, void *mem)
269267
{
270-
k_spinlock_key_t key = k_spin_lock(&slab->lock);
268+
if (!slab_ptr_is_good(slab, mem)) {
269+
__ASSERT(false, "Invalid memory pointer provided");
270+
k_panic();
271+
return;
272+
}
271273

272-
__ASSERT(slab_ptr_is_good(slab, mem), "Invalid memory pointer provided");
274+
k_spinlock_key_t key = k_spin_lock(&slab->lock);
273275

274276
SYS_PORT_TRACING_OBJ_FUNC_ENTER(k_mem_slab, free, slab);
275277
if ((slab->free_list == NULL) && IS_ENABLED(CONFIG_MULTITHREADING)) {

0 commit comments

Comments
 (0)