Skip to content

Commit c425a44

Browse files
committed
Added mutex around malloc/free/... (not for PSRAM yet)
1 parent acae662 commit c425a44

File tree

1 file changed

+11
-0
lines changed

1 file changed

+11
-0
lines changed

cores/rp2040/malloc-lock.cpp

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
#include <Arduino.h>
2222
#include <malloc.h>
2323
#include <reent.h>
24+
#include "pico/mutex.h"
2425
#include "psram.h"
2526

2627
extern "C" void *__real_malloc(size_t size);
@@ -29,6 +30,8 @@ extern "C" void *__real_realloc(void *mem, size_t size);
2930
extern "C" void __real_free(void *mem);
3031
extern "C" struct mallinfo __real_mallinfo();
3132

33+
auto_init_mutex(malloc_lock_mutex);
34+
3235
#ifdef RP2350_PSRAM_CS
3336
extern "C" {
3437
extern uint8_t __psram_start__;
@@ -41,14 +44,18 @@ extern "C" {
4144

4245
extern "C" void *__wrap_malloc(size_t size) {
4346
noInterrupts();
47+
mutex_enter_blocking(&malloc_lock_mutex);
4448
void *rc = __real_malloc(size);
49+
mutex_exit(&malloc_lock_mutex);
4550
interrupts();
4651
return rc;
4752
}
4853

4954
extern "C" void *__wrap_calloc(size_t count, size_t size) {
5055
noInterrupts();
56+
mutex_enter_blocking(&malloc_lock_mutex);
5157
void *rc = __real_calloc(count, size);
58+
mutex_exit(&malloc_lock_mutex);
5259
interrupts();
5360
return rc;
5461
}
@@ -85,7 +92,9 @@ extern "C" void *__wrap_realloc(void *mem, size_t size) {
8592
rc = __real_realloc(mem, size);
8693
}
8794
#else
95+
mutex_enter_blocking(&malloc_lock_mutex);
8896
rc = __real_realloc(mem, size);
97+
mutex_exit(&malloc_lock_mutex);
8998
#endif
9099
interrupts();
91100
return rc;
@@ -100,7 +109,9 @@ extern "C" void __wrap_free(void *mem) {
100109
__real_free(mem);
101110
}
102111
#else
112+
mutex_enter_blocking(&malloc_lock_mutex);
103113
__real_free(mem);
114+
mutex_exit(&malloc_lock_mutex);
104115
#endif
105116
interrupts();
106117
}

0 commit comments

Comments
 (0)