Skip to content

Commit 380044c

Browse files
olsajiriAlexei Starovoitov
authored andcommitted
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: 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>
1 parent d6f5841 commit 380044c

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
@@ -5852,11 +5852,12 @@ static int load_module_btfs(struct bpf_object *obj)
58525852
info.name = ptr_to_u64(name);
58535853
info.name_len = sizeof(name);
58545854

5855+
btf = NULL;
58555856
err = bpf_btf_get_info_by_fd(fd, &info, &len);
58565857
if (err) {
58575858
err = -errno;
58585859
pr_warn("failed to get BTF object #%d info: %s\n", id, errstr(err));
5859-
goto err_out;
5860+
break;
58605861
}
58615862

58625863
/* ignore non-module BTFs */
@@ -5870,32 +5871,32 @@ static int load_module_btfs(struct bpf_object *obj)
58705871
if (err) {
58715872
pr_warn("failed to load module [%s]'s BTF object #%d: %s\n",
58725873
name, id, errstr(err));
5873-
goto err_out;
5874+
break;
58745875
}
58755876

58765877
err = libbpf_ensure_mem((void **)&obj->btf_modules, &obj->btf_module_cap,
58775878
sizeof(*obj->btf_modules), obj->btf_module_cnt + 1);
58785879
if (err)
5879-
goto err_out;
5880+
break;
58805881

5881-
mod_btf = &obj->btf_modules[obj->btf_module_cnt++];
5882+
mod_btf = &obj->btf_modules[obj->btf_module_cnt];
58825883

58835884
mod_btf->btf = btf;
58845885
mod_btf->id = id;
58855886
mod_btf->fd = fd;
58865887
mod_btf->name = strdup(name);
58875888
if (!mod_btf->name) {
58885889
err = -ENOMEM;
5889-
goto err_out;
5890+
break;
58905891
}
5891-
continue;
5892+
obj->btf_module_cnt++;
5893+
}
58925894

5893-
err_out:
5895+
if (err) {
5896+
btf__free(btf);
58945897
close(fd);
5895-
return err;
58965898
}
5897-
5898-
return 0;
5899+
return err;
58995900
}
59005901

59015902
static struct bpf_core_cand_list *

0 commit comments

Comments
 (0)