malloc: Record caller backtrace for each allocation

When CONFIG_MCHECK_HEAP_PROTECTION is enabled, use backtrace_str() to
capture the caller information for each malloc/calloc/realloc/memalign
call. This information is stored in the mcheck header and can be viewed
with 'malloc dump'.

Add a flag to disable the backtrace when the stack is corrupted, since
the backtrace code tries to walks the invalid stack frames and will
crash.

Note: A few allocations made during libbacktrace initialisation may
not have caller info since they occur during the first backtrace call.

Example output showing caller info:
    18a1d010   90  used  log_init:453 <-board_init_r:774
    18a1d0a0 6060  used  membuf_new:420 <-console_record
    18a3b840   90  used  of_alias_scan:911 <-board_init_

Fix up the backtrace test to avoid recursion.

Co-developed-by: Claude <noreply@anthropic.com>
Signed-off-by: Simon Glass <simon.glass@canonical.com>
This commit is contained in:
Simon Glass
2025-12-02 11:14:48 +00:00
parent 36118a9e18
commit 754a755e4a
4 changed files with 62 additions and 7 deletions

View File

@@ -59,6 +59,18 @@ Example
Used: c2ef0 bytes in 931 chunks
Free: 5f3f0c0 bytes in 2 chunks + top
With CONFIG_MCHECK_HEAP_PROTECTION enabled, the caller backtrace is shown::
=> malloc dump
Heap dump: 18a1d000 - 1ea1f000
Address Size Status
----------------------------------
18a1d000 10 (chunk header)
18a1d010 90 used log_init:453 <-board_init_r:774
18a1d0a0 6060 used membuf_new:420 <-console_record
18a3b840 90 used of_alias_scan:911 <-board_init_
...
Configuration
-------------