From ff2eb6e134ebfc225b97b46182af3cc58ed481f6 Mon Sep 17 00:00:00 2001
From: Changqing Li <changqing.li@windriver.com>
Date: Thu, 10 Apr 2025 11:50:04 +0800
Subject: [PATCH] libbpf: check for empty BTF data section in btf_parse_elf

A valid ELF file may contain a SHT_NOBITS .BTF section. This case is
not handled correctly in btf_parse_elf, which leads to a segfault.

Add a null check for a buffer returned by elf_getdata() before
proceeding with its processing.

Bug report: https://github.com/libbpf/libbpf/issues/894

Signed-off-by: Ihor Solodrai <ihor.solodrai@linux.dev>
Acked-by: Mykyta Yatsenko <mykyta.yatsenko5@gmail.com>

Upstream-Status: Backport [https://github.com/kernel-patches/bpf-rc/commit/b02b669fd9398d246c8c9ae901c0d8f5bb36a588]

Signed-off-by: Changqing Li <changqing.li@windriver.com>
---
 btf.c | 6 ++++++
 1 file changed, 6 insertions(+)

diff --git a/btf.c b/btf.c
index e9673c0e..21d38dcf 100644
--- a/btf.c
+++ b/btf.c
@@ -1199,6 +1199,12 @@ static struct btf *btf_parse_elf(const char *path, struct btf *base_btf,
 		goto done;
 	}
 
+	if (!secs.btf_data->d_buf) {
+		pr_warn("BTF data is empty in %s\n", path);
+		err = -ENODATA;
+		goto done;
+	}
+
 	if (secs.btf_base_data) {
 		dist_base_btf = btf_new(secs.btf_base_data->d_buf, secs.btf_base_data->d_size,
 					NULL);
-- 
2.34.1

