Linux kernel mirror (for testing) git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel os linux

libbpf: Sanitise internal map names so they are not rejected by the kernel

The kernel only accepts map names with alphanumeric characters, underscores
and periods in their name. However, the auto-generated internal map names
used by libbpf takes their prefix from the user-supplied BPF object name,
which has no such restriction. This can lead to "Invalid argument" errors
when trying to load a BPF program using global variables.

Fix this by sanitising the map names, replacing any non-allowed characters
with underscores.

Fixes: d859900c4c56 ("bpf, libbpf: support global data/bss/rodata sections")
Signed-off-by: Toke Høiland-Jørgensen <toke@redhat.com>
Signed-off-by: Daniel Borkmann <daniel@iogearbox.net>
Link: https://lore.kernel.org/bpf/20200217171701.215215-1-toke@redhat.com

authored by

Toke Høiland-Jørgensen and committed by
Daniel Borkmann
113e6b7e f25975f4

+7 -1
+7 -1
tools/lib/bpf/libbpf.c
··· 24 24 #include <endian.h> 25 25 #include <fcntl.h> 26 26 #include <errno.h> 27 + #include <ctype.h> 27 28 #include <asm/unistd.h> 28 29 #include <linux/err.h> 29 30 #include <linux/kernel.h> ··· 1284 1283 static char *internal_map_name(struct bpf_object *obj, 1285 1284 enum libbpf_map_type type) 1286 1285 { 1287 - char map_name[BPF_OBJ_NAME_LEN]; 1286 + char map_name[BPF_OBJ_NAME_LEN], *p; 1288 1287 const char *sfx = libbpf_type_to_btf_name[type]; 1289 1288 int sfx_len = max((size_t)7, strlen(sfx)); 1290 1289 int pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1, ··· 1292 1291 1293 1292 snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name, 1294 1293 sfx_len, libbpf_type_to_btf_name[type]); 1294 + 1295 + /* sanitise map name to characters allowed by kernel */ 1296 + for (p = map_name; *p && p < map_name + sizeof(map_name); p++) 1297 + if (!isalnum(*p) && *p != '_' && *p != '.') 1298 + *p = '_'; 1295 1299 1296 1300 return strdup(map_name); 1297 1301 }