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

@@ -68,16 +68,17 @@ static int lib_test_backtrace_str(struct unit_test_state *uts)
line);
ut_asserteq_regex(pattern, str);
/* Test backtrace_str() */
/* Test backtrace_str() - copy result before printf since it may recurse */
line = __LINE__ + 1;
cstr = backtrace_str(0);
ut_assertnonnull(cstr);
strlcpy(buf, cstr, sizeof(buf));
printf("backtrace_str: %s\n", cstr);
printf("backtrace_str: %s\n", buf);
snprintf(pattern, sizeof(pattern),
"lib_test_backtrace_str:%d <-ut_run_test:\\d+ <-ut_run_test_live_flat:\\d+",
line);
ut_asserteq_regex(pattern, cstr);
ut_asserteq_regex(pattern, buf);
return 0;
}