libbpf: Prevent double close and leak of btf objects
authorJiri Olsa <jolsa@kernel.org>
Thu, 16 Apr 2026 10:00:34 +0000 (12:00 +0200)
committerAlexei Starovoitov <ast@kernel.org>
Thu, 16 Apr 2026 23:00:10 +0000 (16:00 -0700)
commit380044c40b1636a72fd8f188b5806be6ae564279
tree2e5cfd342200167af6102f5036e9560e8db34b0c
parentd6f5841a4f291188e0bae21a47c6e540fd937aa8
libbpf: Prevent double close and leak of btf objects

Sashiko found possible double close of btf object fd [1],
which happens when strdup in load_module_btfs fails at which
point the obj->btf_module_cnt is already incremented.

The error path close btf fd and so does later cleanup code in
bpf_object_post_load_cleanup function.

Also libbpf_ensure_mem failure leaves btf object not assigned
and it's leaked.

Replacing the err_out label with break to make the error path
less confusing as suggested by Alan.

Incrementing obj->btf_module_cnt only if there's no failure
and releasing btf object in error path.

Fixes: 91abb4a6d79d ("libbpf: Support attachment of BPF tracing programs to kernel modules")
[1] https://sashiko.dev/#/patchset/20260324081846.2334094-1-jolsa%40kernel.org
Signed-off-by: Jiri Olsa <jolsa@kernel.org>
Link: https://lore.kernel.org/r/20260416100034.1610852-1-jolsa@kernel.org
Signed-off-by: Alexei Starovoitov <ast@kernel.org>
tools/lib/bpf/libbpf.c