[PATCH 5.4 003/102] libbpf: Fix memory leak/double free issue

Greg Kroah-Hartman
2020-01-24T09:33:35Z

From: Andrii Nakryiko <andriin@fb.com>

commit 3dc5e059821376974177cc801d377e3fcdac6712 upstream.

Coverity scan against Github libbpf code found the issue of not freeing memory and
leaving already freed memory still referenced from bpf_program. Fix it by
re-assigning successfully reallocated memory sooner.

Fixes: 2993e0515bb4 ("tools/bpf: add support to read .BTF.ext sections")
Signed-off-by: Andrii Nakryiko <andriin@fb.com>
Signed-off-by: Daniel Borkmann <daniel@iogearbox.net>
Link: https://lore.kernel.org/bpf/20191107020855.3834758-2-andriin@fb.com
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

---
tools/lib/bpf/libbpf.c | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)

--- a/tools/lib/bpf/libbpf.c
+++ b/tools/lib/bpf/libbpf.c
@@ -3220,6 +3220,7 @@ bpf_program__reloc_text(struct bpf_progr
pr_warning("oom in prog realloc\n");
return -ENOMEM;
}
+ prog->insns = new_insn;

if (obj->btf_ext) {
err = bpf_program_reloc_btf_ext(prog, obj,
@@ -3231,7 +3232,6 @@ bpf_program__reloc_text(struct bpf_progr

memcpy(new_insn + prog->insns_cnt, text->insns,
text->insns_cnt * sizeof(*insn));
- prog->insns = new_insn;
prog->main_prog_cnt = prog->insns_cnt;
prog->insns_cnt = new_cnt;
pr_debug("added %zd insn from %s to prog %s\n",