1 // SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
4 * Common eBPF ELF object loading operations.
6 * Copyright (C) 2013-2015 Alexei Starovoitov <ast@kernel.org>
7 * Copyright (C) 2015 Wang Nan <wangnan0@huawei.com>
8 * Copyright (C) 2015 Huawei Inc.
9 * Copyright (C) 2017 Nicira, Inc.
10 * Copyright (C) 2019 Isovalent, Inc.
26 #include <asm/unistd.h>
27 #include <linux/err.h>
28 #include <linux/kernel.h>
29 #include <linux/bpf.h>
30 #include <linux/btf.h>
31 #include <linux/filter.h>
32 #include <linux/list.h>
33 #include <linux/limits.h>
34 #include <linux/perf_event.h>
35 #include <linux/ring_buffer.h>
36 #include <linux/version.h>
37 #include <sys/epoll.h>
38 #include <sys/ioctl.h>
41 #include <sys/types.h>
43 #include <sys/utsname.h>
44 #include <sys/resource.h>
45 #include <tools/libc_compat.h>
53 #include "str_error.h"
54 #include "libbpf_internal.h"
62 #define BPF_FS_MAGIC 0xcafe4a11
65 /* vsprintf() in __base_pr() uses nonliteral format string. It may break
66 * compilation if user enables corresponding warning. Disable it explicitly.
68 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
70 #define __printf(a, b) __attribute__((format(printf, a, b)))
72 static int __base_pr(enum libbpf_print_level level, const char *format,
75 if (level == LIBBPF_DEBUG)
78 return vfprintf(stderr, format, args);
81 static libbpf_print_fn_t __libbpf_pr = __base_pr;
83 libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn)
85 libbpf_print_fn_t old_print_fn = __libbpf_pr;
92 void libbpf_print(enum libbpf_print_level level, const char *format, ...)
99 va_start(args, format);
100 __libbpf_pr(level, format, args);
104 static void pr_perm_msg(int err)
109 if (err != -EPERM || geteuid() != 0)
112 err = getrlimit(RLIMIT_MEMLOCK, &limit);
116 if (limit.rlim_cur == RLIM_INFINITY)
119 if (limit.rlim_cur < 1024)
120 snprintf(buf, sizeof(buf), "%lu bytes", limit.rlim_cur);
121 else if (limit.rlim_cur < 1024*1024)
122 snprintf(buf, sizeof(buf), "%.1f KiB", (double)limit.rlim_cur / 1024);
124 snprintf(buf, sizeof(buf), "%.1f MiB", (double)limit.rlim_cur / (1024*1024));
126 pr_warn("permission error while running as root; try raising 'ulimit -l'? current value: %s\n",
130 #define STRERR_BUFSIZE 128
132 /* Copied from tools/perf/util/util.h */
134 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
138 # define zclose(fd) ({ \
141 ___err = close((fd)); \
146 #ifdef HAVE_LIBELF_MMAP_SUPPORT
147 # define LIBBPF_ELF_C_READ_MMAP ELF_C_READ_MMAP
149 # define LIBBPF_ELF_C_READ_MMAP ELF_C_READ
152 static inline __u64 ptr_to_u64(const void *ptr)
154 return (__u64) (unsigned long) ptr;
157 struct bpf_capabilities {
158 /* v4.14: kernel support for program & map names. */
160 /* v5.2: kernel support for global data sections. */
162 /* BTF_KIND_FUNC and BTF_KIND_FUNC_PROTO support */
164 /* BTF_KIND_VAR and BTF_KIND_DATASEC support */
166 /* BPF_F_MMAPABLE is supported for arrays */
178 enum reloc_type type;
185 * bpf_prog should be a better name but it has been used in
189 /* Index in elf obj file, for relocation use. */
194 /* section_name with / replaced by _; makes recursive pinning
195 * in bpf_object__pin_programs easier
198 struct bpf_insn *insns;
199 size_t insns_cnt, main_prog_cnt;
200 enum bpf_prog_type type;
202 struct reloc_desc *reloc_desc;
210 bpf_program_prep_t preprocessor;
212 struct bpf_object *obj;
214 bpf_program_clear_priv_t clear_priv;
216 enum bpf_attach_type expected_attach_type;
218 __u32 attach_prog_fd;
220 __u32 func_info_rec_size;
223 struct bpf_capabilities *caps;
226 __u32 line_info_rec_size;
231 #define DATA_SEC ".data"
232 #define BSS_SEC ".bss"
233 #define RODATA_SEC ".rodata"
234 #define KCONFIG_SEC ".kconfig"
236 enum libbpf_map_type {
244 static const char * const libbpf_type_to_btf_name[] = {
245 [LIBBPF_MAP_DATA] = DATA_SEC,
246 [LIBBPF_MAP_BSS] = BSS_SEC,
247 [LIBBPF_MAP_RODATA] = RODATA_SEC,
248 [LIBBPF_MAP_KCONFIG] = KCONFIG_SEC,
258 struct bpf_map_def def;
259 __u32 btf_key_type_id;
260 __u32 btf_value_type_id;
262 bpf_map_clear_priv_t clear_priv;
263 enum libbpf_map_type libbpf_type;
283 enum extern_type type;
292 static LIST_HEAD(bpf_objects_list);
295 char name[BPF_OBJ_NAME_LEN];
299 struct bpf_program *programs;
301 struct bpf_map *maps;
306 struct extern_desc *externs;
311 bool has_pseudo_calls;
312 bool relaxed_core_relocs;
315 * Information when doing elf related work. Only valid if fd
343 * All loaded bpf_object is linked in a list, which is
344 * hidden to caller. bpf_objects__<func> handlers deal with
347 struct list_head list;
350 struct btf_ext *btf_ext;
353 bpf_object_clear_priv_t clear_priv;
355 struct bpf_capabilities caps;
359 #define obj_elf_valid(o) ((o)->efile.elf)
361 void bpf_program__unload(struct bpf_program *prog)
369 * If the object is opened but the program was never loaded,
370 * it is possible that prog->instances.nr == -1.
372 if (prog->instances.nr > 0) {
373 for (i = 0; i < prog->instances.nr; i++)
374 zclose(prog->instances.fds[i]);
375 } else if (prog->instances.nr != -1) {
376 pr_warn("Internal error: instances.nr is %d\n",
380 prog->instances.nr = -1;
381 zfree(&prog->instances.fds);
383 zfree(&prog->func_info);
384 zfree(&prog->line_info);
387 static void bpf_program__exit(struct bpf_program *prog)
392 if (prog->clear_priv)
393 prog->clear_priv(prog, prog->priv);
396 prog->clear_priv = NULL;
398 bpf_program__unload(prog);
400 zfree(&prog->section_name);
401 zfree(&prog->pin_name);
403 zfree(&prog->reloc_desc);
410 static char *__bpf_program__pin_name(struct bpf_program *prog)
414 name = p = strdup(prog->section_name);
415 while ((p = strchr(p, '/')))
422 bpf_program__init(void *data, size_t size, char *section_name, int idx,
423 struct bpf_program *prog)
425 const size_t bpf_insn_sz = sizeof(struct bpf_insn);
427 if (size == 0 || size % bpf_insn_sz) {
428 pr_warn("corrupted section '%s', size: %zu\n",
433 memset(prog, 0, sizeof(*prog));
435 prog->section_name = strdup(section_name);
436 if (!prog->section_name) {
437 pr_warn("failed to alloc name for prog under section(%d) %s\n",
442 prog->pin_name = __bpf_program__pin_name(prog);
443 if (!prog->pin_name) {
444 pr_warn("failed to alloc pin name for prog under section(%d) %s\n",
449 prog->insns = malloc(size);
451 pr_warn("failed to alloc insns for prog under section %s\n",
455 prog->insns_cnt = size / bpf_insn_sz;
456 memcpy(prog->insns, data, size);
458 prog->instances.fds = NULL;
459 prog->instances.nr = -1;
460 prog->type = BPF_PROG_TYPE_UNSPEC;
464 bpf_program__exit(prog);
469 bpf_object__add_program(struct bpf_object *obj, void *data, size_t size,
470 char *section_name, int idx)
472 struct bpf_program prog, *progs;
475 err = bpf_program__init(data, size, section_name, idx, &prog);
479 prog.caps = &obj->caps;
480 progs = obj->programs;
481 nr_progs = obj->nr_programs;
483 progs = reallocarray(progs, nr_progs + 1, sizeof(progs[0]));
486 * In this case the original obj->programs
487 * is still valid, so don't need special treat for
488 * bpf_close_object().
490 pr_warn("failed to alloc a new program under section '%s'\n",
492 bpf_program__exit(&prog);
496 pr_debug("found program %s\n", prog.section_name);
497 obj->programs = progs;
498 obj->nr_programs = nr_progs + 1;
500 progs[nr_progs] = prog;
505 bpf_object__init_prog_names(struct bpf_object *obj)
507 Elf_Data *symbols = obj->efile.symbols;
508 struct bpf_program *prog;
511 for (pi = 0; pi < obj->nr_programs; pi++) {
512 const char *name = NULL;
514 prog = &obj->programs[pi];
516 for (si = 0; si < symbols->d_size / sizeof(GElf_Sym) && !name;
520 if (!gelf_getsym(symbols, si, &sym))
522 if (sym.st_shndx != prog->idx)
524 if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL)
527 name = elf_strptr(obj->efile.elf,
528 obj->efile.strtabidx,
531 pr_warn("failed to get sym name string for prog %s\n",
533 return -LIBBPF_ERRNO__LIBELF;
537 if (!name && prog->idx == obj->efile.text_shndx)
541 pr_warn("failed to find sym for prog %s\n",
546 prog->name = strdup(name);
548 pr_warn("failed to allocate memory for prog sym %s\n",
557 static __u32 get_kernel_version(void)
559 __u32 major, minor, patch;
563 if (sscanf(info.release, "%u.%u.%u", &major, &minor, &patch) != 3)
565 return KERNEL_VERSION(major, minor, patch);
568 static struct bpf_object *bpf_object__new(const char *path,
571 const char *obj_name)
573 struct bpf_object *obj;
576 obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
578 pr_warn("alloc memory failed for %s\n", path);
579 return ERR_PTR(-ENOMEM);
582 strcpy(obj->path, path);
584 strncpy(obj->name, obj_name, sizeof(obj->name) - 1);
585 obj->name[sizeof(obj->name) - 1] = 0;
587 /* Using basename() GNU version which doesn't modify arg. */
588 strncpy(obj->name, basename((void *)path),
589 sizeof(obj->name) - 1);
590 end = strchr(obj->name, '.');
597 * Caller of this function should also call
598 * bpf_object__elf_finish() after data collection to return
599 * obj_buf to user. If not, we should duplicate the buffer to
600 * avoid user freeing them before elf finish.
602 obj->efile.obj_buf = obj_buf;
603 obj->efile.obj_buf_sz = obj_buf_sz;
604 obj->efile.maps_shndx = -1;
605 obj->efile.btf_maps_shndx = -1;
606 obj->efile.data_shndx = -1;
607 obj->efile.rodata_shndx = -1;
608 obj->efile.bss_shndx = -1;
609 obj->kconfig_map_idx = -1;
611 obj->kern_version = get_kernel_version();
614 INIT_LIST_HEAD(&obj->list);
615 list_add(&obj->list, &bpf_objects_list);
619 static void bpf_object__elf_finish(struct bpf_object *obj)
621 if (!obj_elf_valid(obj))
624 if (obj->efile.elf) {
625 elf_end(obj->efile.elf);
626 obj->efile.elf = NULL;
628 obj->efile.symbols = NULL;
629 obj->efile.data = NULL;
630 obj->efile.rodata = NULL;
631 obj->efile.bss = NULL;
633 zfree(&obj->efile.reloc_sects);
634 obj->efile.nr_reloc_sects = 0;
635 zclose(obj->efile.fd);
636 obj->efile.obj_buf = NULL;
637 obj->efile.obj_buf_sz = 0;
640 static int bpf_object__elf_init(struct bpf_object *obj)
645 if (obj_elf_valid(obj)) {
646 pr_warn("elf init: internal error\n");
647 return -LIBBPF_ERRNO__LIBELF;
650 if (obj->efile.obj_buf_sz > 0) {
652 * obj_buf should have been validated by
653 * bpf_object__open_buffer().
655 obj->efile.elf = elf_memory((char *)obj->efile.obj_buf,
656 obj->efile.obj_buf_sz);
658 obj->efile.fd = open(obj->path, O_RDONLY);
659 if (obj->efile.fd < 0) {
660 char errmsg[STRERR_BUFSIZE], *cp;
663 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
664 pr_warn("failed to open %s: %s\n", obj->path, cp);
668 obj->efile.elf = elf_begin(obj->efile.fd,
669 LIBBPF_ELF_C_READ_MMAP, NULL);
672 if (!obj->efile.elf) {
673 pr_warn("failed to open %s as ELF file\n", obj->path);
674 err = -LIBBPF_ERRNO__LIBELF;
678 if (!gelf_getehdr(obj->efile.elf, &obj->efile.ehdr)) {
679 pr_warn("failed to get EHDR from %s\n", obj->path);
680 err = -LIBBPF_ERRNO__FORMAT;
683 ep = &obj->efile.ehdr;
685 /* Old LLVM set e_machine to EM_NONE */
686 if (ep->e_type != ET_REL ||
687 (ep->e_machine && ep->e_machine != EM_BPF)) {
688 pr_warn("%s is not an eBPF object file\n", obj->path);
689 err = -LIBBPF_ERRNO__FORMAT;
695 bpf_object__elf_finish(obj);
699 static int bpf_object__check_endianness(struct bpf_object *obj)
701 #if __BYTE_ORDER == __LITTLE_ENDIAN
702 if (obj->efile.ehdr.e_ident[EI_DATA] == ELFDATA2LSB)
704 #elif __BYTE_ORDER == __BIG_ENDIAN
705 if (obj->efile.ehdr.e_ident[EI_DATA] == ELFDATA2MSB)
708 # error "Unrecognized __BYTE_ORDER__"
710 pr_warn("endianness mismatch.\n");
711 return -LIBBPF_ERRNO__ENDIAN;
715 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
717 memcpy(obj->license, data, min(size, sizeof(obj->license) - 1));
718 pr_debug("license of %s is %s\n", obj->path, obj->license);
723 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
727 if (size != sizeof(kver)) {
728 pr_warn("invalid kver section in %s\n", obj->path);
729 return -LIBBPF_ERRNO__FORMAT;
731 memcpy(&kver, data, sizeof(kver));
732 obj->kern_version = kver;
733 pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
737 static int compare_bpf_map(const void *_a, const void *_b)
739 const struct bpf_map *a = _a;
740 const struct bpf_map *b = _b;
742 if (a->sec_idx != b->sec_idx)
743 return a->sec_idx - b->sec_idx;
744 return a->sec_offset - b->sec_offset;
747 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
749 if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
750 type == BPF_MAP_TYPE_HASH_OF_MAPS)
755 static int bpf_object_search_section_size(const struct bpf_object *obj,
756 const char *name, size_t *d_size)
758 const GElf_Ehdr *ep = &obj->efile.ehdr;
759 Elf *elf = obj->efile.elf;
763 while ((scn = elf_nextscn(elf, scn)) != NULL) {
764 const char *sec_name;
769 if (gelf_getshdr(scn, &sh) != &sh) {
770 pr_warn("failed to get section(%d) header from %s\n",
775 sec_name = elf_strptr(elf, ep->e_shstrndx, sh.sh_name);
777 pr_warn("failed to get section(%d) name from %s\n",
782 if (strcmp(name, sec_name))
785 data = elf_getdata(scn, 0);
787 pr_warn("failed to get section(%d) data from %s(%s)\n",
788 idx, name, obj->path);
792 *d_size = data->d_size;
799 int bpf_object__section_size(const struct bpf_object *obj, const char *name,
808 } else if (!strcmp(name, DATA_SEC)) {
810 *size = obj->efile.data->d_size;
811 } else if (!strcmp(name, BSS_SEC)) {
813 *size = obj->efile.bss->d_size;
814 } else if (!strcmp(name, RODATA_SEC)) {
815 if (obj->efile.rodata)
816 *size = obj->efile.rodata->d_size;
818 ret = bpf_object_search_section_size(obj, name, &d_size);
823 return *size ? 0 : ret;
826 int bpf_object__variable_offset(const struct bpf_object *obj, const char *name,
829 Elf_Data *symbols = obj->efile.symbols;
836 for (si = 0; si < symbols->d_size / sizeof(GElf_Sym); si++) {
839 if (!gelf_getsym(symbols, si, &sym))
841 if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL ||
842 GELF_ST_TYPE(sym.st_info) != STT_OBJECT)
845 sname = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
848 pr_warn("failed to get sym name string for var %s\n",
852 if (strcmp(name, sname) == 0) {
861 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
863 struct bpf_map *new_maps;
867 if (obj->nr_maps < obj->maps_cap)
868 return &obj->maps[obj->nr_maps++];
870 new_cap = max((size_t)4, obj->maps_cap * 3 / 2);
871 new_maps = realloc(obj->maps, new_cap * sizeof(*obj->maps));
873 pr_warn("alloc maps for object failed\n");
874 return ERR_PTR(-ENOMEM);
877 obj->maps_cap = new_cap;
878 obj->maps = new_maps;
880 /* zero out new maps */
881 memset(obj->maps + obj->nr_maps, 0,
882 (obj->maps_cap - obj->nr_maps) * sizeof(*obj->maps));
884 * fill all fd with -1 so won't close incorrect fd (fd=0 is stdin)
885 * when failure (zclose won't close negative fd)).
887 for (i = obj->nr_maps; i < obj->maps_cap; i++) {
888 obj->maps[i].fd = -1;
889 obj->maps[i].inner_map_fd = -1;
892 return &obj->maps[obj->nr_maps++];
895 static size_t bpf_map_mmap_sz(const struct bpf_map *map)
897 long page_sz = sysconf(_SC_PAGE_SIZE);
900 map_sz = roundup(map->def.value_size, 8) * map->def.max_entries;
901 map_sz = roundup(map_sz, page_sz);
905 static char *internal_map_name(struct bpf_object *obj,
906 enum libbpf_map_type type)
908 char map_name[BPF_OBJ_NAME_LEN];
909 const char *sfx = libbpf_type_to_btf_name[type];
910 int sfx_len = max((size_t)7, strlen(sfx));
911 int pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1,
914 snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
915 sfx_len, libbpf_type_to_btf_name[type]);
917 return strdup(map_name);
921 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
922 int sec_idx, void *data, size_t data_sz)
924 struct bpf_map_def *def;
928 map = bpf_object__add_map(obj);
932 map->libbpf_type = type;
933 map->sec_idx = sec_idx;
935 map->name = internal_map_name(obj, type);
937 pr_warn("failed to alloc map name\n");
942 def->type = BPF_MAP_TYPE_ARRAY;
943 def->key_size = sizeof(int);
944 def->value_size = data_sz;
945 def->max_entries = 1;
946 def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
947 ? BPF_F_RDONLY_PROG : 0;
948 def->map_flags |= BPF_F_MMAPABLE;
950 pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
951 map->name, map->sec_idx, map->sec_offset, def->map_flags);
953 map->mmaped = mmap(NULL, bpf_map_mmap_sz(map), PROT_READ | PROT_WRITE,
954 MAP_SHARED | MAP_ANONYMOUS, -1, 0);
955 if (map->mmaped == MAP_FAILED) {
958 pr_warn("failed to alloc map '%s' content buffer: %d\n",
965 memcpy(map->mmaped, data, data_sz);
967 pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
971 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
976 * Populate obj->maps with libbpf internal maps.
978 if (obj->efile.data_shndx >= 0) {
979 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
980 obj->efile.data_shndx,
981 obj->efile.data->d_buf,
982 obj->efile.data->d_size);
986 if (obj->efile.rodata_shndx >= 0) {
987 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
988 obj->efile.rodata_shndx,
989 obj->efile.rodata->d_buf,
990 obj->efile.rodata->d_size);
994 if (obj->efile.bss_shndx >= 0) {
995 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
996 obj->efile.bss_shndx,
998 obj->efile.bss->d_size);
1006 static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
1011 for (i = 0; i < obj->nr_extern; i++) {
1012 if (strcmp(obj->externs[i].name, name) == 0)
1013 return &obj->externs[i];
1018 static int set_ext_value_tri(struct extern_desc *ext, void *ext_val,
1021 switch (ext->type) {
1024 pr_warn("extern %s=%c should be tristate or char\n",
1028 *(bool *)ext_val = value == 'y' ? true : false;
1032 *(enum libbpf_tristate *)ext_val = TRI_YES;
1033 else if (value == 'm')
1034 *(enum libbpf_tristate *)ext_val = TRI_MODULE;
1035 else /* value == 'n' */
1036 *(enum libbpf_tristate *)ext_val = TRI_NO;
1039 *(char *)ext_val = value;
1045 pr_warn("extern %s=%c should be bool, tristate, or char\n",
1053 static int set_ext_value_str(struct extern_desc *ext, char *ext_val,
1058 if (ext->type != EXT_CHAR_ARR) {
1059 pr_warn("extern %s=%s should char array\n", ext->name, value);
1063 len = strlen(value);
1064 if (value[len - 1] != '"') {
1065 pr_warn("extern '%s': invalid string config '%s'\n",
1072 if (len >= ext->sz) {
1073 pr_warn("extern '%s': long string config %s of (%zu bytes) truncated to %d bytes\n",
1074 ext->name, value, len, ext->sz - 1);
1077 memcpy(ext_val, value + 1, len);
1078 ext_val[len] = '\0';
1083 static int parse_u64(const char *value, __u64 *res)
1089 *res = strtoull(value, &value_end, 0);
1092 pr_warn("failed to parse '%s' as integer: %d\n", value, err);
1096 pr_warn("failed to parse '%s' as integer completely\n", value);
1102 static bool is_ext_value_in_range(const struct extern_desc *ext, __u64 v)
1104 int bit_sz = ext->sz * 8;
1109 /* Validate that value stored in u64 fits in integer of `ext->sz`
1110 * bytes size without any loss of information. If the target integer
1111 * is signed, we rely on the following limits of integer type of
1112 * Y bits and subsequent transformation:
1114 * -2^(Y-1) <= X <= 2^(Y-1) - 1
1115 * 0 <= X + 2^(Y-1) <= 2^Y - 1
1116 * 0 <= X + 2^(Y-1) < 2^Y
1118 * For unsigned target integer, check that all the (64 - Y) bits are
1122 return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
1124 return (v >> bit_sz) == 0;
1127 static int set_ext_value_num(struct extern_desc *ext, void *ext_val,
1130 if (ext->type != EXT_INT && ext->type != EXT_CHAR) {
1131 pr_warn("extern %s=%llu should be integer\n",
1135 if (!is_ext_value_in_range(ext, value)) {
1136 pr_warn("extern %s=%llu value doesn't fit in %d bytes\n",
1137 ext->name, value, ext->sz);
1141 case 1: *(__u8 *)ext_val = value; break;
1142 case 2: *(__u16 *)ext_val = value; break;
1143 case 4: *(__u32 *)ext_val = value; break;
1144 case 8: *(__u64 *)ext_val = value; break;
1152 static int bpf_object__process_kconfig_line(struct bpf_object *obj,
1153 char *buf, void *data)
1155 struct extern_desc *ext;
1161 if (strncmp(buf, "CONFIG_", 7))
1164 sep = strchr(buf, '=');
1166 pr_warn("failed to parse '%s': no separator\n", buf);
1170 /* Trim ending '\n' */
1172 if (buf[len - 1] == '\n')
1173 buf[len - 1] = '\0';
1174 /* Split on '=' and ensure that a value is present. */
1178 pr_warn("failed to parse '%s': no value\n", buf);
1182 ext = find_extern_by_name(obj, buf);
1183 if (!ext || ext->is_set)
1186 ext_val = data + ext->data_off;
1190 case 'y': case 'n': case 'm':
1191 err = set_ext_value_tri(ext, ext_val, *value);
1194 err = set_ext_value_str(ext, ext_val, value);
1197 /* assume integer */
1198 err = parse_u64(value, &num);
1200 pr_warn("extern %s=%s should be integer\n",
1204 err = set_ext_value_num(ext, ext_val, num);
1209 pr_debug("extern %s=%s\n", ext->name, value);
1213 static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
1221 len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
1224 else if (len >= PATH_MAX)
1225 return -ENAMETOOLONG;
1227 /* gzopen also accepts uncompressed files. */
1228 file = gzopen(buf, "r");
1230 file = gzopen("/proc/config.gz", "r");
1233 pr_warn("failed to open system Kconfig\n");
1237 while (gzgets(file, buf, sizeof(buf))) {
1238 err = bpf_object__process_kconfig_line(obj, buf, data);
1240 pr_warn("error parsing system Kconfig line '%s': %d\n",
1251 static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
1252 const char *config, void *data)
1258 file = fmemopen((void *)config, strlen(config), "r");
1261 pr_warn("failed to open in-memory Kconfig: %d\n", err);
1265 while (fgets(buf, sizeof(buf), file)) {
1266 err = bpf_object__process_kconfig_line(obj, buf, data);
1268 pr_warn("error parsing in-memory Kconfig line '%s': %d\n",
1278 static int bpf_object__init_kconfig_map(struct bpf_object *obj)
1280 struct extern_desc *last_ext;
1284 if (obj->nr_extern == 0)
1287 last_ext = &obj->externs[obj->nr_extern - 1];
1288 map_sz = last_ext->data_off + last_ext->sz;
1290 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
1291 obj->efile.symbols_shndx,
1296 obj->kconfig_map_idx = obj->nr_maps - 1;
1301 static int bpf_object__init_user_maps(struct bpf_object *obj, bool strict)
1303 Elf_Data *symbols = obj->efile.symbols;
1304 int i, map_def_sz = 0, nr_maps = 0, nr_syms;
1305 Elf_Data *data = NULL;
1308 if (obj->efile.maps_shndx < 0)
1314 scn = elf_getscn(obj->efile.elf, obj->efile.maps_shndx);
1316 data = elf_getdata(scn, NULL);
1317 if (!scn || !data) {
1318 pr_warn("failed to get Elf_Data from map section %d\n",
1319 obj->efile.maps_shndx);
1324 * Count number of maps. Each map has a name.
1325 * Array of maps is not supported: only the first element is
1328 * TODO: Detect array of map and report error.
1330 nr_syms = symbols->d_size / sizeof(GElf_Sym);
1331 for (i = 0; i < nr_syms; i++) {
1334 if (!gelf_getsym(symbols, i, &sym))
1336 if (sym.st_shndx != obj->efile.maps_shndx)
1340 /* Assume equally sized map definitions */
1341 pr_debug("maps in %s: %d maps in %zd bytes\n",
1342 obj->path, nr_maps, data->d_size);
1344 if (!data->d_size || nr_maps == 0 || (data->d_size % nr_maps) != 0) {
1345 pr_warn("unable to determine map definition size section %s, %d maps in %zd bytes\n",
1346 obj->path, nr_maps, data->d_size);
1349 map_def_sz = data->d_size / nr_maps;
1351 /* Fill obj->maps using data in "maps" section. */
1352 for (i = 0; i < nr_syms; i++) {
1354 const char *map_name;
1355 struct bpf_map_def *def;
1356 struct bpf_map *map;
1358 if (!gelf_getsym(symbols, i, &sym))
1360 if (sym.st_shndx != obj->efile.maps_shndx)
1363 map = bpf_object__add_map(obj);
1365 return PTR_ERR(map);
1367 map_name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
1370 pr_warn("failed to get map #%d name sym string for obj %s\n",
1372 return -LIBBPF_ERRNO__FORMAT;
1375 map->libbpf_type = LIBBPF_MAP_UNSPEC;
1376 map->sec_idx = sym.st_shndx;
1377 map->sec_offset = sym.st_value;
1378 pr_debug("map '%s' (legacy): at sec_idx %d, offset %zu.\n",
1379 map_name, map->sec_idx, map->sec_offset);
1380 if (sym.st_value + map_def_sz > data->d_size) {
1381 pr_warn("corrupted maps section in %s: last map \"%s\" too small\n",
1382 obj->path, map_name);
1386 map->name = strdup(map_name);
1388 pr_warn("failed to alloc map name\n");
1391 pr_debug("map %d is \"%s\"\n", i, map->name);
1392 def = (struct bpf_map_def *)(data->d_buf + sym.st_value);
1394 * If the definition of the map in the object file fits in
1395 * bpf_map_def, copy it. Any extra fields in our version
1396 * of bpf_map_def will default to zero as a result of the
1399 if (map_def_sz <= sizeof(struct bpf_map_def)) {
1400 memcpy(&map->def, def, map_def_sz);
1403 * Here the map structure being read is bigger than what
1404 * we expect, truncate if the excess bits are all zero.
1405 * If they are not zero, reject this map as
1410 for (b = ((char *)def) + sizeof(struct bpf_map_def);
1411 b < ((char *)def) + map_def_sz; b++) {
1413 pr_warn("maps section in %s: \"%s\" has unrecognized, non-zero options\n",
1414 obj->path, map_name);
1419 memcpy(&map->def, def, sizeof(struct bpf_map_def));
1425 static const struct btf_type *
1426 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
1428 const struct btf_type *t = btf__type_by_id(btf, id);
1433 while (btf_is_mod(t) || btf_is_typedef(t)) {
1436 t = btf__type_by_id(btf, t->type);
1443 * Fetch integer attribute of BTF map definition. Such attributes are
1444 * represented using a pointer to an array, in which dimensionality of array
1445 * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
1446 * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
1447 * type definition, while using only sizeof(void *) space in ELF data section.
1449 static bool get_map_field_int(const char *map_name, const struct btf *btf,
1450 const struct btf_type *def,
1451 const struct btf_member *m, __u32 *res)
1453 const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
1454 const char *name = btf__name_by_offset(btf, m->name_off);
1455 const struct btf_array *arr_info;
1456 const struct btf_type *arr_t;
1458 if (!btf_is_ptr(t)) {
1459 pr_warn("map '%s': attr '%s': expected PTR, got %u.\n",
1460 map_name, name, btf_kind(t));
1464 arr_t = btf__type_by_id(btf, t->type);
1466 pr_warn("map '%s': attr '%s': type [%u] not found.\n",
1467 map_name, name, t->type);
1470 if (!btf_is_array(arr_t)) {
1471 pr_warn("map '%s': attr '%s': expected ARRAY, got %u.\n",
1472 map_name, name, btf_kind(arr_t));
1475 arr_info = btf_array(arr_t);
1476 *res = arr_info->nelems;
1480 static int build_map_pin_path(struct bpf_map *map, const char *path)
1486 path = "/sys/fs/bpf";
1488 len = snprintf(buf, PATH_MAX, "%s/%s", path, bpf_map__name(map));
1491 else if (len >= PATH_MAX)
1492 return -ENAMETOOLONG;
1494 err = bpf_map__set_pin_path(map, buf);
1501 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
1502 const struct btf_type *sec,
1503 int var_idx, int sec_idx,
1504 const Elf_Data *data, bool strict,
1505 const char *pin_root_path)
1507 const struct btf_type *var, *def, *t;
1508 const struct btf_var_secinfo *vi;
1509 const struct btf_var *var_extra;
1510 const struct btf_member *m;
1511 const char *map_name;
1512 struct bpf_map *map;
1515 vi = btf_var_secinfos(sec) + var_idx;
1516 var = btf__type_by_id(obj->btf, vi->type);
1517 var_extra = btf_var(var);
1518 map_name = btf__name_by_offset(obj->btf, var->name_off);
1519 vlen = btf_vlen(var);
1521 if (map_name == NULL || map_name[0] == '\0') {
1522 pr_warn("map #%d: empty name.\n", var_idx);
1525 if ((__u64)vi->offset + vi->size > data->d_size) {
1526 pr_warn("map '%s' BTF data is corrupted.\n", map_name);
1529 if (!btf_is_var(var)) {
1530 pr_warn("map '%s': unexpected var kind %u.\n",
1531 map_name, btf_kind(var));
1534 if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED &&
1535 var_extra->linkage != BTF_VAR_STATIC) {
1536 pr_warn("map '%s': unsupported var linkage %u.\n",
1537 map_name, var_extra->linkage);
1541 def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
1542 if (!btf_is_struct(def)) {
1543 pr_warn("map '%s': unexpected def kind %u.\n",
1544 map_name, btf_kind(var));
1547 if (def->size > vi->size) {
1548 pr_warn("map '%s': invalid def size.\n", map_name);
1552 map = bpf_object__add_map(obj);
1554 return PTR_ERR(map);
1555 map->name = strdup(map_name);
1557 pr_warn("map '%s': failed to alloc map name.\n", map_name);
1560 map->libbpf_type = LIBBPF_MAP_UNSPEC;
1561 map->def.type = BPF_MAP_TYPE_UNSPEC;
1562 map->sec_idx = sec_idx;
1563 map->sec_offset = vi->offset;
1564 pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
1565 map_name, map->sec_idx, map->sec_offset);
1567 vlen = btf_vlen(def);
1568 m = btf_members(def);
1569 for (i = 0; i < vlen; i++, m++) {
1570 const char *name = btf__name_by_offset(obj->btf, m->name_off);
1573 pr_warn("map '%s': invalid field #%d.\n", map_name, i);
1576 if (strcmp(name, "type") == 0) {
1577 if (!get_map_field_int(map_name, obj->btf, def, m,
1580 pr_debug("map '%s': found type = %u.\n",
1581 map_name, map->def.type);
1582 } else if (strcmp(name, "max_entries") == 0) {
1583 if (!get_map_field_int(map_name, obj->btf, def, m,
1584 &map->def.max_entries))
1586 pr_debug("map '%s': found max_entries = %u.\n",
1587 map_name, map->def.max_entries);
1588 } else if (strcmp(name, "map_flags") == 0) {
1589 if (!get_map_field_int(map_name, obj->btf, def, m,
1590 &map->def.map_flags))
1592 pr_debug("map '%s': found map_flags = %u.\n",
1593 map_name, map->def.map_flags);
1594 } else if (strcmp(name, "key_size") == 0) {
1597 if (!get_map_field_int(map_name, obj->btf, def, m,
1600 pr_debug("map '%s': found key_size = %u.\n",
1602 if (map->def.key_size && map->def.key_size != sz) {
1603 pr_warn("map '%s': conflicting key size %u != %u.\n",
1604 map_name, map->def.key_size, sz);
1607 map->def.key_size = sz;
1608 } else if (strcmp(name, "key") == 0) {
1611 t = btf__type_by_id(obj->btf, m->type);
1613 pr_warn("map '%s': key type [%d] not found.\n",
1617 if (!btf_is_ptr(t)) {
1618 pr_warn("map '%s': key spec is not PTR: %u.\n",
1619 map_name, btf_kind(t));
1622 sz = btf__resolve_size(obj->btf, t->type);
1624 pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
1625 map_name, t->type, (ssize_t)sz);
1628 pr_debug("map '%s': found key [%u], sz = %zd.\n",
1629 map_name, t->type, (ssize_t)sz);
1630 if (map->def.key_size && map->def.key_size != sz) {
1631 pr_warn("map '%s': conflicting key size %u != %zd.\n",
1632 map_name, map->def.key_size, (ssize_t)sz);
1635 map->def.key_size = sz;
1636 map->btf_key_type_id = t->type;
1637 } else if (strcmp(name, "value_size") == 0) {
1640 if (!get_map_field_int(map_name, obj->btf, def, m,
1643 pr_debug("map '%s': found value_size = %u.\n",
1645 if (map->def.value_size && map->def.value_size != sz) {
1646 pr_warn("map '%s': conflicting value size %u != %u.\n",
1647 map_name, map->def.value_size, sz);
1650 map->def.value_size = sz;
1651 } else if (strcmp(name, "value") == 0) {
1654 t = btf__type_by_id(obj->btf, m->type);
1656 pr_warn("map '%s': value type [%d] not found.\n",
1660 if (!btf_is_ptr(t)) {
1661 pr_warn("map '%s': value spec is not PTR: %u.\n",
1662 map_name, btf_kind(t));
1665 sz = btf__resolve_size(obj->btf, t->type);
1667 pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
1668 map_name, t->type, (ssize_t)sz);
1671 pr_debug("map '%s': found value [%u], sz = %zd.\n",
1672 map_name, t->type, (ssize_t)sz);
1673 if (map->def.value_size && map->def.value_size != sz) {
1674 pr_warn("map '%s': conflicting value size %u != %zd.\n",
1675 map_name, map->def.value_size, (ssize_t)sz);
1678 map->def.value_size = sz;
1679 map->btf_value_type_id = t->type;
1680 } else if (strcmp(name, "pinning") == 0) {
1684 if (!get_map_field_int(map_name, obj->btf, def, m,
1687 pr_debug("map '%s': found pinning = %u.\n",
1690 if (val != LIBBPF_PIN_NONE &&
1691 val != LIBBPF_PIN_BY_NAME) {
1692 pr_warn("map '%s': invalid pinning value %u.\n",
1696 if (val == LIBBPF_PIN_BY_NAME) {
1697 err = build_map_pin_path(map, pin_root_path);
1699 pr_warn("map '%s': couldn't build pin path.\n",
1706 pr_warn("map '%s': unknown field '%s'.\n",
1710 pr_debug("map '%s': ignoring unknown field '%s'.\n",
1715 if (map->def.type == BPF_MAP_TYPE_UNSPEC) {
1716 pr_warn("map '%s': map type isn't specified.\n", map_name);
1723 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
1724 const char *pin_root_path)
1726 const struct btf_type *sec = NULL;
1727 int nr_types, i, vlen, err;
1728 const struct btf_type *t;
1733 if (obj->efile.btf_maps_shndx < 0)
1736 scn = elf_getscn(obj->efile.elf, obj->efile.btf_maps_shndx);
1738 data = elf_getdata(scn, NULL);
1739 if (!scn || !data) {
1740 pr_warn("failed to get Elf_Data from map section %d (%s)\n",
1741 obj->efile.maps_shndx, MAPS_ELF_SEC);
1745 nr_types = btf__get_nr_types(obj->btf);
1746 for (i = 1; i <= nr_types; i++) {
1747 t = btf__type_by_id(obj->btf, i);
1748 if (!btf_is_datasec(t))
1750 name = btf__name_by_offset(obj->btf, t->name_off);
1751 if (strcmp(name, MAPS_ELF_SEC) == 0) {
1758 pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
1762 vlen = btf_vlen(sec);
1763 for (i = 0; i < vlen; i++) {
1764 err = bpf_object__init_user_btf_map(obj, sec, i,
1765 obj->efile.btf_maps_shndx,
1775 static int bpf_object__init_maps(struct bpf_object *obj,
1776 const struct bpf_object_open_opts *opts)
1778 const char *pin_root_path;
1782 strict = !OPTS_GET(opts, relaxed_maps, false);
1783 pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
1785 err = bpf_object__init_user_maps(obj, strict);
1786 err = err ?: bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
1787 err = err ?: bpf_object__init_global_data_maps(obj);
1788 err = err ?: bpf_object__init_kconfig_map(obj);
1793 qsort(obj->maps, obj->nr_maps, sizeof(obj->maps[0]),
1799 static bool section_have_execinstr(struct bpf_object *obj, int idx)
1804 scn = elf_getscn(obj->efile.elf, idx);
1808 if (gelf_getshdr(scn, &sh) != &sh)
1811 if (sh.sh_flags & SHF_EXECINSTR)
1817 static void bpf_object__sanitize_btf(struct bpf_object *obj)
1819 bool has_datasec = obj->caps.btf_datasec;
1820 bool has_func = obj->caps.btf_func;
1821 struct btf *btf = obj->btf;
1825 if (!obj->btf || (has_func && has_datasec))
1828 for (i = 1; i <= btf__get_nr_types(btf); i++) {
1829 t = (struct btf_type *)btf__type_by_id(btf, i);
1831 if (!has_datasec && btf_is_var(t)) {
1832 /* replace VAR with INT */
1833 t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
1835 * using size = 1 is the safest choice, 4 will be too
1836 * big and cause kernel BTF validation failure if
1837 * original variable took less than 4 bytes
1840 *(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
1841 } else if (!has_datasec && btf_is_datasec(t)) {
1842 /* replace DATASEC with STRUCT */
1843 const struct btf_var_secinfo *v = btf_var_secinfos(t);
1844 struct btf_member *m = btf_members(t);
1845 struct btf_type *vt;
1848 name = (char *)btf__name_by_offset(btf, t->name_off);
1856 t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
1857 for (j = 0; j < vlen; j++, v++, m++) {
1858 /* order of field assignments is important */
1859 m->offset = v->offset * 8;
1861 /* preserve variable name as member name */
1862 vt = (void *)btf__type_by_id(btf, v->type);
1863 m->name_off = vt->name_off;
1865 } else if (!has_func && btf_is_func_proto(t)) {
1866 /* replace FUNC_PROTO with ENUM */
1868 t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
1869 t->size = sizeof(__u32); /* kernel enforced */
1870 } else if (!has_func && btf_is_func(t)) {
1871 /* replace FUNC with TYPEDEF */
1872 t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
1877 static void bpf_object__sanitize_btf_ext(struct bpf_object *obj)
1882 if (!obj->caps.btf_func) {
1883 btf_ext__free(obj->btf_ext);
1884 obj->btf_ext = NULL;
1888 static bool bpf_object__is_btf_mandatory(const struct bpf_object *obj)
1890 return obj->efile.btf_maps_shndx >= 0;
1893 static int bpf_object__init_btf(struct bpf_object *obj,
1895 Elf_Data *btf_ext_data)
1897 bool btf_required = bpf_object__is_btf_mandatory(obj);
1901 obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
1902 if (IS_ERR(obj->btf)) {
1903 pr_warn("Error loading ELF section %s: %d.\n",
1910 pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
1911 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
1914 obj->btf_ext = btf_ext__new(btf_ext_data->d_buf,
1915 btf_ext_data->d_size);
1916 if (IS_ERR(obj->btf_ext)) {
1917 pr_warn("Error loading ELF section %s: %ld. Ignored and continue.\n",
1918 BTF_EXT_ELF_SEC, PTR_ERR(obj->btf_ext));
1919 obj->btf_ext = NULL;
1924 if (err || IS_ERR(obj->btf)) {
1926 err = err ? : PTR_ERR(obj->btf);
1929 if (!IS_ERR_OR_NULL(obj->btf))
1930 btf__free(obj->btf);
1933 if (btf_required && !obj->btf) {
1934 pr_warn("BTF is required, but is missing or corrupted.\n");
1935 return err == 0 ? -ENOENT : err;
1940 static int bpf_object__finalize_btf(struct bpf_object *obj)
1947 err = btf__finalize_data(obj, obj->btf);
1951 pr_warn("Error finalizing %s: %d.\n", BTF_ELF_SEC, err);
1952 btf__free(obj->btf);
1954 btf_ext__free(obj->btf_ext);
1955 obj->btf_ext = NULL;
1957 if (bpf_object__is_btf_mandatory(obj)) {
1958 pr_warn("BTF is required, but is missing or corrupted.\n");
1964 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
1971 bpf_object__sanitize_btf(obj);
1972 bpf_object__sanitize_btf_ext(obj);
1974 err = btf__load(obj->btf);
1976 pr_warn("Error loading %s into kernel: %d.\n",
1978 btf__free(obj->btf);
1980 /* btf_ext can't exist without btf, so free it as well */
1982 btf_ext__free(obj->btf_ext);
1983 obj->btf_ext = NULL;
1986 if (bpf_object__is_btf_mandatory(obj))
1992 static int bpf_object__elf_collect(struct bpf_object *obj)
1994 Elf *elf = obj->efile.elf;
1995 GElf_Ehdr *ep = &obj->efile.ehdr;
1996 Elf_Data *btf_ext_data = NULL;
1997 Elf_Data *btf_data = NULL;
1998 Elf_Scn *scn = NULL;
1999 int idx = 0, err = 0;
2001 /* Elf is corrupted/truncated, avoid calling elf_strptr. */
2002 if (!elf_rawdata(elf_getscn(elf, ep->e_shstrndx), NULL)) {
2003 pr_warn("failed to get e_shstrndx from %s\n", obj->path);
2004 return -LIBBPF_ERRNO__FORMAT;
2007 while ((scn = elf_nextscn(elf, scn)) != NULL) {
2013 if (gelf_getshdr(scn, &sh) != &sh) {
2014 pr_warn("failed to get section(%d) header from %s\n",
2016 return -LIBBPF_ERRNO__FORMAT;
2019 name = elf_strptr(elf, ep->e_shstrndx, sh.sh_name);
2021 pr_warn("failed to get section(%d) name from %s\n",
2023 return -LIBBPF_ERRNO__FORMAT;
2026 data = elf_getdata(scn, 0);
2028 pr_warn("failed to get section(%d) data from %s(%s)\n",
2029 idx, name, obj->path);
2030 return -LIBBPF_ERRNO__FORMAT;
2032 pr_debug("section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
2033 idx, name, (unsigned long)data->d_size,
2034 (int)sh.sh_link, (unsigned long)sh.sh_flags,
2037 if (strcmp(name, "license") == 0) {
2038 err = bpf_object__init_license(obj,
2043 } else if (strcmp(name, "version") == 0) {
2044 err = bpf_object__init_kversion(obj,
2049 } else if (strcmp(name, "maps") == 0) {
2050 obj->efile.maps_shndx = idx;
2051 } else if (strcmp(name, MAPS_ELF_SEC) == 0) {
2052 obj->efile.btf_maps_shndx = idx;
2053 } else if (strcmp(name, BTF_ELF_SEC) == 0) {
2055 } else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
2056 btf_ext_data = data;
2057 } else if (sh.sh_type == SHT_SYMTAB) {
2058 if (obj->efile.symbols) {
2059 pr_warn("bpf: multiple SYMTAB in %s\n",
2061 return -LIBBPF_ERRNO__FORMAT;
2063 obj->efile.symbols = data;
2064 obj->efile.symbols_shndx = idx;
2065 obj->efile.strtabidx = sh.sh_link;
2066 } else if (sh.sh_type == SHT_PROGBITS && data->d_size > 0) {
2067 if (sh.sh_flags & SHF_EXECINSTR) {
2068 if (strcmp(name, ".text") == 0)
2069 obj->efile.text_shndx = idx;
2070 err = bpf_object__add_program(obj, data->d_buf,
2074 char errmsg[STRERR_BUFSIZE];
2077 cp = libbpf_strerror_r(-err, errmsg,
2079 pr_warn("failed to alloc program %s (%s): %s",
2080 name, obj->path, cp);
2083 } else if (strcmp(name, DATA_SEC) == 0) {
2084 obj->efile.data = data;
2085 obj->efile.data_shndx = idx;
2086 } else if (strcmp(name, RODATA_SEC) == 0) {
2087 obj->efile.rodata = data;
2088 obj->efile.rodata_shndx = idx;
2090 pr_debug("skip section(%d) %s\n", idx, name);
2092 } else if (sh.sh_type == SHT_REL) {
2093 int nr_sects = obj->efile.nr_reloc_sects;
2094 void *sects = obj->efile.reloc_sects;
2095 int sec = sh.sh_info; /* points to other section */
2097 /* Only do relo for section with exec instructions */
2098 if (!section_have_execinstr(obj, sec)) {
2099 pr_debug("skip relo %s(%d) for section(%d)\n",
2104 sects = reallocarray(sects, nr_sects + 1,
2105 sizeof(*obj->efile.reloc_sects));
2107 pr_warn("reloc_sects realloc failed\n");
2111 obj->efile.reloc_sects = sects;
2112 obj->efile.nr_reloc_sects++;
2114 obj->efile.reloc_sects[nr_sects].shdr = sh;
2115 obj->efile.reloc_sects[nr_sects].data = data;
2116 } else if (sh.sh_type == SHT_NOBITS &&
2117 strcmp(name, BSS_SEC) == 0) {
2118 obj->efile.bss = data;
2119 obj->efile.bss_shndx = idx;
2121 pr_debug("skip section(%d) %s\n", idx, name);
2125 if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
2126 pr_warn("Corrupted ELF file: index of strtab invalid\n");
2127 return -LIBBPF_ERRNO__FORMAT;
2129 return bpf_object__init_btf(obj, btf_data, btf_ext_data);
2132 static bool sym_is_extern(const GElf_Sym *sym)
2134 int bind = GELF_ST_BIND(sym->st_info);
2135 /* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
2136 return sym->st_shndx == SHN_UNDEF &&
2137 (bind == STB_GLOBAL || bind == STB_WEAK) &&
2138 GELF_ST_TYPE(sym->st_info) == STT_NOTYPE;
2141 static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
2143 const struct btf_type *t;
2144 const char *var_name;
2150 n = btf__get_nr_types(btf);
2151 for (i = 1; i <= n; i++) {
2152 t = btf__type_by_id(btf, i);
2157 var_name = btf__name_by_offset(btf, t->name_off);
2158 if (strcmp(var_name, ext_name))
2161 if (btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
2170 static enum extern_type find_extern_type(const struct btf *btf, int id,
2173 const struct btf_type *t;
2176 t = skip_mods_and_typedefs(btf, id, NULL);
2177 name = btf__name_by_offset(btf, t->name_off);
2181 switch (btf_kind(t)) {
2182 case BTF_KIND_INT: {
2183 int enc = btf_int_encoding(t);
2185 if (enc & BTF_INT_BOOL)
2186 return t->size == 1 ? EXT_BOOL : EXT_UNKNOWN;
2188 *is_signed = enc & BTF_INT_SIGNED;
2191 if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
2198 if (strcmp(name, "libbpf_tristate"))
2200 return EXT_TRISTATE;
2201 case BTF_KIND_ARRAY:
2202 if (btf_array(t)->nelems == 0)
2204 if (find_extern_type(btf, btf_array(t)->type, NULL) != EXT_CHAR)
2206 return EXT_CHAR_ARR;
2212 static int cmp_externs(const void *_a, const void *_b)
2214 const struct extern_desc *a = _a;
2215 const struct extern_desc *b = _b;
2217 /* descending order by alignment requirements */
2218 if (a->align != b->align)
2219 return a->align > b->align ? -1 : 1;
2220 /* ascending order by size, within same alignment class */
2222 return a->sz < b->sz ? -1 : 1;
2223 /* resolve ties by name */
2224 return strcmp(a->name, b->name);
2227 static int bpf_object__collect_externs(struct bpf_object *obj)
2229 const struct btf_type *t;
2230 struct extern_desc *ext;
2231 int i, n, off, btf_id;
2232 struct btf_type *sec;
2233 const char *ext_name;
2237 if (!obj->efile.symbols)
2240 scn = elf_getscn(obj->efile.elf, obj->efile.symbols_shndx);
2242 return -LIBBPF_ERRNO__FORMAT;
2243 if (gelf_getshdr(scn, &sh) != &sh)
2244 return -LIBBPF_ERRNO__FORMAT;
2245 n = sh.sh_size / sh.sh_entsize;
2247 pr_debug("looking for externs among %d symbols...\n", n);
2248 for (i = 0; i < n; i++) {
2251 if (!gelf_getsym(obj->efile.symbols, i, &sym))
2252 return -LIBBPF_ERRNO__FORMAT;
2253 if (!sym_is_extern(&sym))
2255 ext_name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
2257 if (!ext_name || !ext_name[0])
2261 ext = reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
2265 ext = &ext[obj->nr_extern];
2266 memset(ext, 0, sizeof(*ext));
2269 ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
2270 if (ext->btf_id <= 0) {
2271 pr_warn("failed to find BTF for extern '%s': %d\n",
2272 ext_name, ext->btf_id);
2275 t = btf__type_by_id(obj->btf, ext->btf_id);
2276 ext->name = btf__name_by_offset(obj->btf, t->name_off);
2278 ext->is_weak = GELF_ST_BIND(sym.st_info) == STB_WEAK;
2279 ext->sz = btf__resolve_size(obj->btf, t->type);
2281 pr_warn("failed to resolve size of extern '%s': %d\n",
2285 ext->align = btf__align_of(obj->btf, t->type);
2286 if (ext->align <= 0) {
2287 pr_warn("failed to determine alignment of extern '%s': %d\n",
2288 ext_name, ext->align);
2291 ext->type = find_extern_type(obj->btf, t->type,
2293 if (ext->type == EXT_UNKNOWN) {
2294 pr_warn("extern '%s' type is unsupported\n", ext_name);
2298 pr_debug("collected %d externs total\n", obj->nr_extern);
2300 if (!obj->nr_extern)
2303 /* sort externs by (alignment, size, name) and calculate their offsets
2305 qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
2307 for (i = 0; i < obj->nr_extern; i++) {
2308 ext = &obj->externs[i];
2309 ext->data_off = roundup(off, ext->align);
2310 off = ext->data_off + ext->sz;
2311 pr_debug("extern #%d: symbol %d, off %u, name %s\n",
2312 i, ext->sym_idx, ext->data_off, ext->name);
2315 btf_id = btf__find_by_name(obj->btf, KCONFIG_SEC);
2317 pr_warn("no BTF info found for '%s' datasec\n", KCONFIG_SEC);
2321 sec = (struct btf_type *)btf__type_by_id(obj->btf, btf_id);
2324 for (i = 0; i < n; i++) {
2325 struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
2327 t = btf__type_by_id(obj->btf, vs->type);
2328 ext_name = btf__name_by_offset(obj->btf, t->name_off);
2329 ext = find_extern_by_name(obj, ext_name);
2331 pr_warn("failed to find extern definition for BTF var '%s'\n",
2335 vs->offset = ext->data_off;
2336 btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
2342 static struct bpf_program *
2343 bpf_object__find_prog_by_idx(struct bpf_object *obj, int idx)
2345 struct bpf_program *prog;
2348 for (i = 0; i < obj->nr_programs; i++) {
2349 prog = &obj->programs[i];
2350 if (prog->idx == idx)
2356 struct bpf_program *
2357 bpf_object__find_program_by_title(const struct bpf_object *obj,
2360 struct bpf_program *pos;
2362 bpf_object__for_each_program(pos, obj) {
2363 if (pos->section_name && !strcmp(pos->section_name, title))
2369 struct bpf_program *
2370 bpf_object__find_program_by_name(const struct bpf_object *obj,
2373 struct bpf_program *prog;
2375 bpf_object__for_each_program(prog, obj) {
2376 if (!strcmp(prog->name, name))
2382 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
2385 return shndx == obj->efile.data_shndx ||
2386 shndx == obj->efile.bss_shndx ||
2387 shndx == obj->efile.rodata_shndx;
2390 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
2393 return shndx == obj->efile.maps_shndx ||
2394 shndx == obj->efile.btf_maps_shndx;
2397 static enum libbpf_map_type
2398 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
2400 if (shndx == obj->efile.data_shndx)
2401 return LIBBPF_MAP_DATA;
2402 else if (shndx == obj->efile.bss_shndx)
2403 return LIBBPF_MAP_BSS;
2404 else if (shndx == obj->efile.rodata_shndx)
2405 return LIBBPF_MAP_RODATA;
2406 else if (shndx == obj->efile.symbols_shndx)
2407 return LIBBPF_MAP_KCONFIG;
2409 return LIBBPF_MAP_UNSPEC;
2412 static int bpf_program__record_reloc(struct bpf_program *prog,
2413 struct reloc_desc *reloc_desc,
2414 __u32 insn_idx, const char *name,
2415 const GElf_Sym *sym, const GElf_Rel *rel)
2417 struct bpf_insn *insn = &prog->insns[insn_idx];
2418 size_t map_idx, nr_maps = prog->obj->nr_maps;
2419 struct bpf_object *obj = prog->obj;
2420 __u32 shdr_idx = sym->st_shndx;
2421 enum libbpf_map_type type;
2422 struct bpf_map *map;
2424 /* sub-program call relocation */
2425 if (insn->code == (BPF_JMP | BPF_CALL)) {
2426 if (insn->src_reg != BPF_PSEUDO_CALL) {
2427 pr_warn("incorrect bpf_call opcode\n");
2428 return -LIBBPF_ERRNO__RELOC;
2430 /* text_shndx can be 0, if no default "main" program exists */
2431 if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
2432 pr_warn("bad call relo against section %u\n", shdr_idx);
2433 return -LIBBPF_ERRNO__RELOC;
2435 if (sym->st_value % 8) {
2436 pr_warn("bad call relo offset: %zu\n",
2437 (size_t)sym->st_value);
2438 return -LIBBPF_ERRNO__RELOC;
2440 reloc_desc->type = RELO_CALL;
2441 reloc_desc->insn_idx = insn_idx;
2442 reloc_desc->sym_off = sym->st_value;
2443 obj->has_pseudo_calls = true;
2447 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) {
2448 pr_warn("invalid relo for insns[%d].code 0x%x\n",
2449 insn_idx, insn->code);
2450 return -LIBBPF_ERRNO__RELOC;
2453 if (sym_is_extern(sym)) {
2454 int sym_idx = GELF_R_SYM(rel->r_info);
2455 int i, n = obj->nr_extern;
2456 struct extern_desc *ext;
2458 for (i = 0; i < n; i++) {
2459 ext = &obj->externs[i];
2460 if (ext->sym_idx == sym_idx)
2464 pr_warn("extern relo failed to find extern for sym %d\n",
2466 return -LIBBPF_ERRNO__RELOC;
2468 pr_debug("found extern #%d '%s' (sym %d, off %u) for insn %u\n",
2469 i, ext->name, ext->sym_idx, ext->data_off, insn_idx);
2470 reloc_desc->type = RELO_EXTERN;
2471 reloc_desc->insn_idx = insn_idx;
2472 reloc_desc->sym_off = ext->data_off;
2476 if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
2477 pr_warn("invalid relo for \'%s\' in special section 0x%x; forgot to initialize global var?..\n",
2479 return -LIBBPF_ERRNO__RELOC;
2482 type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
2484 /* generic map reference relocation */
2485 if (type == LIBBPF_MAP_UNSPEC) {
2486 if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
2487 pr_warn("bad map relo against section %u\n",
2489 return -LIBBPF_ERRNO__RELOC;
2491 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
2492 map = &obj->maps[map_idx];
2493 if (map->libbpf_type != type ||
2494 map->sec_idx != sym->st_shndx ||
2495 map->sec_offset != sym->st_value)
2497 pr_debug("found map %zd (%s, sec %d, off %zu) for insn %u\n",
2498 map_idx, map->name, map->sec_idx,
2499 map->sec_offset, insn_idx);
2502 if (map_idx >= nr_maps) {
2503 pr_warn("map relo failed to find map for sec %u, off %zu\n",
2504 shdr_idx, (size_t)sym->st_value);
2505 return -LIBBPF_ERRNO__RELOC;
2507 reloc_desc->type = RELO_LD64;
2508 reloc_desc->insn_idx = insn_idx;
2509 reloc_desc->map_idx = map_idx;
2510 reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
2514 /* global data map relocation */
2515 if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
2516 pr_warn("bad data relo against section %u\n", shdr_idx);
2517 return -LIBBPF_ERRNO__RELOC;
2519 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
2520 map = &obj->maps[map_idx];
2521 if (map->libbpf_type != type)
2523 pr_debug("found data map %zd (%s, sec %d, off %zu) for insn %u\n",
2524 map_idx, map->name, map->sec_idx, map->sec_offset,
2528 if (map_idx >= nr_maps) {
2529 pr_warn("data relo failed to find map for sec %u\n",
2531 return -LIBBPF_ERRNO__RELOC;
2534 reloc_desc->type = RELO_DATA;
2535 reloc_desc->insn_idx = insn_idx;
2536 reloc_desc->map_idx = map_idx;
2537 reloc_desc->sym_off = sym->st_value;
2542 bpf_program__collect_reloc(struct bpf_program *prog, GElf_Shdr *shdr,
2543 Elf_Data *data, struct bpf_object *obj)
2545 Elf_Data *symbols = obj->efile.symbols;
2548 pr_debug("collecting relocating info for: '%s'\n", prog->section_name);
2549 nrels = shdr->sh_size / shdr->sh_entsize;
2551 prog->reloc_desc = malloc(sizeof(*prog->reloc_desc) * nrels);
2552 if (!prog->reloc_desc) {
2553 pr_warn("failed to alloc memory in relocation\n");
2556 prog->nr_reloc = nrels;
2558 for (i = 0; i < nrels; i++) {
2564 if (!gelf_getrel(data, i, &rel)) {
2565 pr_warn("relocation: failed to get %d reloc\n", i);
2566 return -LIBBPF_ERRNO__FORMAT;
2568 if (!gelf_getsym(symbols, GELF_R_SYM(rel.r_info), &sym)) {
2569 pr_warn("relocation: symbol %"PRIx64" not found\n",
2570 GELF_R_SYM(rel.r_info));
2571 return -LIBBPF_ERRNO__FORMAT;
2573 if (rel.r_offset % sizeof(struct bpf_insn))
2574 return -LIBBPF_ERRNO__FORMAT;
2576 insn_idx = rel.r_offset / sizeof(struct bpf_insn);
2577 name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
2578 sym.st_name) ? : "<?>";
2580 pr_debug("relo for shdr %u, symb %zu, value %zu, type %d, bind %d, name %d (\'%s\'), insn %u\n",
2581 (__u32)sym.st_shndx, (size_t)GELF_R_SYM(rel.r_info),
2582 (size_t)sym.st_value, GELF_ST_TYPE(sym.st_info),
2583 GELF_ST_BIND(sym.st_info), sym.st_name, name,
2586 err = bpf_program__record_reloc(prog, &prog->reloc_desc[i],
2587 insn_idx, name, &sym, &rel);
2594 static int bpf_map_find_btf_info(struct bpf_object *obj, struct bpf_map *map)
2596 struct bpf_map_def *def = &map->def;
2597 __u32 key_type_id = 0, value_type_id = 0;
2600 /* if it's BTF-defined map, we don't need to search for type IDs */
2601 if (map->sec_idx == obj->efile.btf_maps_shndx)
2604 if (!bpf_map__is_internal(map)) {
2605 ret = btf__get_map_kv_tids(obj->btf, map->name, def->key_size,
2606 def->value_size, &key_type_id,
2610 * LLVM annotates global data differently in BTF, that is,
2611 * only as '.data', '.bss' or '.rodata'.
2613 ret = btf__find_by_name(obj->btf,
2614 libbpf_type_to_btf_name[map->libbpf_type]);
2619 map->btf_key_type_id = key_type_id;
2620 map->btf_value_type_id = bpf_map__is_internal(map) ?
2621 ret : value_type_id;
2625 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
2627 struct bpf_map_info info = {};
2628 __u32 len = sizeof(info);
2632 err = bpf_obj_get_info_by_fd(fd, &info, &len);
2636 new_name = strdup(info.name);
2640 new_fd = open("/", O_RDONLY | O_CLOEXEC);
2643 goto err_free_new_name;
2646 new_fd = dup3(fd, new_fd, O_CLOEXEC);
2649 goto err_close_new_fd;
2652 err = zclose(map->fd);
2655 goto err_close_new_fd;
2660 map->name = new_name;
2661 map->def.type = info.type;
2662 map->def.key_size = info.key_size;
2663 map->def.value_size = info.value_size;
2664 map->def.max_entries = info.max_entries;
2665 map->def.map_flags = info.map_flags;
2666 map->btf_key_type_id = info.btf_key_type_id;
2667 map->btf_value_type_id = info.btf_value_type_id;
2679 int bpf_map__resize(struct bpf_map *map, __u32 max_entries)
2681 if (!map || !max_entries)
2684 /* If map already created, its attributes can't be changed. */
2688 map->def.max_entries = max_entries;
2694 bpf_object__probe_name(struct bpf_object *obj)
2696 struct bpf_load_program_attr attr;
2697 char *cp, errmsg[STRERR_BUFSIZE];
2698 struct bpf_insn insns[] = {
2699 BPF_MOV64_IMM(BPF_REG_0, 0),
2704 /* make sure basic loading works */
2706 memset(&attr, 0, sizeof(attr));
2707 attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
2709 attr.insns_cnt = ARRAY_SIZE(insns);
2710 attr.license = "GPL";
2712 ret = bpf_load_program_xattr(&attr, NULL, 0);
2714 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
2715 pr_warn("Error in %s():%s(%d). Couldn't load basic 'r0 = 0' BPF program.\n",
2716 __func__, cp, errno);
2721 /* now try the same program, but with the name */
2724 ret = bpf_load_program_xattr(&attr, NULL, 0);
2734 bpf_object__probe_global_data(struct bpf_object *obj)
2736 struct bpf_load_program_attr prg_attr;
2737 struct bpf_create_map_attr map_attr;
2738 char *cp, errmsg[STRERR_BUFSIZE];
2739 struct bpf_insn insns[] = {
2740 BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16),
2741 BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42),
2742 BPF_MOV64_IMM(BPF_REG_0, 0),
2747 memset(&map_attr, 0, sizeof(map_attr));
2748 map_attr.map_type = BPF_MAP_TYPE_ARRAY;
2749 map_attr.key_size = sizeof(int);
2750 map_attr.value_size = 32;
2751 map_attr.max_entries = 1;
2753 map = bpf_create_map_xattr(&map_attr);
2755 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
2756 pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
2757 __func__, cp, errno);
2763 memset(&prg_attr, 0, sizeof(prg_attr));
2764 prg_attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
2765 prg_attr.insns = insns;
2766 prg_attr.insns_cnt = ARRAY_SIZE(insns);
2767 prg_attr.license = "GPL";
2769 ret = bpf_load_program_xattr(&prg_attr, NULL, 0);
2771 obj->caps.global_data = 1;
2779 static int bpf_object__probe_btf_func(struct bpf_object *obj)
2781 static const char strs[] = "\0int\0x\0a";
2782 /* void x(int a) {} */
2785 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
2786 /* FUNC_PROTO */ /* [2] */
2787 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
2788 BTF_PARAM_ENC(7, 1),
2789 /* FUNC x */ /* [3] */
2790 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0), 2),
2794 btf_fd = libbpf__load_raw_btf((char *)types, sizeof(types),
2795 strs, sizeof(strs));
2797 obj->caps.btf_func = 1;
2805 static int bpf_object__probe_btf_datasec(struct bpf_object *obj)
2807 static const char strs[] = "\0x\0.data";
2811 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
2812 /* VAR x */ /* [2] */
2813 BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
2815 /* DATASEC val */ /* [3] */
2816 BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC, 0, 1), 4),
2817 BTF_VAR_SECINFO_ENC(2, 0, 4),
2821 btf_fd = libbpf__load_raw_btf((char *)types, sizeof(types),
2822 strs, sizeof(strs));
2824 obj->caps.btf_datasec = 1;
2832 static int bpf_object__probe_array_mmap(struct bpf_object *obj)
2834 struct bpf_create_map_attr attr = {
2835 .map_type = BPF_MAP_TYPE_ARRAY,
2836 .map_flags = BPF_F_MMAPABLE,
2837 .key_size = sizeof(int),
2838 .value_size = sizeof(int),
2843 fd = bpf_create_map_xattr(&attr);
2845 obj->caps.array_mmap = 1;
2854 bpf_object__probe_caps(struct bpf_object *obj)
2856 int (*probe_fn[])(struct bpf_object *obj) = {
2857 bpf_object__probe_name,
2858 bpf_object__probe_global_data,
2859 bpf_object__probe_btf_func,
2860 bpf_object__probe_btf_datasec,
2861 bpf_object__probe_array_mmap,
2865 for (i = 0; i < ARRAY_SIZE(probe_fn); i++) {
2866 ret = probe_fn[i](obj);
2868 pr_debug("Probe #%d failed with %d.\n", i, ret);
2874 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
2876 struct bpf_map_info map_info = {};
2877 char msg[STRERR_BUFSIZE];
2880 map_info_len = sizeof(map_info);
2882 if (bpf_obj_get_info_by_fd(map_fd, &map_info, &map_info_len)) {
2883 pr_warn("failed to get map info for map FD %d: %s\n",
2884 map_fd, libbpf_strerror_r(errno, msg, sizeof(msg)));
2888 return (map_info.type == map->def.type &&
2889 map_info.key_size == map->def.key_size &&
2890 map_info.value_size == map->def.value_size &&
2891 map_info.max_entries == map->def.max_entries &&
2892 map_info.map_flags == map->def.map_flags);
2896 bpf_object__reuse_map(struct bpf_map *map)
2898 char *cp, errmsg[STRERR_BUFSIZE];
2901 pin_fd = bpf_obj_get(map->pin_path);
2904 if (err == -ENOENT) {
2905 pr_debug("found no pinned map to reuse at '%s'\n",
2910 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
2911 pr_warn("couldn't retrieve pinned map '%s': %s\n",
2916 if (!map_is_reuse_compat(map, pin_fd)) {
2917 pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
2923 err = bpf_map__reuse_fd(map, pin_fd);
2929 pr_debug("reused pinned map at '%s'\n", map->pin_path);
2935 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
2937 enum libbpf_map_type map_type = map->libbpf_type;
2938 char *cp, errmsg[STRERR_BUFSIZE];
2941 /* kernel already zero-initializes .bss map. */
2942 if (map_type == LIBBPF_MAP_BSS)
2945 err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
2948 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
2949 pr_warn("Error setting initial map(%s) contents: %s\n",
2954 /* Freeze .rodata and .kconfig map as read-only from syscall side. */
2955 if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
2956 err = bpf_map_freeze(map->fd);
2959 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
2960 pr_warn("Error freezing map(%s) as read-only: %s\n",
2969 bpf_object__create_maps(struct bpf_object *obj)
2971 struct bpf_create_map_attr create_attr = {};
2976 for (i = 0; i < obj->nr_maps; i++) {
2977 struct bpf_map *map = &obj->maps[i];
2978 struct bpf_map_def *def = &map->def;
2979 char *cp, errmsg[STRERR_BUFSIZE];
2980 int *pfd = &map->fd;
2982 if (map->pin_path) {
2983 err = bpf_object__reuse_map(map);
2985 pr_warn("error reusing pinned map %s\n",
2992 pr_debug("skip map create (preset) %s: fd=%d\n",
2993 map->name, map->fd);
2998 create_attr.name = map->name;
2999 create_attr.map_ifindex = map->map_ifindex;
3000 create_attr.map_type = def->type;
3001 create_attr.map_flags = def->map_flags;
3002 create_attr.key_size = def->key_size;
3003 create_attr.value_size = def->value_size;
3004 if (def->type == BPF_MAP_TYPE_PERF_EVENT_ARRAY &&
3005 !def->max_entries) {
3007 nr_cpus = libbpf_num_possible_cpus();
3009 pr_warn("failed to determine number of system CPUs: %d\n",
3014 pr_debug("map '%s': setting size to %d\n",
3015 map->name, nr_cpus);
3016 create_attr.max_entries = nr_cpus;
3018 create_attr.max_entries = def->max_entries;
3020 create_attr.btf_fd = 0;
3021 create_attr.btf_key_type_id = 0;
3022 create_attr.btf_value_type_id = 0;
3023 if (bpf_map_type__is_map_in_map(def->type) &&
3024 map->inner_map_fd >= 0)
3025 create_attr.inner_map_fd = map->inner_map_fd;
3027 if (obj->btf && !bpf_map_find_btf_info(obj, map)) {
3028 create_attr.btf_fd = btf__fd(obj->btf);
3029 create_attr.btf_key_type_id = map->btf_key_type_id;
3030 create_attr.btf_value_type_id = map->btf_value_type_id;
3033 *pfd = bpf_create_map_xattr(&create_attr);
3034 if (*pfd < 0 && (create_attr.btf_key_type_id ||
3035 create_attr.btf_value_type_id)) {
3037 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
3038 pr_warn("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
3039 map->name, cp, err);
3040 create_attr.btf_fd = 0;
3041 create_attr.btf_key_type_id = 0;
3042 create_attr.btf_value_type_id = 0;
3043 map->btf_key_type_id = 0;
3044 map->btf_value_type_id = 0;
3045 *pfd = bpf_create_map_xattr(&create_attr);
3053 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
3054 pr_warn("failed to create map (name: '%s'): %s(%d)\n",
3055 map->name, cp, err);
3057 for (j = 0; j < i; j++)
3058 zclose(obj->maps[j].fd);
3062 if (bpf_map__is_internal(map)) {
3063 err = bpf_object__populate_internal_map(obj, map);
3070 if (map->pin_path && !map->pinned) {
3071 err = bpf_map__pin(map, NULL);
3073 pr_warn("failed to auto-pin map name '%s' at '%s'\n",
3074 map->name, map->pin_path);
3079 pr_debug("created map %s: fd=%d\n", map->name, *pfd);
3086 check_btf_ext_reloc_err(struct bpf_program *prog, int err,
3087 void *btf_prog_info, const char *info_name)
3089 if (err != -ENOENT) {
3090 pr_warn("Error in loading %s for sec %s.\n",
3091 info_name, prog->section_name);
3095 /* err == -ENOENT (i.e. prog->section_name not found in btf_ext) */
3097 if (btf_prog_info) {
3099 * Some info has already been found but has problem
3100 * in the last btf_ext reloc. Must have to error out.
3102 pr_warn("Error in relocating %s for sec %s.\n",
3103 info_name, prog->section_name);
3107 /* Have problem loading the very first info. Ignore the rest. */
3108 pr_warn("Cannot find %s for main program sec %s. Ignore all %s.\n",
3109 info_name, prog->section_name, info_name);
3114 bpf_program_reloc_btf_ext(struct bpf_program *prog, struct bpf_object *obj,
3115 const char *section_name, __u32 insn_offset)
3119 if (!insn_offset || prog->func_info) {
3121 * !insn_offset => main program
3123 * For sub prog, the main program's func_info has to
3124 * be loaded first (i.e. prog->func_info != NULL)
3126 err = btf_ext__reloc_func_info(obj->btf, obj->btf_ext,
3127 section_name, insn_offset,
3129 &prog->func_info_cnt);
3131 return check_btf_ext_reloc_err(prog, err,
3135 prog->func_info_rec_size = btf_ext__func_info_rec_size(obj->btf_ext);
3138 if (!insn_offset || prog->line_info) {
3139 err = btf_ext__reloc_line_info(obj->btf, obj->btf_ext,
3140 section_name, insn_offset,
3142 &prog->line_info_cnt);
3144 return check_btf_ext_reloc_err(prog, err,
3148 prog->line_info_rec_size = btf_ext__line_info_rec_size(obj->btf_ext);
3154 #define BPF_CORE_SPEC_MAX_LEN 64
3156 /* represents BPF CO-RE field or array element accessor */
3157 struct bpf_core_accessor {
3158 __u32 type_id; /* struct/union type or array element type */
3159 __u32 idx; /* field index or array index */
3160 const char *name; /* field name or NULL for array accessor */
3163 struct bpf_core_spec {
3164 const struct btf *btf;
3165 /* high-level spec: named fields and array indices only */
3166 struct bpf_core_accessor spec[BPF_CORE_SPEC_MAX_LEN];
3167 /* high-level spec length */
3169 /* raw, low-level spec: 1-to-1 with accessor spec string */
3170 int raw_spec[BPF_CORE_SPEC_MAX_LEN];
3171 /* raw spec length */
3173 /* field bit offset represented by spec */
3177 static bool str_is_empty(const char *s)
3182 static bool is_flex_arr(const struct btf *btf,
3183 const struct bpf_core_accessor *acc,
3184 const struct btf_array *arr)
3186 const struct btf_type *t;
3188 /* not a flexible array, if not inside a struct or has non-zero size */
3189 if (!acc->name || arr->nelems > 0)
3192 /* has to be the last member of enclosing struct */
3193 t = btf__type_by_id(btf, acc->type_id);
3194 return acc->idx == btf_vlen(t) - 1;
3198 * Turn bpf_field_reloc into a low- and high-level spec representation,
3199 * validating correctness along the way, as well as calculating resulting
3200 * field bit offset, specified by accessor string. Low-level spec captures
3201 * every single level of nestedness, including traversing anonymous
3202 * struct/union members. High-level one only captures semantically meaningful
3203 * "turning points": named fields and array indicies.
3204 * E.g., for this case:
3207 * int __unimportant;
3215 * struct sample *s = ...;
3217 * int x = &s->a[3]; // access string = '0:1:2:3'
3219 * Low-level spec has 1:1 mapping with each element of access string (it's
3220 * just a parsed access string representation): [0, 1, 2, 3].
3222 * High-level spec will capture only 3 points:
3223 * - intial zero-index access by pointer (&s->... is the same as &s[0]...);
3224 * - field 'a' access (corresponds to '2' in low-level spec);
3225 * - array element #3 access (corresponds to '3' in low-level spec).
3228 static int bpf_core_spec_parse(const struct btf *btf,
3230 const char *spec_str,
3231 struct bpf_core_spec *spec)
3233 int access_idx, parsed_len, i;
3234 struct bpf_core_accessor *acc;
3235 const struct btf_type *t;
3240 if (str_is_empty(spec_str) || *spec_str == ':')
3243 memset(spec, 0, sizeof(*spec));
3246 /* parse spec_str="0:1:2:3:4" into array raw_spec=[0, 1, 2, 3, 4] */
3248 if (*spec_str == ':')
3250 if (sscanf(spec_str, "%d%n", &access_idx, &parsed_len) != 1)
3252 if (spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
3254 spec_str += parsed_len;
3255 spec->raw_spec[spec->raw_len++] = access_idx;
3258 if (spec->raw_len == 0)
3261 /* first spec value is always reloc type array index */
3262 t = skip_mods_and_typedefs(btf, type_id, &id);
3266 access_idx = spec->raw_spec[0];
3267 spec->spec[0].type_id = id;
3268 spec->spec[0].idx = access_idx;
3271 sz = btf__resolve_size(btf, id);
3274 spec->bit_offset = access_idx * sz * 8;
3276 for (i = 1; i < spec->raw_len; i++) {
3277 t = skip_mods_and_typedefs(btf, id, &id);
3281 access_idx = spec->raw_spec[i];
3282 acc = &spec->spec[spec->len];
3284 if (btf_is_composite(t)) {
3285 const struct btf_member *m;
3288 if (access_idx >= btf_vlen(t))
3291 bit_offset = btf_member_bit_offset(t, access_idx);
3292 spec->bit_offset += bit_offset;
3294 m = btf_members(t) + access_idx;
3296 name = btf__name_by_offset(btf, m->name_off);
3297 if (str_is_empty(name))
3301 acc->idx = access_idx;
3307 } else if (btf_is_array(t)) {
3308 const struct btf_array *a = btf_array(t);
3311 t = skip_mods_and_typedefs(btf, a->type, &id);
3315 flex = is_flex_arr(btf, acc - 1, a);
3316 if (!flex && access_idx >= a->nelems)
3319 spec->spec[spec->len].type_id = id;
3320 spec->spec[spec->len].idx = access_idx;
3323 sz = btf__resolve_size(btf, id);
3326 spec->bit_offset += access_idx * sz * 8;
3328 pr_warn("relo for [%u] %s (at idx %d) captures type [%d] of unexpected kind %d\n",
3329 type_id, spec_str, i, id, btf_kind(t));
3337 static bool bpf_core_is_flavor_sep(const char *s)
3339 /* check X___Y name pattern, where X and Y are not underscores */
3340 return s[0] != '_' && /* X */
3341 s[1] == '_' && s[2] == '_' && s[3] == '_' && /* ___ */
3342 s[4] != '_'; /* Y */
3345 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
3346 * before last triple underscore. Struct name part after last triple
3347 * underscore is ignored by BPF CO-RE relocation during relocation matching.
3349 static size_t bpf_core_essential_name_len(const char *name)
3351 size_t n = strlen(name);
3354 for (i = n - 5; i >= 0; i--) {
3355 if (bpf_core_is_flavor_sep(name + i))
3361 /* dynamically sized list of type IDs */
3367 static void bpf_core_free_cands(struct ids_vec *cand_ids)
3369 free(cand_ids->data);
3373 static struct ids_vec *bpf_core_find_cands(const struct btf *local_btf,
3374 __u32 local_type_id,
3375 const struct btf *targ_btf)
3377 size_t local_essent_len, targ_essent_len;
3378 const char *local_name, *targ_name;
3379 const struct btf_type *t;
3380 struct ids_vec *cand_ids;
3384 t = btf__type_by_id(local_btf, local_type_id);
3386 return ERR_PTR(-EINVAL);
3388 local_name = btf__name_by_offset(local_btf, t->name_off);
3389 if (str_is_empty(local_name))
3390 return ERR_PTR(-EINVAL);
3391 local_essent_len = bpf_core_essential_name_len(local_name);
3393 cand_ids = calloc(1, sizeof(*cand_ids));
3395 return ERR_PTR(-ENOMEM);
3397 n = btf__get_nr_types(targ_btf);
3398 for (i = 1; i <= n; i++) {
3399 t = btf__type_by_id(targ_btf, i);
3400 targ_name = btf__name_by_offset(targ_btf, t->name_off);
3401 if (str_is_empty(targ_name))
3404 targ_essent_len = bpf_core_essential_name_len(targ_name);
3405 if (targ_essent_len != local_essent_len)
3408 if (strncmp(local_name, targ_name, local_essent_len) == 0) {
3409 pr_debug("[%d] %s: found candidate [%d] %s\n",
3410 local_type_id, local_name, i, targ_name);
3411 new_ids = realloc(cand_ids->data, cand_ids->len + 1);
3416 cand_ids->data = new_ids;
3417 cand_ids->data[cand_ids->len++] = i;
3422 bpf_core_free_cands(cand_ids);
3423 return ERR_PTR(err);
3426 /* Check two types for compatibility, skipping const/volatile/restrict and
3427 * typedefs, to ensure we are relocating compatible entities:
3428 * - any two STRUCTs/UNIONs are compatible and can be mixed;
3429 * - any two FWDs are compatible, if their names match (modulo flavor suffix);
3430 * - any two PTRs are always compatible;
3431 * - for ENUMs, names should be the same (ignoring flavor suffix) or at
3432 * least one of enums should be anonymous;
3433 * - for ENUMs, check sizes, names are ignored;
3434 * - for INT, size and signedness are ignored;
3435 * - for ARRAY, dimensionality is ignored, element types are checked for
3436 * compatibility recursively;
3437 * - everything else shouldn't be ever a target of relocation.
3438 * These rules are not set in stone and probably will be adjusted as we get
3439 * more experience with using BPF CO-RE relocations.
3441 static int bpf_core_fields_are_compat(const struct btf *local_btf,
3443 const struct btf *targ_btf,
3446 const struct btf_type *local_type, *targ_type;
3449 local_type = skip_mods_and_typedefs(local_btf, local_id, &local_id);
3450 targ_type = skip_mods_and_typedefs(targ_btf, targ_id, &targ_id);
3451 if (!local_type || !targ_type)
3454 if (btf_is_composite(local_type) && btf_is_composite(targ_type))
3456 if (btf_kind(local_type) != btf_kind(targ_type))
3459 switch (btf_kind(local_type)) {
3463 case BTF_KIND_ENUM: {
3464 const char *local_name, *targ_name;
3465 size_t local_len, targ_len;
3467 local_name = btf__name_by_offset(local_btf,
3468 local_type->name_off);
3469 targ_name = btf__name_by_offset(targ_btf, targ_type->name_off);
3470 local_len = bpf_core_essential_name_len(local_name);
3471 targ_len = bpf_core_essential_name_len(targ_name);
3472 /* one of them is anonymous or both w/ same flavor-less names */
3473 return local_len == 0 || targ_len == 0 ||
3474 (local_len == targ_len &&
3475 strncmp(local_name, targ_name, local_len) == 0);
3478 /* just reject deprecated bitfield-like integers; all other
3479 * integers are by default compatible between each other
3481 return btf_int_offset(local_type) == 0 &&
3482 btf_int_offset(targ_type) == 0;
3483 case BTF_KIND_ARRAY:
3484 local_id = btf_array(local_type)->type;
3485 targ_id = btf_array(targ_type)->type;
3488 pr_warn("unexpected kind %d relocated, local [%d], target [%d]\n",
3489 btf_kind(local_type), local_id, targ_id);
3495 * Given single high-level named field accessor in local type, find
3496 * corresponding high-level accessor for a target type. Along the way,
3497 * maintain low-level spec for target as well. Also keep updating target
3500 * Searching is performed through recursive exhaustive enumeration of all
3501 * fields of a struct/union. If there are any anonymous (embedded)
3502 * structs/unions, they are recursively searched as well. If field with
3503 * desired name is found, check compatibility between local and target types,
3504 * before returning result.
3506 * 1 is returned, if field is found.
3507 * 0 is returned if no compatible field is found.
3508 * <0 is returned on error.
3510 static int bpf_core_match_member(const struct btf *local_btf,
3511 const struct bpf_core_accessor *local_acc,
3512 const struct btf *targ_btf,
3514 struct bpf_core_spec *spec,
3515 __u32 *next_targ_id)
3517 const struct btf_type *local_type, *targ_type;
3518 const struct btf_member *local_member, *m;
3519 const char *local_name, *targ_name;
3523 targ_type = skip_mods_and_typedefs(targ_btf, targ_id, &targ_id);
3526 if (!btf_is_composite(targ_type))
3529 local_id = local_acc->type_id;
3530 local_type = btf__type_by_id(local_btf, local_id);
3531 local_member = btf_members(local_type) + local_acc->idx;
3532 local_name = btf__name_by_offset(local_btf, local_member->name_off);
3534 n = btf_vlen(targ_type);
3535 m = btf_members(targ_type);
3536 for (i = 0; i < n; i++, m++) {
3539 bit_offset = btf_member_bit_offset(targ_type, i);
3541 /* too deep struct/union/array nesting */
3542 if (spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
3545 /* speculate this member will be the good one */
3546 spec->bit_offset += bit_offset;
3547 spec->raw_spec[spec->raw_len++] = i;
3549 targ_name = btf__name_by_offset(targ_btf, m->name_off);
3550 if (str_is_empty(targ_name)) {
3551 /* embedded struct/union, we need to go deeper */
3552 found = bpf_core_match_member(local_btf, local_acc,
3554 spec, next_targ_id);
3555 if (found) /* either found or error */
3557 } else if (strcmp(local_name, targ_name) == 0) {
3558 /* matching named field */
3559 struct bpf_core_accessor *targ_acc;
3561 targ_acc = &spec->spec[spec->len++];
3562 targ_acc->type_id = targ_id;
3564 targ_acc->name = targ_name;
3566 *next_targ_id = m->type;
3567 found = bpf_core_fields_are_compat(local_btf,
3571 spec->len--; /* pop accessor */
3574 /* member turned out not to be what we looked for */
3575 spec->bit_offset -= bit_offset;
3583 * Try to match local spec to a target type and, if successful, produce full
3584 * target spec (high-level, low-level + bit offset).
3586 static int bpf_core_spec_match(struct bpf_core_spec *local_spec,
3587 const struct btf *targ_btf, __u32 targ_id,
3588 struct bpf_core_spec *targ_spec)
3590 const struct btf_type *targ_type;
3591 const struct bpf_core_accessor *local_acc;
3592 struct bpf_core_accessor *targ_acc;
3595 memset(targ_spec, 0, sizeof(*targ_spec));
3596 targ_spec->btf = targ_btf;
3598 local_acc = &local_spec->spec[0];
3599 targ_acc = &targ_spec->spec[0];
3601 for (i = 0; i < local_spec->len; i++, local_acc++, targ_acc++) {
3602 targ_type = skip_mods_and_typedefs(targ_spec->btf, targ_id,
3607 if (local_acc->name) {
3608 matched = bpf_core_match_member(local_spec->btf,
3611 targ_spec, &targ_id);
3615 /* for i=0, targ_id is already treated as array element
3616 * type (because it's the original struct), for others
3617 * we should find array element type first
3620 const struct btf_array *a;
3623 if (!btf_is_array(targ_type))
3626 a = btf_array(targ_type);
3627 flex = is_flex_arr(targ_btf, targ_acc - 1, a);
3628 if (!flex && local_acc->idx >= a->nelems)
3630 if (!skip_mods_and_typedefs(targ_btf, a->type,
3635 /* too deep struct/union/array nesting */
3636 if (targ_spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
3639 targ_acc->type_id = targ_id;
3640 targ_acc->idx = local_acc->idx;
3641 targ_acc->name = NULL;
3643 targ_spec->raw_spec[targ_spec->raw_len] = targ_acc->idx;
3644 targ_spec->raw_len++;
3646 sz = btf__resolve_size(targ_btf, targ_id);
3649 targ_spec->bit_offset += local_acc->idx * sz * 8;
3656 static int bpf_core_calc_field_relo(const struct bpf_program *prog,
3657 const struct bpf_field_reloc *relo,
3658 const struct bpf_core_spec *spec,
3659 __u32 *val, bool *validate)
3661 const struct bpf_core_accessor *acc = &spec->spec[spec->len - 1];
3662 const struct btf_type *t = btf__type_by_id(spec->btf, acc->type_id);
3663 __u32 byte_off, byte_sz, bit_off, bit_sz;
3664 const struct btf_member *m;
3665 const struct btf_type *mt;
3669 /* a[n] accessor needs special handling */
3671 if (relo->kind == BPF_FIELD_BYTE_OFFSET) {
3672 *val = spec->bit_offset / 8;
3673 } else if (relo->kind == BPF_FIELD_BYTE_SIZE) {
3674 sz = btf__resolve_size(spec->btf, acc->type_id);
3679 pr_warn("prog '%s': relo %d at insn #%d can't be applied to array access\n",
3680 bpf_program__title(prog, false),
3681 relo->kind, relo->insn_off / 8);
3689 m = btf_members(t) + acc->idx;
3690 mt = skip_mods_and_typedefs(spec->btf, m->type, NULL);
3691 bit_off = spec->bit_offset;
3692 bit_sz = btf_member_bitfield_size(t, acc->idx);
3694 bitfield = bit_sz > 0;
3697 byte_off = bit_off / 8 / byte_sz * byte_sz;
3698 /* figure out smallest int size necessary for bitfield load */
3699 while (bit_off + bit_sz - byte_off * 8 > byte_sz * 8) {
3701 /* bitfield can't be read with 64-bit read */
3702 pr_warn("prog '%s': relo %d at insn #%d can't be satisfied for bitfield\n",
3703 bpf_program__title(prog, false),
3704 relo->kind, relo->insn_off / 8);
3708 byte_off = bit_off / 8 / byte_sz * byte_sz;
3711 sz = btf__resolve_size(spec->btf, m->type);
3715 byte_off = spec->bit_offset / 8;
3716 bit_sz = byte_sz * 8;
3719 /* for bitfields, all the relocatable aspects are ambiguous and we
3720 * might disagree with compiler, so turn off validation of expected
3721 * value, except for signedness
3724 *validate = !bitfield;
3726 switch (relo->kind) {
3727 case BPF_FIELD_BYTE_OFFSET:
3730 case BPF_FIELD_BYTE_SIZE:
3733 case BPF_FIELD_SIGNED:
3734 /* enums will be assumed unsigned */
3735 *val = btf_is_enum(mt) ||
3736 (btf_int_encoding(mt) & BTF_INT_SIGNED);
3738 *validate = true; /* signedness is never ambiguous */
3740 case BPF_FIELD_LSHIFT_U64:
3741 #if __BYTE_ORDER == __LITTLE_ENDIAN
3742 *val = 64 - (bit_off + bit_sz - byte_off * 8);
3744 *val = (8 - byte_sz) * 8 + (bit_off - byte_off * 8);
3747 case BPF_FIELD_RSHIFT_U64:
3750 *validate = true; /* right shift is never ambiguous */
3752 case BPF_FIELD_EXISTS:
3754 pr_warn("prog '%s': unknown relo %d at insn #%d\n",
3755 bpf_program__title(prog, false),
3756 relo->kind, relo->insn_off / 8);
3764 * Patch relocatable BPF instruction.
3766 * Patched value is determined by relocation kind and target specification.
3767 * For field existence relocation target spec will be NULL if field is not
3769 * Expected insn->imm value is determined using relocation kind and local
3770 * spec, and is checked before patching instruction. If actual insn->imm value
3771 * is wrong, bail out with error.
3773 * Currently three kinds of BPF instructions are supported:
3774 * 1. rX = <imm> (assignment with immediate operand);
3775 * 2. rX += <imm> (arithmetic operations with immediate operand);
3777 static int bpf_core_reloc_insn(struct bpf_program *prog,
3778 const struct bpf_field_reloc *relo,
3779 const struct bpf_core_spec *local_spec,
3780 const struct bpf_core_spec *targ_spec)
3782 bool failed = false, validate = true;
3783 __u32 orig_val, new_val;
3784 struct bpf_insn *insn;
3788 if (relo->insn_off % sizeof(struct bpf_insn))
3790 insn_idx = relo->insn_off / sizeof(struct bpf_insn);
3792 if (relo->kind == BPF_FIELD_EXISTS) {
3793 orig_val = 1; /* can't generate EXISTS relo w/o local field */
3794 new_val = targ_spec ? 1 : 0;
3795 } else if (!targ_spec) {
3797 new_val = (__u32)-1;
3799 err = bpf_core_calc_field_relo(prog, relo, local_spec,
3800 &orig_val, &validate);
3803 err = bpf_core_calc_field_relo(prog, relo, targ_spec,
3809 insn = &prog->insns[insn_idx];
3810 class = BPF_CLASS(insn->code);
3812 if (class == BPF_ALU || class == BPF_ALU64) {
3813 if (BPF_SRC(insn->code) != BPF_K)
3815 if (!failed && validate && insn->imm != orig_val) {
3816 pr_warn("prog '%s': unexpected insn #%d value: got %u, exp %u -> %u\n",
3817 bpf_program__title(prog, false), insn_idx,
3818 insn->imm, orig_val, new_val);
3821 orig_val = insn->imm;
3822 insn->imm = new_val;
3823 pr_debug("prog '%s': patched insn #%d (ALU/ALU64)%s imm %u -> %u\n",
3824 bpf_program__title(prog, false), insn_idx,
3825 failed ? " w/ failed reloc" : "", orig_val, new_val);
3827 pr_warn("prog '%s': trying to relocate unrecognized insn #%d, code:%x, src:%x, dst:%x, off:%x, imm:%x\n",
3828 bpf_program__title(prog, false),
3829 insn_idx, insn->code, insn->src_reg, insn->dst_reg,
3830 insn->off, insn->imm);
3837 static struct btf *btf_load_raw(const char *path)
3845 if (stat(path, &st))
3846 return ERR_PTR(-errno);
3848 data = malloc(st.st_size);
3850 return ERR_PTR(-ENOMEM);
3852 f = fopen(path, "rb");
3854 btf = ERR_PTR(-errno);
3858 read_cnt = fread(data, 1, st.st_size, f);
3860 if (read_cnt < st.st_size) {
3861 btf = ERR_PTR(-EBADF);
3865 btf = btf__new(data, read_cnt);
3873 * Probe few well-known locations for vmlinux kernel image and try to load BTF
3874 * data out of it to use for target BTF.
3876 static struct btf *bpf_core_find_kernel_btf(void)
3879 const char *path_fmt;
3882 /* try canonical vmlinux BTF through sysfs first */
3883 { "/sys/kernel/btf/vmlinux", true /* raw BTF */ },
3884 /* fall back to trying to find vmlinux ELF on disk otherwise */
3885 { "/boot/vmlinux-%1$s" },
3886 { "/lib/modules/%1$s/vmlinux-%1$s" },
3887 { "/lib/modules/%1$s/build/vmlinux" },
3888 { "/usr/lib/modules/%1$s/kernel/vmlinux" },
3889 { "/usr/lib/debug/boot/vmlinux-%1$s" },
3890 { "/usr/lib/debug/boot/vmlinux-%1$s.debug" },
3891 { "/usr/lib/debug/lib/modules/%1$s/vmlinux" },
3893 char path[PATH_MAX + 1];
3900 for (i = 0; i < ARRAY_SIZE(locations); i++) {
3901 snprintf(path, PATH_MAX, locations[i].path_fmt, buf.release);
3903 if (access(path, R_OK))
3906 if (locations[i].raw_btf)
3907 btf = btf_load_raw(path);
3909 btf = btf__parse_elf(path, NULL);
3911 pr_debug("loading kernel BTF '%s': %ld\n",
3912 path, IS_ERR(btf) ? PTR_ERR(btf) : 0);
3919 pr_warn("failed to find valid kernel BTF\n");
3920 return ERR_PTR(-ESRCH);
3923 /* Output spec definition in the format:
3924 * [<type-id>] (<type-name>) + <raw-spec> => <offset>@<spec>,
3925 * where <spec> is a C-syntax view of recorded field access, e.g.: x.a[3].b
3927 static void bpf_core_dump_spec(int level, const struct bpf_core_spec *spec)
3929 const struct btf_type *t;
3934 type_id = spec->spec[0].type_id;
3935 t = btf__type_by_id(spec->btf, type_id);
3936 s = btf__name_by_offset(spec->btf, t->name_off);
3937 libbpf_print(level, "[%u] %s + ", type_id, s);
3939 for (i = 0; i < spec->raw_len; i++)
3940 libbpf_print(level, "%d%s", spec->raw_spec[i],
3941 i == spec->raw_len - 1 ? " => " : ":");
3943 libbpf_print(level, "%u.%u @ &x",
3944 spec->bit_offset / 8, spec->bit_offset % 8);
3946 for (i = 0; i < spec->len; i++) {
3947 if (spec->spec[i].name)
3948 libbpf_print(level, ".%s", spec->spec[i].name);
3950 libbpf_print(level, "[%u]", spec->spec[i].idx);
3955 static size_t bpf_core_hash_fn(const void *key, void *ctx)
3960 static bool bpf_core_equal_fn(const void *k1, const void *k2, void *ctx)
3965 static void *u32_as_hash_key(__u32 x)
3967 return (void *)(uintptr_t)x;
3971 * CO-RE relocate single instruction.
3973 * The outline and important points of the algorithm:
3974 * 1. For given local type, find corresponding candidate target types.
3975 * Candidate type is a type with the same "essential" name, ignoring
3976 * everything after last triple underscore (___). E.g., `sample`,
3977 * `sample___flavor_one`, `sample___flavor_another_one`, are all candidates
3978 * for each other. Names with triple underscore are referred to as
3979 * "flavors" and are useful, among other things, to allow to
3980 * specify/support incompatible variations of the same kernel struct, which
3981 * might differ between different kernel versions and/or build
3984 * N.B. Struct "flavors" could be generated by bpftool's BTF-to-C
3985 * converter, when deduplicated BTF of a kernel still contains more than
3986 * one different types with the same name. In that case, ___2, ___3, etc
3987 * are appended starting from second name conflict. But start flavors are
3988 * also useful to be defined "locally", in BPF program, to extract same
3989 * data from incompatible changes between different kernel
3990 * versions/configurations. For instance, to handle field renames between
3991 * kernel versions, one can use two flavors of the struct name with the
3992 * same common name and use conditional relocations to extract that field,
3993 * depending on target kernel version.
3994 * 2. For each candidate type, try to match local specification to this
3995 * candidate target type. Matching involves finding corresponding
3996 * high-level spec accessors, meaning that all named fields should match,
3997 * as well as all array accesses should be within the actual bounds. Also,
3998 * types should be compatible (see bpf_core_fields_are_compat for details).
3999 * 3. It is supported and expected that there might be multiple flavors
4000 * matching the spec. As long as all the specs resolve to the same set of
4001 * offsets across all candidates, there is no error. If there is any
4002 * ambiguity, CO-RE relocation will fail. This is necessary to accomodate
4003 * imprefection of BTF deduplication, which can cause slight duplication of
4004 * the same BTF type, if some directly or indirectly referenced (by
4005 * pointer) type gets resolved to different actual types in different
4006 * object files. If such situation occurs, deduplicated BTF will end up
4007 * with two (or more) structurally identical types, which differ only in
4008 * types they refer to through pointer. This should be OK in most cases and
4010 * 4. Candidate types search is performed by linearly scanning through all
4011 * types in target BTF. It is anticipated that this is overall more
4012 * efficient memory-wise and not significantly worse (if not better)
4013 * CPU-wise compared to prebuilding a map from all local type names to
4014 * a list of candidate type names. It's also sped up by caching resolved
4015 * list of matching candidates per each local "root" type ID, that has at
4016 * least one bpf_field_reloc associated with it. This list is shared
4017 * between multiple relocations for the same type ID and is updated as some
4018 * of the candidates are pruned due to structural incompatibility.
4020 static int bpf_core_reloc_field(struct bpf_program *prog,
4021 const struct bpf_field_reloc *relo,
4023 const struct btf *local_btf,
4024 const struct btf *targ_btf,
4025 struct hashmap *cand_cache)
4027 const char *prog_name = bpf_program__title(prog, false);
4028 struct bpf_core_spec local_spec, cand_spec, targ_spec;
4029 const void *type_key = u32_as_hash_key(relo->type_id);
4030 const struct btf_type *local_type, *cand_type;
4031 const char *local_name, *cand_name;
4032 struct ids_vec *cand_ids;
4033 __u32 local_id, cand_id;
4034 const char *spec_str;
4037 local_id = relo->type_id;
4038 local_type = btf__type_by_id(local_btf, local_id);
4042 local_name = btf__name_by_offset(local_btf, local_type->name_off);
4043 if (str_is_empty(local_name))
4046 spec_str = btf__name_by_offset(local_btf, relo->access_str_off);
4047 if (str_is_empty(spec_str))
4050 err = bpf_core_spec_parse(local_btf, local_id, spec_str, &local_spec);
4052 pr_warn("prog '%s': relo #%d: parsing [%d] %s + %s failed: %d\n",
4053 prog_name, relo_idx, local_id, local_name, spec_str,
4058 pr_debug("prog '%s': relo #%d: kind %d, spec is ", prog_name, relo_idx,
4060 bpf_core_dump_spec(LIBBPF_DEBUG, &local_spec);
4061 libbpf_print(LIBBPF_DEBUG, "\n");
4063 if (!hashmap__find(cand_cache, type_key, (void **)&cand_ids)) {
4064 cand_ids = bpf_core_find_cands(local_btf, local_id, targ_btf);
4065 if (IS_ERR(cand_ids)) {
4066 pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s: %ld",
4067 prog_name, relo_idx, local_id, local_name,
4069 return PTR_ERR(cand_ids);
4071 err = hashmap__set(cand_cache, type_key, cand_ids, NULL, NULL);
4073 bpf_core_free_cands(cand_ids);
4078 for (i = 0, j = 0; i < cand_ids->len; i++) {
4079 cand_id = cand_ids->data[i];
4080 cand_type = btf__type_by_id(targ_btf, cand_id);
4081 cand_name = btf__name_by_offset(targ_btf, cand_type->name_off);
4083 err = bpf_core_spec_match(&local_spec, targ_btf,
4084 cand_id, &cand_spec);
4085 pr_debug("prog '%s': relo #%d: matching candidate #%d %s against spec ",
4086 prog_name, relo_idx, i, cand_name);
4087 bpf_core_dump_spec(LIBBPF_DEBUG, &cand_spec);
4088 libbpf_print(LIBBPF_DEBUG, ": %d\n", err);
4090 pr_warn("prog '%s': relo #%d: matching error: %d\n",
4091 prog_name, relo_idx, err);
4098 targ_spec = cand_spec;
4099 } else if (cand_spec.bit_offset != targ_spec.bit_offset) {
4100 /* if there are many candidates, they should all
4101 * resolve to the same bit offset
4103 pr_warn("prog '%s': relo #%d: offset ambiguity: %u != %u\n",
4104 prog_name, relo_idx, cand_spec.bit_offset,
4105 targ_spec.bit_offset);
4109 cand_ids->data[j++] = cand_spec.spec[0].type_id;
4113 * For BPF_FIELD_EXISTS relo or when relaxed CO-RE reloc mode is
4114 * requested, it's expected that we might not find any candidates.
4115 * In this case, if field wasn't found in any candidate, the list of
4116 * candidates shouldn't change at all, we'll just handle relocating
4117 * appropriately, depending on relo's kind.
4122 if (j == 0 && !prog->obj->relaxed_core_relocs &&
4123 relo->kind != BPF_FIELD_EXISTS) {
4124 pr_warn("prog '%s': relo #%d: no matching targets found for [%d] %s + %s\n",
4125 prog_name, relo_idx, local_id, local_name, spec_str);
4129 /* bpf_core_reloc_insn should know how to handle missing targ_spec */
4130 err = bpf_core_reloc_insn(prog, relo, &local_spec,
4131 j ? &targ_spec : NULL);
4133 pr_warn("prog '%s': relo #%d: failed to patch insn at offset %d: %d\n",
4134 prog_name, relo_idx, relo->insn_off, err);
4142 bpf_core_reloc_fields(struct bpf_object *obj, const char *targ_btf_path)
4144 const struct btf_ext_info_sec *sec;
4145 const struct bpf_field_reloc *rec;
4146 const struct btf_ext_info *seg;
4147 struct hashmap_entry *entry;
4148 struct hashmap *cand_cache = NULL;
4149 struct bpf_program *prog;
4150 struct btf *targ_btf;
4151 const char *sec_name;
4155 targ_btf = btf__parse_elf(targ_btf_path, NULL);
4157 targ_btf = bpf_core_find_kernel_btf();
4158 if (IS_ERR(targ_btf)) {
4159 pr_warn("failed to get target BTF: %ld\n", PTR_ERR(targ_btf));
4160 return PTR_ERR(targ_btf);
4163 cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
4164 if (IS_ERR(cand_cache)) {
4165 err = PTR_ERR(cand_cache);
4169 seg = &obj->btf_ext->field_reloc_info;
4170 for_each_btf_ext_sec(seg, sec) {
4171 sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
4172 if (str_is_empty(sec_name)) {
4176 prog = bpf_object__find_program_by_title(obj, sec_name);
4178 pr_warn("failed to find program '%s' for CO-RE offset relocation\n",
4184 pr_debug("prog '%s': performing %d CO-RE offset relocs\n",
4185 sec_name, sec->num_info);
4187 for_each_btf_ext_rec(seg, sec, i, rec) {
4188 err = bpf_core_reloc_field(prog, rec, i, obj->btf,
4189 targ_btf, cand_cache);
4191 pr_warn("prog '%s': relo #%d: failed to relocate: %d\n",
4199 btf__free(targ_btf);
4200 if (!IS_ERR_OR_NULL(cand_cache)) {
4201 hashmap__for_each_entry(cand_cache, entry, i) {
4202 bpf_core_free_cands(entry->value);
4204 hashmap__free(cand_cache);
4210 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
4214 if (obj->btf_ext->field_reloc_info.len)
4215 err = bpf_core_reloc_fields(obj, targ_btf_path);
4221 bpf_program__reloc_text(struct bpf_program *prog, struct bpf_object *obj,
4222 struct reloc_desc *relo)
4224 struct bpf_insn *insn, *new_insn;
4225 struct bpf_program *text;
4229 if (prog->idx == obj->efile.text_shndx) {
4230 pr_warn("relo in .text insn %d into off %d (insn #%d)\n",
4231 relo->insn_idx, relo->sym_off, relo->sym_off / 8);
4232 return -LIBBPF_ERRNO__RELOC;
4235 if (prog->main_prog_cnt == 0) {
4236 text = bpf_object__find_prog_by_idx(obj, obj->efile.text_shndx);
4238 pr_warn("no .text section found yet relo into text exist\n");
4239 return -LIBBPF_ERRNO__RELOC;
4241 new_cnt = prog->insns_cnt + text->insns_cnt;
4242 new_insn = reallocarray(prog->insns, new_cnt, sizeof(*insn));
4244 pr_warn("oom in prog realloc\n");
4247 prog->insns = new_insn;
4250 err = bpf_program_reloc_btf_ext(prog, obj,
4257 memcpy(new_insn + prog->insns_cnt, text->insns,
4258 text->insns_cnt * sizeof(*insn));
4259 prog->main_prog_cnt = prog->insns_cnt;
4260 prog->insns_cnt = new_cnt;
4261 pr_debug("added %zd insn from %s to prog %s\n",
4262 text->insns_cnt, text->section_name,
4263 prog->section_name);
4265 insn = &prog->insns[relo->insn_idx];
4266 insn->imm += relo->sym_off / 8 + prog->main_prog_cnt - relo->insn_idx;
4271 bpf_program__relocate(struct bpf_program *prog, struct bpf_object *obj)
4279 err = bpf_program_reloc_btf_ext(prog, obj,
4280 prog->section_name, 0);
4285 if (!prog->reloc_desc)
4288 for (i = 0; i < prog->nr_reloc; i++) {
4289 struct reloc_desc *relo = &prog->reloc_desc[i];
4290 struct bpf_insn *insn = &prog->insns[relo->insn_idx];
4292 if (relo->insn_idx + 1 >= (int)prog->insns_cnt) {
4293 pr_warn("relocation out of range: '%s'\n",
4294 prog->section_name);
4295 return -LIBBPF_ERRNO__RELOC;
4298 switch (relo->type) {
4300 insn[0].src_reg = BPF_PSEUDO_MAP_FD;
4301 insn[0].imm = obj->maps[relo->map_idx].fd;
4304 insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
4305 insn[1].imm = insn[0].imm + relo->sym_off;
4306 insn[0].imm = obj->maps[relo->map_idx].fd;
4309 insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
4310 insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
4311 insn[1].imm = relo->sym_off;
4314 err = bpf_program__reloc_text(prog, obj, relo);
4319 pr_warn("relo #%d: bad relo type %d\n", i, relo->type);
4324 zfree(&prog->reloc_desc);
4330 bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
4332 struct bpf_program *prog;
4337 err = bpf_object__relocate_core(obj, targ_btf_path);
4339 pr_warn("failed to perform CO-RE relocations: %d\n",
4344 for (i = 0; i < obj->nr_programs; i++) {
4345 prog = &obj->programs[i];
4347 err = bpf_program__relocate(prog, obj);
4349 pr_warn("failed to relocate '%s'\n", prog->section_name);
4356 static int bpf_object__collect_reloc(struct bpf_object *obj)
4360 if (!obj_elf_valid(obj)) {
4361 pr_warn("Internal error: elf object is closed\n");
4362 return -LIBBPF_ERRNO__INTERNAL;
4365 for (i = 0; i < obj->efile.nr_reloc_sects; i++) {
4366 GElf_Shdr *shdr = &obj->efile.reloc_sects[i].shdr;
4367 Elf_Data *data = obj->efile.reloc_sects[i].data;
4368 int idx = shdr->sh_info;
4369 struct bpf_program *prog;
4371 if (shdr->sh_type != SHT_REL) {
4372 pr_warn("internal error at %d\n", __LINE__);
4373 return -LIBBPF_ERRNO__INTERNAL;
4376 prog = bpf_object__find_prog_by_idx(obj, idx);
4378 pr_warn("relocation failed: no section(%d)\n", idx);
4379 return -LIBBPF_ERRNO__RELOC;
4382 err = bpf_program__collect_reloc(prog, shdr, data, obj);
4390 load_program(struct bpf_program *prog, struct bpf_insn *insns, int insns_cnt,
4391 char *license, __u32 kern_version, int *pfd)
4393 struct bpf_load_program_attr load_attr;
4394 char *cp, errmsg[STRERR_BUFSIZE];
4395 int log_buf_size = BPF_LOG_BUF_SIZE;
4399 if (!insns || !insns_cnt)
4402 memset(&load_attr, 0, sizeof(struct bpf_load_program_attr));
4403 load_attr.prog_type = prog->type;
4404 load_attr.expected_attach_type = prog->expected_attach_type;
4405 if (prog->caps->name)
4406 load_attr.name = prog->name;
4407 load_attr.insns = insns;
4408 load_attr.insns_cnt = insns_cnt;
4409 load_attr.license = license;
4410 if (prog->type == BPF_PROG_TYPE_TRACING) {
4411 load_attr.attach_prog_fd = prog->attach_prog_fd;
4412 load_attr.attach_btf_id = prog->attach_btf_id;
4414 load_attr.kern_version = kern_version;
4415 load_attr.prog_ifindex = prog->prog_ifindex;
4417 /* if .BTF.ext was loaded, kernel supports associated BTF for prog */
4418 if (prog->obj->btf_ext)
4419 btf_fd = bpf_object__btf_fd(prog->obj);
4422 load_attr.prog_btf_fd = btf_fd >= 0 ? btf_fd : 0;
4423 load_attr.func_info = prog->func_info;
4424 load_attr.func_info_rec_size = prog->func_info_rec_size;
4425 load_attr.func_info_cnt = prog->func_info_cnt;
4426 load_attr.line_info = prog->line_info;
4427 load_attr.line_info_rec_size = prog->line_info_rec_size;
4428 load_attr.line_info_cnt = prog->line_info_cnt;
4429 load_attr.log_level = prog->log_level;
4430 load_attr.prog_flags = prog->prog_flags;
4433 log_buf = malloc(log_buf_size);
4435 pr_warn("Alloc log buffer for bpf loader error, continue without log\n");
4437 ret = bpf_load_program_xattr(&load_attr, log_buf, log_buf_size);
4440 if (load_attr.log_level)
4441 pr_debug("verifier log:\n%s", log_buf);
4447 if (errno == ENOSPC) {
4453 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
4454 pr_warn("load bpf program failed: %s\n", cp);
4457 if (log_buf && log_buf[0] != '\0') {
4458 ret = -LIBBPF_ERRNO__VERIFY;
4459 pr_warn("-- BEGIN DUMP LOG ---\n");
4460 pr_warn("\n%s\n", log_buf);
4461 pr_warn("-- END LOG --\n");
4462 } else if (load_attr.insns_cnt >= BPF_MAXINSNS) {
4463 pr_warn("Program too large (%zu insns), at most %d insns\n",
4464 load_attr.insns_cnt, BPF_MAXINSNS);
4465 ret = -LIBBPF_ERRNO__PROG2BIG;
4466 } else if (load_attr.prog_type != BPF_PROG_TYPE_KPROBE) {
4467 /* Wrong program type? */
4470 load_attr.prog_type = BPF_PROG_TYPE_KPROBE;
4471 load_attr.expected_attach_type = 0;
4472 fd = bpf_load_program_xattr(&load_attr, NULL, 0);
4475 ret = -LIBBPF_ERRNO__PROGTYPE;
4485 static int libbpf_find_attach_btf_id(const char *name,
4486 enum bpf_attach_type attach_type,
4487 __u32 attach_prog_fd);
4489 int bpf_program__load(struct bpf_program *prog, char *license, __u32 kern_ver)
4491 int err = 0, fd, i, btf_id;
4493 if (prog->type == BPF_PROG_TYPE_TRACING) {
4494 btf_id = libbpf_find_attach_btf_id(prog->section_name,
4495 prog->expected_attach_type,
4496 prog->attach_prog_fd);
4499 prog->attach_btf_id = btf_id;
4502 if (prog->instances.nr < 0 || !prog->instances.fds) {
4503 if (prog->preprocessor) {
4504 pr_warn("Internal error: can't load program '%s'\n",
4505 prog->section_name);
4506 return -LIBBPF_ERRNO__INTERNAL;
4509 prog->instances.fds = malloc(sizeof(int));
4510 if (!prog->instances.fds) {
4511 pr_warn("Not enough memory for BPF fds\n");
4514 prog->instances.nr = 1;
4515 prog->instances.fds[0] = -1;
4518 if (!prog->preprocessor) {
4519 if (prog->instances.nr != 1) {
4520 pr_warn("Program '%s' is inconsistent: nr(%d) != 1\n",
4521 prog->section_name, prog->instances.nr);
4523 err = load_program(prog, prog->insns, prog->insns_cnt,
4524 license, kern_ver, &fd);
4526 prog->instances.fds[0] = fd;
4530 for (i = 0; i < prog->instances.nr; i++) {
4531 struct bpf_prog_prep_result result;
4532 bpf_program_prep_t preprocessor = prog->preprocessor;
4534 memset(&result, 0, sizeof(result));
4535 err = preprocessor(prog, i, prog->insns,
4536 prog->insns_cnt, &result);
4538 pr_warn("Preprocessing the %dth instance of program '%s' failed\n",
4539 i, prog->section_name);
4543 if (!result.new_insn_ptr || !result.new_insn_cnt) {
4544 pr_debug("Skip loading the %dth instance of program '%s'\n",
4545 i, prog->section_name);
4546 prog->instances.fds[i] = -1;
4552 err = load_program(prog, result.new_insn_ptr,
4553 result.new_insn_cnt, license, kern_ver, &fd);
4555 pr_warn("Loading the %dth instance of program '%s' failed\n",
4556 i, prog->section_name);
4562 prog->instances.fds[i] = fd;
4566 pr_warn("failed to load program '%s'\n", prog->section_name);
4567 zfree(&prog->insns);
4568 prog->insns_cnt = 0;
4572 static bool bpf_program__is_function_storage(const struct bpf_program *prog,
4573 const struct bpf_object *obj)
4575 return prog->idx == obj->efile.text_shndx && obj->has_pseudo_calls;
4579 bpf_object__load_progs(struct bpf_object *obj, int log_level)
4584 for (i = 0; i < obj->nr_programs; i++) {
4585 if (bpf_program__is_function_storage(&obj->programs[i], obj))
4587 obj->programs[i].log_level |= log_level;
4588 err = bpf_program__load(&obj->programs[i],
4597 static struct bpf_object *
4598 __bpf_object__open(const char *path, const void *obj_buf, size_t obj_buf_sz,
4599 const struct bpf_object_open_opts *opts)
4601 const char *obj_name, *kconfig;
4602 struct bpf_program *prog;
4603 struct bpf_object *obj;
4607 if (elf_version(EV_CURRENT) == EV_NONE) {
4608 pr_warn("failed to init libelf for %s\n",
4609 path ? : "(mem buf)");
4610 return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
4613 if (!OPTS_VALID(opts, bpf_object_open_opts))
4614 return ERR_PTR(-EINVAL);
4616 obj_name = OPTS_GET(opts, object_name, NULL);
4619 snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
4620 (unsigned long)obj_buf,
4621 (unsigned long)obj_buf_sz);
4622 obj_name = tmp_name;
4625 pr_debug("loading object '%s' from buffer\n", obj_name);
4628 obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
4632 obj->relaxed_core_relocs = OPTS_GET(opts, relaxed_core_relocs, false);
4633 kconfig = OPTS_GET(opts, kconfig, NULL);
4635 obj->kconfig = strdup(kconfig);
4637 return ERR_PTR(-ENOMEM);
4640 err = bpf_object__elf_init(obj);
4641 err = err ? : bpf_object__check_endianness(obj);
4642 err = err ? : bpf_object__elf_collect(obj);
4643 err = err ? : bpf_object__collect_externs(obj);
4644 err = err ? : bpf_object__finalize_btf(obj);
4645 err = err ? : bpf_object__init_maps(obj, opts);
4646 err = err ? : bpf_object__init_prog_names(obj);
4647 err = err ? : bpf_object__collect_reloc(obj);
4650 bpf_object__elf_finish(obj);
4652 bpf_object__for_each_program(prog, obj) {
4653 enum bpf_prog_type prog_type;
4654 enum bpf_attach_type attach_type;
4656 err = libbpf_prog_type_by_name(prog->section_name, &prog_type,
4659 /* couldn't guess, but user might manually specify */
4664 bpf_program__set_type(prog, prog_type);
4665 bpf_program__set_expected_attach_type(prog, attach_type);
4666 if (prog_type == BPF_PROG_TYPE_TRACING)
4667 prog->attach_prog_fd = OPTS_GET(opts, attach_prog_fd, 0);
4672 bpf_object__close(obj);
4673 return ERR_PTR(err);
4676 static struct bpf_object *
4677 __bpf_object__open_xattr(struct bpf_object_open_attr *attr, int flags)
4679 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts,
4680 .relaxed_maps = flags & MAPS_RELAX_COMPAT,
4683 /* param validation */
4687 pr_debug("loading %s\n", attr->file);
4688 return __bpf_object__open(attr->file, NULL, 0, &opts);
4691 struct bpf_object *bpf_object__open_xattr(struct bpf_object_open_attr *attr)
4693 return __bpf_object__open_xattr(attr, 0);
4696 struct bpf_object *bpf_object__open(const char *path)
4698 struct bpf_object_open_attr attr = {
4700 .prog_type = BPF_PROG_TYPE_UNSPEC,
4703 return bpf_object__open_xattr(&attr);
4707 bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
4710 return ERR_PTR(-EINVAL);
4712 pr_debug("loading %s\n", path);
4714 return __bpf_object__open(path, NULL, 0, opts);
4718 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
4719 const struct bpf_object_open_opts *opts)
4721 if (!obj_buf || obj_buf_sz == 0)
4722 return ERR_PTR(-EINVAL);
4724 return __bpf_object__open(NULL, obj_buf, obj_buf_sz, opts);
4728 bpf_object__open_buffer(const void *obj_buf, size_t obj_buf_sz,
4731 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts,
4732 .object_name = name,
4733 /* wrong default, but backwards-compatible */
4734 .relaxed_maps = true,
4737 /* returning NULL is wrong, but backwards-compatible */
4738 if (!obj_buf || obj_buf_sz == 0)
4741 return bpf_object__open_mem(obj_buf, obj_buf_sz, &opts);
4744 int bpf_object__unload(struct bpf_object *obj)
4751 for (i = 0; i < obj->nr_maps; i++)
4752 zclose(obj->maps[i].fd);
4754 for (i = 0; i < obj->nr_programs; i++)
4755 bpf_program__unload(&obj->programs[i]);
4760 static int bpf_object__sanitize_maps(struct bpf_object *obj)
4764 bpf_object__for_each_map(m, obj) {
4765 if (!bpf_map__is_internal(m))
4767 if (!obj->caps.global_data) {
4768 pr_warn("kernel doesn't support global data\n");
4771 if (!obj->caps.array_mmap)
4772 m->def.map_flags ^= BPF_F_MMAPABLE;
4778 static int bpf_object__resolve_externs(struct bpf_object *obj,
4779 const char *extra_kconfig)
4781 bool need_config = false;
4782 struct extern_desc *ext;
4786 if (obj->nr_extern == 0)
4789 data = obj->maps[obj->kconfig_map_idx].mmaped;
4791 for (i = 0; i < obj->nr_extern; i++) {
4792 ext = &obj->externs[i];
4794 if (strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
4795 void *ext_val = data + ext->data_off;
4796 __u32 kver = get_kernel_version();
4799 pr_warn("failed to get kernel version\n");
4802 err = set_ext_value_num(ext, ext_val, kver);
4805 pr_debug("extern %s=0x%x\n", ext->name, kver);
4806 } else if (strncmp(ext->name, "CONFIG_", 7) == 0) {
4809 pr_warn("unrecognized extern '%s'\n", ext->name);
4813 if (need_config && extra_kconfig) {
4814 err = bpf_object__read_kconfig_mem(obj, extra_kconfig, data);
4817 need_config = false;
4818 for (i = 0; i < obj->nr_extern; i++) {
4819 ext = &obj->externs[i];
4827 err = bpf_object__read_kconfig_file(obj, data);
4831 for (i = 0; i < obj->nr_extern; i++) {
4832 ext = &obj->externs[i];
4834 if (!ext->is_set && !ext->is_weak) {
4835 pr_warn("extern %s (strong) not resolved\n", ext->name);
4837 } else if (!ext->is_set) {
4838 pr_debug("extern %s (weak) not resolved, defaulting to zero\n",
4846 int bpf_object__load_xattr(struct bpf_object_load_attr *attr)
4848 struct bpf_object *obj;
4858 pr_warn("object should not be loaded twice\n");
4864 err = bpf_object__probe_caps(obj);
4865 err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
4866 err = err ? : bpf_object__sanitize_and_load_btf(obj);
4867 err = err ? : bpf_object__sanitize_maps(obj);
4868 err = err ? : bpf_object__create_maps(obj);
4869 err = err ? : bpf_object__relocate(obj, attr->target_btf_path);
4870 err = err ? : bpf_object__load_progs(obj, attr->log_level);
4876 /* unpin any maps that were auto-pinned during load */
4877 for (i = 0; i < obj->nr_maps; i++)
4878 if (obj->maps[i].pinned && !obj->maps[i].reused)
4879 bpf_map__unpin(&obj->maps[i], NULL);
4881 bpf_object__unload(obj);
4882 pr_warn("failed to load object '%s'\n", obj->path);
4886 int bpf_object__load(struct bpf_object *obj)
4888 struct bpf_object_load_attr attr = {
4892 return bpf_object__load_xattr(&attr);
4895 static int make_parent_dir(const char *path)
4897 char *cp, errmsg[STRERR_BUFSIZE];
4901 dname = strdup(path);
4905 dir = dirname(dname);
4906 if (mkdir(dir, 0700) && errno != EEXIST)
4911 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
4912 pr_warn("failed to mkdir %s: %s\n", path, cp);
4917 static int check_path(const char *path)
4919 char *cp, errmsg[STRERR_BUFSIZE];
4920 struct statfs st_fs;
4927 dname = strdup(path);
4931 dir = dirname(dname);
4932 if (statfs(dir, &st_fs)) {
4933 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
4934 pr_warn("failed to statfs %s: %s\n", dir, cp);
4939 if (!err && st_fs.f_type != BPF_FS_MAGIC) {
4940 pr_warn("specified path %s is not on BPF FS\n", path);
4947 int bpf_program__pin_instance(struct bpf_program *prog, const char *path,
4950 char *cp, errmsg[STRERR_BUFSIZE];
4953 err = make_parent_dir(path);
4957 err = check_path(path);
4962 pr_warn("invalid program pointer\n");
4966 if (instance < 0 || instance >= prog->instances.nr) {
4967 pr_warn("invalid prog instance %d of prog %s (max %d)\n",
4968 instance, prog->section_name, prog->instances.nr);
4972 if (bpf_obj_pin(prog->instances.fds[instance], path)) {
4973 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
4974 pr_warn("failed to pin program: %s\n", cp);
4977 pr_debug("pinned program '%s'\n", path);
4982 int bpf_program__unpin_instance(struct bpf_program *prog, const char *path,
4987 err = check_path(path);
4992 pr_warn("invalid program pointer\n");
4996 if (instance < 0 || instance >= prog->instances.nr) {
4997 pr_warn("invalid prog instance %d of prog %s (max %d)\n",
4998 instance, prog->section_name, prog->instances.nr);
5005 pr_debug("unpinned program '%s'\n", path);
5010 int bpf_program__pin(struct bpf_program *prog, const char *path)
5014 err = make_parent_dir(path);
5018 err = check_path(path);
5023 pr_warn("invalid program pointer\n");
5027 if (prog->instances.nr <= 0) {
5028 pr_warn("no instances of prog %s to pin\n",
5029 prog->section_name);
5033 if (prog->instances.nr == 1) {
5034 /* don't create subdirs when pinning single instance */
5035 return bpf_program__pin_instance(prog, path, 0);
5038 for (i = 0; i < prog->instances.nr; i++) {
5042 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
5046 } else if (len >= PATH_MAX) {
5047 err = -ENAMETOOLONG;
5051 err = bpf_program__pin_instance(prog, buf, i);
5059 for (i = i - 1; i >= 0; i--) {
5063 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
5066 else if (len >= PATH_MAX)
5069 bpf_program__unpin_instance(prog, buf, i);
5077 int bpf_program__unpin(struct bpf_program *prog, const char *path)
5081 err = check_path(path);
5086 pr_warn("invalid program pointer\n");
5090 if (prog->instances.nr <= 0) {
5091 pr_warn("no instances of prog %s to pin\n",
5092 prog->section_name);
5096 if (prog->instances.nr == 1) {
5097 /* don't create subdirs when pinning single instance */
5098 return bpf_program__unpin_instance(prog, path, 0);
5101 for (i = 0; i < prog->instances.nr; i++) {
5105 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
5108 else if (len >= PATH_MAX)
5109 return -ENAMETOOLONG;
5111 err = bpf_program__unpin_instance(prog, buf, i);
5123 int bpf_map__pin(struct bpf_map *map, const char *path)
5125 char *cp, errmsg[STRERR_BUFSIZE];
5129 pr_warn("invalid map pointer\n");
5133 if (map->pin_path) {
5134 if (path && strcmp(path, map->pin_path)) {
5135 pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
5136 bpf_map__name(map), map->pin_path, path);
5138 } else if (map->pinned) {
5139 pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
5140 bpf_map__name(map), map->pin_path);
5145 pr_warn("missing a path to pin map '%s' at\n",
5146 bpf_map__name(map));
5148 } else if (map->pinned) {
5149 pr_warn("map '%s' already pinned\n", bpf_map__name(map));
5153 map->pin_path = strdup(path);
5154 if (!map->pin_path) {
5160 err = make_parent_dir(map->pin_path);
5164 err = check_path(map->pin_path);
5168 if (bpf_obj_pin(map->fd, map->pin_path)) {
5174 pr_debug("pinned map '%s'\n", map->pin_path);
5179 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
5180 pr_warn("failed to pin map: %s\n", cp);
5184 int bpf_map__unpin(struct bpf_map *map, const char *path)
5189 pr_warn("invalid map pointer\n");
5193 if (map->pin_path) {
5194 if (path && strcmp(path, map->pin_path)) {
5195 pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
5196 bpf_map__name(map), map->pin_path, path);
5199 path = map->pin_path;
5201 pr_warn("no path to unpin map '%s' from\n",
5202 bpf_map__name(map));
5206 err = check_path(path);
5214 map->pinned = false;
5215 pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
5220 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
5230 free(map->pin_path);
5231 map->pin_path = new;
5235 const char *bpf_map__get_pin_path(const struct bpf_map *map)
5237 return map->pin_path;
5240 bool bpf_map__is_pinned(const struct bpf_map *map)
5245 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
5247 struct bpf_map *map;
5254 pr_warn("object not yet loaded; load it first\n");
5258 bpf_object__for_each_map(map, obj) {
5259 char *pin_path = NULL;
5265 len = snprintf(buf, PATH_MAX, "%s/%s", path,
5266 bpf_map__name(map));
5269 goto err_unpin_maps;
5270 } else if (len >= PATH_MAX) {
5271 err = -ENAMETOOLONG;
5272 goto err_unpin_maps;
5275 } else if (!map->pin_path) {
5279 err = bpf_map__pin(map, pin_path);
5281 goto err_unpin_maps;
5287 while ((map = bpf_map__prev(map, obj))) {
5291 bpf_map__unpin(map, NULL);
5297 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
5299 struct bpf_map *map;
5305 bpf_object__for_each_map(map, obj) {
5306 char *pin_path = NULL;
5312 len = snprintf(buf, PATH_MAX, "%s/%s", path,
5313 bpf_map__name(map));
5316 else if (len >= PATH_MAX)
5317 return -ENAMETOOLONG;
5319 } else if (!map->pin_path) {
5323 err = bpf_map__unpin(map, pin_path);
5331 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
5333 struct bpf_program *prog;
5340 pr_warn("object not yet loaded; load it first\n");
5344 bpf_object__for_each_program(prog, obj) {
5348 len = snprintf(buf, PATH_MAX, "%s/%s", path,
5352 goto err_unpin_programs;
5353 } else if (len >= PATH_MAX) {
5354 err = -ENAMETOOLONG;
5355 goto err_unpin_programs;
5358 err = bpf_program__pin(prog, buf);
5360 goto err_unpin_programs;
5366 while ((prog = bpf_program__prev(prog, obj))) {
5370 len = snprintf(buf, PATH_MAX, "%s/%s", path,
5374 else if (len >= PATH_MAX)
5377 bpf_program__unpin(prog, buf);
5383 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
5385 struct bpf_program *prog;
5391 bpf_object__for_each_program(prog, obj) {
5395 len = snprintf(buf, PATH_MAX, "%s/%s", path,
5399 else if (len >= PATH_MAX)
5400 return -ENAMETOOLONG;
5402 err = bpf_program__unpin(prog, buf);
5410 int bpf_object__pin(struct bpf_object *obj, const char *path)
5414 err = bpf_object__pin_maps(obj, path);
5418 err = bpf_object__pin_programs(obj, path);
5420 bpf_object__unpin_maps(obj, path);
5427 void bpf_object__close(struct bpf_object *obj)
5434 if (obj->clear_priv)
5435 obj->clear_priv(obj, obj->priv);
5437 bpf_object__elf_finish(obj);
5438 bpf_object__unload(obj);
5439 btf__free(obj->btf);
5440 btf_ext__free(obj->btf_ext);
5442 for (i = 0; i < obj->nr_maps; i++) {
5443 struct bpf_map *map = &obj->maps[i];
5445 if (map->clear_priv)
5446 map->clear_priv(map, map->priv);
5448 map->clear_priv = NULL;
5451 munmap(map->mmaped, bpf_map_mmap_sz(map));
5456 zfree(&map->pin_path);
5459 zfree(&obj->kconfig);
5460 zfree(&obj->externs);
5466 if (obj->programs && obj->nr_programs) {
5467 for (i = 0; i < obj->nr_programs; i++)
5468 bpf_program__exit(&obj->programs[i]);
5470 zfree(&obj->programs);
5472 list_del(&obj->list);
5477 bpf_object__next(struct bpf_object *prev)
5479 struct bpf_object *next;
5482 next = list_first_entry(&bpf_objects_list,
5486 next = list_next_entry(prev, list);
5488 /* Empty list is noticed here so don't need checking on entry. */
5489 if (&next->list == &bpf_objects_list)
5495 const char *bpf_object__name(const struct bpf_object *obj)
5497 return obj ? obj->name : ERR_PTR(-EINVAL);
5500 unsigned int bpf_object__kversion(const struct bpf_object *obj)
5502 return obj ? obj->kern_version : 0;
5505 struct btf *bpf_object__btf(const struct bpf_object *obj)
5507 return obj ? obj->btf : NULL;
5510 int bpf_object__btf_fd(const struct bpf_object *obj)
5512 return obj->btf ? btf__fd(obj->btf) : -1;
5515 int bpf_object__set_priv(struct bpf_object *obj, void *priv,
5516 bpf_object_clear_priv_t clear_priv)
5518 if (obj->priv && obj->clear_priv)
5519 obj->clear_priv(obj, obj->priv);
5522 obj->clear_priv = clear_priv;
5526 void *bpf_object__priv(const struct bpf_object *obj)
5528 return obj ? obj->priv : ERR_PTR(-EINVAL);
5531 static struct bpf_program *
5532 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
5535 size_t nr_programs = obj->nr_programs;
5542 /* Iter from the beginning */
5543 return forward ? &obj->programs[0] :
5544 &obj->programs[nr_programs - 1];
5546 if (p->obj != obj) {
5547 pr_warn("error: program handler doesn't match object\n");
5551 idx = (p - obj->programs) + (forward ? 1 : -1);
5552 if (idx >= obj->nr_programs || idx < 0)
5554 return &obj->programs[idx];
5557 struct bpf_program *
5558 bpf_program__next(struct bpf_program *prev, const struct bpf_object *obj)
5560 struct bpf_program *prog = prev;
5563 prog = __bpf_program__iter(prog, obj, true);
5564 } while (prog && bpf_program__is_function_storage(prog, obj));
5569 struct bpf_program *
5570 bpf_program__prev(struct bpf_program *next, const struct bpf_object *obj)
5572 struct bpf_program *prog = next;
5575 prog = __bpf_program__iter(prog, obj, false);
5576 } while (prog && bpf_program__is_function_storage(prog, obj));
5581 int bpf_program__set_priv(struct bpf_program *prog, void *priv,
5582 bpf_program_clear_priv_t clear_priv)
5584 if (prog->priv && prog->clear_priv)
5585 prog->clear_priv(prog, prog->priv);
5588 prog->clear_priv = clear_priv;
5592 void *bpf_program__priv(const struct bpf_program *prog)
5594 return prog ? prog->priv : ERR_PTR(-EINVAL);
5597 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
5599 prog->prog_ifindex = ifindex;
5602 const char *bpf_program__name(const struct bpf_program *prog)
5607 const char *bpf_program__title(const struct bpf_program *prog, bool needs_copy)
5611 title = prog->section_name;
5613 title = strdup(title);
5615 pr_warn("failed to strdup program title\n");
5616 return ERR_PTR(-ENOMEM);
5623 int bpf_program__fd(const struct bpf_program *prog)
5625 return bpf_program__nth_fd(prog, 0);
5628 size_t bpf_program__size(const struct bpf_program *prog)
5630 return prog->insns_cnt * sizeof(struct bpf_insn);
5633 int bpf_program__set_prep(struct bpf_program *prog, int nr_instances,
5634 bpf_program_prep_t prep)
5638 if (nr_instances <= 0 || !prep)
5641 if (prog->instances.nr > 0 || prog->instances.fds) {
5642 pr_warn("Can't set pre-processor after loading\n");
5646 instances_fds = malloc(sizeof(int) * nr_instances);
5647 if (!instances_fds) {
5648 pr_warn("alloc memory failed for fds\n");
5652 /* fill all fd with -1 */
5653 memset(instances_fds, -1, sizeof(int) * nr_instances);
5655 prog->instances.nr = nr_instances;
5656 prog->instances.fds = instances_fds;
5657 prog->preprocessor = prep;
5661 int bpf_program__nth_fd(const struct bpf_program *prog, int n)
5668 if (n >= prog->instances.nr || n < 0) {
5669 pr_warn("Can't get the %dth fd from program %s: only %d instances\n",
5670 n, prog->section_name, prog->instances.nr);
5674 fd = prog->instances.fds[n];
5676 pr_warn("%dth instance of program '%s' is invalid\n",
5677 n, prog->section_name);
5684 enum bpf_prog_type bpf_program__get_type(struct bpf_program *prog)
5689 void bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
5694 static bool bpf_program__is_type(const struct bpf_program *prog,
5695 enum bpf_prog_type type)
5697 return prog ? (prog->type == type) : false;
5700 #define BPF_PROG_TYPE_FNS(NAME, TYPE) \
5701 int bpf_program__set_##NAME(struct bpf_program *prog) \
5705 bpf_program__set_type(prog, TYPE); \
5709 bool bpf_program__is_##NAME(const struct bpf_program *prog) \
5711 return bpf_program__is_type(prog, TYPE); \
5714 BPF_PROG_TYPE_FNS(socket_filter, BPF_PROG_TYPE_SOCKET_FILTER);
5715 BPF_PROG_TYPE_FNS(kprobe, BPF_PROG_TYPE_KPROBE);
5716 BPF_PROG_TYPE_FNS(sched_cls, BPF_PROG_TYPE_SCHED_CLS);
5717 BPF_PROG_TYPE_FNS(sched_act, BPF_PROG_TYPE_SCHED_ACT);
5718 BPF_PROG_TYPE_FNS(tracepoint, BPF_PROG_TYPE_TRACEPOINT);
5719 BPF_PROG_TYPE_FNS(raw_tracepoint, BPF_PROG_TYPE_RAW_TRACEPOINT);
5720 BPF_PROG_TYPE_FNS(xdp, BPF_PROG_TYPE_XDP);
5721 BPF_PROG_TYPE_FNS(perf_event, BPF_PROG_TYPE_PERF_EVENT);
5722 BPF_PROG_TYPE_FNS(tracing, BPF_PROG_TYPE_TRACING);
5724 enum bpf_attach_type
5725 bpf_program__get_expected_attach_type(struct bpf_program *prog)
5727 return prog->expected_attach_type;
5730 void bpf_program__set_expected_attach_type(struct bpf_program *prog,
5731 enum bpf_attach_type type)
5733 prog->expected_attach_type = type;
5736 #define BPF_PROG_SEC_IMPL(string, ptype, eatype, is_attachable, btf, atype) \
5737 { string, sizeof(string) - 1, ptype, eatype, is_attachable, btf, atype }
5739 /* Programs that can NOT be attached. */
5740 #define BPF_PROG_SEC(string, ptype) BPF_PROG_SEC_IMPL(string, ptype, 0, 0, 0, 0)
5742 /* Programs that can be attached. */
5743 #define BPF_APROG_SEC(string, ptype, atype) \
5744 BPF_PROG_SEC_IMPL(string, ptype, 0, 1, 0, atype)
5746 /* Programs that must specify expected attach type at load time. */
5747 #define BPF_EAPROG_SEC(string, ptype, eatype) \
5748 BPF_PROG_SEC_IMPL(string, ptype, eatype, 1, 0, eatype)
5750 /* Programs that use BTF to identify attach point */
5751 #define BPF_PROG_BTF(string, ptype, eatype) \
5752 BPF_PROG_SEC_IMPL(string, ptype, eatype, 0, 1, 0)
5754 /* Programs that can be attached but attach type can't be identified by section
5755 * name. Kept for backward compatibility.
5757 #define BPF_APROG_COMPAT(string, ptype) BPF_PROG_SEC(string, ptype)
5759 #define SEC_DEF(sec_pfx, ptype, ...) { \
5761 .len = sizeof(sec_pfx) - 1, \
5762 .prog_type = BPF_PROG_TYPE_##ptype, \
5768 typedef struct bpf_link *(*attach_fn_t)(const struct bpf_sec_def *sec,
5769 struct bpf_program *prog);
5771 static struct bpf_link *attach_kprobe(const struct bpf_sec_def *sec,
5772 struct bpf_program *prog);
5773 static struct bpf_link *attach_tp(const struct bpf_sec_def *sec,
5774 struct bpf_program *prog);
5775 static struct bpf_link *attach_raw_tp(const struct bpf_sec_def *sec,
5776 struct bpf_program *prog);
5777 static struct bpf_link *attach_trace(const struct bpf_sec_def *sec,
5778 struct bpf_program *prog);
5780 struct bpf_sec_def {
5783 enum bpf_prog_type prog_type;
5784 enum bpf_attach_type expected_attach_type;
5787 enum bpf_attach_type attach_type;
5788 attach_fn_t attach_fn;
5791 static const struct bpf_sec_def section_defs[] = {
5792 BPF_PROG_SEC("socket", BPF_PROG_TYPE_SOCKET_FILTER),
5793 BPF_PROG_SEC("sk_reuseport", BPF_PROG_TYPE_SK_REUSEPORT),
5794 SEC_DEF("kprobe/", KPROBE,
5795 .attach_fn = attach_kprobe),
5796 BPF_PROG_SEC("uprobe/", BPF_PROG_TYPE_KPROBE),
5797 SEC_DEF("kretprobe/", KPROBE,
5798 .attach_fn = attach_kprobe),
5799 BPF_PROG_SEC("uretprobe/", BPF_PROG_TYPE_KPROBE),
5800 BPF_PROG_SEC("classifier", BPF_PROG_TYPE_SCHED_CLS),
5801 BPF_PROG_SEC("action", BPF_PROG_TYPE_SCHED_ACT),
5802 SEC_DEF("tracepoint/", TRACEPOINT,
5803 .attach_fn = attach_tp),
5804 SEC_DEF("tp/", TRACEPOINT,
5805 .attach_fn = attach_tp),
5806 SEC_DEF("raw_tracepoint/", RAW_TRACEPOINT,
5807 .attach_fn = attach_raw_tp),
5808 SEC_DEF("raw_tp/", RAW_TRACEPOINT,
5809 .attach_fn = attach_raw_tp),
5810 SEC_DEF("tp_btf/", TRACING,
5811 .expected_attach_type = BPF_TRACE_RAW_TP,
5812 .is_attach_btf = true,
5813 .attach_fn = attach_trace),
5814 SEC_DEF("fentry/", TRACING,
5815 .expected_attach_type = BPF_TRACE_FENTRY,
5816 .is_attach_btf = true,
5817 .attach_fn = attach_trace),
5818 SEC_DEF("fexit/", TRACING,
5819 .expected_attach_type = BPF_TRACE_FEXIT,
5820 .is_attach_btf = true,
5821 .attach_fn = attach_trace),
5822 BPF_PROG_SEC("xdp", BPF_PROG_TYPE_XDP),
5823 BPF_PROG_SEC("perf_event", BPF_PROG_TYPE_PERF_EVENT),
5824 BPF_PROG_SEC("lwt_in", BPF_PROG_TYPE_LWT_IN),
5825 BPF_PROG_SEC("lwt_out", BPF_PROG_TYPE_LWT_OUT),
5826 BPF_PROG_SEC("lwt_xmit", BPF_PROG_TYPE_LWT_XMIT),
5827 BPF_PROG_SEC("lwt_seg6local", BPF_PROG_TYPE_LWT_SEG6LOCAL),
5828 BPF_APROG_SEC("cgroup_skb/ingress", BPF_PROG_TYPE_CGROUP_SKB,
5829 BPF_CGROUP_INET_INGRESS),
5830 BPF_APROG_SEC("cgroup_skb/egress", BPF_PROG_TYPE_CGROUP_SKB,
5831 BPF_CGROUP_INET_EGRESS),
5832 BPF_APROG_COMPAT("cgroup/skb", BPF_PROG_TYPE_CGROUP_SKB),
5833 BPF_APROG_SEC("cgroup/sock", BPF_PROG_TYPE_CGROUP_SOCK,
5834 BPF_CGROUP_INET_SOCK_CREATE),
5835 BPF_EAPROG_SEC("cgroup/post_bind4", BPF_PROG_TYPE_CGROUP_SOCK,
5836 BPF_CGROUP_INET4_POST_BIND),
5837 BPF_EAPROG_SEC("cgroup/post_bind6", BPF_PROG_TYPE_CGROUP_SOCK,
5838 BPF_CGROUP_INET6_POST_BIND),
5839 BPF_APROG_SEC("cgroup/dev", BPF_PROG_TYPE_CGROUP_DEVICE,
5841 BPF_APROG_SEC("sockops", BPF_PROG_TYPE_SOCK_OPS,
5842 BPF_CGROUP_SOCK_OPS),
5843 BPF_APROG_SEC("sk_skb/stream_parser", BPF_PROG_TYPE_SK_SKB,
5844 BPF_SK_SKB_STREAM_PARSER),
5845 BPF_APROG_SEC("sk_skb/stream_verdict", BPF_PROG_TYPE_SK_SKB,
5846 BPF_SK_SKB_STREAM_VERDICT),
5847 BPF_APROG_COMPAT("sk_skb", BPF_PROG_TYPE_SK_SKB),
5848 BPF_APROG_SEC("sk_msg", BPF_PROG_TYPE_SK_MSG,
5849 BPF_SK_MSG_VERDICT),
5850 BPF_APROG_SEC("lirc_mode2", BPF_PROG_TYPE_LIRC_MODE2,
5852 BPF_APROG_SEC("flow_dissector", BPF_PROG_TYPE_FLOW_DISSECTOR,
5853 BPF_FLOW_DISSECTOR),
5854 BPF_EAPROG_SEC("cgroup/bind4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
5855 BPF_CGROUP_INET4_BIND),
5856 BPF_EAPROG_SEC("cgroup/bind6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
5857 BPF_CGROUP_INET6_BIND),
5858 BPF_EAPROG_SEC("cgroup/connect4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
5859 BPF_CGROUP_INET4_CONNECT),
5860 BPF_EAPROG_SEC("cgroup/connect6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
5861 BPF_CGROUP_INET6_CONNECT),
5862 BPF_EAPROG_SEC("cgroup/sendmsg4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
5863 BPF_CGROUP_UDP4_SENDMSG),
5864 BPF_EAPROG_SEC("cgroup/sendmsg6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
5865 BPF_CGROUP_UDP6_SENDMSG),
5866 BPF_EAPROG_SEC("cgroup/recvmsg4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
5867 BPF_CGROUP_UDP4_RECVMSG),
5868 BPF_EAPROG_SEC("cgroup/recvmsg6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
5869 BPF_CGROUP_UDP6_RECVMSG),
5870 BPF_EAPROG_SEC("cgroup/sysctl", BPF_PROG_TYPE_CGROUP_SYSCTL,
5872 BPF_EAPROG_SEC("cgroup/getsockopt", BPF_PROG_TYPE_CGROUP_SOCKOPT,
5873 BPF_CGROUP_GETSOCKOPT),
5874 BPF_EAPROG_SEC("cgroup/setsockopt", BPF_PROG_TYPE_CGROUP_SOCKOPT,
5875 BPF_CGROUP_SETSOCKOPT),
5878 #undef BPF_PROG_SEC_IMPL
5880 #undef BPF_APROG_SEC
5881 #undef BPF_EAPROG_SEC
5882 #undef BPF_APROG_COMPAT
5885 #define MAX_TYPE_NAME_SIZE 32
5887 static const struct bpf_sec_def *find_sec_def(const char *sec_name)
5889 int i, n = ARRAY_SIZE(section_defs);
5891 for (i = 0; i < n; i++) {
5892 if (strncmp(sec_name,
5893 section_defs[i].sec, section_defs[i].len))
5895 return §ion_defs[i];
5900 static char *libbpf_get_type_names(bool attach_type)
5902 int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
5910 /* Forge string buf with all available names */
5911 for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
5912 if (attach_type && !section_defs[i].is_attachable)
5915 if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
5920 strcat(buf, section_defs[i].sec);
5926 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
5927 enum bpf_attach_type *expected_attach_type)
5929 const struct bpf_sec_def *sec_def;
5935 sec_def = find_sec_def(name);
5937 *prog_type = sec_def->prog_type;
5938 *expected_attach_type = sec_def->expected_attach_type;
5942 pr_debug("failed to guess program type from ELF section '%s'\n", name);
5943 type_names = libbpf_get_type_names(false);
5944 if (type_names != NULL) {
5945 pr_debug("supported section(type) names are:%s\n", type_names);
5952 #define BTF_PREFIX "btf_trace_"
5953 int libbpf_find_vmlinux_btf_id(const char *name,
5954 enum bpf_attach_type attach_type)
5956 struct btf *btf = bpf_core_find_kernel_btf();
5957 char raw_tp_btf[128] = BTF_PREFIX;
5958 char *dst = raw_tp_btf + sizeof(BTF_PREFIX) - 1;
5959 const char *btf_name;
5964 pr_warn("vmlinux BTF is not found\n");
5968 if (attach_type == BPF_TRACE_RAW_TP) {
5969 /* prepend "btf_trace_" prefix per kernel convention */
5970 strncat(dst, name, sizeof(raw_tp_btf) - sizeof(BTF_PREFIX));
5971 btf_name = raw_tp_btf;
5972 kind = BTF_KIND_TYPEDEF;
5975 kind = BTF_KIND_FUNC;
5977 err = btf__find_by_name_kind(btf, btf_name, kind);
5982 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd)
5984 struct bpf_prog_info_linear *info_linear;
5985 struct bpf_prog_info *info;
5986 struct btf *btf = NULL;
5989 info_linear = bpf_program__get_prog_info_linear(attach_prog_fd, 0);
5990 if (IS_ERR_OR_NULL(info_linear)) {
5991 pr_warn("failed get_prog_info_linear for FD %d\n",
5995 info = &info_linear->info;
5996 if (!info->btf_id) {
5997 pr_warn("The target program doesn't have BTF\n");
6000 if (btf__get_from_id(info->btf_id, &btf)) {
6001 pr_warn("Failed to get BTF of the program\n");
6004 err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
6007 pr_warn("%s is not found in prog's BTF\n", name);
6015 static int libbpf_find_attach_btf_id(const char *name,
6016 enum bpf_attach_type attach_type,
6017 __u32 attach_prog_fd)
6024 for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
6025 if (!section_defs[i].is_attach_btf)
6027 if (strncmp(name, section_defs[i].sec, section_defs[i].len))
6030 err = libbpf_find_prog_btf_id(name + section_defs[i].len,
6033 err = libbpf_find_vmlinux_btf_id(name + section_defs[i].len,
6036 pr_warn("%s is not found in vmlinux BTF\n", name);
6039 pr_warn("failed to identify btf_id based on ELF section name '%s'\n", name);
6043 int libbpf_attach_type_by_name(const char *name,
6044 enum bpf_attach_type *attach_type)
6052 for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
6053 if (strncmp(name, section_defs[i].sec, section_defs[i].len))
6055 if (!section_defs[i].is_attachable)
6057 *attach_type = section_defs[i].attach_type;
6060 pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
6061 type_names = libbpf_get_type_names(true);
6062 if (type_names != NULL) {
6063 pr_debug("attachable section(type) names are:%s\n", type_names);
6070 int bpf_map__fd(const struct bpf_map *map)
6072 return map ? map->fd : -EINVAL;
6075 const struct bpf_map_def *bpf_map__def(const struct bpf_map *map)
6077 return map ? &map->def : ERR_PTR(-EINVAL);
6080 const char *bpf_map__name(const struct bpf_map *map)
6082 return map ? map->name : NULL;
6085 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
6087 return map ? map->btf_key_type_id : 0;
6090 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
6092 return map ? map->btf_value_type_id : 0;
6095 int bpf_map__set_priv(struct bpf_map *map, void *priv,
6096 bpf_map_clear_priv_t clear_priv)
6102 if (map->clear_priv)
6103 map->clear_priv(map, map->priv);
6107 map->clear_priv = clear_priv;
6111 void *bpf_map__priv(const struct bpf_map *map)
6113 return map ? map->priv : ERR_PTR(-EINVAL);
6116 bool bpf_map__is_offload_neutral(const struct bpf_map *map)
6118 return map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY;
6121 bool bpf_map__is_internal(const struct bpf_map *map)
6123 return map->libbpf_type != LIBBPF_MAP_UNSPEC;
6126 void bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
6128 map->map_ifindex = ifindex;
6131 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
6133 if (!bpf_map_type__is_map_in_map(map->def.type)) {
6134 pr_warn("error: unsupported map type\n");
6137 if (map->inner_map_fd != -1) {
6138 pr_warn("error: inner_map_fd already specified\n");
6141 map->inner_map_fd = fd;
6145 static struct bpf_map *
6146 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
6149 struct bpf_map *s, *e;
6151 if (!obj || !obj->maps)
6155 e = obj->maps + obj->nr_maps;
6157 if ((m < s) || (m >= e)) {
6158 pr_warn("error in %s: map handler doesn't belong to object\n",
6163 idx = (m - obj->maps) + i;
6164 if (idx >= obj->nr_maps || idx < 0)
6166 return &obj->maps[idx];
6170 bpf_map__next(const struct bpf_map *prev, const struct bpf_object *obj)
6175 return __bpf_map__iter(prev, obj, 1);
6179 bpf_map__prev(const struct bpf_map *next, const struct bpf_object *obj)
6184 return obj->maps + obj->nr_maps - 1;
6187 return __bpf_map__iter(next, obj, -1);
6191 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
6193 struct bpf_map *pos;
6195 bpf_object__for_each_map(pos, obj) {
6196 if (pos->name && !strcmp(pos->name, name))
6203 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
6205 return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
6209 bpf_object__find_map_by_offset(struct bpf_object *obj, size_t offset)
6211 return ERR_PTR(-ENOTSUP);
6214 long libbpf_get_error(const void *ptr)
6216 return PTR_ERR_OR_ZERO(ptr);
6219 int bpf_prog_load(const char *file, enum bpf_prog_type type,
6220 struct bpf_object **pobj, int *prog_fd)
6222 struct bpf_prog_load_attr attr;
6224 memset(&attr, 0, sizeof(struct bpf_prog_load_attr));
6226 attr.prog_type = type;
6227 attr.expected_attach_type = 0;
6229 return bpf_prog_load_xattr(&attr, pobj, prog_fd);
6232 int bpf_prog_load_xattr(const struct bpf_prog_load_attr *attr,
6233 struct bpf_object **pobj, int *prog_fd)
6235 struct bpf_object_open_attr open_attr = {};
6236 struct bpf_program *prog, *first_prog = NULL;
6237 struct bpf_object *obj;
6238 struct bpf_map *map;
6246 open_attr.file = attr->file;
6247 open_attr.prog_type = attr->prog_type;
6249 obj = bpf_object__open_xattr(&open_attr);
6250 if (IS_ERR_OR_NULL(obj))
6253 bpf_object__for_each_program(prog, obj) {
6254 enum bpf_attach_type attach_type = attr->expected_attach_type;
6256 * to preserve backwards compatibility, bpf_prog_load treats
6257 * attr->prog_type, if specified, as an override to whatever
6258 * bpf_object__open guessed
6260 if (attr->prog_type != BPF_PROG_TYPE_UNSPEC) {
6261 bpf_program__set_type(prog, attr->prog_type);
6262 bpf_program__set_expected_attach_type(prog,
6265 if (bpf_program__get_type(prog) == BPF_PROG_TYPE_UNSPEC) {
6267 * we haven't guessed from section name and user
6268 * didn't provide a fallback type, too bad...
6270 bpf_object__close(obj);
6274 prog->prog_ifindex = attr->ifindex;
6275 prog->log_level = attr->log_level;
6276 prog->prog_flags = attr->prog_flags;
6281 bpf_object__for_each_map(map, obj) {
6282 if (!bpf_map__is_offload_neutral(map))
6283 map->map_ifindex = attr->ifindex;
6287 pr_warn("object file doesn't contain bpf program\n");
6288 bpf_object__close(obj);
6292 err = bpf_object__load(obj);
6294 bpf_object__close(obj);
6299 *prog_fd = bpf_program__fd(first_prog);
6304 int (*detach)(struct bpf_link *link);
6305 int (*destroy)(struct bpf_link *link);
6309 /* Release "ownership" of underlying BPF resource (typically, BPF program
6310 * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
6311 * link, when destructed through bpf_link__destroy() call won't attempt to
6312 * detach/unregisted that BPF resource. This is useful in situations where,
6313 * say, attached BPF program has to outlive userspace program that attached it
6314 * in the system. Depending on type of BPF program, though, there might be
6315 * additional steps (like pinning BPF program in BPF FS) necessary to ensure
6316 * exit of userspace program doesn't trigger automatic detachment and clean up
6317 * inside the kernel.
6319 void bpf_link__disconnect(struct bpf_link *link)
6321 link->disconnected = true;
6324 int bpf_link__destroy(struct bpf_link *link)
6331 if (!link->disconnected && link->detach)
6332 err = link->detach(link);
6334 link->destroy(link);
6340 struct bpf_link_fd {
6341 struct bpf_link link; /* has to be at the top of struct */
6342 int fd; /* hook FD */
6345 static int bpf_link__detach_perf_event(struct bpf_link *link)
6347 struct bpf_link_fd *l = (void *)link;
6350 err = ioctl(l->fd, PERF_EVENT_IOC_DISABLE, 0);
6358 struct bpf_link *bpf_program__attach_perf_event(struct bpf_program *prog,
6361 char errmsg[STRERR_BUFSIZE];
6362 struct bpf_link_fd *link;
6366 pr_warn("program '%s': invalid perf event FD %d\n",
6367 bpf_program__title(prog, false), pfd);
6368 return ERR_PTR(-EINVAL);
6370 prog_fd = bpf_program__fd(prog);
6372 pr_warn("program '%s': can't attach BPF program w/o FD (did you load it?)\n",
6373 bpf_program__title(prog, false));
6374 return ERR_PTR(-EINVAL);
6377 link = calloc(1, sizeof(*link));
6379 return ERR_PTR(-ENOMEM);
6380 link->link.detach = &bpf_link__detach_perf_event;
6383 if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
6386 pr_warn("program '%s': failed to attach to pfd %d: %s\n",
6387 bpf_program__title(prog, false), pfd,
6388 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
6389 return ERR_PTR(err);
6391 if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
6394 pr_warn("program '%s': failed to enable pfd %d: %s\n",
6395 bpf_program__title(prog, false), pfd,
6396 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
6397 return ERR_PTR(err);
6399 return (struct bpf_link *)link;
6403 * this function is expected to parse integer in the range of [0, 2^31-1] from
6404 * given file using scanf format string fmt. If actual parsed value is
6405 * negative, the result might be indistinguishable from error
6407 static int parse_uint_from_file(const char *file, const char *fmt)
6409 char buf[STRERR_BUFSIZE];
6413 f = fopen(file, "r");
6416 pr_debug("failed to open '%s': %s\n", file,
6417 libbpf_strerror_r(err, buf, sizeof(buf)));
6420 err = fscanf(f, fmt, &ret);
6422 err = err == EOF ? -EIO : -errno;
6423 pr_debug("failed to parse '%s': %s\n", file,
6424 libbpf_strerror_r(err, buf, sizeof(buf)));
6432 static int determine_kprobe_perf_type(void)
6434 const char *file = "/sys/bus/event_source/devices/kprobe/type";
6436 return parse_uint_from_file(file, "%d\n");
6439 static int determine_uprobe_perf_type(void)
6441 const char *file = "/sys/bus/event_source/devices/uprobe/type";
6443 return parse_uint_from_file(file, "%d\n");
6446 static int determine_kprobe_retprobe_bit(void)
6448 const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
6450 return parse_uint_from_file(file, "config:%d\n");
6453 static int determine_uprobe_retprobe_bit(void)
6455 const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
6457 return parse_uint_from_file(file, "config:%d\n");
6460 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
6461 uint64_t offset, int pid)
6463 struct perf_event_attr attr = {};
6464 char errmsg[STRERR_BUFSIZE];
6467 type = uprobe ? determine_uprobe_perf_type()
6468 : determine_kprobe_perf_type();
6470 pr_warn("failed to determine %s perf type: %s\n",
6471 uprobe ? "uprobe" : "kprobe",
6472 libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
6476 int bit = uprobe ? determine_uprobe_retprobe_bit()
6477 : determine_kprobe_retprobe_bit();
6480 pr_warn("failed to determine %s retprobe bit: %s\n",
6481 uprobe ? "uprobe" : "kprobe",
6482 libbpf_strerror_r(bit, errmsg, sizeof(errmsg)));
6485 attr.config |= 1 << bit;
6487 attr.size = sizeof(attr);
6489 attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
6490 attr.config2 = offset; /* kprobe_addr or probe_offset */
6492 /* pid filter is meaningful only for uprobes */
6493 pfd = syscall(__NR_perf_event_open, &attr,
6494 pid < 0 ? -1 : pid /* pid */,
6495 pid == -1 ? 0 : -1 /* cpu */,
6496 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
6499 pr_warn("%s perf_event_open() failed: %s\n",
6500 uprobe ? "uprobe" : "kprobe",
6501 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
6507 struct bpf_link *bpf_program__attach_kprobe(struct bpf_program *prog,
6509 const char *func_name)
6511 char errmsg[STRERR_BUFSIZE];
6512 struct bpf_link *link;
6515 pfd = perf_event_open_probe(false /* uprobe */, retprobe, func_name,
6516 0 /* offset */, -1 /* pid */);
6518 pr_warn("program '%s': failed to create %s '%s' perf event: %s\n",
6519 bpf_program__title(prog, false),
6520 retprobe ? "kretprobe" : "kprobe", func_name,
6521 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
6522 return ERR_PTR(pfd);
6524 link = bpf_program__attach_perf_event(prog, pfd);
6527 err = PTR_ERR(link);
6528 pr_warn("program '%s': failed to attach to %s '%s': %s\n",
6529 bpf_program__title(prog, false),
6530 retprobe ? "kretprobe" : "kprobe", func_name,
6531 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
6537 static struct bpf_link *attach_kprobe(const struct bpf_sec_def *sec,
6538 struct bpf_program *prog)
6540 const char *func_name;
6543 func_name = bpf_program__title(prog, false) + sec->len;
6544 retprobe = strcmp(sec->sec, "kretprobe/") == 0;
6546 return bpf_program__attach_kprobe(prog, retprobe, func_name);
6549 struct bpf_link *bpf_program__attach_uprobe(struct bpf_program *prog,
6550 bool retprobe, pid_t pid,
6551 const char *binary_path,
6554 char errmsg[STRERR_BUFSIZE];
6555 struct bpf_link *link;
6558 pfd = perf_event_open_probe(true /* uprobe */, retprobe,
6559 binary_path, func_offset, pid);
6561 pr_warn("program '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
6562 bpf_program__title(prog, false),
6563 retprobe ? "uretprobe" : "uprobe",
6564 binary_path, func_offset,
6565 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
6566 return ERR_PTR(pfd);
6568 link = bpf_program__attach_perf_event(prog, pfd);
6571 err = PTR_ERR(link);
6572 pr_warn("program '%s': failed to attach to %s '%s:0x%zx': %s\n",
6573 bpf_program__title(prog, false),
6574 retprobe ? "uretprobe" : "uprobe",
6575 binary_path, func_offset,
6576 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
6582 static int determine_tracepoint_id(const char *tp_category,
6583 const char *tp_name)
6585 char file[PATH_MAX];
6588 ret = snprintf(file, sizeof(file),
6589 "/sys/kernel/debug/tracing/events/%s/%s/id",
6590 tp_category, tp_name);
6593 if (ret >= sizeof(file)) {
6594 pr_debug("tracepoint %s/%s path is too long\n",
6595 tp_category, tp_name);
6598 return parse_uint_from_file(file, "%d\n");
6601 static int perf_event_open_tracepoint(const char *tp_category,
6602 const char *tp_name)
6604 struct perf_event_attr attr = {};
6605 char errmsg[STRERR_BUFSIZE];
6606 int tp_id, pfd, err;
6608 tp_id = determine_tracepoint_id(tp_category, tp_name);
6610 pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
6611 tp_category, tp_name,
6612 libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
6616 attr.type = PERF_TYPE_TRACEPOINT;
6617 attr.size = sizeof(attr);
6618 attr.config = tp_id;
6620 pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
6621 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
6624 pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
6625 tp_category, tp_name,
6626 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
6632 struct bpf_link *bpf_program__attach_tracepoint(struct bpf_program *prog,
6633 const char *tp_category,
6634 const char *tp_name)
6636 char errmsg[STRERR_BUFSIZE];
6637 struct bpf_link *link;
6640 pfd = perf_event_open_tracepoint(tp_category, tp_name);
6642 pr_warn("program '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
6643 bpf_program__title(prog, false),
6644 tp_category, tp_name,
6645 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
6646 return ERR_PTR(pfd);
6648 link = bpf_program__attach_perf_event(prog, pfd);
6651 err = PTR_ERR(link);
6652 pr_warn("program '%s': failed to attach to tracepoint '%s/%s': %s\n",
6653 bpf_program__title(prog, false),
6654 tp_category, tp_name,
6655 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
6661 static struct bpf_link *attach_tp(const struct bpf_sec_def *sec,
6662 struct bpf_program *prog)
6664 char *sec_name, *tp_cat, *tp_name;
6665 struct bpf_link *link;
6667 sec_name = strdup(bpf_program__title(prog, false));
6669 return ERR_PTR(-ENOMEM);
6671 /* extract "tp/<category>/<name>" */
6672 tp_cat = sec_name + sec->len;
6673 tp_name = strchr(tp_cat, '/');
6675 link = ERR_PTR(-EINVAL);
6681 link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
6687 static int bpf_link__detach_fd(struct bpf_link *link)
6689 struct bpf_link_fd *l = (void *)link;
6691 return close(l->fd);
6694 struct bpf_link *bpf_program__attach_raw_tracepoint(struct bpf_program *prog,
6695 const char *tp_name)
6697 char errmsg[STRERR_BUFSIZE];
6698 struct bpf_link_fd *link;
6701 prog_fd = bpf_program__fd(prog);
6703 pr_warn("program '%s': can't attach before loaded\n",
6704 bpf_program__title(prog, false));
6705 return ERR_PTR(-EINVAL);
6708 link = calloc(1, sizeof(*link));
6710 return ERR_PTR(-ENOMEM);
6711 link->link.detach = &bpf_link__detach_fd;
6713 pfd = bpf_raw_tracepoint_open(tp_name, prog_fd);
6717 pr_warn("program '%s': failed to attach to raw tracepoint '%s': %s\n",
6718 bpf_program__title(prog, false), tp_name,
6719 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
6720 return ERR_PTR(pfd);
6723 return (struct bpf_link *)link;
6726 static struct bpf_link *attach_raw_tp(const struct bpf_sec_def *sec,
6727 struct bpf_program *prog)
6729 const char *tp_name = bpf_program__title(prog, false) + sec->len;
6731 return bpf_program__attach_raw_tracepoint(prog, tp_name);
6734 struct bpf_link *bpf_program__attach_trace(struct bpf_program *prog)
6736 char errmsg[STRERR_BUFSIZE];
6737 struct bpf_link_fd *link;
6740 prog_fd = bpf_program__fd(prog);
6742 pr_warn("program '%s': can't attach before loaded\n",
6743 bpf_program__title(prog, false));
6744 return ERR_PTR(-EINVAL);
6747 link = calloc(1, sizeof(*link));
6749 return ERR_PTR(-ENOMEM);
6750 link->link.detach = &bpf_link__detach_fd;
6752 pfd = bpf_raw_tracepoint_open(NULL, prog_fd);
6756 pr_warn("program '%s': failed to attach to trace: %s\n",
6757 bpf_program__title(prog, false),
6758 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
6759 return ERR_PTR(pfd);
6762 return (struct bpf_link *)link;
6765 static struct bpf_link *attach_trace(const struct bpf_sec_def *sec,
6766 struct bpf_program *prog)
6768 return bpf_program__attach_trace(prog);
6771 struct bpf_link *bpf_program__attach(struct bpf_program *prog)
6773 const struct bpf_sec_def *sec_def;
6775 sec_def = find_sec_def(bpf_program__title(prog, false));
6776 if (!sec_def || !sec_def->attach_fn)
6777 return ERR_PTR(-ESRCH);
6779 return sec_def->attach_fn(sec_def, prog);
6782 enum bpf_perf_event_ret
6783 bpf_perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
6784 void **copy_mem, size_t *copy_size,
6785 bpf_perf_event_print_t fn, void *private_data)
6787 struct perf_event_mmap_page *header = mmap_mem;
6788 __u64 data_head = ring_buffer_read_head(header);
6789 __u64 data_tail = header->data_tail;
6790 void *base = ((__u8 *)header) + page_size;
6791 int ret = LIBBPF_PERF_EVENT_CONT;
6792 struct perf_event_header *ehdr;
6795 while (data_head != data_tail) {
6796 ehdr = base + (data_tail & (mmap_size - 1));
6797 ehdr_size = ehdr->size;
6799 if (((void *)ehdr) + ehdr_size > base + mmap_size) {
6800 void *copy_start = ehdr;
6801 size_t len_first = base + mmap_size - copy_start;
6802 size_t len_secnd = ehdr_size - len_first;
6804 if (*copy_size < ehdr_size) {
6806 *copy_mem = malloc(ehdr_size);
6809 ret = LIBBPF_PERF_EVENT_ERROR;
6812 *copy_size = ehdr_size;
6815 memcpy(*copy_mem, copy_start, len_first);
6816 memcpy(*copy_mem + len_first, base, len_secnd);
6820 ret = fn(ehdr, private_data);
6821 data_tail += ehdr_size;
6822 if (ret != LIBBPF_PERF_EVENT_CONT)
6826 ring_buffer_write_tail(header, data_tail);
6832 struct perf_buffer_params {
6833 struct perf_event_attr *attr;
6834 /* if event_cb is specified, it takes precendence */
6835 perf_buffer_event_fn event_cb;
6836 /* sample_cb and lost_cb are higher-level common-case callbacks */
6837 perf_buffer_sample_fn sample_cb;
6838 perf_buffer_lost_fn lost_cb;
6845 struct perf_cpu_buf {
6846 struct perf_buffer *pb;
6847 void *base; /* mmap()'ed memory */
6848 void *buf; /* for reconstructing segmented data */
6855 struct perf_buffer {
6856 perf_buffer_event_fn event_cb;
6857 perf_buffer_sample_fn sample_cb;
6858 perf_buffer_lost_fn lost_cb;
6859 void *ctx; /* passed into callbacks */
6863 struct perf_cpu_buf **cpu_bufs;
6864 struct epoll_event *events;
6865 int cpu_cnt; /* number of allocated CPU buffers */
6866 int epoll_fd; /* perf event FD */
6867 int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
6870 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
6871 struct perf_cpu_buf *cpu_buf)
6875 if (cpu_buf->base &&
6876 munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
6877 pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
6878 if (cpu_buf->fd >= 0) {
6879 ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
6886 void perf_buffer__free(struct perf_buffer *pb)
6893 for (i = 0; i < pb->cpu_cnt && pb->cpu_bufs[i]; i++) {
6894 struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
6896 bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
6897 perf_buffer__free_cpu_buf(pb, cpu_buf);
6901 if (pb->epoll_fd >= 0)
6902 close(pb->epoll_fd);
6907 static struct perf_cpu_buf *
6908 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
6909 int cpu, int map_key)
6911 struct perf_cpu_buf *cpu_buf;
6912 char msg[STRERR_BUFSIZE];
6915 cpu_buf = calloc(1, sizeof(*cpu_buf));
6917 return ERR_PTR(-ENOMEM);
6921 cpu_buf->map_key = map_key;
6923 cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
6924 -1, PERF_FLAG_FD_CLOEXEC);
6925 if (cpu_buf->fd < 0) {
6927 pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
6928 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
6932 cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
6933 PROT_READ | PROT_WRITE, MAP_SHARED,
6935 if (cpu_buf->base == MAP_FAILED) {
6936 cpu_buf->base = NULL;
6938 pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
6939 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
6943 if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
6945 pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
6946 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
6953 perf_buffer__free_cpu_buf(pb, cpu_buf);
6954 return (struct perf_cpu_buf *)ERR_PTR(err);
6957 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
6958 struct perf_buffer_params *p);
6960 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
6961 const struct perf_buffer_opts *opts)
6963 struct perf_buffer_params p = {};
6964 struct perf_event_attr attr = { 0, };
6966 attr.config = PERF_COUNT_SW_BPF_OUTPUT,
6967 attr.type = PERF_TYPE_SOFTWARE;
6968 attr.sample_type = PERF_SAMPLE_RAW;
6969 attr.sample_period = 1;
6970 attr.wakeup_events = 1;
6973 p.sample_cb = opts ? opts->sample_cb : NULL;
6974 p.lost_cb = opts ? opts->lost_cb : NULL;
6975 p.ctx = opts ? opts->ctx : NULL;
6977 return __perf_buffer__new(map_fd, page_cnt, &p);
6980 struct perf_buffer *
6981 perf_buffer__new_raw(int map_fd, size_t page_cnt,
6982 const struct perf_buffer_raw_opts *opts)
6984 struct perf_buffer_params p = {};
6986 p.attr = opts->attr;
6987 p.event_cb = opts->event_cb;
6989 p.cpu_cnt = opts->cpu_cnt;
6990 p.cpus = opts->cpus;
6991 p.map_keys = opts->map_keys;
6993 return __perf_buffer__new(map_fd, page_cnt, &p);
6996 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
6997 struct perf_buffer_params *p)
6999 const char *online_cpus_file = "/sys/devices/system/cpu/online";
7000 struct bpf_map_info map = {};
7001 char msg[STRERR_BUFSIZE];
7002 struct perf_buffer *pb;
7003 bool *online = NULL;
7007 if (page_cnt & (page_cnt - 1)) {
7008 pr_warn("page count should be power of two, but is %zu\n",
7010 return ERR_PTR(-EINVAL);
7013 map_info_len = sizeof(map);
7014 err = bpf_obj_get_info_by_fd(map_fd, &map, &map_info_len);
7017 pr_warn("failed to get map info for map FD %d: %s\n",
7018 map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
7019 return ERR_PTR(err);
7022 if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
7023 pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
7025 return ERR_PTR(-EINVAL);
7028 pb = calloc(1, sizeof(*pb));
7030 return ERR_PTR(-ENOMEM);
7032 pb->event_cb = p->event_cb;
7033 pb->sample_cb = p->sample_cb;
7034 pb->lost_cb = p->lost_cb;
7037 pb->page_size = getpagesize();
7038 pb->mmap_size = pb->page_size * page_cnt;
7039 pb->map_fd = map_fd;
7041 pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
7042 if (pb->epoll_fd < 0) {
7044 pr_warn("failed to create epoll instance: %s\n",
7045 libbpf_strerror_r(err, msg, sizeof(msg)));
7049 if (p->cpu_cnt > 0) {
7050 pb->cpu_cnt = p->cpu_cnt;
7052 pb->cpu_cnt = libbpf_num_possible_cpus();
7053 if (pb->cpu_cnt < 0) {
7057 if (map.max_entries < pb->cpu_cnt)
7058 pb->cpu_cnt = map.max_entries;
7061 pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
7064 pr_warn("failed to allocate events: out of memory\n");
7067 pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
7068 if (!pb->cpu_bufs) {
7070 pr_warn("failed to allocate buffers: out of memory\n");
7074 err = parse_cpu_mask_file(online_cpus_file, &online, &n);
7076 pr_warn("failed to get online CPU mask: %d\n", err);
7080 for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
7081 struct perf_cpu_buf *cpu_buf;
7084 cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
7085 map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
7087 /* in case user didn't explicitly requested particular CPUs to
7088 * be attached to, skip offline/not present CPUs
7090 if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
7093 cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
7094 if (IS_ERR(cpu_buf)) {
7095 err = PTR_ERR(cpu_buf);
7099 pb->cpu_bufs[j] = cpu_buf;
7101 err = bpf_map_update_elem(pb->map_fd, &map_key,
7105 pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
7106 cpu, map_key, cpu_buf->fd,
7107 libbpf_strerror_r(err, msg, sizeof(msg)));
7111 pb->events[j].events = EPOLLIN;
7112 pb->events[j].data.ptr = cpu_buf;
7113 if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
7114 &pb->events[j]) < 0) {
7116 pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
7118 libbpf_strerror_r(err, msg, sizeof(msg)));
7131 perf_buffer__free(pb);
7132 return ERR_PTR(err);
7135 struct perf_sample_raw {
7136 struct perf_event_header header;
7141 struct perf_sample_lost {
7142 struct perf_event_header header;
7148 static enum bpf_perf_event_ret
7149 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
7151 struct perf_cpu_buf *cpu_buf = ctx;
7152 struct perf_buffer *pb = cpu_buf->pb;
7155 /* user wants full control over parsing perf event */
7157 return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
7160 case PERF_RECORD_SAMPLE: {
7161 struct perf_sample_raw *s = data;
7164 pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
7167 case PERF_RECORD_LOST: {
7168 struct perf_sample_lost *s = data;
7171 pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
7175 pr_warn("unknown perf sample type %d\n", e->type);
7176 return LIBBPF_PERF_EVENT_ERROR;
7178 return LIBBPF_PERF_EVENT_CONT;
7181 static int perf_buffer__process_records(struct perf_buffer *pb,
7182 struct perf_cpu_buf *cpu_buf)
7184 enum bpf_perf_event_ret ret;
7186 ret = bpf_perf_event_read_simple(cpu_buf->base, pb->mmap_size,
7187 pb->page_size, &cpu_buf->buf,
7189 perf_buffer__process_record, cpu_buf);
7190 if (ret != LIBBPF_PERF_EVENT_CONT)
7195 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
7199 cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
7200 for (i = 0; i < cnt; i++) {
7201 struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
7203 err = perf_buffer__process_records(pb, cpu_buf);
7205 pr_warn("error while processing records: %d\n", err);
7209 return cnt < 0 ? -errno : cnt;
7212 struct bpf_prog_info_array_desc {
7213 int array_offset; /* e.g. offset of jited_prog_insns */
7214 int count_offset; /* e.g. offset of jited_prog_len */
7215 int size_offset; /* > 0: offset of rec size,
7216 * < 0: fix size of -size_offset
7220 static struct bpf_prog_info_array_desc bpf_prog_info_array_desc[] = {
7221 [BPF_PROG_INFO_JITED_INSNS] = {
7222 offsetof(struct bpf_prog_info, jited_prog_insns),
7223 offsetof(struct bpf_prog_info, jited_prog_len),
7226 [BPF_PROG_INFO_XLATED_INSNS] = {
7227 offsetof(struct bpf_prog_info, xlated_prog_insns),
7228 offsetof(struct bpf_prog_info, xlated_prog_len),
7231 [BPF_PROG_INFO_MAP_IDS] = {
7232 offsetof(struct bpf_prog_info, map_ids),
7233 offsetof(struct bpf_prog_info, nr_map_ids),
7234 -(int)sizeof(__u32),
7236 [BPF_PROG_INFO_JITED_KSYMS] = {
7237 offsetof(struct bpf_prog_info, jited_ksyms),
7238 offsetof(struct bpf_prog_info, nr_jited_ksyms),
7239 -(int)sizeof(__u64),
7241 [BPF_PROG_INFO_JITED_FUNC_LENS] = {
7242 offsetof(struct bpf_prog_info, jited_func_lens),
7243 offsetof(struct bpf_prog_info, nr_jited_func_lens),
7244 -(int)sizeof(__u32),
7246 [BPF_PROG_INFO_FUNC_INFO] = {
7247 offsetof(struct bpf_prog_info, func_info),
7248 offsetof(struct bpf_prog_info, nr_func_info),
7249 offsetof(struct bpf_prog_info, func_info_rec_size),
7251 [BPF_PROG_INFO_LINE_INFO] = {
7252 offsetof(struct bpf_prog_info, line_info),
7253 offsetof(struct bpf_prog_info, nr_line_info),
7254 offsetof(struct bpf_prog_info, line_info_rec_size),
7256 [BPF_PROG_INFO_JITED_LINE_INFO] = {
7257 offsetof(struct bpf_prog_info, jited_line_info),
7258 offsetof(struct bpf_prog_info, nr_jited_line_info),
7259 offsetof(struct bpf_prog_info, jited_line_info_rec_size),
7261 [BPF_PROG_INFO_PROG_TAGS] = {
7262 offsetof(struct bpf_prog_info, prog_tags),
7263 offsetof(struct bpf_prog_info, nr_prog_tags),
7264 -(int)sizeof(__u8) * BPF_TAG_SIZE,
7269 static __u32 bpf_prog_info_read_offset_u32(struct bpf_prog_info *info,
7272 __u32 *array = (__u32 *)info;
7275 return array[offset / sizeof(__u32)];
7276 return -(int)offset;
7279 static __u64 bpf_prog_info_read_offset_u64(struct bpf_prog_info *info,
7282 __u64 *array = (__u64 *)info;
7285 return array[offset / sizeof(__u64)];
7286 return -(int)offset;
7289 static void bpf_prog_info_set_offset_u32(struct bpf_prog_info *info, int offset,
7292 __u32 *array = (__u32 *)info;
7295 array[offset / sizeof(__u32)] = val;
7298 static void bpf_prog_info_set_offset_u64(struct bpf_prog_info *info, int offset,
7301 __u64 *array = (__u64 *)info;
7304 array[offset / sizeof(__u64)] = val;
7307 struct bpf_prog_info_linear *
7308 bpf_program__get_prog_info_linear(int fd, __u64 arrays)
7310 struct bpf_prog_info_linear *info_linear;
7311 struct bpf_prog_info info = {};
7312 __u32 info_len = sizeof(info);
7317 if (arrays >> BPF_PROG_INFO_LAST_ARRAY)
7318 return ERR_PTR(-EINVAL);
7320 /* step 1: get array dimensions */
7321 err = bpf_obj_get_info_by_fd(fd, &info, &info_len);
7323 pr_debug("can't get prog info: %s", strerror(errno));
7324 return ERR_PTR(-EFAULT);
7327 /* step 2: calculate total size of all arrays */
7328 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
7329 bool include_array = (arrays & (1UL << i)) > 0;
7330 struct bpf_prog_info_array_desc *desc;
7333 desc = bpf_prog_info_array_desc + i;
7335 /* kernel is too old to support this field */
7336 if (info_len < desc->array_offset + sizeof(__u32) ||
7337 info_len < desc->count_offset + sizeof(__u32) ||
7338 (desc->size_offset > 0 && info_len < desc->size_offset))
7339 include_array = false;
7341 if (!include_array) {
7342 arrays &= ~(1UL << i); /* clear the bit */
7346 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
7347 size = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
7349 data_len += count * size;
7352 /* step 3: allocate continuous memory */
7353 data_len = roundup(data_len, sizeof(__u64));
7354 info_linear = malloc(sizeof(struct bpf_prog_info_linear) + data_len);
7356 return ERR_PTR(-ENOMEM);
7358 /* step 4: fill data to info_linear->info */
7359 info_linear->arrays = arrays;
7360 memset(&info_linear->info, 0, sizeof(info));
7361 ptr = info_linear->data;
7363 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
7364 struct bpf_prog_info_array_desc *desc;
7367 if ((arrays & (1UL << i)) == 0)
7370 desc = bpf_prog_info_array_desc + i;
7371 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
7372 size = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
7373 bpf_prog_info_set_offset_u32(&info_linear->info,
7374 desc->count_offset, count);
7375 bpf_prog_info_set_offset_u32(&info_linear->info,
7376 desc->size_offset, size);
7377 bpf_prog_info_set_offset_u64(&info_linear->info,
7380 ptr += count * size;
7383 /* step 5: call syscall again to get required arrays */
7384 err = bpf_obj_get_info_by_fd(fd, &info_linear->info, &info_len);
7386 pr_debug("can't get prog info: %s", strerror(errno));
7388 return ERR_PTR(-EFAULT);
7391 /* step 6: verify the data */
7392 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
7393 struct bpf_prog_info_array_desc *desc;
7396 if ((arrays & (1UL << i)) == 0)
7399 desc = bpf_prog_info_array_desc + i;
7400 v1 = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
7401 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
7402 desc->count_offset);
7404 pr_warn("%s: mismatch in element count\n", __func__);
7406 v1 = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
7407 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
7410 pr_warn("%s: mismatch in rec size\n", __func__);
7413 /* step 7: update info_len and data_len */
7414 info_linear->info_len = sizeof(struct bpf_prog_info);
7415 info_linear->data_len = data_len;
7420 void bpf_program__bpil_addr_to_offs(struct bpf_prog_info_linear *info_linear)
7424 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
7425 struct bpf_prog_info_array_desc *desc;
7428 if ((info_linear->arrays & (1UL << i)) == 0)
7431 desc = bpf_prog_info_array_desc + i;
7432 addr = bpf_prog_info_read_offset_u64(&info_linear->info,
7433 desc->array_offset);
7434 offs = addr - ptr_to_u64(info_linear->data);
7435 bpf_prog_info_set_offset_u64(&info_linear->info,
7436 desc->array_offset, offs);
7440 void bpf_program__bpil_offs_to_addr(struct bpf_prog_info_linear *info_linear)
7444 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
7445 struct bpf_prog_info_array_desc *desc;
7448 if ((info_linear->arrays & (1UL << i)) == 0)
7451 desc = bpf_prog_info_array_desc + i;
7452 offs = bpf_prog_info_read_offset_u64(&info_linear->info,
7453 desc->array_offset);
7454 addr = offs + ptr_to_u64(info_linear->data);
7455 bpf_prog_info_set_offset_u64(&info_linear->info,
7456 desc->array_offset, addr);
7460 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
7462 int err = 0, n, len, start, end = -1;
7468 /* Each sub string separated by ',' has format \d+-\d+ or \d+ */
7470 if (*s == ',' || *s == '\n') {
7474 n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
7475 if (n <= 0 || n > 2) {
7476 pr_warn("Failed to get CPU range %s: %d\n", s, n);
7479 } else if (n == 1) {
7482 if (start < 0 || start > end) {
7483 pr_warn("Invalid CPU range [%d,%d] in %s\n",
7488 tmp = realloc(*mask, end + 1);
7494 memset(tmp + *mask_sz, 0, start - *mask_sz);
7495 memset(tmp + start, 1, end - start + 1);
7500 pr_warn("Empty CPU range\n");
7510 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
7512 int fd, err = 0, len;
7515 fd = open(fcpu, O_RDONLY);
7518 pr_warn("Failed to open cpu mask file %s: %d\n", fcpu, err);
7521 len = read(fd, buf, sizeof(buf));
7524 err = len ? -errno : -EINVAL;
7525 pr_warn("Failed to read cpu mask from %s: %d\n", fcpu, err);
7528 if (len >= sizeof(buf)) {
7529 pr_warn("CPU mask is too big in file %s\n", fcpu);
7534 return parse_cpu_mask_str(buf, mask, mask_sz);
7537 int libbpf_num_possible_cpus(void)
7539 static const char *fcpu = "/sys/devices/system/cpu/possible";
7541 int err, n, i, tmp_cpus;
7544 tmp_cpus = READ_ONCE(cpus);
7548 err = parse_cpu_mask_file(fcpu, &mask, &n);
7553 for (i = 0; i < n; i++) {
7559 WRITE_ONCE(cpus, tmp_cpus);
7563 int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
7564 const struct bpf_object_open_opts *opts)
7566 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, skel_opts,
7567 .object_name = s->name,
7569 struct bpf_object *obj;
7572 /* Attempt to preserve opts->object_name, unless overriden by user
7573 * explicitly. Overwriting object name for skeletons is discouraged,
7574 * as it breaks global data maps, because they contain object name
7575 * prefix as their own map name prefix. When skeleton is generated,
7576 * bpftool is making an assumption that this name will stay the same.
7579 memcpy(&skel_opts, opts, sizeof(*opts));
7580 if (!opts->object_name)
7581 skel_opts.object_name = s->name;
7584 obj = bpf_object__open_mem(s->data, s->data_sz, &skel_opts);
7586 pr_warn("failed to initialize skeleton BPF object '%s': %ld\n",
7587 s->name, PTR_ERR(obj));
7588 return PTR_ERR(obj);
7593 for (i = 0; i < s->map_cnt; i++) {
7594 struct bpf_map **map = s->maps[i].map;
7595 const char *name = s->maps[i].name;
7596 void **mmaped = s->maps[i].mmaped;
7598 *map = bpf_object__find_map_by_name(obj, name);
7600 pr_warn("failed to find skeleton map '%s'\n", name);
7604 /* externs shouldn't be pre-setup from user code */
7605 if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
7606 *mmaped = (*map)->mmaped;
7609 for (i = 0; i < s->prog_cnt; i++) {
7610 struct bpf_program **prog = s->progs[i].prog;
7611 const char *name = s->progs[i].name;
7613 *prog = bpf_object__find_program_by_name(obj, name);
7615 pr_warn("failed to find skeleton program '%s'\n", name);
7623 int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
7627 err = bpf_object__load(*s->obj);
7629 pr_warn("failed to load BPF skeleton '%s': %d\n", s->name, err);
7633 for (i = 0; i < s->map_cnt; i++) {
7634 struct bpf_map *map = *s->maps[i].map;
7635 size_t mmap_sz = bpf_map_mmap_sz(map);
7636 int prot, map_fd = bpf_map__fd(map);
7637 void **mmaped = s->maps[i].mmaped;
7642 if (!(map->def.map_flags & BPF_F_MMAPABLE)) {
7647 if (map->def.map_flags & BPF_F_RDONLY_PROG)
7650 prot = PROT_READ | PROT_WRITE;
7652 /* Remap anonymous mmap()-ed "map initialization image" as
7653 * a BPF map-backed mmap()-ed memory, but preserving the same
7654 * memory address. This will cause kernel to change process'
7655 * page table to point to a different piece of kernel memory,
7656 * but from userspace point of view memory address (and its
7657 * contents, being identical at this point) will stay the
7658 * same. This mapping will be released by bpf_object__close()
7659 * as per normal clean up procedure, so we don't need to worry
7660 * about it from skeleton's clean up perspective.
7662 *mmaped = mmap(map->mmaped, mmap_sz, prot,
7663 MAP_SHARED | MAP_FIXED, map_fd, 0);
7664 if (*mmaped == MAP_FAILED) {
7667 pr_warn("failed to re-mmap() map '%s': %d\n",
7668 bpf_map__name(map), err);
7676 int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
7680 for (i = 0; i < s->prog_cnt; i++) {
7681 struct bpf_program *prog = *s->progs[i].prog;
7682 struct bpf_link **link = s->progs[i].link;
7683 const struct bpf_sec_def *sec_def;
7684 const char *sec_name = bpf_program__title(prog, false);
7686 sec_def = find_sec_def(sec_name);
7687 if (!sec_def || !sec_def->attach_fn)
7690 *link = sec_def->attach_fn(sec_def, prog);
7691 if (IS_ERR(*link)) {
7692 pr_warn("failed to auto-attach program '%s': %ld\n",
7693 bpf_program__name(prog), PTR_ERR(*link));
7694 return PTR_ERR(*link);
7701 void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
7705 for (i = 0; i < s->prog_cnt; i++) {
7706 struct bpf_link **link = s->progs[i].link;
7708 if (!IS_ERR_OR_NULL(*link))
7709 bpf_link__destroy(*link);
7714 void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
7717 bpf_object__detach_skeleton(s);
7719 bpf_object__close(*s->obj);