[PATCH] libbpf: Fix null pointer dereference in btf_dump__free on allocation failure

chenyuan posted 1 patch 3 months, 3 weeks ago
There is a newer version of this series
tools/lib/bpf/btf_dump.c | 3 +++
1 file changed, 3 insertions(+)
[PATCH] libbpf: Fix null pointer dereference in btf_dump__free on allocation failure
Posted by chenyuan 3 months, 3 weeks ago
From: chenyuan <chenyuan@kylinos.cn>

When btf_dump__new() fails to allocate memory for the internal hashmap
(btf_dump->type_names), it returns an error code. However, the cleanup
function btf_dump__free() does not check if btf_dump->type_names is NULL
before attempting to free it. This leads to a null pointer dereference
when btf_dump__free() is called on a btf_dump object.

Fix: 351131b51c7a ("libbpf: add btf_dump API for BTF-to-C conversion")
Signed-off-by: chenyuan <chenyuan@kylinos.cn>
---
 tools/lib/bpf/btf_dump.c | 3 +++
 1 file changed, 3 insertions(+)

diff --git a/tools/lib/bpf/btf_dump.c b/tools/lib/bpf/btf_dump.c
index 7c2f1f13f958..80b7bec201f7 100644
--- a/tools/lib/bpf/btf_dump.c
+++ b/tools/lib/bpf/btf_dump.c
@@ -227,6 +227,9 @@ static void btf_dump_free_names(struct hashmap *map)
 	size_t bkt;
 	struct hashmap_entry *cur;
 
+	if (IS_ERR_OR_NULL(map))
+		return;
+
 	hashmap__for_each_entry(map, cur, bkt)
 		free((void *)cur->pkey);
 
-- 
2.25.1
Re: [PATCH] libbpf: Fix null pointer dereference in btf_dump__free on allocation failure
Posted by Andrii Nakryiko 3 months, 3 weeks ago
On Tue, Jun 17, 2025 at 1:56 AM chenyuan <chenyuan_fl@163.com> wrote:
>
> From: chenyuan <chenyuan@kylinos.cn>
>
> When btf_dump__new() fails to allocate memory for the internal hashmap
> (btf_dump->type_names), it returns an error code. However, the cleanup
> function btf_dump__free() does not check if btf_dump->type_names is NULL
> before attempting to free it. This leads to a null pointer dereference
> when btf_dump__free() is called on a btf_dump object.
>
> Fix: 351131b51c7a ("libbpf: add btf_dump API for BTF-to-C conversion")
> Signed-off-by: chenyuan <chenyuan@kylinos.cn>
> ---
>  tools/lib/bpf/btf_dump.c | 3 +++
>  1 file changed, 3 insertions(+)
>
> diff --git a/tools/lib/bpf/btf_dump.c b/tools/lib/bpf/btf_dump.c
> index 7c2f1f13f958..80b7bec201f7 100644
> --- a/tools/lib/bpf/btf_dump.c
> +++ b/tools/lib/bpf/btf_dump.c
> @@ -227,6 +227,9 @@ static void btf_dump_free_names(struct hashmap *map)
>         size_t bkt;
>         struct hashmap_entry *cur;
>
> +       if (IS_ERR_OR_NULL(map))
> +               return;
> +

it looks like btf_dump__new() will always reset those failed hashmaps
to null, so it should be enough (and a bit cleaner) to just do

if (!map)
    return;

pw-bot: cr

>         hashmap__for_each_entry(map, cur, bkt)
>                 free((void *)cur->pkey);
>
> --
> 2.25.1
>
>