Skip to content

Commit e8bd827

Browse files
olsajirigregkh
authored andcommitted
libbpf: Prevent double close and leak of btf objects
[ Upstream commit 380044c ] 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: 91abb4a ("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> Signed-off-by: Sasha Levin <sashal@kernel.org>
1 parent 8abad85 commit e8bd827

1 file changed

Lines changed: 11 additions & 10 deletions

File tree

tools/lib/bpf/libbpf.c

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -5746,11 +5746,12 @@ static int load_module_btfs(struct bpf_object *obj)
57465746
info.name = ptr_to_u64(name);
57475747
info.name_len = sizeof(name);
57485748

5749+
btf = NULL;
57495750
err = bpf_btf_get_info_by_fd(fd, &info, &len);
57505751
if (err) {
57515752
err = -errno;
57525753
pr_warn("failed to get BTF object #%d info: %s\n", id, errstr(err));
5753-
goto err_out;
5754+
break;
57545755
}
57555756

57565757
/* ignore non-module BTFs */
@@ -5764,32 +5765,32 @@ static int load_module_btfs(struct bpf_object *obj)
57645765
if (err) {
57655766
pr_warn("failed to load module [%s]'s BTF object #%d: %s\n",
57665767
name, id, errstr(err));
5767-
goto err_out;
5768+
break;
57685769
}
57695770

57705771
err = libbpf_ensure_mem((void **)&obj->btf_modules, &obj->btf_module_cap,
57715772
sizeof(*obj->btf_modules), obj->btf_module_cnt + 1);
57725773
if (err)
5773-
goto err_out;
5774+
break;
57745775

5775-
mod_btf = &obj->btf_modules[obj->btf_module_cnt++];
5776+
mod_btf = &obj->btf_modules[obj->btf_module_cnt];
57765777

57775778
mod_btf->btf = btf;
57785779
mod_btf->id = id;
57795780
mod_btf->fd = fd;
57805781
mod_btf->name = strdup(name);
57815782
if (!mod_btf->name) {
57825783
err = -ENOMEM;
5783-
goto err_out;
5784+
break;
57845785
}
5785-
continue;
5786+
obj->btf_module_cnt++;
5787+
}
57865788

5787-
err_out:
5789+
if (err) {
5790+
btf__free(btf);
57885791
close(fd);
5789-
return err;
57905792
}
5791-
5792-
return 0;
5793+
return err;
57935794
}
57945795

57955796
static struct bpf_core_cand_list *

0 commit comments

Comments
 (0)