Skip to content

Commit fbb1bdb

Browse files
committed
lib: newlib: Add malloc lock
This commit adds a lock implementation for the newlib heap memory management functions (`malloc` and `free`). The `__malloc_lock` and `__malloc_unlock` functions are called by the newlib `malloc` and `free` functions to synchronise access to the heap region. Without this lock, making use of the `malloc` and `free` functions from multiple threads will result in the corruption of the heap region. Signed-off-by: Stephanos Ioannidis <[email protected]>
1 parent fd20ad2 commit fbb1bdb

File tree

1 file changed

+13
-0
lines changed

1 file changed

+13
-0
lines changed

lib/libc/newlib/libc-hooks.c

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
#include <app_memory/app_memdomain.h>
1717
#include <init.h>
1818
#include <sys/sem.h>
19+
#include <sys/mutex.h>
1920
#include <sys/mem_manage.h>
2021

2122
#define LIBC_BSS K_APP_BMEM(z_libc_partition)
@@ -291,6 +292,18 @@ void *_sbrk(intptr_t count)
291292
}
292293
__weak FUNC_ALIAS(_sbrk, sbrk, void *);
293294

295+
static LIBC_DATA SYS_MUTEX_DEFINE(heap_mutex);
296+
297+
void __malloc_lock(struct _reent *reent)
298+
{
299+
sys_mutex_lock(&heap_mutex, K_FOREVER);
300+
}
301+
302+
void __malloc_unlock(struct _reent *reent)
303+
{
304+
sys_mutex_unlock(&heap_mutex);
305+
}
306+
294307
__weak int *__errno(void)
295308
{
296309
return z_errno();

0 commit comments

Comments
 (0)