Skip to content

Commit f87d39d

Browse files
liuhangbinkernel-patches-bot
authored andcommitted
libbpf: close map fd if init map slots failed
Previously we forgot to close the map fd if bpf_map_update_elem() failed during map slot init, which will leak map fd. Let's move map slot initialization to new function init_map_slots() to simplify the code. And close the map fd if init slot failed. Reported-by: Andrii Nakryiko <andrii.nakryiko@gmail.com> Signed-off-by: Hangbin Liu <liuhangbin@gmail.com> Acked-by: Andrii Nakryiko <andrii@kernel.org>
1 parent 07d2e5a commit f87d39d

File tree

1 file changed

+34
-21
lines changed

1 file changed

+34
-21
lines changed

tools/lib/bpf/libbpf.c

Lines changed: 34 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -4203,6 +4203,36 @@ static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map)
42034203
return 0;
42044204
}
42054205

4206+
static int init_map_slots(struct bpf_map *map)
4207+
{
4208+
const struct bpf_map *targ_map;
4209+
unsigned int i;
4210+
int fd, err;
4211+
4212+
for (i = 0; i < map->init_slots_sz; i++) {
4213+
if (!map->init_slots[i])
4214+
continue;
4215+
4216+
targ_map = map->init_slots[i];
4217+
fd = bpf_map__fd(targ_map);
4218+
err = bpf_map_update_elem(map->fd, &i, &fd, 0);
4219+
if (err) {
4220+
err = -errno;
4221+
pr_warn("map '%s': failed to initialize slot [%d] to map '%s' fd=%d: %d\n",
4222+
map->name, i, targ_map->name,
4223+
fd, err);
4224+
return err;
4225+
}
4226+
pr_debug("map '%s': slot [%d] set to map '%s' fd=%d\n",
4227+
map->name, i, targ_map->name, fd);
4228+
}
4229+
4230+
zfree(&map->init_slots);
4231+
map->init_slots_sz = 0;
4232+
4233+
return 0;
4234+
}
4235+
42064236
static int
42074237
bpf_object__create_maps(struct bpf_object *obj)
42084238
{
@@ -4245,28 +4275,11 @@ bpf_object__create_maps(struct bpf_object *obj)
42454275
}
42464276

42474277
if (map->init_slots_sz) {
4248-
for (j = 0; j < map->init_slots_sz; j++) {
4249-
const struct bpf_map *targ_map;
4250-
int fd;
4251-
4252-
if (!map->init_slots[j])
4253-
continue;
4254-
4255-
targ_map = map->init_slots[j];
4256-
fd = bpf_map__fd(targ_map);
4257-
err = bpf_map_update_elem(map->fd, &j, &fd, 0);
4258-
if (err) {
4259-
err = -errno;
4260-
pr_warn("map '%s': failed to initialize slot [%d] to map '%s' fd=%d: %d\n",
4261-
map->name, j, targ_map->name,
4262-
fd, err);
4263-
goto err_out;
4264-
}
4265-
pr_debug("map '%s': slot [%d] set to map '%s' fd=%d\n",
4266-
map->name, j, targ_map->name, fd);
4278+
err = init_map_slots(map);
4279+
if (err < 0) {
4280+
zclose(map->fd);
4281+
goto err_out;
42674282
}
4268-
zfree(&map->init_slots);
4269-
map->init_slots_sz = 0;
42704283
}
42714284

42724285
if (map->pin_path && !map->pinned) {

0 commit comments

Comments
 (0)