Wrap realloc() call with malloc_mutex in multicore (#864)
Protect against heap corruption by mutex-protecting the realloc() call
(like malloc/free are already).
Fixes #863
Fixes https://github.com/maxgerhardt/platform-raspberrypi/issues/7
Fixes https://github.com/earlephilhower/arduino-pico/issues/614
diff --git a/src/rp2_common/pico_malloc/CMakeLists.txt b/src/rp2_common/pico_malloc/CMakeLists.txt
index deeb30f..57ac267 100644
--- a/src/rp2_common/pico_malloc/CMakeLists.txt
+++ b/src/rp2_common/pico_malloc/CMakeLists.txt
@@ -10,6 +10,7 @@
pico_wrap_function(pico_malloc malloc)
pico_wrap_function(pico_malloc calloc)
+ pico_wrap_function(pico_malloc realloc)
pico_wrap_function(pico_malloc free)
target_link_libraries(pico_malloc INTERFACE pico_sync)
diff --git a/src/rp2_common/pico_malloc/pico_malloc.c b/src/rp2_common/pico_malloc/pico_malloc.c
index 4928a8e..a053986 100644
--- a/src/rp2_common/pico_malloc/pico_malloc.c
+++ b/src/rp2_common/pico_malloc/pico_malloc.c
@@ -16,6 +16,7 @@
extern void *__real_malloc(size_t size);
extern void *__real_calloc(size_t count, size_t size);
+extern void *__real_realloc(void *mem, size_t size);
extern void __real_free(void *mem);
extern char __StackLimit; /* Set by linker. */
@@ -62,6 +63,23 @@
return rc;
}
+void *__wrap_realloc(void *mem, size_t size) {
+#if PICO_USE_MALLOC_MUTEX
+ mutex_enter_blocking(&malloc_mutex);
+#endif
+ void *rc = __real_realloc(mem, size);
+#if PICO_USE_MALLOC_MUTEX
+ mutex_exit(&malloc_mutex);
+#endif
+#if PICO_DEBUG_MALLOC
+ if (!rc || ((uint8_t *)rc) + size > (uint8_t*)PICO_DEBUG_MALLOC_LOW_WATER) {
+ printf("realloc %p %d->%p\n", mem, (uint) size, rc);
+ }
+#endif
+ check_alloc(rc, size);
+ return rc;
+}
+
void __wrap_free(void *mem) {
#if PICO_USE_MALLOC_MUTEX
mutex_enter_blocking(&malloc_mutex);