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
This commit is contained in:
Earle F. Philhower, III 2022-06-17 07:50:53 -07:00 committed by GitHub
parent bdd9746635
commit 705b5cedcd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 19 additions and 0 deletions

View File

@ -10,6 +10,7 @@ if (NOT TARGET pico_malloc)
pico_wrap_function(pico_malloc malloc) pico_wrap_function(pico_malloc malloc)
pico_wrap_function(pico_malloc calloc) pico_wrap_function(pico_malloc calloc)
pico_wrap_function(pico_malloc realloc)
pico_wrap_function(pico_malloc free) pico_wrap_function(pico_malloc free)
target_link_libraries(pico_malloc INTERFACE pico_sync) target_link_libraries(pico_malloc INTERFACE pico_sync)

View File

@ -16,6 +16,7 @@ auto_init_mutex(malloc_mutex);
extern void *__real_malloc(size_t size); extern void *__real_malloc(size_t size);
extern void *__real_calloc(size_t count, 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 void __real_free(void *mem);
extern char __StackLimit; /* Set by linker. */ extern char __StackLimit; /* Set by linker. */
@ -62,6 +63,23 @@ void *__wrap_calloc(size_t count, size_t size) {
return rc; 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) { void __wrap_free(void *mem) {
#if PICO_USE_MALLOC_MUTEX #if PICO_USE_MALLOC_MUTEX
mutex_enter_blocking(&malloc_mutex); mutex_enter_blocking(&malloc_mutex);