Skip to content

Commit

Permalink
[nrf noup] Add debug logs for sys_heap malloc
Browse files Browse the repository at this point in the history
When CONFIG_CHIP_MALLOC_SYS_HEAP_DEBUG is enabled, log
every malloc/realloc/free to trace the source of memory
leaks in the application.
  • Loading branch information
Damian-Nordic committed Dec 18, 2023
1 parent 6c1531c commit 529841d
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
7 changes: 7 additions & 0 deletions config/zephyr/Kconfig
Original file line number Diff line number Diff line change
Expand Up @@ -462,6 +462,13 @@ config CHIP_MALLOC_SYS_HEAP_WATERMARKS_SUPPORT
Enables support for getting current heap high watermark and resetting
watermarks.

config CHIP_MALLOC_SYS_HEAP_DEBUG
bool "Log every allocated or freed memory block"
help
Enables debug logs printed whenever a heap memory block is allocated or
freed. The logs can be used to trace the source of memory leaks in the
application.

endif

module = MATTER
Expand Down
20 changes: 18 additions & 2 deletions src/platform/Zephyr/SysHeapMalloc.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,13 @@ void * Malloc(size_t size)
{
LockGuard lockGuard;

return lockGuard.Locked() ? sys_heap_aligned_alloc(&sHeap, kMallocAlignment, size) : nullptr;
void * const mem = lockGuard.Locked() ? sys_heap_aligned_alloc(&sHeap, kMallocAlignment, size) : nullptr;

#ifdef CONFIG_CHIP_MALLOC_SYS_HEAP_DEBUG
ChipLogProgress(DeviceLayer, "Malloc(%u) = %p, caller: %p", size, mem, __builtin_return_address(0));
#endif

return mem;
}

void * Calloc(size_t num, size_t size)
Expand All @@ -110,7 +116,13 @@ void * Realloc(void * mem, size_t size)
{
LockGuard lockGuard;

return lockGuard.Locked() ? sys_heap_aligned_realloc(&sHeap, mem, kMallocAlignment, size) : nullptr;
void * const new_mem = lockGuard.Locked() ? sys_heap_aligned_realloc(&sHeap, mem, kMallocAlignment, size) : nullptr;

#ifdef CONFIG_CHIP_MALLOC_SYS_HEAP_DEBUG
ChipLogProgress(DeviceLayer, "Realloc(%p, %u) = %p, caller: %p", mem, size, new_mem, __builtin_return_address(0));
#endif

return new_mem;
}

void Free(void * mem)
Expand All @@ -119,6 +131,10 @@ void Free(void * mem)

VerifyOrReturn(lockGuard.Locked());
sys_heap_free(&sHeap, mem);

#ifdef CONFIG_CHIP_MALLOC_SYS_HEAP_DEBUG
ChipLogProgress(DeviceLayer, "Free(%p), caller: %p", mem, __builtin_return_address(0));
#endif
}

#ifdef CONFIG_SYS_HEAP_RUNTIME_STATS
Expand Down

0 comments on commit 529841d

Please sign in to comment.