[RFC PATCH] perf util: asprintf helper for leak sanitizer

From: Ian Rogers
Date: Tue Jun 13 2023 - 15:16:53 EST


asprintf is a source of memory leaks but produces bad stack traces on
my Debian linux. This patch adds a simple asprintf implementation to
util.c that works around it.

Before output:
```
==1541752==ERROR: LeakSanitizer: detected memory leaks

Direct leak of 10 byte(s) in 1 object(s) allocated from:
#0 0x7f90c76b89cf in __interceptor_malloc ../../../../src/libsanitizer/asan/asan_malloc_linux.cpp:69
#1 0x7f90c649d2c7 in __vasprintf_internal libio/vasprintf.c:71
#2 0x55ad9b79afbf (/tmp/perf/perf+0x850fbf)

SUMMARY: AddressSanitizer: 10 byte(s) leaked in 1 allocation(s).
```

After output:
```
==1545918==ERROR: LeakSanitizer: detected memory leaks

Direct leak of 10 byte(s) in 1 object(s) allocated from:
#0 0x7f2755a7077b in __interceptor_strdup ../../../../src/libsanitizer/asan/asan_interceptors.cpp:439
#1 0x564986a8df31 in asprintf util/util.c:566
#2 0x5649869b5901 in metricgroup__lookup_default_metricgroup util/metricgroup.c:1520
#3 0x5649869b5e57 in metricgroup__lookup_create util/metricgroup.c:1579
#4 0x5649869b6ddc in parse_groups util/metricgroup.c:1698
#5 0x5649869b7714 in metricgroup__parse_groups util/metricgroup.c:1771
#6 0x5649867da9d5 in add_default_attributes tools/perf/builtin-stat.c:2164
#7 0x5649867ddbfb in cmd_stat tools/perf/builtin-stat.c:2707
#8 0x5649868fa5a2 in run_builtin tools/perf/perf.c:323
#9 0x5649868fab13 in handle_internal_command tools/perf/perf.c:377
#10 0x5649868faedb in run_argv tools/perf/perf.c:421
#11 0x5649868fb443 in main tools/perf/perf.c:537
#12 0x7f2754846189 in __libc_start_call_main ../sysdeps/nptl/libc_start_call_main.h:58

SUMMARY: AddressSanitizer: 10 byte(s) leaked in 1 allocation(s).
```

RFC: is this useful for others? Should we have a build flag for it?
---
tools/perf/util/util.c | 19 +++++++++++++++++++
1 file changed, 19 insertions(+)

diff --git a/tools/perf/util/util.c b/tools/perf/util/util.c
index c1fd9ba6d697..57eb528c5fed 100644
--- a/tools/perf/util/util.c
+++ b/tools/perf/util/util.c
@@ -552,3 +552,22 @@ int sched_getcpu(void)
return -1;
}
#endif
+
+int asprintf(char **restrict strp, const char *restrict fmt, ...)
+{
+ char buf[1024];
+ va_list ap;
+ int size;
+ char *result;
+
+ va_start(ap, fmt);
+ size = vsnprintf(buf, sizeof(buf), fmt, ap);
+ if (size < (int)sizeof(buf))
+ result = strdup(buf);
+ else
+ size = vasprintf(&result, fmt, ap);
+
+ *strp = result;
+ va_end(ap);
+ return size;
+}
--
2.41.0.162.gfafddb0af9-goog