[PATCH 5.13 094/300] libbpf: Fix the possible memory leak on error

From: Greg Kroah-Hartman
Date: Mon Sep 13 2021 - 10:04:29 EST


From: Shuyi Cheng <chengshuyi@xxxxxxxxxxxxxxxxx>

[ Upstream commit 18353c87e0e0440d4c7c746ed740738bbc1b538e ]

If the strdup() fails then we need to call bpf_object__close(obj) to
avoid a resource leak.

Fixes: 166750bc1dd2 ("libbpf: Support libbpf-provided extern variables")
Signed-off-by: Shuyi Cheng <chengshuyi@xxxxxxxxxxxxxxxxx>
Signed-off-by: Andrii Nakryiko <andrii@xxxxxxxxxx>
Link: https://lore.kernel.org/bpf/1626180159-112996-3-git-send-email-chengshuyi@xxxxxxxxxxxxxxxxx
Signed-off-by: Sasha Levin <sashal@xxxxxxxxxx>
---
tools/lib/bpf/libbpf.c | 6 ++++--
1 file changed, 4 insertions(+), 2 deletions(-)

diff --git a/tools/lib/bpf/libbpf.c b/tools/lib/bpf/libbpf.c
index c41d9b2b59ac..2af2d0e4a231 100644
--- a/tools/lib/bpf/libbpf.c
+++ b/tools/lib/bpf/libbpf.c
@@ -7365,8 +7365,10 @@ __bpf_object__open(const char *path, const void *obj_buf, size_t obj_buf_sz,
kconfig = OPTS_GET(opts, kconfig, NULL);
if (kconfig) {
obj->kconfig = strdup(kconfig);
- if (!obj->kconfig)
- return ERR_PTR(-ENOMEM);
+ if (!obj->kconfig) {
+ err = -ENOMEM;
+ goto out;
+ }
}

err = bpf_object__elf_init(obj);
--
2.30.2