From cfe4f2ffdb9b8a7bc65ee8b3318cb7caa0a907bd Mon Sep 17 00:00:00 2001 From: Jason Pepas Date: Thu, 4 Jul 2024 21:09:05 -0500 Subject: [PATCH] PICO_MALLOC_TRACK_PEAK, peak allocation tracking for malloc --- .../pico_malloc/include/pico/malloc.h | 13 +++++++++++- src/rp2_common/pico_malloc/pico_malloc.c | 20 +++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/src/rp2_common/pico_malloc/include/pico/malloc.h b/src/rp2_common/pico_malloc/include/pico/malloc.h index b4ae2b636..b964eda15 100644 --- a/src/rp2_common/pico_malloc/include/pico/malloc.h +++ b/src/rp2_common/pico_malloc/include/pico/malloc.h @@ -35,4 +35,15 @@ #define PICO_DEBUG_MALLOC_LOW_WATER 0 #endif -#endif \ No newline at end of file +// PICO_CONFIG: PICO_MALLOC_TRACK_PEAK, Enable/disable tracking the peak allocated bytes by malloc, type=bool, default=0, group=pico_malloc +#ifndef PICO_MALLOC_TRACK_PEAK +#define PICO_MALLOC_TRACK_PEAK 0 +#endif + +#if PICO_MALLOC_TRACK_PEAK +#include +extern size_t malloc_peak_bytes; +void malloc_reset_peak(); +#endif + +#endif diff --git a/src/rp2_common/pico_malloc/pico_malloc.c b/src/rp2_common/pico_malloc/pico_malloc.c index 868a455d2..a4ba3758a 100644 --- a/src/rp2_common/pico_malloc/pico_malloc.c +++ b/src/rp2_common/pico_malloc/pico_malloc.c @@ -28,11 +28,29 @@ static inline void check_alloc(__unused void *mem, __unused uint size) { #endif } +#if PICO_MALLOC_TRACK_PEAK +#include +size_t malloc_peak_bytes = 0; +void malloc_reset_peak() { + malloc_peak_bytes = mallinfo().uordblks; +} +#endif + +static inline void update_peak() { +#if PICO_MALLOC_TRACK_PEAK + struct mallinfo mi = mallinfo(); + if (mi.uordblks > malloc_peak_bytes) { + malloc_peak_bytes = mi.uordblks; + } +#endif +} + void *WRAPPER_FUNC(malloc)(size_t size) { #if PICO_USE_MALLOC_MUTEX mutex_enter_blocking(&malloc_mutex); #endif void *rc = REAL_FUNC(malloc)(size); + update_peak(); #if PICO_USE_MALLOC_MUTEX mutex_exit(&malloc_mutex); #endif @@ -50,6 +68,7 @@ void *WRAPPER_FUNC(calloc)(size_t count, size_t size) { mutex_enter_blocking(&malloc_mutex); #endif void *rc = REAL_FUNC(calloc)(count, size); + update_peak(); #if PICO_USE_MALLOC_MUTEX mutex_exit(&malloc_mutex); #endif @@ -67,6 +86,7 @@ void *WRAPPER_FUNC(realloc)(void *mem, size_t size) { mutex_enter_blocking(&malloc_mutex); #endif void *rc = REAL_FUNC(realloc)(mem, size); + update_peak(); #if PICO_USE_MALLOC_MUTEX mutex_exit(&malloc_mutex); #endif