[PATCH 5.10 267/599] libbpf: Fix possible NULL pointer dereference when destroying skeleton

From: Greg Kroah-Hartman
Date: Tue Apr 05 2022 - 16:56:47 EST

From: Yafang Shao <laoar.shao@xxxxxxxxx>

[ Upstream commit a32ea51a3f17ce6524c9fc19d311e708331c8b5f ]

When I checked the code in skeleton header file generated with my own
bpf prog, I found there may be possible NULL pointer dereference when
destroying skeleton. Then I checked the in-tree bpf progs, finding that is
a common issue. Let's take the generated samples/bpf/xdp_redirect_cpu.skel.h
for example. Below is the generated code in

struct bpf_object_skeleton *s;
s = (struct bpf_object_skeleton *)calloc(1, sizeof(*s));
if (!s)
goto error;
return -ENOMEM;

After goto error, the NULL 's' will be deferenced in

We can simply fix this issue by just adding a NULL check in

Fixes: d66562fba1ce ("libbpf: Add BPF object skeleton support")
Signed-off-by: Yafang Shao <laoar.shao@xxxxxxxxx>
Signed-off-by: Andrii Nakryiko <andrii@xxxxxxxxxx>
Link: https://lore.kernel.org/bpf/20220108134739.32541-1-laoar.shao@xxxxxxxxx
Signed-off-by: Sasha Levin <sashal@xxxxxxxxxx>
tools/lib/bpf/libbpf.c | 3 +++
1 file changed, 3 insertions(+)

diff --git a/tools/lib/bpf/libbpf.c b/tools/lib/bpf/libbpf.c
index b337d6f29098..61df26f048d9 100644
--- a/tools/lib/bpf/libbpf.c
+++ b/tools/lib/bpf/libbpf.c
@@ -10923,6 +10923,9 @@ void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)

void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
+ if (!s)
+ return;
if (s->progs)
if (s->obj)