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

From: Greg Kroah-Hartman
Date: Fri Jan 24 2020 - 04:33:36 EST


From: Andrii Nakryiko <andriin@xxxxxx>

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@xxxxxx>
Signed-off-by: Daniel Borkmann <daniel@xxxxxxxxxxxxx>
Link: https://lore.kernel.org/bpf/20191107020855.3834758-2-andriin@xxxxxx
Signed-off-by: Greg Kroah-Hartman <gregkh@xxxxxxxxxxxxxxxxxxx>

---
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",