[PATCH 4/4] perf libbfd: Fix memory leaks and NULL fclose in BPF disassembly
Arnaldo Carvalho de Melo <[email protected]> Sun, 2 Aug 2026 11:27:12 -0300
| Newsgroups | org.kernel.vger.linux-perf-users,org.kernel.vger.linux-kernel |
|---|---|
| Message-ID | <[email protected]> |
From: Arnaldo Carvalho de Melo <[email protected]> symbol__disassemble_bpf_libbfd() has four resource management bugs: 1. free(prog_linfo) leaks internal arrays. bpf_prog_linfo contains raw_linfo, raw_jited_linfo, nr_jited_linfo_per_func, and jited_linfo_func_idx pointers that are only freed by the proper destructor bpf_prog_linfo__free(). 2. open_memstream(&buf, &buf_size) allocates a dynamic buffer that the caller must free after fclose(). The function calls fclose(s) but never free(buf), leaking the stream buffer on every call. 3. args->line = strdup(srcline) is immediately consumed by disasm_line__new(args) which internally calls strdup(args->line) again via annotation_line__init(). The first strdup result is then overwritten by args->line = buf + prev_buf_size without being freed. 4. If open_memstream() fails, the error path jumps to 'out:' which calls fclose(s) with s == NULL — undefined behavior. Fix by using bpf_prog_linfo__free(), initializing buf to NULL, adding free(buf) after fclose(s), guarding fclose() against NULL, and removing the redundant strdup since annotation_line__init() makes its own copy. Fixes: 6987561c9e86eace ("perf annotate: Enable annotation of BPF programs") Reported-by: sashiko-bot <[email protected]> Cc: Song Liu <[email protected]> Cc: Ian Rogers <[email protected]> Assisted-by: Claude:claude-opus-4.6 Signed-off-by: Arnaldo Carvalho de Melo <[email protected]> --- tools/perf/util/libbfd.c | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/tools/perf/util/libbfd.c b/tools/perf/util/libbfd.c index 0b7164f0e9fdbbed..33dc6158b2b1ffab 100644 --- a/tools/perf/util/libbfd.c +++ b/tools/perf/util/libbfd.c @@ -15,6 +15,7 @@ #ifdef HAVE_LIBBPF_SUPPORT #include <bpf/bpf.h> #include <bpf/btf.h> +#include <bpf/libbpf.h> #endif #include <fcntl.h> #include <stdio.h> @@ -510,7 +511,7 @@ int symbol__disassemble_bpf_libbfd(struct symbol *sym __maybe_unused, char tpath[PATH_MAX]; size_t buf_size; int nr_skip = 0; - char *buf; + char *buf = NULL; bfd *bfdf; int ret; FILE *s; @@ -620,7 +621,7 @@ int symbol__disassemble_bpf_libbfd(struct symbol *sym __maybe_unused, if (!annotate_opts.hide_src_code && srcline) { args->offset = -1; - args->line = strdup(srcline); + args->line = (char *)srcline; args->line_nr = 0; args->fileloc = NULL; args->ms->sym = sym; @@ -645,9 +646,12 @@ int symbol__disassemble_bpf_libbfd(struct symbol *sym __maybe_unused, ret = 0; out: - free(prog_linfo); + bpf_prog_linfo__free(prog_linfo); btf__free(btf); - fclose(s); + if (s) { + fclose(s); + free(buf); + } bfd_close(bfdf); return ret; #else -- 2.55.0