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 <tools/libc_compat.h>
51 #include "str_error.h"
52 #include "libbpf_internal.h"
60 #define BPF_FS_MAGIC 0xcafe4a11
63 /* vsprintf() in __base_pr() uses nonliteral format string. It may break
64 * compilation if user enables corresponding warning. Disable it explicitly.
66 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
68 #define __printf(a, b) __attribute__((format(printf, a, b)))
70 static int __base_pr(enum libbpf_print_level level, const char *format,
73 if (level == LIBBPF_DEBUG)
76 return vfprintf(stderr, format, args);
79 static libbpf_print_fn_t __libbpf_pr = __base_pr;
81 libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn)
83 libbpf_print_fn_t old_print_fn = __libbpf_pr;
90 void libbpf_print(enum libbpf_print_level level, const char *format, ...)
97 va_start(args, format);
98 __libbpf_pr(level, format, args);
102 #define STRERR_BUFSIZE 128
104 /* Copied from tools/perf/util/util.h */
106 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
110 # define zclose(fd) ({ \
113 ___err = close((fd)); \
118 #ifdef HAVE_LIBELF_MMAP_SUPPORT
119 # define LIBBPF_ELF_C_READ_MMAP ELF_C_READ_MMAP
121 # define LIBBPF_ELF_C_READ_MMAP ELF_C_READ
124 static inline __u64 ptr_to_u64(const void *ptr)
126 return (__u64) (unsigned long) ptr;
129 struct bpf_capabilities {
130 /* v4.14: kernel support for program & map names. */
132 /* v5.2: kernel support for global data sections. */
134 /* BTF_KIND_FUNC and BTF_KIND_FUNC_PROTO support */
136 /* BTF_KIND_VAR and BTF_KIND_DATASEC support */
138 /* BPF_F_MMAPABLE is supported for arrays */
143 * bpf_prog should be a better name but it has been used in
147 /* Index in elf obj file, for relocation use. */
152 /* section_name with / replaced by _; makes recursive pinning
153 * in bpf_object__pin_programs easier
156 struct bpf_insn *insns;
157 size_t insns_cnt, main_prog_cnt;
158 enum bpf_prog_type type;
177 bpf_program_prep_t preprocessor;
179 struct bpf_object *obj;
181 bpf_program_clear_priv_t clear_priv;
183 enum bpf_attach_type expected_attach_type;
185 __u32 attach_prog_fd;
187 __u32 func_info_rec_size;
190 struct bpf_capabilities *caps;
193 __u32 line_info_rec_size;
198 #define DATA_SEC ".data"
199 #define BSS_SEC ".bss"
200 #define RODATA_SEC ".rodata"
202 enum libbpf_map_type {
209 static const char * const libbpf_type_to_btf_name[] = {
210 [LIBBPF_MAP_DATA] = DATA_SEC,
211 [LIBBPF_MAP_BSS] = BSS_SEC,
212 [LIBBPF_MAP_RODATA] = RODATA_SEC,
222 struct bpf_map_def def;
223 __u32 btf_key_type_id;
224 __u32 btf_value_type_id;
226 bpf_map_clear_priv_t clear_priv;
227 enum libbpf_map_type libbpf_type;
234 static LIST_HEAD(bpf_objects_list);
237 char name[BPF_OBJ_NAME_LEN];
241 struct bpf_program *programs;
243 struct bpf_map *maps;
248 bool has_pseudo_calls;
249 bool relaxed_core_relocs;
252 * Information when doing elf related work. Only valid if fd
279 * All loaded bpf_object is linked in a list, which is
280 * hidden to caller. bpf_objects__<func> handlers deal with
283 struct list_head list;
286 struct btf_ext *btf_ext;
289 bpf_object_clear_priv_t clear_priv;
291 struct bpf_capabilities caps;
295 #define obj_elf_valid(o) ((o)->efile.elf)
297 void bpf_program__unload(struct bpf_program *prog)
305 * If the object is opened but the program was never loaded,
306 * it is possible that prog->instances.nr == -1.
308 if (prog->instances.nr > 0) {
309 for (i = 0; i < prog->instances.nr; i++)
310 zclose(prog->instances.fds[i]);
311 } else if (prog->instances.nr != -1) {
312 pr_warn("Internal error: instances.nr is %d\n",
316 prog->instances.nr = -1;
317 zfree(&prog->instances.fds);
319 zfree(&prog->func_info);
320 zfree(&prog->line_info);
323 static void bpf_program__exit(struct bpf_program *prog)
328 if (prog->clear_priv)
329 prog->clear_priv(prog, prog->priv);
332 prog->clear_priv = NULL;
334 bpf_program__unload(prog);
336 zfree(&prog->section_name);
337 zfree(&prog->pin_name);
339 zfree(&prog->reloc_desc);
346 static char *__bpf_program__pin_name(struct bpf_program *prog)
350 name = p = strdup(prog->section_name);
351 while ((p = strchr(p, '/')))
358 bpf_program__init(void *data, size_t size, char *section_name, int idx,
359 struct bpf_program *prog)
361 const size_t bpf_insn_sz = sizeof(struct bpf_insn);
363 if (size == 0 || size % bpf_insn_sz) {
364 pr_warn("corrupted section '%s', size: %zu\n",
369 memset(prog, 0, sizeof(*prog));
371 prog->section_name = strdup(section_name);
372 if (!prog->section_name) {
373 pr_warn("failed to alloc name for prog under section(%d) %s\n",
378 prog->pin_name = __bpf_program__pin_name(prog);
379 if (!prog->pin_name) {
380 pr_warn("failed to alloc pin name for prog under section(%d) %s\n",
385 prog->insns = malloc(size);
387 pr_warn("failed to alloc insns for prog under section %s\n",
391 prog->insns_cnt = size / bpf_insn_sz;
392 memcpy(prog->insns, data, size);
394 prog->instances.fds = NULL;
395 prog->instances.nr = -1;
396 prog->type = BPF_PROG_TYPE_UNSPEC;
400 bpf_program__exit(prog);
405 bpf_object__add_program(struct bpf_object *obj, void *data, size_t size,
406 char *section_name, int idx)
408 struct bpf_program prog, *progs;
411 err = bpf_program__init(data, size, section_name, idx, &prog);
415 prog.caps = &obj->caps;
416 progs = obj->programs;
417 nr_progs = obj->nr_programs;
419 progs = reallocarray(progs, nr_progs + 1, sizeof(progs[0]));
422 * In this case the original obj->programs
423 * is still valid, so don't need special treat for
424 * bpf_close_object().
426 pr_warn("failed to alloc a new program under section '%s'\n",
428 bpf_program__exit(&prog);
432 pr_debug("found program %s\n", prog.section_name);
433 obj->programs = progs;
434 obj->nr_programs = nr_progs + 1;
436 progs[nr_progs] = prog;
441 bpf_object__init_prog_names(struct bpf_object *obj)
443 Elf_Data *symbols = obj->efile.symbols;
444 struct bpf_program *prog;
447 for (pi = 0; pi < obj->nr_programs; pi++) {
448 const char *name = NULL;
450 prog = &obj->programs[pi];
452 for (si = 0; si < symbols->d_size / sizeof(GElf_Sym) && !name;
456 if (!gelf_getsym(symbols, si, &sym))
458 if (sym.st_shndx != prog->idx)
460 if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL)
463 name = elf_strptr(obj->efile.elf,
464 obj->efile.strtabidx,
467 pr_warn("failed to get sym name string for prog %s\n",
469 return -LIBBPF_ERRNO__LIBELF;
473 if (!name && prog->idx == obj->efile.text_shndx)
477 pr_warn("failed to find sym for prog %s\n",
482 prog->name = strdup(name);
484 pr_warn("failed to allocate memory for prog sym %s\n",
493 static __u32 get_kernel_version(void)
495 __u32 major, minor, patch;
499 if (sscanf(info.release, "%u.%u.%u", &major, &minor, &patch) != 3)
501 return KERNEL_VERSION(major, minor, patch);
504 static struct bpf_object *bpf_object__new(const char *path,
507 const char *obj_name)
509 struct bpf_object *obj;
512 obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
514 pr_warn("alloc memory failed for %s\n", path);
515 return ERR_PTR(-ENOMEM);
518 strcpy(obj->path, path);
520 strncpy(obj->name, obj_name, sizeof(obj->name) - 1);
521 obj->name[sizeof(obj->name) - 1] = 0;
523 /* Using basename() GNU version which doesn't modify arg. */
524 strncpy(obj->name, basename((void *)path),
525 sizeof(obj->name) - 1);
526 end = strchr(obj->name, '.');
533 * Caller of this function should also call
534 * bpf_object__elf_finish() after data collection to return
535 * obj_buf to user. If not, we should duplicate the buffer to
536 * avoid user freeing them before elf finish.
538 obj->efile.obj_buf = obj_buf;
539 obj->efile.obj_buf_sz = obj_buf_sz;
540 obj->efile.maps_shndx = -1;
541 obj->efile.btf_maps_shndx = -1;
542 obj->efile.data_shndx = -1;
543 obj->efile.rodata_shndx = -1;
544 obj->efile.bss_shndx = -1;
546 obj->kern_version = get_kernel_version();
549 INIT_LIST_HEAD(&obj->list);
550 list_add(&obj->list, &bpf_objects_list);
554 static void bpf_object__elf_finish(struct bpf_object *obj)
556 if (!obj_elf_valid(obj))
559 if (obj->efile.elf) {
560 elf_end(obj->efile.elf);
561 obj->efile.elf = NULL;
563 obj->efile.symbols = NULL;
564 obj->efile.data = NULL;
565 obj->efile.rodata = NULL;
566 obj->efile.bss = NULL;
568 zfree(&obj->efile.reloc_sects);
569 obj->efile.nr_reloc_sects = 0;
570 zclose(obj->efile.fd);
571 obj->efile.obj_buf = NULL;
572 obj->efile.obj_buf_sz = 0;
575 static int bpf_object__elf_init(struct bpf_object *obj)
580 if (obj_elf_valid(obj)) {
581 pr_warn("elf init: internal error\n");
582 return -LIBBPF_ERRNO__LIBELF;
585 if (obj->efile.obj_buf_sz > 0) {
587 * obj_buf should have been validated by
588 * bpf_object__open_buffer().
590 obj->efile.elf = elf_memory((char *)obj->efile.obj_buf,
591 obj->efile.obj_buf_sz);
593 obj->efile.fd = open(obj->path, O_RDONLY);
594 if (obj->efile.fd < 0) {
595 char errmsg[STRERR_BUFSIZE], *cp;
598 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
599 pr_warn("failed to open %s: %s\n", obj->path, cp);
603 obj->efile.elf = elf_begin(obj->efile.fd,
604 LIBBPF_ELF_C_READ_MMAP, NULL);
607 if (!obj->efile.elf) {
608 pr_warn("failed to open %s as ELF file\n", obj->path);
609 err = -LIBBPF_ERRNO__LIBELF;
613 if (!gelf_getehdr(obj->efile.elf, &obj->efile.ehdr)) {
614 pr_warn("failed to get EHDR from %s\n", obj->path);
615 err = -LIBBPF_ERRNO__FORMAT;
618 ep = &obj->efile.ehdr;
620 /* Old LLVM set e_machine to EM_NONE */
621 if (ep->e_type != ET_REL ||
622 (ep->e_machine && ep->e_machine != EM_BPF)) {
623 pr_warn("%s is not an eBPF object file\n", obj->path);
624 err = -LIBBPF_ERRNO__FORMAT;
630 bpf_object__elf_finish(obj);
634 static int bpf_object__check_endianness(struct bpf_object *obj)
636 #if __BYTE_ORDER == __LITTLE_ENDIAN
637 if (obj->efile.ehdr.e_ident[EI_DATA] == ELFDATA2LSB)
639 #elif __BYTE_ORDER == __BIG_ENDIAN
640 if (obj->efile.ehdr.e_ident[EI_DATA] == ELFDATA2MSB)
643 # error "Unrecognized __BYTE_ORDER__"
645 pr_warn("endianness mismatch.\n");
646 return -LIBBPF_ERRNO__ENDIAN;
650 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
652 memcpy(obj->license, data, min(size, sizeof(obj->license) - 1));
653 pr_debug("license of %s is %s\n", obj->path, obj->license);
658 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
662 if (size != sizeof(kver)) {
663 pr_warn("invalid kver section in %s\n", obj->path);
664 return -LIBBPF_ERRNO__FORMAT;
666 memcpy(&kver, data, sizeof(kver));
667 obj->kern_version = kver;
668 pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
672 static int compare_bpf_map(const void *_a, const void *_b)
674 const struct bpf_map *a = _a;
675 const struct bpf_map *b = _b;
677 if (a->sec_idx != b->sec_idx)
678 return a->sec_idx - b->sec_idx;
679 return a->sec_offset - b->sec_offset;
682 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
684 if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
685 type == BPF_MAP_TYPE_HASH_OF_MAPS)
690 static int bpf_object_search_section_size(const struct bpf_object *obj,
691 const char *name, size_t *d_size)
693 const GElf_Ehdr *ep = &obj->efile.ehdr;
694 Elf *elf = obj->efile.elf;
698 while ((scn = elf_nextscn(elf, scn)) != NULL) {
699 const char *sec_name;
704 if (gelf_getshdr(scn, &sh) != &sh) {
705 pr_warn("failed to get section(%d) header from %s\n",
710 sec_name = elf_strptr(elf, ep->e_shstrndx, sh.sh_name);
712 pr_warn("failed to get section(%d) name from %s\n",
717 if (strcmp(name, sec_name))
720 data = elf_getdata(scn, 0);
722 pr_warn("failed to get section(%d) data from %s(%s)\n",
723 idx, name, obj->path);
727 *d_size = data->d_size;
734 int bpf_object__section_size(const struct bpf_object *obj, const char *name,
743 } else if (!strcmp(name, DATA_SEC)) {
745 *size = obj->efile.data->d_size;
746 } else if (!strcmp(name, BSS_SEC)) {
748 *size = obj->efile.bss->d_size;
749 } else if (!strcmp(name, RODATA_SEC)) {
750 if (obj->efile.rodata)
751 *size = obj->efile.rodata->d_size;
753 ret = bpf_object_search_section_size(obj, name, &d_size);
758 return *size ? 0 : ret;
761 int bpf_object__variable_offset(const struct bpf_object *obj, const char *name,
764 Elf_Data *symbols = obj->efile.symbols;
771 for (si = 0; si < symbols->d_size / sizeof(GElf_Sym); si++) {
774 if (!gelf_getsym(symbols, si, &sym))
776 if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL ||
777 GELF_ST_TYPE(sym.st_info) != STT_OBJECT)
780 sname = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
783 pr_warn("failed to get sym name string for var %s\n",
787 if (strcmp(name, sname) == 0) {
796 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
798 struct bpf_map *new_maps;
802 if (obj->nr_maps < obj->maps_cap)
803 return &obj->maps[obj->nr_maps++];
805 new_cap = max((size_t)4, obj->maps_cap * 3 / 2);
806 new_maps = realloc(obj->maps, new_cap * sizeof(*obj->maps));
808 pr_warn("alloc maps for object failed\n");
809 return ERR_PTR(-ENOMEM);
812 obj->maps_cap = new_cap;
813 obj->maps = new_maps;
815 /* zero out new maps */
816 memset(obj->maps + obj->nr_maps, 0,
817 (obj->maps_cap - obj->nr_maps) * sizeof(*obj->maps));
819 * fill all fd with -1 so won't close incorrect fd (fd=0 is stdin)
820 * when failure (zclose won't close negative fd)).
822 for (i = obj->nr_maps; i < obj->maps_cap; i++) {
823 obj->maps[i].fd = -1;
824 obj->maps[i].inner_map_fd = -1;
827 return &obj->maps[obj->nr_maps++];
830 static size_t bpf_map_mmap_sz(const struct bpf_map *map)
832 long page_sz = sysconf(_SC_PAGE_SIZE);
835 map_sz = roundup(map->def.value_size, 8) * map->def.max_entries;
836 map_sz = roundup(map_sz, page_sz);
841 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
842 int sec_idx, void *data, size_t data_sz)
844 char map_name[BPF_OBJ_NAME_LEN];
845 struct bpf_map_def *def;
849 map = bpf_object__add_map(obj);
853 map->libbpf_type = type;
854 map->sec_idx = sec_idx;
856 snprintf(map_name, sizeof(map_name), "%.8s%.7s", obj->name,
857 libbpf_type_to_btf_name[type]);
858 map->name = strdup(map_name);
860 pr_warn("failed to alloc map name\n");
865 def->type = BPF_MAP_TYPE_ARRAY;
866 def->key_size = sizeof(int);
867 def->value_size = data_sz;
868 def->max_entries = 1;
869 def->map_flags = type == LIBBPF_MAP_RODATA ? BPF_F_RDONLY_PROG : 0;
870 def->map_flags |= BPF_F_MMAPABLE;
872 pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
873 map_name, map->sec_idx, map->sec_offset, def->map_flags);
875 map->mmaped = mmap(NULL, bpf_map_mmap_sz(map), PROT_READ | PROT_WRITE,
876 MAP_SHARED | MAP_ANONYMOUS, -1, 0);
877 if (map->mmaped == MAP_FAILED) {
880 pr_warn("failed to alloc map '%s' content buffer: %d\n",
886 if (type != LIBBPF_MAP_BSS)
887 memcpy(map->mmaped, data, data_sz);
889 pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
893 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
898 * Populate obj->maps with libbpf internal maps.
900 if (obj->efile.data_shndx >= 0) {
901 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
902 obj->efile.data_shndx,
903 obj->efile.data->d_buf,
904 obj->efile.data->d_size);
908 if (obj->efile.rodata_shndx >= 0) {
909 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
910 obj->efile.rodata_shndx,
911 obj->efile.rodata->d_buf,
912 obj->efile.rodata->d_size);
916 if (obj->efile.bss_shndx >= 0) {
917 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
918 obj->efile.bss_shndx,
920 obj->efile.bss->d_size);
927 static int bpf_object__init_user_maps(struct bpf_object *obj, bool strict)
929 Elf_Data *symbols = obj->efile.symbols;
930 int i, map_def_sz = 0, nr_maps = 0, nr_syms;
931 Elf_Data *data = NULL;
934 if (obj->efile.maps_shndx < 0)
940 scn = elf_getscn(obj->efile.elf, obj->efile.maps_shndx);
942 data = elf_getdata(scn, NULL);
944 pr_warn("failed to get Elf_Data from map section %d\n",
945 obj->efile.maps_shndx);
950 * Count number of maps. Each map has a name.
951 * Array of maps is not supported: only the first element is
954 * TODO: Detect array of map and report error.
956 nr_syms = symbols->d_size / sizeof(GElf_Sym);
957 for (i = 0; i < nr_syms; i++) {
960 if (!gelf_getsym(symbols, i, &sym))
962 if (sym.st_shndx != obj->efile.maps_shndx)
966 /* Assume equally sized map definitions */
967 pr_debug("maps in %s: %d maps in %zd bytes\n",
968 obj->path, nr_maps, data->d_size);
970 if (!data->d_size || nr_maps == 0 || (data->d_size % nr_maps) != 0) {
971 pr_warn("unable to determine map definition size section %s, %d maps in %zd bytes\n",
972 obj->path, nr_maps, data->d_size);
975 map_def_sz = data->d_size / nr_maps;
977 /* Fill obj->maps using data in "maps" section. */
978 for (i = 0; i < nr_syms; i++) {
980 const char *map_name;
981 struct bpf_map_def *def;
984 if (!gelf_getsym(symbols, i, &sym))
986 if (sym.st_shndx != obj->efile.maps_shndx)
989 map = bpf_object__add_map(obj);
993 map_name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
996 pr_warn("failed to get map #%d name sym string for obj %s\n",
998 return -LIBBPF_ERRNO__FORMAT;
1001 map->libbpf_type = LIBBPF_MAP_UNSPEC;
1002 map->sec_idx = sym.st_shndx;
1003 map->sec_offset = sym.st_value;
1004 pr_debug("map '%s' (legacy): at sec_idx %d, offset %zu.\n",
1005 map_name, map->sec_idx, map->sec_offset);
1006 if (sym.st_value + map_def_sz > data->d_size) {
1007 pr_warn("corrupted maps section in %s: last map \"%s\" too small\n",
1008 obj->path, map_name);
1012 map->name = strdup(map_name);
1014 pr_warn("failed to alloc map name\n");
1017 pr_debug("map %d is \"%s\"\n", i, map->name);
1018 def = (struct bpf_map_def *)(data->d_buf + sym.st_value);
1020 * If the definition of the map in the object file fits in
1021 * bpf_map_def, copy it. Any extra fields in our version
1022 * of bpf_map_def will default to zero as a result of the
1025 if (map_def_sz <= sizeof(struct bpf_map_def)) {
1026 memcpy(&map->def, def, map_def_sz);
1029 * Here the map structure being read is bigger than what
1030 * we expect, truncate if the excess bits are all zero.
1031 * If they are not zero, reject this map as
1036 for (b = ((char *)def) + sizeof(struct bpf_map_def);
1037 b < ((char *)def) + map_def_sz; b++) {
1039 pr_warn("maps section in %s: \"%s\" has unrecognized, non-zero options\n",
1040 obj->path, map_name);
1045 memcpy(&map->def, def, sizeof(struct bpf_map_def));
1051 static const struct btf_type *
1052 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
1054 const struct btf_type *t = btf__type_by_id(btf, id);
1059 while (btf_is_mod(t) || btf_is_typedef(t)) {
1062 t = btf__type_by_id(btf, t->type);
1069 * Fetch integer attribute of BTF map definition. Such attributes are
1070 * represented using a pointer to an array, in which dimensionality of array
1071 * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
1072 * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
1073 * type definition, while using only sizeof(void *) space in ELF data section.
1075 static bool get_map_field_int(const char *map_name, const struct btf *btf,
1076 const struct btf_type *def,
1077 const struct btf_member *m, __u32 *res)
1079 const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
1080 const char *name = btf__name_by_offset(btf, m->name_off);
1081 const struct btf_array *arr_info;
1082 const struct btf_type *arr_t;
1084 if (!btf_is_ptr(t)) {
1085 pr_warn("map '%s': attr '%s': expected PTR, got %u.\n",
1086 map_name, name, btf_kind(t));
1090 arr_t = btf__type_by_id(btf, t->type);
1092 pr_warn("map '%s': attr '%s': type [%u] not found.\n",
1093 map_name, name, t->type);
1096 if (!btf_is_array(arr_t)) {
1097 pr_warn("map '%s': attr '%s': expected ARRAY, got %u.\n",
1098 map_name, name, btf_kind(arr_t));
1101 arr_info = btf_array(arr_t);
1102 *res = arr_info->nelems;
1106 static int build_map_pin_path(struct bpf_map *map, const char *path)
1112 path = "/sys/fs/bpf";
1114 len = snprintf(buf, PATH_MAX, "%s/%s", path, bpf_map__name(map));
1117 else if (len >= PATH_MAX)
1118 return -ENAMETOOLONG;
1120 err = bpf_map__set_pin_path(map, buf);
1127 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
1128 const struct btf_type *sec,
1129 int var_idx, int sec_idx,
1130 const Elf_Data *data, bool strict,
1131 const char *pin_root_path)
1133 const struct btf_type *var, *def, *t;
1134 const struct btf_var_secinfo *vi;
1135 const struct btf_var *var_extra;
1136 const struct btf_member *m;
1137 const char *map_name;
1138 struct bpf_map *map;
1141 vi = btf_var_secinfos(sec) + var_idx;
1142 var = btf__type_by_id(obj->btf, vi->type);
1143 var_extra = btf_var(var);
1144 map_name = btf__name_by_offset(obj->btf, var->name_off);
1145 vlen = btf_vlen(var);
1147 if (map_name == NULL || map_name[0] == '\0') {
1148 pr_warn("map #%d: empty name.\n", var_idx);
1151 if ((__u64)vi->offset + vi->size > data->d_size) {
1152 pr_warn("map '%s' BTF data is corrupted.\n", map_name);
1155 if (!btf_is_var(var)) {
1156 pr_warn("map '%s': unexpected var kind %u.\n",
1157 map_name, btf_kind(var));
1160 if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED &&
1161 var_extra->linkage != BTF_VAR_STATIC) {
1162 pr_warn("map '%s': unsupported var linkage %u.\n",
1163 map_name, var_extra->linkage);
1167 def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
1168 if (!btf_is_struct(def)) {
1169 pr_warn("map '%s': unexpected def kind %u.\n",
1170 map_name, btf_kind(var));
1173 if (def->size > vi->size) {
1174 pr_warn("map '%s': invalid def size.\n", map_name);
1178 map = bpf_object__add_map(obj);
1180 return PTR_ERR(map);
1181 map->name = strdup(map_name);
1183 pr_warn("map '%s': failed to alloc map name.\n", map_name);
1186 map->libbpf_type = LIBBPF_MAP_UNSPEC;
1187 map->def.type = BPF_MAP_TYPE_UNSPEC;
1188 map->sec_idx = sec_idx;
1189 map->sec_offset = vi->offset;
1190 pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
1191 map_name, map->sec_idx, map->sec_offset);
1193 vlen = btf_vlen(def);
1194 m = btf_members(def);
1195 for (i = 0; i < vlen; i++, m++) {
1196 const char *name = btf__name_by_offset(obj->btf, m->name_off);
1199 pr_warn("map '%s': invalid field #%d.\n", map_name, i);
1202 if (strcmp(name, "type") == 0) {
1203 if (!get_map_field_int(map_name, obj->btf, def, m,
1206 pr_debug("map '%s': found type = %u.\n",
1207 map_name, map->def.type);
1208 } else if (strcmp(name, "max_entries") == 0) {
1209 if (!get_map_field_int(map_name, obj->btf, def, m,
1210 &map->def.max_entries))
1212 pr_debug("map '%s': found max_entries = %u.\n",
1213 map_name, map->def.max_entries);
1214 } else if (strcmp(name, "map_flags") == 0) {
1215 if (!get_map_field_int(map_name, obj->btf, def, m,
1216 &map->def.map_flags))
1218 pr_debug("map '%s': found map_flags = %u.\n",
1219 map_name, map->def.map_flags);
1220 } else if (strcmp(name, "key_size") == 0) {
1223 if (!get_map_field_int(map_name, obj->btf, def, m,
1226 pr_debug("map '%s': found key_size = %u.\n",
1228 if (map->def.key_size && map->def.key_size != sz) {
1229 pr_warn("map '%s': conflicting key size %u != %u.\n",
1230 map_name, map->def.key_size, sz);
1233 map->def.key_size = sz;
1234 } else if (strcmp(name, "key") == 0) {
1237 t = btf__type_by_id(obj->btf, m->type);
1239 pr_warn("map '%s': key type [%d] not found.\n",
1243 if (!btf_is_ptr(t)) {
1244 pr_warn("map '%s': key spec is not PTR: %u.\n",
1245 map_name, btf_kind(t));
1248 sz = btf__resolve_size(obj->btf, t->type);
1250 pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
1251 map_name, t->type, (ssize_t)sz);
1254 pr_debug("map '%s': found key [%u], sz = %zd.\n",
1255 map_name, t->type, (ssize_t)sz);
1256 if (map->def.key_size && map->def.key_size != sz) {
1257 pr_warn("map '%s': conflicting key size %u != %zd.\n",
1258 map_name, map->def.key_size, (ssize_t)sz);
1261 map->def.key_size = sz;
1262 map->btf_key_type_id = t->type;
1263 } else if (strcmp(name, "value_size") == 0) {
1266 if (!get_map_field_int(map_name, obj->btf, def, m,
1269 pr_debug("map '%s': found value_size = %u.\n",
1271 if (map->def.value_size && map->def.value_size != sz) {
1272 pr_warn("map '%s': conflicting value size %u != %u.\n",
1273 map_name, map->def.value_size, sz);
1276 map->def.value_size = sz;
1277 } else if (strcmp(name, "value") == 0) {
1280 t = btf__type_by_id(obj->btf, m->type);
1282 pr_warn("map '%s': value type [%d] not found.\n",
1286 if (!btf_is_ptr(t)) {
1287 pr_warn("map '%s': value spec is not PTR: %u.\n",
1288 map_name, btf_kind(t));
1291 sz = btf__resolve_size(obj->btf, t->type);
1293 pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
1294 map_name, t->type, (ssize_t)sz);
1297 pr_debug("map '%s': found value [%u], sz = %zd.\n",
1298 map_name, t->type, (ssize_t)sz);
1299 if (map->def.value_size && map->def.value_size != sz) {
1300 pr_warn("map '%s': conflicting value size %u != %zd.\n",
1301 map_name, map->def.value_size, (ssize_t)sz);
1304 map->def.value_size = sz;
1305 map->btf_value_type_id = t->type;
1306 } else if (strcmp(name, "pinning") == 0) {
1310 if (!get_map_field_int(map_name, obj->btf, def, m,
1313 pr_debug("map '%s': found pinning = %u.\n",
1316 if (val != LIBBPF_PIN_NONE &&
1317 val != LIBBPF_PIN_BY_NAME) {
1318 pr_warn("map '%s': invalid pinning value %u.\n",
1322 if (val == LIBBPF_PIN_BY_NAME) {
1323 err = build_map_pin_path(map, pin_root_path);
1325 pr_warn("map '%s': couldn't build pin path.\n",
1332 pr_warn("map '%s': unknown field '%s'.\n",
1336 pr_debug("map '%s': ignoring unknown field '%s'.\n",
1341 if (map->def.type == BPF_MAP_TYPE_UNSPEC) {
1342 pr_warn("map '%s': map type isn't specified.\n", map_name);
1349 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
1350 const char *pin_root_path)
1352 const struct btf_type *sec = NULL;
1353 int nr_types, i, vlen, err;
1354 const struct btf_type *t;
1359 if (obj->efile.btf_maps_shndx < 0)
1362 scn = elf_getscn(obj->efile.elf, obj->efile.btf_maps_shndx);
1364 data = elf_getdata(scn, NULL);
1365 if (!scn || !data) {
1366 pr_warn("failed to get Elf_Data from map section %d (%s)\n",
1367 obj->efile.maps_shndx, MAPS_ELF_SEC);
1371 nr_types = btf__get_nr_types(obj->btf);
1372 for (i = 1; i <= nr_types; i++) {
1373 t = btf__type_by_id(obj->btf, i);
1374 if (!btf_is_datasec(t))
1376 name = btf__name_by_offset(obj->btf, t->name_off);
1377 if (strcmp(name, MAPS_ELF_SEC) == 0) {
1384 pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
1388 vlen = btf_vlen(sec);
1389 for (i = 0; i < vlen; i++) {
1390 err = bpf_object__init_user_btf_map(obj, sec, i,
1391 obj->efile.btf_maps_shndx,
1401 static int bpf_object__init_maps(struct bpf_object *obj,
1402 const struct bpf_object_open_opts *opts)
1404 const char *pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
1405 bool strict = !OPTS_GET(opts, relaxed_maps, false);
1408 err = bpf_object__init_user_maps(obj, strict);
1412 err = bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
1416 err = bpf_object__init_global_data_maps(obj);
1421 qsort(obj->maps, obj->nr_maps, sizeof(obj->maps[0]),
1427 static bool section_have_execinstr(struct bpf_object *obj, int idx)
1432 scn = elf_getscn(obj->efile.elf, idx);
1436 if (gelf_getshdr(scn, &sh) != &sh)
1439 if (sh.sh_flags & SHF_EXECINSTR)
1445 static void bpf_object__sanitize_btf(struct bpf_object *obj)
1447 bool has_datasec = obj->caps.btf_datasec;
1448 bool has_func = obj->caps.btf_func;
1449 struct btf *btf = obj->btf;
1453 if (!obj->btf || (has_func && has_datasec))
1456 for (i = 1; i <= btf__get_nr_types(btf); i++) {
1457 t = (struct btf_type *)btf__type_by_id(btf, i);
1459 if (!has_datasec && btf_is_var(t)) {
1460 /* replace VAR with INT */
1461 t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
1463 * using size = 1 is the safest choice, 4 will be too
1464 * big and cause kernel BTF validation failure if
1465 * original variable took less than 4 bytes
1468 *(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
1469 } else if (!has_datasec && btf_is_datasec(t)) {
1470 /* replace DATASEC with STRUCT */
1471 const struct btf_var_secinfo *v = btf_var_secinfos(t);
1472 struct btf_member *m = btf_members(t);
1473 struct btf_type *vt;
1476 name = (char *)btf__name_by_offset(btf, t->name_off);
1484 t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
1485 for (j = 0; j < vlen; j++, v++, m++) {
1486 /* order of field assignments is important */
1487 m->offset = v->offset * 8;
1489 /* preserve variable name as member name */
1490 vt = (void *)btf__type_by_id(btf, v->type);
1491 m->name_off = vt->name_off;
1493 } else if (!has_func && btf_is_func_proto(t)) {
1494 /* replace FUNC_PROTO with ENUM */
1496 t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
1497 t->size = sizeof(__u32); /* kernel enforced */
1498 } else if (!has_func && btf_is_func(t)) {
1499 /* replace FUNC with TYPEDEF */
1500 t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
1505 static void bpf_object__sanitize_btf_ext(struct bpf_object *obj)
1510 if (!obj->caps.btf_func) {
1511 btf_ext__free(obj->btf_ext);
1512 obj->btf_ext = NULL;
1516 static bool bpf_object__is_btf_mandatory(const struct bpf_object *obj)
1518 return obj->efile.btf_maps_shndx >= 0;
1521 static int bpf_object__init_btf(struct bpf_object *obj,
1523 Elf_Data *btf_ext_data)
1525 bool btf_required = bpf_object__is_btf_mandatory(obj);
1529 obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
1530 if (IS_ERR(obj->btf)) {
1531 pr_warn("Error loading ELF section %s: %d.\n",
1535 err = btf__finalize_data(obj, obj->btf);
1537 pr_warn("Error finalizing %s: %d.\n", BTF_ELF_SEC, err);
1543 pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
1544 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
1547 obj->btf_ext = btf_ext__new(btf_ext_data->d_buf,
1548 btf_ext_data->d_size);
1549 if (IS_ERR(obj->btf_ext)) {
1550 pr_warn("Error loading ELF section %s: %ld. Ignored and continue.\n",
1551 BTF_EXT_ELF_SEC, PTR_ERR(obj->btf_ext));
1552 obj->btf_ext = NULL;
1557 if (err || IS_ERR(obj->btf)) {
1559 err = err ? : PTR_ERR(obj->btf);
1562 if (!IS_ERR_OR_NULL(obj->btf))
1563 btf__free(obj->btf);
1566 if (btf_required && !obj->btf) {
1567 pr_warn("BTF is required, but is missing or corrupted.\n");
1568 return err == 0 ? -ENOENT : err;
1573 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
1580 bpf_object__sanitize_btf(obj);
1581 bpf_object__sanitize_btf_ext(obj);
1583 err = btf__load(obj->btf);
1585 pr_warn("Error loading %s into kernel: %d.\n",
1587 btf__free(obj->btf);
1589 /* btf_ext can't exist without btf, so free it as well */
1591 btf_ext__free(obj->btf_ext);
1592 obj->btf_ext = NULL;
1595 if (bpf_object__is_btf_mandatory(obj))
1601 static int bpf_object__elf_collect(struct bpf_object *obj)
1603 Elf *elf = obj->efile.elf;
1604 GElf_Ehdr *ep = &obj->efile.ehdr;
1605 Elf_Data *btf_ext_data = NULL;
1606 Elf_Data *btf_data = NULL;
1607 Elf_Scn *scn = NULL;
1608 int idx = 0, err = 0;
1610 /* Elf is corrupted/truncated, avoid calling elf_strptr. */
1611 if (!elf_rawdata(elf_getscn(elf, ep->e_shstrndx), NULL)) {
1612 pr_warn("failed to get e_shstrndx from %s\n", obj->path);
1613 return -LIBBPF_ERRNO__FORMAT;
1616 while ((scn = elf_nextscn(elf, scn)) != NULL) {
1622 if (gelf_getshdr(scn, &sh) != &sh) {
1623 pr_warn("failed to get section(%d) header from %s\n",
1625 return -LIBBPF_ERRNO__FORMAT;
1628 name = elf_strptr(elf, ep->e_shstrndx, sh.sh_name);
1630 pr_warn("failed to get section(%d) name from %s\n",
1632 return -LIBBPF_ERRNO__FORMAT;
1635 data = elf_getdata(scn, 0);
1637 pr_warn("failed to get section(%d) data from %s(%s)\n",
1638 idx, name, obj->path);
1639 return -LIBBPF_ERRNO__FORMAT;
1641 pr_debug("section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
1642 idx, name, (unsigned long)data->d_size,
1643 (int)sh.sh_link, (unsigned long)sh.sh_flags,
1646 if (strcmp(name, "license") == 0) {
1647 err = bpf_object__init_license(obj,
1652 } else if (strcmp(name, "version") == 0) {
1653 err = bpf_object__init_kversion(obj,
1658 } else if (strcmp(name, "maps") == 0) {
1659 obj->efile.maps_shndx = idx;
1660 } else if (strcmp(name, MAPS_ELF_SEC) == 0) {
1661 obj->efile.btf_maps_shndx = idx;
1662 } else if (strcmp(name, BTF_ELF_SEC) == 0) {
1664 } else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
1665 btf_ext_data = data;
1666 } else if (sh.sh_type == SHT_SYMTAB) {
1667 if (obj->efile.symbols) {
1668 pr_warn("bpf: multiple SYMTAB in %s\n",
1670 return -LIBBPF_ERRNO__FORMAT;
1672 obj->efile.symbols = data;
1673 obj->efile.strtabidx = sh.sh_link;
1674 } else if (sh.sh_type == SHT_PROGBITS && data->d_size > 0) {
1675 if (sh.sh_flags & SHF_EXECINSTR) {
1676 if (strcmp(name, ".text") == 0)
1677 obj->efile.text_shndx = idx;
1678 err = bpf_object__add_program(obj, data->d_buf,
1682 char errmsg[STRERR_BUFSIZE];
1685 cp = libbpf_strerror_r(-err, errmsg,
1687 pr_warn("failed to alloc program %s (%s): %s",
1688 name, obj->path, cp);
1691 } else if (strcmp(name, DATA_SEC) == 0) {
1692 obj->efile.data = data;
1693 obj->efile.data_shndx = idx;
1694 } else if (strcmp(name, RODATA_SEC) == 0) {
1695 obj->efile.rodata = data;
1696 obj->efile.rodata_shndx = idx;
1698 pr_debug("skip section(%d) %s\n", idx, name);
1700 } else if (sh.sh_type == SHT_REL) {
1701 int nr_sects = obj->efile.nr_reloc_sects;
1702 void *sects = obj->efile.reloc_sects;
1703 int sec = sh.sh_info; /* points to other section */
1705 /* Only do relo for section with exec instructions */
1706 if (!section_have_execinstr(obj, sec)) {
1707 pr_debug("skip relo %s(%d) for section(%d)\n",
1712 sects = reallocarray(sects, nr_sects + 1,
1713 sizeof(*obj->efile.reloc_sects));
1715 pr_warn("reloc_sects realloc failed\n");
1719 obj->efile.reloc_sects = sects;
1720 obj->efile.nr_reloc_sects++;
1722 obj->efile.reloc_sects[nr_sects].shdr = sh;
1723 obj->efile.reloc_sects[nr_sects].data = data;
1724 } else if (sh.sh_type == SHT_NOBITS &&
1725 strcmp(name, BSS_SEC) == 0) {
1726 obj->efile.bss = data;
1727 obj->efile.bss_shndx = idx;
1729 pr_debug("skip section(%d) %s\n", idx, name);
1733 if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
1734 pr_warn("Corrupted ELF file: index of strtab invalid\n");
1735 return -LIBBPF_ERRNO__FORMAT;
1737 return bpf_object__init_btf(obj, btf_data, btf_ext_data);
1740 static struct bpf_program *
1741 bpf_object__find_prog_by_idx(struct bpf_object *obj, int idx)
1743 struct bpf_program *prog;
1746 for (i = 0; i < obj->nr_programs; i++) {
1747 prog = &obj->programs[i];
1748 if (prog->idx == idx)
1754 struct bpf_program *
1755 bpf_object__find_program_by_title(const struct bpf_object *obj,
1758 struct bpf_program *pos;
1760 bpf_object__for_each_program(pos, obj) {
1761 if (pos->section_name && !strcmp(pos->section_name, title))
1767 struct bpf_program *
1768 bpf_object__find_program_by_name(const struct bpf_object *obj,
1771 struct bpf_program *prog;
1773 bpf_object__for_each_program(prog, obj) {
1774 if (!strcmp(prog->name, name))
1780 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
1783 return shndx == obj->efile.data_shndx ||
1784 shndx == obj->efile.bss_shndx ||
1785 shndx == obj->efile.rodata_shndx;
1788 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
1791 return shndx == obj->efile.maps_shndx ||
1792 shndx == obj->efile.btf_maps_shndx;
1795 static enum libbpf_map_type
1796 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
1798 if (shndx == obj->efile.data_shndx)
1799 return LIBBPF_MAP_DATA;
1800 else if (shndx == obj->efile.bss_shndx)
1801 return LIBBPF_MAP_BSS;
1802 else if (shndx == obj->efile.rodata_shndx)
1803 return LIBBPF_MAP_RODATA;
1805 return LIBBPF_MAP_UNSPEC;
1808 static int bpf_program__record_reloc(struct bpf_program *prog,
1809 struct reloc_desc *reloc_desc,
1810 __u32 insn_idx, const char *name,
1811 const GElf_Sym *sym, const GElf_Rel *rel)
1813 struct bpf_insn *insn = &prog->insns[insn_idx];
1814 size_t map_idx, nr_maps = prog->obj->nr_maps;
1815 struct bpf_object *obj = prog->obj;
1816 __u32 shdr_idx = sym->st_shndx;
1817 enum libbpf_map_type type;
1818 struct bpf_map *map;
1820 /* sub-program call relocation */
1821 if (insn->code == (BPF_JMP | BPF_CALL)) {
1822 if (insn->src_reg != BPF_PSEUDO_CALL) {
1823 pr_warn("incorrect bpf_call opcode\n");
1824 return -LIBBPF_ERRNO__RELOC;
1826 /* text_shndx can be 0, if no default "main" program exists */
1827 if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
1828 pr_warn("bad call relo against section %u\n", shdr_idx);
1829 return -LIBBPF_ERRNO__RELOC;
1831 if (sym->st_value % 8) {
1832 pr_warn("bad call relo offset: %zu\n",
1833 (size_t)sym->st_value);
1834 return -LIBBPF_ERRNO__RELOC;
1836 reloc_desc->type = RELO_CALL;
1837 reloc_desc->insn_idx = insn_idx;
1838 reloc_desc->sym_off = sym->st_value;
1839 obj->has_pseudo_calls = true;
1843 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) {
1844 pr_warn("invalid relo for insns[%d].code 0x%x\n",
1845 insn_idx, insn->code);
1846 return -LIBBPF_ERRNO__RELOC;
1848 if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
1849 pr_warn("invalid relo for \'%s\' in special section 0x%x; forgot to initialize global var?..\n",
1851 return -LIBBPF_ERRNO__RELOC;
1854 type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
1856 /* generic map reference relocation */
1857 if (type == LIBBPF_MAP_UNSPEC) {
1858 if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
1859 pr_warn("bad map relo against section %u\n",
1861 return -LIBBPF_ERRNO__RELOC;
1863 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
1864 map = &obj->maps[map_idx];
1865 if (map->libbpf_type != type ||
1866 map->sec_idx != sym->st_shndx ||
1867 map->sec_offset != sym->st_value)
1869 pr_debug("found map %zd (%s, sec %d, off %zu) for insn %u\n",
1870 map_idx, map->name, map->sec_idx,
1871 map->sec_offset, insn_idx);
1874 if (map_idx >= nr_maps) {
1875 pr_warn("map relo failed to find map for sec %u, off %zu\n",
1876 shdr_idx, (size_t)sym->st_value);
1877 return -LIBBPF_ERRNO__RELOC;
1879 reloc_desc->type = RELO_LD64;
1880 reloc_desc->insn_idx = insn_idx;
1881 reloc_desc->map_idx = map_idx;
1882 reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
1886 /* global data map relocation */
1887 if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
1888 pr_warn("bad data relo against section %u\n", shdr_idx);
1889 return -LIBBPF_ERRNO__RELOC;
1891 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
1892 map = &obj->maps[map_idx];
1893 if (map->libbpf_type != type)
1895 pr_debug("found data map %zd (%s, sec %d, off %zu) for insn %u\n",
1896 map_idx, map->name, map->sec_idx, map->sec_offset,
1900 if (map_idx >= nr_maps) {
1901 pr_warn("data relo failed to find map for sec %u\n",
1903 return -LIBBPF_ERRNO__RELOC;
1906 reloc_desc->type = RELO_DATA;
1907 reloc_desc->insn_idx = insn_idx;
1908 reloc_desc->map_idx = map_idx;
1909 reloc_desc->sym_off = sym->st_value;
1914 bpf_program__collect_reloc(struct bpf_program *prog, GElf_Shdr *shdr,
1915 Elf_Data *data, struct bpf_object *obj)
1917 Elf_Data *symbols = obj->efile.symbols;
1920 pr_debug("collecting relocating info for: '%s'\n", prog->section_name);
1921 nrels = shdr->sh_size / shdr->sh_entsize;
1923 prog->reloc_desc = malloc(sizeof(*prog->reloc_desc) * nrels);
1924 if (!prog->reloc_desc) {
1925 pr_warn("failed to alloc memory in relocation\n");
1928 prog->nr_reloc = nrels;
1930 for (i = 0; i < nrels; i++) {
1936 if (!gelf_getrel(data, i, &rel)) {
1937 pr_warn("relocation: failed to get %d reloc\n", i);
1938 return -LIBBPF_ERRNO__FORMAT;
1940 if (!gelf_getsym(symbols, GELF_R_SYM(rel.r_info), &sym)) {
1941 pr_warn("relocation: symbol %"PRIx64" not found\n",
1942 GELF_R_SYM(rel.r_info));
1943 return -LIBBPF_ERRNO__FORMAT;
1945 if (rel.r_offset % sizeof(struct bpf_insn))
1946 return -LIBBPF_ERRNO__FORMAT;
1948 insn_idx = rel.r_offset / sizeof(struct bpf_insn);
1949 name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
1950 sym.st_name) ? : "<?>";
1952 pr_debug("relo for shdr %u, symb %zu, value %zu, type %d, bind %d, name %d (\'%s\'), insn %u\n",
1953 (__u32)sym.st_shndx, (size_t)GELF_R_SYM(rel.r_info),
1954 (size_t)sym.st_value, GELF_ST_TYPE(sym.st_info),
1955 GELF_ST_BIND(sym.st_info), sym.st_name, name,
1958 err = bpf_program__record_reloc(prog, &prog->reloc_desc[i],
1959 insn_idx, name, &sym, &rel);
1966 static int bpf_map_find_btf_info(struct bpf_object *obj, struct bpf_map *map)
1968 struct bpf_map_def *def = &map->def;
1969 __u32 key_type_id = 0, value_type_id = 0;
1972 /* if it's BTF-defined map, we don't need to search for type IDs */
1973 if (map->sec_idx == obj->efile.btf_maps_shndx)
1976 if (!bpf_map__is_internal(map)) {
1977 ret = btf__get_map_kv_tids(obj->btf, map->name, def->key_size,
1978 def->value_size, &key_type_id,
1982 * LLVM annotates global data differently in BTF, that is,
1983 * only as '.data', '.bss' or '.rodata'.
1985 ret = btf__find_by_name(obj->btf,
1986 libbpf_type_to_btf_name[map->libbpf_type]);
1991 map->btf_key_type_id = key_type_id;
1992 map->btf_value_type_id = bpf_map__is_internal(map) ?
1993 ret : value_type_id;
1997 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
1999 struct bpf_map_info info = {};
2000 __u32 len = sizeof(info);
2004 err = bpf_obj_get_info_by_fd(fd, &info, &len);
2008 new_name = strdup(info.name);
2012 new_fd = open("/", O_RDONLY | O_CLOEXEC);
2015 goto err_free_new_name;
2018 new_fd = dup3(fd, new_fd, O_CLOEXEC);
2021 goto err_close_new_fd;
2024 err = zclose(map->fd);
2027 goto err_close_new_fd;
2032 map->name = new_name;
2033 map->def.type = info.type;
2034 map->def.key_size = info.key_size;
2035 map->def.value_size = info.value_size;
2036 map->def.max_entries = info.max_entries;
2037 map->def.map_flags = info.map_flags;
2038 map->btf_key_type_id = info.btf_key_type_id;
2039 map->btf_value_type_id = info.btf_value_type_id;
2051 int bpf_map__resize(struct bpf_map *map, __u32 max_entries)
2053 if (!map || !max_entries)
2056 /* If map already created, its attributes can't be changed. */
2060 map->def.max_entries = max_entries;
2066 bpf_object__probe_name(struct bpf_object *obj)
2068 struct bpf_load_program_attr attr;
2069 char *cp, errmsg[STRERR_BUFSIZE];
2070 struct bpf_insn insns[] = {
2071 BPF_MOV64_IMM(BPF_REG_0, 0),
2076 /* make sure basic loading works */
2078 memset(&attr, 0, sizeof(attr));
2079 attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
2081 attr.insns_cnt = ARRAY_SIZE(insns);
2082 attr.license = "GPL";
2084 ret = bpf_load_program_xattr(&attr, NULL, 0);
2086 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
2087 pr_warn("Error in %s():%s(%d). Couldn't load basic 'r0 = 0' BPF program.\n",
2088 __func__, cp, errno);
2093 /* now try the same program, but with the name */
2096 ret = bpf_load_program_xattr(&attr, NULL, 0);
2106 bpf_object__probe_global_data(struct bpf_object *obj)
2108 struct bpf_load_program_attr prg_attr;
2109 struct bpf_create_map_attr map_attr;
2110 char *cp, errmsg[STRERR_BUFSIZE];
2111 struct bpf_insn insns[] = {
2112 BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16),
2113 BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42),
2114 BPF_MOV64_IMM(BPF_REG_0, 0),
2119 memset(&map_attr, 0, sizeof(map_attr));
2120 map_attr.map_type = BPF_MAP_TYPE_ARRAY;
2121 map_attr.key_size = sizeof(int);
2122 map_attr.value_size = 32;
2123 map_attr.max_entries = 1;
2125 map = bpf_create_map_xattr(&map_attr);
2127 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
2128 pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
2129 __func__, cp, errno);
2135 memset(&prg_attr, 0, sizeof(prg_attr));
2136 prg_attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
2137 prg_attr.insns = insns;
2138 prg_attr.insns_cnt = ARRAY_SIZE(insns);
2139 prg_attr.license = "GPL";
2141 ret = bpf_load_program_xattr(&prg_attr, NULL, 0);
2143 obj->caps.global_data = 1;
2151 static int bpf_object__probe_btf_func(struct bpf_object *obj)
2153 static const char strs[] = "\0int\0x\0a";
2154 /* void x(int a) {} */
2157 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
2158 /* FUNC_PROTO */ /* [2] */
2159 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
2160 BTF_PARAM_ENC(7, 1),
2161 /* FUNC x */ /* [3] */
2162 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0), 2),
2166 btf_fd = libbpf__load_raw_btf((char *)types, sizeof(types),
2167 strs, sizeof(strs));
2169 obj->caps.btf_func = 1;
2177 static int bpf_object__probe_btf_datasec(struct bpf_object *obj)
2179 static const char strs[] = "\0x\0.data";
2183 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
2184 /* VAR x */ /* [2] */
2185 BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
2187 /* DATASEC val */ /* [3] */
2188 BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC, 0, 1), 4),
2189 BTF_VAR_SECINFO_ENC(2, 0, 4),
2193 btf_fd = libbpf__load_raw_btf((char *)types, sizeof(types),
2194 strs, sizeof(strs));
2196 obj->caps.btf_datasec = 1;
2204 static int bpf_object__probe_array_mmap(struct bpf_object *obj)
2206 struct bpf_create_map_attr attr = {
2207 .map_type = BPF_MAP_TYPE_ARRAY,
2208 .map_flags = BPF_F_MMAPABLE,
2209 .key_size = sizeof(int),
2210 .value_size = sizeof(int),
2215 fd = bpf_create_map_xattr(&attr);
2217 obj->caps.array_mmap = 1;
2226 bpf_object__probe_caps(struct bpf_object *obj)
2228 int (*probe_fn[])(struct bpf_object *obj) = {
2229 bpf_object__probe_name,
2230 bpf_object__probe_global_data,
2231 bpf_object__probe_btf_func,
2232 bpf_object__probe_btf_datasec,
2233 bpf_object__probe_array_mmap,
2237 for (i = 0; i < ARRAY_SIZE(probe_fn); i++) {
2238 ret = probe_fn[i](obj);
2240 pr_debug("Probe #%d failed with %d.\n", i, ret);
2246 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
2248 struct bpf_map_info map_info = {};
2249 char msg[STRERR_BUFSIZE];
2252 map_info_len = sizeof(map_info);
2254 if (bpf_obj_get_info_by_fd(map_fd, &map_info, &map_info_len)) {
2255 pr_warn("failed to get map info for map FD %d: %s\n",
2256 map_fd, libbpf_strerror_r(errno, msg, sizeof(msg)));
2260 return (map_info.type == map->def.type &&
2261 map_info.key_size == map->def.key_size &&
2262 map_info.value_size == map->def.value_size &&
2263 map_info.max_entries == map->def.max_entries &&
2264 map_info.map_flags == map->def.map_flags);
2268 bpf_object__reuse_map(struct bpf_map *map)
2270 char *cp, errmsg[STRERR_BUFSIZE];
2273 pin_fd = bpf_obj_get(map->pin_path);
2276 if (err == -ENOENT) {
2277 pr_debug("found no pinned map to reuse at '%s'\n",
2282 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
2283 pr_warn("couldn't retrieve pinned map '%s': %s\n",
2288 if (!map_is_reuse_compat(map, pin_fd)) {
2289 pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
2295 err = bpf_map__reuse_fd(map, pin_fd);
2301 pr_debug("reused pinned map at '%s'\n", map->pin_path);
2307 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
2309 char *cp, errmsg[STRERR_BUFSIZE];
2312 /* Nothing to do here since kernel already zero-initializes .bss map. */
2313 if (map->libbpf_type == LIBBPF_MAP_BSS)
2316 err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
2319 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
2320 pr_warn("Error setting initial map(%s) contents: %s\n",
2325 /* Freeze .rodata map as read-only from syscall side. */
2326 if (map->libbpf_type == LIBBPF_MAP_RODATA) {
2327 err = bpf_map_freeze(map->fd);
2330 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
2331 pr_warn("Error freezing map(%s) as read-only: %s\n",
2340 bpf_object__create_maps(struct bpf_object *obj)
2342 struct bpf_create_map_attr create_attr = {};
2347 for (i = 0; i < obj->nr_maps; i++) {
2348 struct bpf_map *map = &obj->maps[i];
2349 struct bpf_map_def *def = &map->def;
2350 char *cp, errmsg[STRERR_BUFSIZE];
2351 int *pfd = &map->fd;
2353 if (map->pin_path) {
2354 err = bpf_object__reuse_map(map);
2356 pr_warn("error reusing pinned map %s\n",
2363 pr_debug("skip map create (preset) %s: fd=%d\n",
2364 map->name, map->fd);
2369 create_attr.name = map->name;
2370 create_attr.map_ifindex = map->map_ifindex;
2371 create_attr.map_type = def->type;
2372 create_attr.map_flags = def->map_flags;
2373 create_attr.key_size = def->key_size;
2374 create_attr.value_size = def->value_size;
2375 if (def->type == BPF_MAP_TYPE_PERF_EVENT_ARRAY &&
2376 !def->max_entries) {
2378 nr_cpus = libbpf_num_possible_cpus();
2380 pr_warn("failed to determine number of system CPUs: %d\n",
2385 pr_debug("map '%s': setting size to %d\n",
2386 map->name, nr_cpus);
2387 create_attr.max_entries = nr_cpus;
2389 create_attr.max_entries = def->max_entries;
2391 create_attr.btf_fd = 0;
2392 create_attr.btf_key_type_id = 0;
2393 create_attr.btf_value_type_id = 0;
2394 if (bpf_map_type__is_map_in_map(def->type) &&
2395 map->inner_map_fd >= 0)
2396 create_attr.inner_map_fd = map->inner_map_fd;
2398 if (obj->btf && !bpf_map_find_btf_info(obj, map)) {
2399 create_attr.btf_fd = btf__fd(obj->btf);
2400 create_attr.btf_key_type_id = map->btf_key_type_id;
2401 create_attr.btf_value_type_id = map->btf_value_type_id;
2404 *pfd = bpf_create_map_xattr(&create_attr);
2405 if (*pfd < 0 && (create_attr.btf_key_type_id ||
2406 create_attr.btf_value_type_id)) {
2408 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
2409 pr_warn("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
2410 map->name, cp, err);
2411 create_attr.btf_fd = 0;
2412 create_attr.btf_key_type_id = 0;
2413 create_attr.btf_value_type_id = 0;
2414 map->btf_key_type_id = 0;
2415 map->btf_value_type_id = 0;
2416 *pfd = bpf_create_map_xattr(&create_attr);
2424 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
2425 pr_warn("failed to create map (name: '%s'): %s(%d)\n",
2426 map->name, cp, err);
2427 for (j = 0; j < i; j++)
2428 zclose(obj->maps[j].fd);
2432 if (bpf_map__is_internal(map)) {
2433 err = bpf_object__populate_internal_map(obj, map);
2440 if (map->pin_path && !map->pinned) {
2441 err = bpf_map__pin(map, NULL);
2443 pr_warn("failed to auto-pin map name '%s' at '%s'\n",
2444 map->name, map->pin_path);
2449 pr_debug("created map %s: fd=%d\n", map->name, *pfd);
2456 check_btf_ext_reloc_err(struct bpf_program *prog, int err,
2457 void *btf_prog_info, const char *info_name)
2459 if (err != -ENOENT) {
2460 pr_warn("Error in loading %s for sec %s.\n",
2461 info_name, prog->section_name);
2465 /* err == -ENOENT (i.e. prog->section_name not found in btf_ext) */
2467 if (btf_prog_info) {
2469 * Some info has already been found but has problem
2470 * in the last btf_ext reloc. Must have to error out.
2472 pr_warn("Error in relocating %s for sec %s.\n",
2473 info_name, prog->section_name);
2477 /* Have problem loading the very first info. Ignore the rest. */
2478 pr_warn("Cannot find %s for main program sec %s. Ignore all %s.\n",
2479 info_name, prog->section_name, info_name);
2484 bpf_program_reloc_btf_ext(struct bpf_program *prog, struct bpf_object *obj,
2485 const char *section_name, __u32 insn_offset)
2489 if (!insn_offset || prog->func_info) {
2491 * !insn_offset => main program
2493 * For sub prog, the main program's func_info has to
2494 * be loaded first (i.e. prog->func_info != NULL)
2496 err = btf_ext__reloc_func_info(obj->btf, obj->btf_ext,
2497 section_name, insn_offset,
2499 &prog->func_info_cnt);
2501 return check_btf_ext_reloc_err(prog, err,
2505 prog->func_info_rec_size = btf_ext__func_info_rec_size(obj->btf_ext);
2508 if (!insn_offset || prog->line_info) {
2509 err = btf_ext__reloc_line_info(obj->btf, obj->btf_ext,
2510 section_name, insn_offset,
2512 &prog->line_info_cnt);
2514 return check_btf_ext_reloc_err(prog, err,
2518 prog->line_info_rec_size = btf_ext__line_info_rec_size(obj->btf_ext);
2524 #define BPF_CORE_SPEC_MAX_LEN 64
2526 /* represents BPF CO-RE field or array element accessor */
2527 struct bpf_core_accessor {
2528 __u32 type_id; /* struct/union type or array element type */
2529 __u32 idx; /* field index or array index */
2530 const char *name; /* field name or NULL for array accessor */
2533 struct bpf_core_spec {
2534 const struct btf *btf;
2535 /* high-level spec: named fields and array indices only */
2536 struct bpf_core_accessor spec[BPF_CORE_SPEC_MAX_LEN];
2537 /* high-level spec length */
2539 /* raw, low-level spec: 1-to-1 with accessor spec string */
2540 int raw_spec[BPF_CORE_SPEC_MAX_LEN];
2541 /* raw spec length */
2543 /* field bit offset represented by spec */
2547 static bool str_is_empty(const char *s)
2553 * Turn bpf_field_reloc into a low- and high-level spec representation,
2554 * validating correctness along the way, as well as calculating resulting
2555 * field bit offset, specified by accessor string. Low-level spec captures
2556 * every single level of nestedness, including traversing anonymous
2557 * struct/union members. High-level one only captures semantically meaningful
2558 * "turning points": named fields and array indicies.
2559 * E.g., for this case:
2562 * int __unimportant;
2570 * struct sample *s = ...;
2572 * int x = &s->a[3]; // access string = '0:1:2:3'
2574 * Low-level spec has 1:1 mapping with each element of access string (it's
2575 * just a parsed access string representation): [0, 1, 2, 3].
2577 * High-level spec will capture only 3 points:
2578 * - intial zero-index access by pointer (&s->... is the same as &s[0]...);
2579 * - field 'a' access (corresponds to '2' in low-level spec);
2580 * - array element #3 access (corresponds to '3' in low-level spec).
2583 static int bpf_core_spec_parse(const struct btf *btf,
2585 const char *spec_str,
2586 struct bpf_core_spec *spec)
2588 int access_idx, parsed_len, i;
2589 const struct btf_type *t;
2594 if (str_is_empty(spec_str) || *spec_str == ':')
2597 memset(spec, 0, sizeof(*spec));
2600 /* parse spec_str="0:1:2:3:4" into array raw_spec=[0, 1, 2, 3, 4] */
2602 if (*spec_str == ':')
2604 if (sscanf(spec_str, "%d%n", &access_idx, &parsed_len) != 1)
2606 if (spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
2608 spec_str += parsed_len;
2609 spec->raw_spec[spec->raw_len++] = access_idx;
2612 if (spec->raw_len == 0)
2615 /* first spec value is always reloc type array index */
2616 t = skip_mods_and_typedefs(btf, type_id, &id);
2620 access_idx = spec->raw_spec[0];
2621 spec->spec[0].type_id = id;
2622 spec->spec[0].idx = access_idx;
2625 sz = btf__resolve_size(btf, id);
2628 spec->bit_offset = access_idx * sz * 8;
2630 for (i = 1; i < spec->raw_len; i++) {
2631 t = skip_mods_and_typedefs(btf, id, &id);
2635 access_idx = spec->raw_spec[i];
2637 if (btf_is_composite(t)) {
2638 const struct btf_member *m;
2641 if (access_idx >= btf_vlen(t))
2644 bit_offset = btf_member_bit_offset(t, access_idx);
2645 spec->bit_offset += bit_offset;
2647 m = btf_members(t) + access_idx;
2649 name = btf__name_by_offset(btf, m->name_off);
2650 if (str_is_empty(name))
2653 spec->spec[spec->len].type_id = id;
2654 spec->spec[spec->len].idx = access_idx;
2655 spec->spec[spec->len].name = name;
2660 } else if (btf_is_array(t)) {
2661 const struct btf_array *a = btf_array(t);
2663 t = skip_mods_and_typedefs(btf, a->type, &id);
2664 if (!t || access_idx >= a->nelems)
2667 spec->spec[spec->len].type_id = id;
2668 spec->spec[spec->len].idx = access_idx;
2671 sz = btf__resolve_size(btf, id);
2674 spec->bit_offset += access_idx * sz * 8;
2676 pr_warn("relo for [%u] %s (at idx %d) captures type [%d] of unexpected kind %d\n",
2677 type_id, spec_str, i, id, btf_kind(t));
2685 static bool bpf_core_is_flavor_sep(const char *s)
2687 /* check X___Y name pattern, where X and Y are not underscores */
2688 return s[0] != '_' && /* X */
2689 s[1] == '_' && s[2] == '_' && s[3] == '_' && /* ___ */
2690 s[4] != '_'; /* Y */
2693 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
2694 * before last triple underscore. Struct name part after last triple
2695 * underscore is ignored by BPF CO-RE relocation during relocation matching.
2697 static size_t bpf_core_essential_name_len(const char *name)
2699 size_t n = strlen(name);
2702 for (i = n - 5; i >= 0; i--) {
2703 if (bpf_core_is_flavor_sep(name + i))
2709 /* dynamically sized list of type IDs */
2715 static void bpf_core_free_cands(struct ids_vec *cand_ids)
2717 free(cand_ids->data);
2721 static struct ids_vec *bpf_core_find_cands(const struct btf *local_btf,
2722 __u32 local_type_id,
2723 const struct btf *targ_btf)
2725 size_t local_essent_len, targ_essent_len;
2726 const char *local_name, *targ_name;
2727 const struct btf_type *t;
2728 struct ids_vec *cand_ids;
2732 t = btf__type_by_id(local_btf, local_type_id);
2734 return ERR_PTR(-EINVAL);
2736 local_name = btf__name_by_offset(local_btf, t->name_off);
2737 if (str_is_empty(local_name))
2738 return ERR_PTR(-EINVAL);
2739 local_essent_len = bpf_core_essential_name_len(local_name);
2741 cand_ids = calloc(1, sizeof(*cand_ids));
2743 return ERR_PTR(-ENOMEM);
2745 n = btf__get_nr_types(targ_btf);
2746 for (i = 1; i <= n; i++) {
2747 t = btf__type_by_id(targ_btf, i);
2748 targ_name = btf__name_by_offset(targ_btf, t->name_off);
2749 if (str_is_empty(targ_name))
2752 targ_essent_len = bpf_core_essential_name_len(targ_name);
2753 if (targ_essent_len != local_essent_len)
2756 if (strncmp(local_name, targ_name, local_essent_len) == 0) {
2757 pr_debug("[%d] %s: found candidate [%d] %s\n",
2758 local_type_id, local_name, i, targ_name);
2759 new_ids = realloc(cand_ids->data, cand_ids->len + 1);
2764 cand_ids->data = new_ids;
2765 cand_ids->data[cand_ids->len++] = i;
2770 bpf_core_free_cands(cand_ids);
2771 return ERR_PTR(err);
2774 /* Check two types for compatibility, skipping const/volatile/restrict and
2775 * typedefs, to ensure we are relocating compatible entities:
2776 * - any two STRUCTs/UNIONs are compatible and can be mixed;
2777 * - any two FWDs are compatible, if their names match (modulo flavor suffix);
2778 * - any two PTRs are always compatible;
2779 * - for ENUMs, names should be the same (ignoring flavor suffix) or at
2780 * least one of enums should be anonymous;
2781 * - for ENUMs, check sizes, names are ignored;
2782 * - for INT, size and signedness are ignored;
2783 * - for ARRAY, dimensionality is ignored, element types are checked for
2784 * compatibility recursively;
2785 * - everything else shouldn't be ever a target of relocation.
2786 * These rules are not set in stone and probably will be adjusted as we get
2787 * more experience with using BPF CO-RE relocations.
2789 static int bpf_core_fields_are_compat(const struct btf *local_btf,
2791 const struct btf *targ_btf,
2794 const struct btf_type *local_type, *targ_type;
2797 local_type = skip_mods_and_typedefs(local_btf, local_id, &local_id);
2798 targ_type = skip_mods_and_typedefs(targ_btf, targ_id, &targ_id);
2799 if (!local_type || !targ_type)
2802 if (btf_is_composite(local_type) && btf_is_composite(targ_type))
2804 if (btf_kind(local_type) != btf_kind(targ_type))
2807 switch (btf_kind(local_type)) {
2811 case BTF_KIND_ENUM: {
2812 const char *local_name, *targ_name;
2813 size_t local_len, targ_len;
2815 local_name = btf__name_by_offset(local_btf,
2816 local_type->name_off);
2817 targ_name = btf__name_by_offset(targ_btf, targ_type->name_off);
2818 local_len = bpf_core_essential_name_len(local_name);
2819 targ_len = bpf_core_essential_name_len(targ_name);
2820 /* one of them is anonymous or both w/ same flavor-less names */
2821 return local_len == 0 || targ_len == 0 ||
2822 (local_len == targ_len &&
2823 strncmp(local_name, targ_name, local_len) == 0);
2826 /* just reject deprecated bitfield-like integers; all other
2827 * integers are by default compatible between each other
2829 return btf_int_offset(local_type) == 0 &&
2830 btf_int_offset(targ_type) == 0;
2831 case BTF_KIND_ARRAY:
2832 local_id = btf_array(local_type)->type;
2833 targ_id = btf_array(targ_type)->type;
2836 pr_warn("unexpected kind %d relocated, local [%d], target [%d]\n",
2837 btf_kind(local_type), local_id, targ_id);
2843 * Given single high-level named field accessor in local type, find
2844 * corresponding high-level accessor for a target type. Along the way,
2845 * maintain low-level spec for target as well. Also keep updating target
2848 * Searching is performed through recursive exhaustive enumeration of all
2849 * fields of a struct/union. If there are any anonymous (embedded)
2850 * structs/unions, they are recursively searched as well. If field with
2851 * desired name is found, check compatibility between local and target types,
2852 * before returning result.
2854 * 1 is returned, if field is found.
2855 * 0 is returned if no compatible field is found.
2856 * <0 is returned on error.
2858 static int bpf_core_match_member(const struct btf *local_btf,
2859 const struct bpf_core_accessor *local_acc,
2860 const struct btf *targ_btf,
2862 struct bpf_core_spec *spec,
2863 __u32 *next_targ_id)
2865 const struct btf_type *local_type, *targ_type;
2866 const struct btf_member *local_member, *m;
2867 const char *local_name, *targ_name;
2871 targ_type = skip_mods_and_typedefs(targ_btf, targ_id, &targ_id);
2874 if (!btf_is_composite(targ_type))
2877 local_id = local_acc->type_id;
2878 local_type = btf__type_by_id(local_btf, local_id);
2879 local_member = btf_members(local_type) + local_acc->idx;
2880 local_name = btf__name_by_offset(local_btf, local_member->name_off);
2882 n = btf_vlen(targ_type);
2883 m = btf_members(targ_type);
2884 for (i = 0; i < n; i++, m++) {
2887 bit_offset = btf_member_bit_offset(targ_type, i);
2889 /* too deep struct/union/array nesting */
2890 if (spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
2893 /* speculate this member will be the good one */
2894 spec->bit_offset += bit_offset;
2895 spec->raw_spec[spec->raw_len++] = i;
2897 targ_name = btf__name_by_offset(targ_btf, m->name_off);
2898 if (str_is_empty(targ_name)) {
2899 /* embedded struct/union, we need to go deeper */
2900 found = bpf_core_match_member(local_btf, local_acc,
2902 spec, next_targ_id);
2903 if (found) /* either found or error */
2905 } else if (strcmp(local_name, targ_name) == 0) {
2906 /* matching named field */
2907 struct bpf_core_accessor *targ_acc;
2909 targ_acc = &spec->spec[spec->len++];
2910 targ_acc->type_id = targ_id;
2912 targ_acc->name = targ_name;
2914 *next_targ_id = m->type;
2915 found = bpf_core_fields_are_compat(local_btf,
2919 spec->len--; /* pop accessor */
2922 /* member turned out not to be what we looked for */
2923 spec->bit_offset -= bit_offset;
2931 * Try to match local spec to a target type and, if successful, produce full
2932 * target spec (high-level, low-level + bit offset).
2934 static int bpf_core_spec_match(struct bpf_core_spec *local_spec,
2935 const struct btf *targ_btf, __u32 targ_id,
2936 struct bpf_core_spec *targ_spec)
2938 const struct btf_type *targ_type;
2939 const struct bpf_core_accessor *local_acc;
2940 struct bpf_core_accessor *targ_acc;
2943 memset(targ_spec, 0, sizeof(*targ_spec));
2944 targ_spec->btf = targ_btf;
2946 local_acc = &local_spec->spec[0];
2947 targ_acc = &targ_spec->spec[0];
2949 for (i = 0; i < local_spec->len; i++, local_acc++, targ_acc++) {
2950 targ_type = skip_mods_and_typedefs(targ_spec->btf, targ_id,
2955 if (local_acc->name) {
2956 matched = bpf_core_match_member(local_spec->btf,
2959 targ_spec, &targ_id);
2963 /* for i=0, targ_id is already treated as array element
2964 * type (because it's the original struct), for others
2965 * we should find array element type first
2968 const struct btf_array *a;
2970 if (!btf_is_array(targ_type))
2973 a = btf_array(targ_type);
2974 if (local_acc->idx >= a->nelems)
2976 if (!skip_mods_and_typedefs(targ_btf, a->type,
2981 /* too deep struct/union/array nesting */
2982 if (targ_spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
2985 targ_acc->type_id = targ_id;
2986 targ_acc->idx = local_acc->idx;
2987 targ_acc->name = NULL;
2989 targ_spec->raw_spec[targ_spec->raw_len] = targ_acc->idx;
2990 targ_spec->raw_len++;
2992 sz = btf__resolve_size(targ_btf, targ_id);
2995 targ_spec->bit_offset += local_acc->idx * sz * 8;
3002 static int bpf_core_calc_field_relo(const struct bpf_program *prog,
3003 const struct bpf_field_reloc *relo,
3004 const struct bpf_core_spec *spec,
3005 __u32 *val, bool *validate)
3007 const struct bpf_core_accessor *acc = &spec->spec[spec->len - 1];
3008 const struct btf_type *t = btf__type_by_id(spec->btf, acc->type_id);
3009 __u32 byte_off, byte_sz, bit_off, bit_sz;
3010 const struct btf_member *m;
3011 const struct btf_type *mt;
3015 /* a[n] accessor needs special handling */
3017 if (relo->kind == BPF_FIELD_BYTE_OFFSET) {
3018 *val = spec->bit_offset / 8;
3019 } else if (relo->kind == BPF_FIELD_BYTE_SIZE) {
3020 sz = btf__resolve_size(spec->btf, acc->type_id);
3025 pr_warn("prog '%s': relo %d at insn #%d can't be applied to array access\n",
3026 bpf_program__title(prog, false),
3027 relo->kind, relo->insn_off / 8);
3035 m = btf_members(t) + acc->idx;
3036 mt = skip_mods_and_typedefs(spec->btf, m->type, NULL);
3037 bit_off = spec->bit_offset;
3038 bit_sz = btf_member_bitfield_size(t, acc->idx);
3040 bitfield = bit_sz > 0;
3043 byte_off = bit_off / 8 / byte_sz * byte_sz;
3044 /* figure out smallest int size necessary for bitfield load */
3045 while (bit_off + bit_sz - byte_off * 8 > byte_sz * 8) {
3047 /* bitfield can't be read with 64-bit read */
3048 pr_warn("prog '%s': relo %d at insn #%d can't be satisfied for bitfield\n",
3049 bpf_program__title(prog, false),
3050 relo->kind, relo->insn_off / 8);
3054 byte_off = bit_off / 8 / byte_sz * byte_sz;
3057 sz = btf__resolve_size(spec->btf, m->type);
3061 byte_off = spec->bit_offset / 8;
3062 bit_sz = byte_sz * 8;
3065 /* for bitfields, all the relocatable aspects are ambiguous and we
3066 * might disagree with compiler, so turn off validation of expected
3067 * value, except for signedness
3070 *validate = !bitfield;
3072 switch (relo->kind) {
3073 case BPF_FIELD_BYTE_OFFSET:
3076 case BPF_FIELD_BYTE_SIZE:
3079 case BPF_FIELD_SIGNED:
3080 /* enums will be assumed unsigned */
3081 *val = btf_is_enum(mt) ||
3082 (btf_int_encoding(mt) & BTF_INT_SIGNED);
3084 *validate = true; /* signedness is never ambiguous */
3086 case BPF_FIELD_LSHIFT_U64:
3087 #if __BYTE_ORDER == __LITTLE_ENDIAN
3088 *val = 64 - (bit_off + bit_sz - byte_off * 8);
3090 *val = (8 - byte_sz) * 8 + (bit_off - byte_off * 8);
3093 case BPF_FIELD_RSHIFT_U64:
3096 *validate = true; /* right shift is never ambiguous */
3098 case BPF_FIELD_EXISTS:
3100 pr_warn("prog '%s': unknown relo %d at insn #%d\n",
3101 bpf_program__title(prog, false),
3102 relo->kind, relo->insn_off / 8);
3110 * Patch relocatable BPF instruction.
3112 * Patched value is determined by relocation kind and target specification.
3113 * For field existence relocation target spec will be NULL if field is not
3115 * Expected insn->imm value is determined using relocation kind and local
3116 * spec, and is checked before patching instruction. If actual insn->imm value
3117 * is wrong, bail out with error.
3119 * Currently three kinds of BPF instructions are supported:
3120 * 1. rX = <imm> (assignment with immediate operand);
3121 * 2. rX += <imm> (arithmetic operations with immediate operand);
3123 static int bpf_core_reloc_insn(struct bpf_program *prog,
3124 const struct bpf_field_reloc *relo,
3125 const struct bpf_core_spec *local_spec,
3126 const struct bpf_core_spec *targ_spec)
3128 bool failed = false, validate = true;
3129 __u32 orig_val, new_val;
3130 struct bpf_insn *insn;
3134 if (relo->insn_off % sizeof(struct bpf_insn))
3136 insn_idx = relo->insn_off / sizeof(struct bpf_insn);
3138 if (relo->kind == BPF_FIELD_EXISTS) {
3139 orig_val = 1; /* can't generate EXISTS relo w/o local field */
3140 new_val = targ_spec ? 1 : 0;
3141 } else if (!targ_spec) {
3143 new_val = (__u32)-1;
3145 err = bpf_core_calc_field_relo(prog, relo, local_spec,
3146 &orig_val, &validate);
3149 err = bpf_core_calc_field_relo(prog, relo, targ_spec,
3155 insn = &prog->insns[insn_idx];
3156 class = BPF_CLASS(insn->code);
3158 if (class == BPF_ALU || class == BPF_ALU64) {
3159 if (BPF_SRC(insn->code) != BPF_K)
3161 if (!failed && validate && insn->imm != orig_val) {
3162 pr_warn("prog '%s': unexpected insn #%d value: got %u, exp %u -> %u\n",
3163 bpf_program__title(prog, false), insn_idx,
3164 insn->imm, orig_val, new_val);
3167 orig_val = insn->imm;
3168 insn->imm = new_val;
3169 pr_debug("prog '%s': patched insn #%d (ALU/ALU64)%s imm %u -> %u\n",
3170 bpf_program__title(prog, false), insn_idx,
3171 failed ? " w/ failed reloc" : "", orig_val, new_val);
3173 pr_warn("prog '%s': trying to relocate unrecognized insn #%d, code:%x, src:%x, dst:%x, off:%x, imm:%x\n",
3174 bpf_program__title(prog, false),
3175 insn_idx, insn->code, insn->src_reg, insn->dst_reg,
3176 insn->off, insn->imm);
3183 static struct btf *btf_load_raw(const char *path)
3191 if (stat(path, &st))
3192 return ERR_PTR(-errno);
3194 data = malloc(st.st_size);
3196 return ERR_PTR(-ENOMEM);
3198 f = fopen(path, "rb");
3200 btf = ERR_PTR(-errno);
3204 read_cnt = fread(data, 1, st.st_size, f);
3206 if (read_cnt < st.st_size) {
3207 btf = ERR_PTR(-EBADF);
3211 btf = btf__new(data, read_cnt);
3219 * Probe few well-known locations for vmlinux kernel image and try to load BTF
3220 * data out of it to use for target BTF.
3222 static struct btf *bpf_core_find_kernel_btf(void)
3225 const char *path_fmt;
3228 /* try canonical vmlinux BTF through sysfs first */
3229 { "/sys/kernel/btf/vmlinux", true /* raw BTF */ },
3230 /* fall back to trying to find vmlinux ELF on disk otherwise */
3231 { "/boot/vmlinux-%1$s" },
3232 { "/lib/modules/%1$s/vmlinux-%1$s" },
3233 { "/lib/modules/%1$s/build/vmlinux" },
3234 { "/usr/lib/modules/%1$s/kernel/vmlinux" },
3235 { "/usr/lib/debug/boot/vmlinux-%1$s" },
3236 { "/usr/lib/debug/boot/vmlinux-%1$s.debug" },
3237 { "/usr/lib/debug/lib/modules/%1$s/vmlinux" },
3239 char path[PATH_MAX + 1];
3246 for (i = 0; i < ARRAY_SIZE(locations); i++) {
3247 snprintf(path, PATH_MAX, locations[i].path_fmt, buf.release);
3249 if (access(path, R_OK))
3252 if (locations[i].raw_btf)
3253 btf = btf_load_raw(path);
3255 btf = btf__parse_elf(path, NULL);
3257 pr_debug("loading kernel BTF '%s': %ld\n",
3258 path, IS_ERR(btf) ? PTR_ERR(btf) : 0);
3265 pr_warn("failed to find valid kernel BTF\n");
3266 return ERR_PTR(-ESRCH);
3269 /* Output spec definition in the format:
3270 * [<type-id>] (<type-name>) + <raw-spec> => <offset>@<spec>,
3271 * where <spec> is a C-syntax view of recorded field access, e.g.: x.a[3].b
3273 static void bpf_core_dump_spec(int level, const struct bpf_core_spec *spec)
3275 const struct btf_type *t;
3280 type_id = spec->spec[0].type_id;
3281 t = btf__type_by_id(spec->btf, type_id);
3282 s = btf__name_by_offset(spec->btf, t->name_off);
3283 libbpf_print(level, "[%u] %s + ", type_id, s);
3285 for (i = 0; i < spec->raw_len; i++)
3286 libbpf_print(level, "%d%s", spec->raw_spec[i],
3287 i == spec->raw_len - 1 ? " => " : ":");
3289 libbpf_print(level, "%u.%u @ &x",
3290 spec->bit_offset / 8, spec->bit_offset % 8);
3292 for (i = 0; i < spec->len; i++) {
3293 if (spec->spec[i].name)
3294 libbpf_print(level, ".%s", spec->spec[i].name);
3296 libbpf_print(level, "[%u]", spec->spec[i].idx);
3301 static size_t bpf_core_hash_fn(const void *key, void *ctx)
3306 static bool bpf_core_equal_fn(const void *k1, const void *k2, void *ctx)
3311 static void *u32_as_hash_key(__u32 x)
3313 return (void *)(uintptr_t)x;
3317 * CO-RE relocate single instruction.
3319 * The outline and important points of the algorithm:
3320 * 1. For given local type, find corresponding candidate target types.
3321 * Candidate type is a type with the same "essential" name, ignoring
3322 * everything after last triple underscore (___). E.g., `sample`,
3323 * `sample___flavor_one`, `sample___flavor_another_one`, are all candidates
3324 * for each other. Names with triple underscore are referred to as
3325 * "flavors" and are useful, among other things, to allow to
3326 * specify/support incompatible variations of the same kernel struct, which
3327 * might differ between different kernel versions and/or build
3330 * N.B. Struct "flavors" could be generated by bpftool's BTF-to-C
3331 * converter, when deduplicated BTF of a kernel still contains more than
3332 * one different types with the same name. In that case, ___2, ___3, etc
3333 * are appended starting from second name conflict. But start flavors are
3334 * also useful to be defined "locally", in BPF program, to extract same
3335 * data from incompatible changes between different kernel
3336 * versions/configurations. For instance, to handle field renames between
3337 * kernel versions, one can use two flavors of the struct name with the
3338 * same common name and use conditional relocations to extract that field,
3339 * depending on target kernel version.
3340 * 2. For each candidate type, try to match local specification to this
3341 * candidate target type. Matching involves finding corresponding
3342 * high-level spec accessors, meaning that all named fields should match,
3343 * as well as all array accesses should be within the actual bounds. Also,
3344 * types should be compatible (see bpf_core_fields_are_compat for details).
3345 * 3. It is supported and expected that there might be multiple flavors
3346 * matching the spec. As long as all the specs resolve to the same set of
3347 * offsets across all candidates, there is no error. If there is any
3348 * ambiguity, CO-RE relocation will fail. This is necessary to accomodate
3349 * imprefection of BTF deduplication, which can cause slight duplication of
3350 * the same BTF type, if some directly or indirectly referenced (by
3351 * pointer) type gets resolved to different actual types in different
3352 * object files. If such situation occurs, deduplicated BTF will end up
3353 * with two (or more) structurally identical types, which differ only in
3354 * types they refer to through pointer. This should be OK in most cases and
3356 * 4. Candidate types search is performed by linearly scanning through all
3357 * types in target BTF. It is anticipated that this is overall more
3358 * efficient memory-wise and not significantly worse (if not better)
3359 * CPU-wise compared to prebuilding a map from all local type names to
3360 * a list of candidate type names. It's also sped up by caching resolved
3361 * list of matching candidates per each local "root" type ID, that has at
3362 * least one bpf_field_reloc associated with it. This list is shared
3363 * between multiple relocations for the same type ID and is updated as some
3364 * of the candidates are pruned due to structural incompatibility.
3366 static int bpf_core_reloc_field(struct bpf_program *prog,
3367 const struct bpf_field_reloc *relo,
3369 const struct btf *local_btf,
3370 const struct btf *targ_btf,
3371 struct hashmap *cand_cache)
3373 const char *prog_name = bpf_program__title(prog, false);
3374 struct bpf_core_spec local_spec, cand_spec, targ_spec;
3375 const void *type_key = u32_as_hash_key(relo->type_id);
3376 const struct btf_type *local_type, *cand_type;
3377 const char *local_name, *cand_name;
3378 struct ids_vec *cand_ids;
3379 __u32 local_id, cand_id;
3380 const char *spec_str;
3383 local_id = relo->type_id;
3384 local_type = btf__type_by_id(local_btf, local_id);
3388 local_name = btf__name_by_offset(local_btf, local_type->name_off);
3389 if (str_is_empty(local_name))
3392 spec_str = btf__name_by_offset(local_btf, relo->access_str_off);
3393 if (str_is_empty(spec_str))
3396 err = bpf_core_spec_parse(local_btf, local_id, spec_str, &local_spec);
3398 pr_warn("prog '%s': relo #%d: parsing [%d] %s + %s failed: %d\n",
3399 prog_name, relo_idx, local_id, local_name, spec_str,
3404 pr_debug("prog '%s': relo #%d: kind %d, spec is ", prog_name, relo_idx,
3406 bpf_core_dump_spec(LIBBPF_DEBUG, &local_spec);
3407 libbpf_print(LIBBPF_DEBUG, "\n");
3409 if (!hashmap__find(cand_cache, type_key, (void **)&cand_ids)) {
3410 cand_ids = bpf_core_find_cands(local_btf, local_id, targ_btf);
3411 if (IS_ERR(cand_ids)) {
3412 pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s: %ld",
3413 prog_name, relo_idx, local_id, local_name,
3415 return PTR_ERR(cand_ids);
3417 err = hashmap__set(cand_cache, type_key, cand_ids, NULL, NULL);
3419 bpf_core_free_cands(cand_ids);
3424 for (i = 0, j = 0; i < cand_ids->len; i++) {
3425 cand_id = cand_ids->data[i];
3426 cand_type = btf__type_by_id(targ_btf, cand_id);
3427 cand_name = btf__name_by_offset(targ_btf, cand_type->name_off);
3429 err = bpf_core_spec_match(&local_spec, targ_btf,
3430 cand_id, &cand_spec);
3431 pr_debug("prog '%s': relo #%d: matching candidate #%d %s against spec ",
3432 prog_name, relo_idx, i, cand_name);
3433 bpf_core_dump_spec(LIBBPF_DEBUG, &cand_spec);
3434 libbpf_print(LIBBPF_DEBUG, ": %d\n", err);
3436 pr_warn("prog '%s': relo #%d: matching error: %d\n",
3437 prog_name, relo_idx, err);
3444 targ_spec = cand_spec;
3445 } else if (cand_spec.bit_offset != targ_spec.bit_offset) {
3446 /* if there are many candidates, they should all
3447 * resolve to the same bit offset
3449 pr_warn("prog '%s': relo #%d: offset ambiguity: %u != %u\n",
3450 prog_name, relo_idx, cand_spec.bit_offset,
3451 targ_spec.bit_offset);
3455 cand_ids->data[j++] = cand_spec.spec[0].type_id;
3459 * For BPF_FIELD_EXISTS relo or when relaxed CO-RE reloc mode is
3460 * requested, it's expected that we might not find any candidates.
3461 * In this case, if field wasn't found in any candidate, the list of
3462 * candidates shouldn't change at all, we'll just handle relocating
3463 * appropriately, depending on relo's kind.
3468 if (j == 0 && !prog->obj->relaxed_core_relocs &&
3469 relo->kind != BPF_FIELD_EXISTS) {
3470 pr_warn("prog '%s': relo #%d: no matching targets found for [%d] %s + %s\n",
3471 prog_name, relo_idx, local_id, local_name, spec_str);
3475 /* bpf_core_reloc_insn should know how to handle missing targ_spec */
3476 err = bpf_core_reloc_insn(prog, relo, &local_spec,
3477 j ? &targ_spec : NULL);
3479 pr_warn("prog '%s': relo #%d: failed to patch insn at offset %d: %d\n",
3480 prog_name, relo_idx, relo->insn_off, err);
3488 bpf_core_reloc_fields(struct bpf_object *obj, const char *targ_btf_path)
3490 const struct btf_ext_info_sec *sec;
3491 const struct bpf_field_reloc *rec;
3492 const struct btf_ext_info *seg;
3493 struct hashmap_entry *entry;
3494 struct hashmap *cand_cache = NULL;
3495 struct bpf_program *prog;
3496 struct btf *targ_btf;
3497 const char *sec_name;
3501 targ_btf = btf__parse_elf(targ_btf_path, NULL);
3503 targ_btf = bpf_core_find_kernel_btf();
3504 if (IS_ERR(targ_btf)) {
3505 pr_warn("failed to get target BTF: %ld\n", PTR_ERR(targ_btf));
3506 return PTR_ERR(targ_btf);
3509 cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
3510 if (IS_ERR(cand_cache)) {
3511 err = PTR_ERR(cand_cache);
3515 seg = &obj->btf_ext->field_reloc_info;
3516 for_each_btf_ext_sec(seg, sec) {
3517 sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
3518 if (str_is_empty(sec_name)) {
3522 prog = bpf_object__find_program_by_title(obj, sec_name);
3524 pr_warn("failed to find program '%s' for CO-RE offset relocation\n",
3530 pr_debug("prog '%s': performing %d CO-RE offset relocs\n",
3531 sec_name, sec->num_info);
3533 for_each_btf_ext_rec(seg, sec, i, rec) {
3534 err = bpf_core_reloc_field(prog, rec, i, obj->btf,
3535 targ_btf, cand_cache);
3537 pr_warn("prog '%s': relo #%d: failed to relocate: %d\n",
3545 btf__free(targ_btf);
3546 if (!IS_ERR_OR_NULL(cand_cache)) {
3547 hashmap__for_each_entry(cand_cache, entry, i) {
3548 bpf_core_free_cands(entry->value);
3550 hashmap__free(cand_cache);
3556 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
3560 if (obj->btf_ext->field_reloc_info.len)
3561 err = bpf_core_reloc_fields(obj, targ_btf_path);
3567 bpf_program__reloc_text(struct bpf_program *prog, struct bpf_object *obj,
3568 struct reloc_desc *relo)
3570 struct bpf_insn *insn, *new_insn;
3571 struct bpf_program *text;
3575 if (relo->type != RELO_CALL)
3576 return -LIBBPF_ERRNO__RELOC;
3578 if (prog->idx == obj->efile.text_shndx) {
3579 pr_warn("relo in .text insn %d into off %d (insn #%d)\n",
3580 relo->insn_idx, relo->sym_off, relo->sym_off / 8);
3581 return -LIBBPF_ERRNO__RELOC;
3584 if (prog->main_prog_cnt == 0) {
3585 text = bpf_object__find_prog_by_idx(obj, obj->efile.text_shndx);
3587 pr_warn("no .text section found yet relo into text exist\n");
3588 return -LIBBPF_ERRNO__RELOC;
3590 new_cnt = prog->insns_cnt + text->insns_cnt;
3591 new_insn = reallocarray(prog->insns, new_cnt, sizeof(*insn));
3593 pr_warn("oom in prog realloc\n");
3596 prog->insns = new_insn;
3599 err = bpf_program_reloc_btf_ext(prog, obj,
3606 memcpy(new_insn + prog->insns_cnt, text->insns,
3607 text->insns_cnt * sizeof(*insn));
3608 prog->main_prog_cnt = prog->insns_cnt;
3609 prog->insns_cnt = new_cnt;
3610 pr_debug("added %zd insn from %s to prog %s\n",
3611 text->insns_cnt, text->section_name,
3612 prog->section_name);
3614 insn = &prog->insns[relo->insn_idx];
3615 insn->imm += relo->sym_off / 8 + prog->main_prog_cnt - relo->insn_idx;
3620 bpf_program__relocate(struct bpf_program *prog, struct bpf_object *obj)
3628 err = bpf_program_reloc_btf_ext(prog, obj,
3629 prog->section_name, 0);
3634 if (!prog->reloc_desc)
3637 for (i = 0; i < prog->nr_reloc; i++) {
3638 struct reloc_desc *relo = &prog->reloc_desc[i];
3640 if (relo->type == RELO_LD64 || relo->type == RELO_DATA) {
3641 struct bpf_insn *insn = &prog->insns[relo->insn_idx];
3643 if (relo->insn_idx + 1 >= (int)prog->insns_cnt) {
3644 pr_warn("relocation out of range: '%s'\n",
3645 prog->section_name);
3646 return -LIBBPF_ERRNO__RELOC;
3649 if (relo->type != RELO_DATA) {
3650 insn[0].src_reg = BPF_PSEUDO_MAP_FD;
3652 insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
3653 insn[1].imm = insn[0].imm + relo->sym_off;
3655 insn[0].imm = obj->maps[relo->map_idx].fd;
3656 } else if (relo->type == RELO_CALL) {
3657 err = bpf_program__reloc_text(prog, obj, relo);
3663 zfree(&prog->reloc_desc);
3669 bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
3671 struct bpf_program *prog;
3676 err = bpf_object__relocate_core(obj, targ_btf_path);
3678 pr_warn("failed to perform CO-RE relocations: %d\n",
3683 for (i = 0; i < obj->nr_programs; i++) {
3684 prog = &obj->programs[i];
3686 err = bpf_program__relocate(prog, obj);
3688 pr_warn("failed to relocate '%s'\n", prog->section_name);
3695 static int bpf_object__collect_reloc(struct bpf_object *obj)
3699 if (!obj_elf_valid(obj)) {
3700 pr_warn("Internal error: elf object is closed\n");
3701 return -LIBBPF_ERRNO__INTERNAL;
3704 for (i = 0; i < obj->efile.nr_reloc_sects; i++) {
3705 GElf_Shdr *shdr = &obj->efile.reloc_sects[i].shdr;
3706 Elf_Data *data = obj->efile.reloc_sects[i].data;
3707 int idx = shdr->sh_info;
3708 struct bpf_program *prog;
3710 if (shdr->sh_type != SHT_REL) {
3711 pr_warn("internal error at %d\n", __LINE__);
3712 return -LIBBPF_ERRNO__INTERNAL;
3715 prog = bpf_object__find_prog_by_idx(obj, idx);
3717 pr_warn("relocation failed: no section(%d)\n", idx);
3718 return -LIBBPF_ERRNO__RELOC;
3721 err = bpf_program__collect_reloc(prog, shdr, data, obj);
3729 load_program(struct bpf_program *prog, struct bpf_insn *insns, int insns_cnt,
3730 char *license, __u32 kern_version, int *pfd)
3732 struct bpf_load_program_attr load_attr;
3733 char *cp, errmsg[STRERR_BUFSIZE];
3734 int log_buf_size = BPF_LOG_BUF_SIZE;
3738 if (!insns || !insns_cnt)
3741 memset(&load_attr, 0, sizeof(struct bpf_load_program_attr));
3742 load_attr.prog_type = prog->type;
3743 load_attr.expected_attach_type = prog->expected_attach_type;
3744 if (prog->caps->name)
3745 load_attr.name = prog->name;
3746 load_attr.insns = insns;
3747 load_attr.insns_cnt = insns_cnt;
3748 load_attr.license = license;
3749 if (prog->type == BPF_PROG_TYPE_TRACING) {
3750 load_attr.attach_prog_fd = prog->attach_prog_fd;
3751 load_attr.attach_btf_id = prog->attach_btf_id;
3753 load_attr.kern_version = kern_version;
3754 load_attr.prog_ifindex = prog->prog_ifindex;
3756 /* if .BTF.ext was loaded, kernel supports associated BTF for prog */
3757 if (prog->obj->btf_ext)
3758 btf_fd = bpf_object__btf_fd(prog->obj);
3761 load_attr.prog_btf_fd = btf_fd >= 0 ? btf_fd : 0;
3762 load_attr.func_info = prog->func_info;
3763 load_attr.func_info_rec_size = prog->func_info_rec_size;
3764 load_attr.func_info_cnt = prog->func_info_cnt;
3765 load_attr.line_info = prog->line_info;
3766 load_attr.line_info_rec_size = prog->line_info_rec_size;
3767 load_attr.line_info_cnt = prog->line_info_cnt;
3768 load_attr.log_level = prog->log_level;
3769 load_attr.prog_flags = prog->prog_flags;
3772 log_buf = malloc(log_buf_size);
3774 pr_warn("Alloc log buffer for bpf loader error, continue without log\n");
3776 ret = bpf_load_program_xattr(&load_attr, log_buf, log_buf_size);
3779 if (load_attr.log_level)
3780 pr_debug("verifier log:\n%s", log_buf);
3786 if (errno == ENOSPC) {
3792 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
3793 pr_warn("load bpf program failed: %s\n", cp);
3795 if (log_buf && log_buf[0] != '\0') {
3796 ret = -LIBBPF_ERRNO__VERIFY;
3797 pr_warn("-- BEGIN DUMP LOG ---\n");
3798 pr_warn("\n%s\n", log_buf);
3799 pr_warn("-- END LOG --\n");
3800 } else if (load_attr.insns_cnt >= BPF_MAXINSNS) {
3801 pr_warn("Program too large (%zu insns), at most %d insns\n",
3802 load_attr.insns_cnt, BPF_MAXINSNS);
3803 ret = -LIBBPF_ERRNO__PROG2BIG;
3804 } else if (load_attr.prog_type != BPF_PROG_TYPE_KPROBE) {
3805 /* Wrong program type? */
3808 load_attr.prog_type = BPF_PROG_TYPE_KPROBE;
3809 load_attr.expected_attach_type = 0;
3810 fd = bpf_load_program_xattr(&load_attr, NULL, 0);
3813 ret = -LIBBPF_ERRNO__PROGTYPE;
3823 static int libbpf_find_attach_btf_id(const char *name,
3824 enum bpf_attach_type attach_type,
3825 __u32 attach_prog_fd);
3827 int bpf_program__load(struct bpf_program *prog, char *license, __u32 kern_ver)
3829 int err = 0, fd, i, btf_id;
3831 if (prog->type == BPF_PROG_TYPE_TRACING) {
3832 btf_id = libbpf_find_attach_btf_id(prog->section_name,
3833 prog->expected_attach_type,
3834 prog->attach_prog_fd);
3837 prog->attach_btf_id = btf_id;
3840 if (prog->instances.nr < 0 || !prog->instances.fds) {
3841 if (prog->preprocessor) {
3842 pr_warn("Internal error: can't load program '%s'\n",
3843 prog->section_name);
3844 return -LIBBPF_ERRNO__INTERNAL;
3847 prog->instances.fds = malloc(sizeof(int));
3848 if (!prog->instances.fds) {
3849 pr_warn("Not enough memory for BPF fds\n");
3852 prog->instances.nr = 1;
3853 prog->instances.fds[0] = -1;
3856 if (!prog->preprocessor) {
3857 if (prog->instances.nr != 1) {
3858 pr_warn("Program '%s' is inconsistent: nr(%d) != 1\n",
3859 prog->section_name, prog->instances.nr);
3861 err = load_program(prog, prog->insns, prog->insns_cnt,
3862 license, kern_ver, &fd);
3864 prog->instances.fds[0] = fd;
3868 for (i = 0; i < prog->instances.nr; i++) {
3869 struct bpf_prog_prep_result result;
3870 bpf_program_prep_t preprocessor = prog->preprocessor;
3872 memset(&result, 0, sizeof(result));
3873 err = preprocessor(prog, i, prog->insns,
3874 prog->insns_cnt, &result);
3876 pr_warn("Preprocessing the %dth instance of program '%s' failed\n",
3877 i, prog->section_name);
3881 if (!result.new_insn_ptr || !result.new_insn_cnt) {
3882 pr_debug("Skip loading the %dth instance of program '%s'\n",
3883 i, prog->section_name);
3884 prog->instances.fds[i] = -1;
3890 err = load_program(prog, result.new_insn_ptr,
3891 result.new_insn_cnt, license, kern_ver, &fd);
3893 pr_warn("Loading the %dth instance of program '%s' failed\n",
3894 i, prog->section_name);
3900 prog->instances.fds[i] = fd;
3904 pr_warn("failed to load program '%s'\n", prog->section_name);
3905 zfree(&prog->insns);
3906 prog->insns_cnt = 0;
3910 static bool bpf_program__is_function_storage(const struct bpf_program *prog,
3911 const struct bpf_object *obj)
3913 return prog->idx == obj->efile.text_shndx && obj->has_pseudo_calls;
3917 bpf_object__load_progs(struct bpf_object *obj, int log_level)
3922 for (i = 0; i < obj->nr_programs; i++) {
3923 if (bpf_program__is_function_storage(&obj->programs[i], obj))
3925 obj->programs[i].log_level |= log_level;
3926 err = bpf_program__load(&obj->programs[i],
3935 static struct bpf_object *
3936 __bpf_object__open(const char *path, const void *obj_buf, size_t obj_buf_sz,
3937 const struct bpf_object_open_opts *opts)
3939 struct bpf_program *prog;
3940 struct bpf_object *obj;
3941 const char *obj_name;
3943 __u32 attach_prog_fd;
3946 if (elf_version(EV_CURRENT) == EV_NONE) {
3947 pr_warn("failed to init libelf for %s\n",
3948 path ? : "(mem buf)");
3949 return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
3952 if (!OPTS_VALID(opts, bpf_object_open_opts))
3953 return ERR_PTR(-EINVAL);
3955 obj_name = OPTS_GET(opts, object_name, NULL);
3958 snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
3959 (unsigned long)obj_buf,
3960 (unsigned long)obj_buf_sz);
3961 obj_name = tmp_name;
3964 pr_debug("loading object '%s' from buffer\n", obj_name);
3967 obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
3971 obj->relaxed_core_relocs = OPTS_GET(opts, relaxed_core_relocs, false);
3972 attach_prog_fd = OPTS_GET(opts, attach_prog_fd, 0);
3974 err = bpf_object__elf_init(obj);
3975 err = err ? : bpf_object__check_endianness(obj);
3976 err = err ? : bpf_object__elf_collect(obj);
3977 err = err ? : bpf_object__init_maps(obj, opts);
3978 err = err ? : bpf_object__init_prog_names(obj);
3979 err = err ? : bpf_object__collect_reloc(obj);
3982 bpf_object__elf_finish(obj);
3984 bpf_object__for_each_program(prog, obj) {
3985 enum bpf_prog_type prog_type;
3986 enum bpf_attach_type attach_type;
3988 err = libbpf_prog_type_by_name(prog->section_name, &prog_type,
3991 /* couldn't guess, but user might manually specify */
3996 bpf_program__set_type(prog, prog_type);
3997 bpf_program__set_expected_attach_type(prog, attach_type);
3998 if (prog_type == BPF_PROG_TYPE_TRACING)
3999 prog->attach_prog_fd = attach_prog_fd;
4004 bpf_object__close(obj);
4005 return ERR_PTR(err);
4008 static struct bpf_object *
4009 __bpf_object__open_xattr(struct bpf_object_open_attr *attr, int flags)
4011 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts,
4012 .relaxed_maps = flags & MAPS_RELAX_COMPAT,
4015 /* param validation */
4019 pr_debug("loading %s\n", attr->file);
4020 return __bpf_object__open(attr->file, NULL, 0, &opts);
4023 struct bpf_object *bpf_object__open_xattr(struct bpf_object_open_attr *attr)
4025 return __bpf_object__open_xattr(attr, 0);
4028 struct bpf_object *bpf_object__open(const char *path)
4030 struct bpf_object_open_attr attr = {
4032 .prog_type = BPF_PROG_TYPE_UNSPEC,
4035 return bpf_object__open_xattr(&attr);
4039 bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
4042 return ERR_PTR(-EINVAL);
4044 pr_debug("loading %s\n", path);
4046 return __bpf_object__open(path, NULL, 0, opts);
4050 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
4051 const struct bpf_object_open_opts *opts)
4053 if (!obj_buf || obj_buf_sz == 0)
4054 return ERR_PTR(-EINVAL);
4056 return __bpf_object__open(NULL, obj_buf, obj_buf_sz, opts);
4060 bpf_object__open_buffer(const void *obj_buf, size_t obj_buf_sz,
4063 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts,
4064 .object_name = name,
4065 /* wrong default, but backwards-compatible */
4066 .relaxed_maps = true,
4069 /* returning NULL is wrong, but backwards-compatible */
4070 if (!obj_buf || obj_buf_sz == 0)
4073 return bpf_object__open_mem(obj_buf, obj_buf_sz, &opts);
4076 int bpf_object__unload(struct bpf_object *obj)
4083 for (i = 0; i < obj->nr_maps; i++)
4084 zclose(obj->maps[i].fd);
4086 for (i = 0; i < obj->nr_programs; i++)
4087 bpf_program__unload(&obj->programs[i]);
4092 static int bpf_object__sanitize_maps(struct bpf_object *obj)
4096 bpf_object__for_each_map(m, obj) {
4097 if (!bpf_map__is_internal(m))
4099 if (!obj->caps.global_data) {
4100 pr_warn("kernel doesn't support global data\n");
4103 if (!obj->caps.array_mmap)
4104 m->def.map_flags ^= BPF_F_MMAPABLE;
4110 int bpf_object__load_xattr(struct bpf_object_load_attr *attr)
4112 struct bpf_object *obj;
4122 pr_warn("object should not be loaded twice\n");
4128 err = bpf_object__probe_caps(obj);
4129 err = err ? : bpf_object__sanitize_and_load_btf(obj);
4130 err = err ? : bpf_object__sanitize_maps(obj);
4131 err = err ? : bpf_object__create_maps(obj);
4132 err = err ? : bpf_object__relocate(obj, attr->target_btf_path);
4133 err = err ? : bpf_object__load_progs(obj, attr->log_level);
4139 /* unpin any maps that were auto-pinned during load */
4140 for (i = 0; i < obj->nr_maps; i++)
4141 if (obj->maps[i].pinned && !obj->maps[i].reused)
4142 bpf_map__unpin(&obj->maps[i], NULL);
4144 bpf_object__unload(obj);
4145 pr_warn("failed to load object '%s'\n", obj->path);
4149 int bpf_object__load(struct bpf_object *obj)
4151 struct bpf_object_load_attr attr = {
4155 return bpf_object__load_xattr(&attr);
4158 static int make_parent_dir(const char *path)
4160 char *cp, errmsg[STRERR_BUFSIZE];
4164 dname = strdup(path);
4168 dir = dirname(dname);
4169 if (mkdir(dir, 0700) && errno != EEXIST)
4174 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
4175 pr_warn("failed to mkdir %s: %s\n", path, cp);
4180 static int check_path(const char *path)
4182 char *cp, errmsg[STRERR_BUFSIZE];
4183 struct statfs st_fs;
4190 dname = strdup(path);
4194 dir = dirname(dname);
4195 if (statfs(dir, &st_fs)) {
4196 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
4197 pr_warn("failed to statfs %s: %s\n", dir, cp);
4202 if (!err && st_fs.f_type != BPF_FS_MAGIC) {
4203 pr_warn("specified path %s is not on BPF FS\n", path);
4210 int bpf_program__pin_instance(struct bpf_program *prog, const char *path,
4213 char *cp, errmsg[STRERR_BUFSIZE];
4216 err = make_parent_dir(path);
4220 err = check_path(path);
4225 pr_warn("invalid program pointer\n");
4229 if (instance < 0 || instance >= prog->instances.nr) {
4230 pr_warn("invalid prog instance %d of prog %s (max %d)\n",
4231 instance, prog->section_name, prog->instances.nr);
4235 if (bpf_obj_pin(prog->instances.fds[instance], path)) {
4236 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
4237 pr_warn("failed to pin program: %s\n", cp);
4240 pr_debug("pinned program '%s'\n", path);
4245 int bpf_program__unpin_instance(struct bpf_program *prog, const char *path,
4250 err = check_path(path);
4255 pr_warn("invalid program pointer\n");
4259 if (instance < 0 || instance >= prog->instances.nr) {
4260 pr_warn("invalid prog instance %d of prog %s (max %d)\n",
4261 instance, prog->section_name, prog->instances.nr);
4268 pr_debug("unpinned program '%s'\n", path);
4273 int bpf_program__pin(struct bpf_program *prog, const char *path)
4277 err = make_parent_dir(path);
4281 err = check_path(path);
4286 pr_warn("invalid program pointer\n");
4290 if (prog->instances.nr <= 0) {
4291 pr_warn("no instances of prog %s to pin\n",
4292 prog->section_name);
4296 if (prog->instances.nr == 1) {
4297 /* don't create subdirs when pinning single instance */
4298 return bpf_program__pin_instance(prog, path, 0);
4301 for (i = 0; i < prog->instances.nr; i++) {
4305 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
4309 } else if (len >= PATH_MAX) {
4310 err = -ENAMETOOLONG;
4314 err = bpf_program__pin_instance(prog, buf, i);
4322 for (i = i - 1; i >= 0; i--) {
4326 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
4329 else if (len >= PATH_MAX)
4332 bpf_program__unpin_instance(prog, buf, i);
4340 int bpf_program__unpin(struct bpf_program *prog, const char *path)
4344 err = check_path(path);
4349 pr_warn("invalid program pointer\n");
4353 if (prog->instances.nr <= 0) {
4354 pr_warn("no instances of prog %s to pin\n",
4355 prog->section_name);
4359 if (prog->instances.nr == 1) {
4360 /* don't create subdirs when pinning single instance */
4361 return bpf_program__unpin_instance(prog, path, 0);
4364 for (i = 0; i < prog->instances.nr; i++) {
4368 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
4371 else if (len >= PATH_MAX)
4372 return -ENAMETOOLONG;
4374 err = bpf_program__unpin_instance(prog, buf, i);
4386 int bpf_map__pin(struct bpf_map *map, const char *path)
4388 char *cp, errmsg[STRERR_BUFSIZE];
4392 pr_warn("invalid map pointer\n");
4396 if (map->pin_path) {
4397 if (path && strcmp(path, map->pin_path)) {
4398 pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
4399 bpf_map__name(map), map->pin_path, path);
4401 } else if (map->pinned) {
4402 pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
4403 bpf_map__name(map), map->pin_path);
4408 pr_warn("missing a path to pin map '%s' at\n",
4409 bpf_map__name(map));
4411 } else if (map->pinned) {
4412 pr_warn("map '%s' already pinned\n", bpf_map__name(map));
4416 map->pin_path = strdup(path);
4417 if (!map->pin_path) {
4423 err = make_parent_dir(map->pin_path);
4427 err = check_path(map->pin_path);
4431 if (bpf_obj_pin(map->fd, map->pin_path)) {
4437 pr_debug("pinned map '%s'\n", map->pin_path);
4442 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
4443 pr_warn("failed to pin map: %s\n", cp);
4447 int bpf_map__unpin(struct bpf_map *map, const char *path)
4452 pr_warn("invalid map pointer\n");
4456 if (map->pin_path) {
4457 if (path && strcmp(path, map->pin_path)) {
4458 pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
4459 bpf_map__name(map), map->pin_path, path);
4462 path = map->pin_path;
4464 pr_warn("no path to unpin map '%s' from\n",
4465 bpf_map__name(map));
4469 err = check_path(path);
4477 map->pinned = false;
4478 pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
4483 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
4493 free(map->pin_path);
4494 map->pin_path = new;
4498 const char *bpf_map__get_pin_path(const struct bpf_map *map)
4500 return map->pin_path;
4503 bool bpf_map__is_pinned(const struct bpf_map *map)
4508 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
4510 struct bpf_map *map;
4517 pr_warn("object not yet loaded; load it first\n");
4521 bpf_object__for_each_map(map, obj) {
4522 char *pin_path = NULL;
4528 len = snprintf(buf, PATH_MAX, "%s/%s", path,
4529 bpf_map__name(map));
4532 goto err_unpin_maps;
4533 } else if (len >= PATH_MAX) {
4534 err = -ENAMETOOLONG;
4535 goto err_unpin_maps;
4538 } else if (!map->pin_path) {
4542 err = bpf_map__pin(map, pin_path);
4544 goto err_unpin_maps;
4550 while ((map = bpf_map__prev(map, obj))) {
4554 bpf_map__unpin(map, NULL);
4560 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
4562 struct bpf_map *map;
4568 bpf_object__for_each_map(map, obj) {
4569 char *pin_path = NULL;
4575 len = snprintf(buf, PATH_MAX, "%s/%s", path,
4576 bpf_map__name(map));
4579 else if (len >= PATH_MAX)
4580 return -ENAMETOOLONG;
4582 } else if (!map->pin_path) {
4586 err = bpf_map__unpin(map, pin_path);
4594 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
4596 struct bpf_program *prog;
4603 pr_warn("object not yet loaded; load it first\n");
4607 bpf_object__for_each_program(prog, obj) {
4611 len = snprintf(buf, PATH_MAX, "%s/%s", path,
4615 goto err_unpin_programs;
4616 } else if (len >= PATH_MAX) {
4617 err = -ENAMETOOLONG;
4618 goto err_unpin_programs;
4621 err = bpf_program__pin(prog, buf);
4623 goto err_unpin_programs;
4629 while ((prog = bpf_program__prev(prog, obj))) {
4633 len = snprintf(buf, PATH_MAX, "%s/%s", path,
4637 else if (len >= PATH_MAX)
4640 bpf_program__unpin(prog, buf);
4646 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
4648 struct bpf_program *prog;
4654 bpf_object__for_each_program(prog, obj) {
4658 len = snprintf(buf, PATH_MAX, "%s/%s", path,
4662 else if (len >= PATH_MAX)
4663 return -ENAMETOOLONG;
4665 err = bpf_program__unpin(prog, buf);
4673 int bpf_object__pin(struct bpf_object *obj, const char *path)
4677 err = bpf_object__pin_maps(obj, path);
4681 err = bpf_object__pin_programs(obj, path);
4683 bpf_object__unpin_maps(obj, path);
4690 void bpf_object__close(struct bpf_object *obj)
4697 if (obj->clear_priv)
4698 obj->clear_priv(obj, obj->priv);
4700 bpf_object__elf_finish(obj);
4701 bpf_object__unload(obj);
4702 btf__free(obj->btf);
4703 btf_ext__free(obj->btf_ext);
4705 for (i = 0; i < obj->nr_maps; i++) {
4706 struct bpf_map *map = &obj->maps[i];
4708 if (map->clear_priv)
4709 map->clear_priv(map, map->priv);
4711 map->clear_priv = NULL;
4714 munmap(map->mmaped, bpf_map_mmap_sz(map));
4719 zfree(&map->pin_path);
4725 if (obj->programs && obj->nr_programs) {
4726 for (i = 0; i < obj->nr_programs; i++)
4727 bpf_program__exit(&obj->programs[i]);
4729 zfree(&obj->programs);
4731 list_del(&obj->list);
4736 bpf_object__next(struct bpf_object *prev)
4738 struct bpf_object *next;
4741 next = list_first_entry(&bpf_objects_list,
4745 next = list_next_entry(prev, list);
4747 /* Empty list is noticed here so don't need checking on entry. */
4748 if (&next->list == &bpf_objects_list)
4754 const char *bpf_object__name(const struct bpf_object *obj)
4756 return obj ? obj->name : ERR_PTR(-EINVAL);
4759 unsigned int bpf_object__kversion(const struct bpf_object *obj)
4761 return obj ? obj->kern_version : 0;
4764 struct btf *bpf_object__btf(const struct bpf_object *obj)
4766 return obj ? obj->btf : NULL;
4769 int bpf_object__btf_fd(const struct bpf_object *obj)
4771 return obj->btf ? btf__fd(obj->btf) : -1;
4774 int bpf_object__set_priv(struct bpf_object *obj, void *priv,
4775 bpf_object_clear_priv_t clear_priv)
4777 if (obj->priv && obj->clear_priv)
4778 obj->clear_priv(obj, obj->priv);
4781 obj->clear_priv = clear_priv;
4785 void *bpf_object__priv(const struct bpf_object *obj)
4787 return obj ? obj->priv : ERR_PTR(-EINVAL);
4790 static struct bpf_program *
4791 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
4794 size_t nr_programs = obj->nr_programs;
4801 /* Iter from the beginning */
4802 return forward ? &obj->programs[0] :
4803 &obj->programs[nr_programs - 1];
4805 if (p->obj != obj) {
4806 pr_warn("error: program handler doesn't match object\n");
4810 idx = (p - obj->programs) + (forward ? 1 : -1);
4811 if (idx >= obj->nr_programs || idx < 0)
4813 return &obj->programs[idx];
4816 struct bpf_program *
4817 bpf_program__next(struct bpf_program *prev, const struct bpf_object *obj)
4819 struct bpf_program *prog = prev;
4822 prog = __bpf_program__iter(prog, obj, true);
4823 } while (prog && bpf_program__is_function_storage(prog, obj));
4828 struct bpf_program *
4829 bpf_program__prev(struct bpf_program *next, const struct bpf_object *obj)
4831 struct bpf_program *prog = next;
4834 prog = __bpf_program__iter(prog, obj, false);
4835 } while (prog && bpf_program__is_function_storage(prog, obj));
4840 int bpf_program__set_priv(struct bpf_program *prog, void *priv,
4841 bpf_program_clear_priv_t clear_priv)
4843 if (prog->priv && prog->clear_priv)
4844 prog->clear_priv(prog, prog->priv);
4847 prog->clear_priv = clear_priv;
4851 void *bpf_program__priv(const struct bpf_program *prog)
4853 return prog ? prog->priv : ERR_PTR(-EINVAL);
4856 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
4858 prog->prog_ifindex = ifindex;
4861 const char *bpf_program__name(const struct bpf_program *prog)
4866 const char *bpf_program__title(const struct bpf_program *prog, bool needs_copy)
4870 title = prog->section_name;
4872 title = strdup(title);
4874 pr_warn("failed to strdup program title\n");
4875 return ERR_PTR(-ENOMEM);
4882 int bpf_program__fd(const struct bpf_program *prog)
4884 return bpf_program__nth_fd(prog, 0);
4887 size_t bpf_program__size(const struct bpf_program *prog)
4889 return prog->insns_cnt * sizeof(struct bpf_insn);
4892 int bpf_program__set_prep(struct bpf_program *prog, int nr_instances,
4893 bpf_program_prep_t prep)
4897 if (nr_instances <= 0 || !prep)
4900 if (prog->instances.nr > 0 || prog->instances.fds) {
4901 pr_warn("Can't set pre-processor after loading\n");
4905 instances_fds = malloc(sizeof(int) * nr_instances);
4906 if (!instances_fds) {
4907 pr_warn("alloc memory failed for fds\n");
4911 /* fill all fd with -1 */
4912 memset(instances_fds, -1, sizeof(int) * nr_instances);
4914 prog->instances.nr = nr_instances;
4915 prog->instances.fds = instances_fds;
4916 prog->preprocessor = prep;
4920 int bpf_program__nth_fd(const struct bpf_program *prog, int n)
4927 if (n >= prog->instances.nr || n < 0) {
4928 pr_warn("Can't get the %dth fd from program %s: only %d instances\n",
4929 n, prog->section_name, prog->instances.nr);
4933 fd = prog->instances.fds[n];
4935 pr_warn("%dth instance of program '%s' is invalid\n",
4936 n, prog->section_name);
4943 enum bpf_prog_type bpf_program__get_type(struct bpf_program *prog)
4948 void bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
4953 static bool bpf_program__is_type(const struct bpf_program *prog,
4954 enum bpf_prog_type type)
4956 return prog ? (prog->type == type) : false;
4959 #define BPF_PROG_TYPE_FNS(NAME, TYPE) \
4960 int bpf_program__set_##NAME(struct bpf_program *prog) \
4964 bpf_program__set_type(prog, TYPE); \
4968 bool bpf_program__is_##NAME(const struct bpf_program *prog) \
4970 return bpf_program__is_type(prog, TYPE); \
4973 BPF_PROG_TYPE_FNS(socket_filter, BPF_PROG_TYPE_SOCKET_FILTER);
4974 BPF_PROG_TYPE_FNS(kprobe, BPF_PROG_TYPE_KPROBE);
4975 BPF_PROG_TYPE_FNS(sched_cls, BPF_PROG_TYPE_SCHED_CLS);
4976 BPF_PROG_TYPE_FNS(sched_act, BPF_PROG_TYPE_SCHED_ACT);
4977 BPF_PROG_TYPE_FNS(tracepoint, BPF_PROG_TYPE_TRACEPOINT);
4978 BPF_PROG_TYPE_FNS(raw_tracepoint, BPF_PROG_TYPE_RAW_TRACEPOINT);
4979 BPF_PROG_TYPE_FNS(xdp, BPF_PROG_TYPE_XDP);
4980 BPF_PROG_TYPE_FNS(perf_event, BPF_PROG_TYPE_PERF_EVENT);
4981 BPF_PROG_TYPE_FNS(tracing, BPF_PROG_TYPE_TRACING);
4983 enum bpf_attach_type
4984 bpf_program__get_expected_attach_type(struct bpf_program *prog)
4986 return prog->expected_attach_type;
4989 void bpf_program__set_expected_attach_type(struct bpf_program *prog,
4990 enum bpf_attach_type type)
4992 prog->expected_attach_type = type;
4995 #define BPF_PROG_SEC_IMPL(string, ptype, eatype, is_attachable, btf, atype) \
4996 { string, sizeof(string) - 1, ptype, eatype, is_attachable, btf, atype }
4998 /* Programs that can NOT be attached. */
4999 #define BPF_PROG_SEC(string, ptype) BPF_PROG_SEC_IMPL(string, ptype, 0, 0, 0, 0)
5001 /* Programs that can be attached. */
5002 #define BPF_APROG_SEC(string, ptype, atype) \
5003 BPF_PROG_SEC_IMPL(string, ptype, 0, 1, 0, atype)
5005 /* Programs that must specify expected attach type at load time. */
5006 #define BPF_EAPROG_SEC(string, ptype, eatype) \
5007 BPF_PROG_SEC_IMPL(string, ptype, eatype, 1, 0, eatype)
5009 /* Programs that use BTF to identify attach point */
5010 #define BPF_PROG_BTF(string, ptype, eatype) \
5011 BPF_PROG_SEC_IMPL(string, ptype, eatype, 0, 1, 0)
5013 /* Programs that can be attached but attach type can't be identified by section
5014 * name. Kept for backward compatibility.
5016 #define BPF_APROG_COMPAT(string, ptype) BPF_PROG_SEC(string, ptype)
5018 #define SEC_DEF(sec_pfx, ptype, ...) { \
5020 .len = sizeof(sec_pfx) - 1, \
5021 .prog_type = BPF_PROG_TYPE_##ptype, \
5027 typedef struct bpf_link *(*attach_fn_t)(const struct bpf_sec_def *sec,
5028 struct bpf_program *prog);
5030 static struct bpf_link *attach_kprobe(const struct bpf_sec_def *sec,
5031 struct bpf_program *prog);
5032 static struct bpf_link *attach_tp(const struct bpf_sec_def *sec,
5033 struct bpf_program *prog);
5034 static struct bpf_link *attach_raw_tp(const struct bpf_sec_def *sec,
5035 struct bpf_program *prog);
5036 static struct bpf_link *attach_trace(const struct bpf_sec_def *sec,
5037 struct bpf_program *prog);
5039 struct bpf_sec_def {
5042 enum bpf_prog_type prog_type;
5043 enum bpf_attach_type expected_attach_type;
5046 enum bpf_attach_type attach_type;
5047 attach_fn_t attach_fn;
5050 static const struct bpf_sec_def section_defs[] = {
5051 BPF_PROG_SEC("socket", BPF_PROG_TYPE_SOCKET_FILTER),
5052 BPF_PROG_SEC("sk_reuseport", BPF_PROG_TYPE_SK_REUSEPORT),
5053 SEC_DEF("kprobe/", KPROBE,
5054 .attach_fn = attach_kprobe),
5055 BPF_PROG_SEC("uprobe/", BPF_PROG_TYPE_KPROBE),
5056 SEC_DEF("kretprobe/", KPROBE,
5057 .attach_fn = attach_kprobe),
5058 BPF_PROG_SEC("uretprobe/", BPF_PROG_TYPE_KPROBE),
5059 BPF_PROG_SEC("classifier", BPF_PROG_TYPE_SCHED_CLS),
5060 BPF_PROG_SEC("action", BPF_PROG_TYPE_SCHED_ACT),
5061 SEC_DEF("tracepoint/", TRACEPOINT,
5062 .attach_fn = attach_tp),
5063 SEC_DEF("tp/", TRACEPOINT,
5064 .attach_fn = attach_tp),
5065 SEC_DEF("raw_tracepoint/", RAW_TRACEPOINT,
5066 .attach_fn = attach_raw_tp),
5067 SEC_DEF("raw_tp/", RAW_TRACEPOINT,
5068 .attach_fn = attach_raw_tp),
5069 SEC_DEF("tp_btf/", TRACING,
5070 .expected_attach_type = BPF_TRACE_RAW_TP,
5071 .is_attach_btf = true,
5072 .attach_fn = attach_trace),
5073 SEC_DEF("fentry/", TRACING,
5074 .expected_attach_type = BPF_TRACE_FENTRY,
5075 .is_attach_btf = true,
5076 .attach_fn = attach_trace),
5077 SEC_DEF("fexit/", TRACING,
5078 .expected_attach_type = BPF_TRACE_FEXIT,
5079 .is_attach_btf = true,
5080 .attach_fn = attach_trace),
5081 BPF_PROG_SEC("xdp", BPF_PROG_TYPE_XDP),
5082 BPF_PROG_SEC("perf_event", BPF_PROG_TYPE_PERF_EVENT),
5083 BPF_PROG_SEC("lwt_in", BPF_PROG_TYPE_LWT_IN),
5084 BPF_PROG_SEC("lwt_out", BPF_PROG_TYPE_LWT_OUT),
5085 BPF_PROG_SEC("lwt_xmit", BPF_PROG_TYPE_LWT_XMIT),
5086 BPF_PROG_SEC("lwt_seg6local", BPF_PROG_TYPE_LWT_SEG6LOCAL),
5087 BPF_APROG_SEC("cgroup_skb/ingress", BPF_PROG_TYPE_CGROUP_SKB,
5088 BPF_CGROUP_INET_INGRESS),
5089 BPF_APROG_SEC("cgroup_skb/egress", BPF_PROG_TYPE_CGROUP_SKB,
5090 BPF_CGROUP_INET_EGRESS),
5091 BPF_APROG_COMPAT("cgroup/skb", BPF_PROG_TYPE_CGROUP_SKB),
5092 BPF_APROG_SEC("cgroup/sock", BPF_PROG_TYPE_CGROUP_SOCK,
5093 BPF_CGROUP_INET_SOCK_CREATE),
5094 BPF_EAPROG_SEC("cgroup/post_bind4", BPF_PROG_TYPE_CGROUP_SOCK,
5095 BPF_CGROUP_INET4_POST_BIND),
5096 BPF_EAPROG_SEC("cgroup/post_bind6", BPF_PROG_TYPE_CGROUP_SOCK,
5097 BPF_CGROUP_INET6_POST_BIND),
5098 BPF_APROG_SEC("cgroup/dev", BPF_PROG_TYPE_CGROUP_DEVICE,
5100 BPF_APROG_SEC("sockops", BPF_PROG_TYPE_SOCK_OPS,
5101 BPF_CGROUP_SOCK_OPS),
5102 BPF_APROG_SEC("sk_skb/stream_parser", BPF_PROG_TYPE_SK_SKB,
5103 BPF_SK_SKB_STREAM_PARSER),
5104 BPF_APROG_SEC("sk_skb/stream_verdict", BPF_PROG_TYPE_SK_SKB,
5105 BPF_SK_SKB_STREAM_VERDICT),
5106 BPF_APROG_COMPAT("sk_skb", BPF_PROG_TYPE_SK_SKB),
5107 BPF_APROG_SEC("sk_msg", BPF_PROG_TYPE_SK_MSG,
5108 BPF_SK_MSG_VERDICT),
5109 BPF_APROG_SEC("lirc_mode2", BPF_PROG_TYPE_LIRC_MODE2,
5111 BPF_APROG_SEC("flow_dissector", BPF_PROG_TYPE_FLOW_DISSECTOR,
5112 BPF_FLOW_DISSECTOR),
5113 BPF_EAPROG_SEC("cgroup/bind4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
5114 BPF_CGROUP_INET4_BIND),
5115 BPF_EAPROG_SEC("cgroup/bind6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
5116 BPF_CGROUP_INET6_BIND),
5117 BPF_EAPROG_SEC("cgroup/connect4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
5118 BPF_CGROUP_INET4_CONNECT),
5119 BPF_EAPROG_SEC("cgroup/connect6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
5120 BPF_CGROUP_INET6_CONNECT),
5121 BPF_EAPROG_SEC("cgroup/sendmsg4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
5122 BPF_CGROUP_UDP4_SENDMSG),
5123 BPF_EAPROG_SEC("cgroup/sendmsg6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
5124 BPF_CGROUP_UDP6_SENDMSG),
5125 BPF_EAPROG_SEC("cgroup/recvmsg4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
5126 BPF_CGROUP_UDP4_RECVMSG),
5127 BPF_EAPROG_SEC("cgroup/recvmsg6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
5128 BPF_CGROUP_UDP6_RECVMSG),
5129 BPF_EAPROG_SEC("cgroup/sysctl", BPF_PROG_TYPE_CGROUP_SYSCTL,
5131 BPF_EAPROG_SEC("cgroup/getsockopt", BPF_PROG_TYPE_CGROUP_SOCKOPT,
5132 BPF_CGROUP_GETSOCKOPT),
5133 BPF_EAPROG_SEC("cgroup/setsockopt", BPF_PROG_TYPE_CGROUP_SOCKOPT,
5134 BPF_CGROUP_SETSOCKOPT),
5137 #undef BPF_PROG_SEC_IMPL
5139 #undef BPF_APROG_SEC
5140 #undef BPF_EAPROG_SEC
5141 #undef BPF_APROG_COMPAT
5144 #define MAX_TYPE_NAME_SIZE 32
5146 static const struct bpf_sec_def *find_sec_def(const char *sec_name)
5148 int i, n = ARRAY_SIZE(section_defs);
5150 for (i = 0; i < n; i++) {
5151 if (strncmp(sec_name,
5152 section_defs[i].sec, section_defs[i].len))
5154 return §ion_defs[i];
5159 static char *libbpf_get_type_names(bool attach_type)
5161 int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
5169 /* Forge string buf with all available names */
5170 for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
5171 if (attach_type && !section_defs[i].is_attachable)
5174 if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
5179 strcat(buf, section_defs[i].sec);
5185 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
5186 enum bpf_attach_type *expected_attach_type)
5188 const struct bpf_sec_def *sec_def;
5194 sec_def = find_sec_def(name);
5196 *prog_type = sec_def->prog_type;
5197 *expected_attach_type = sec_def->expected_attach_type;
5201 pr_warn("failed to guess program type from ELF section '%s'\n", name);
5202 type_names = libbpf_get_type_names(false);
5203 if (type_names != NULL) {
5204 pr_debug("supported section(type) names are:%s\n", type_names);
5211 #define BTF_PREFIX "btf_trace_"
5212 int libbpf_find_vmlinux_btf_id(const char *name,
5213 enum bpf_attach_type attach_type)
5215 struct btf *btf = bpf_core_find_kernel_btf();
5216 char raw_tp_btf[128] = BTF_PREFIX;
5217 char *dst = raw_tp_btf + sizeof(BTF_PREFIX) - 1;
5218 const char *btf_name;
5223 pr_warn("vmlinux BTF is not found\n");
5227 if (attach_type == BPF_TRACE_RAW_TP) {
5228 /* prepend "btf_trace_" prefix per kernel convention */
5229 strncat(dst, name, sizeof(raw_tp_btf) - sizeof(BTF_PREFIX));
5230 btf_name = raw_tp_btf;
5231 kind = BTF_KIND_TYPEDEF;
5234 kind = BTF_KIND_FUNC;
5236 err = btf__find_by_name_kind(btf, btf_name, kind);
5241 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd)
5243 struct bpf_prog_info_linear *info_linear;
5244 struct bpf_prog_info *info;
5245 struct btf *btf = NULL;
5248 info_linear = bpf_program__get_prog_info_linear(attach_prog_fd, 0);
5249 if (IS_ERR_OR_NULL(info_linear)) {
5250 pr_warn("failed get_prog_info_linear for FD %d\n",
5254 info = &info_linear->info;
5255 if (!info->btf_id) {
5256 pr_warn("The target program doesn't have BTF\n");
5259 if (btf__get_from_id(info->btf_id, &btf)) {
5260 pr_warn("Failed to get BTF of the program\n");
5263 err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
5266 pr_warn("%s is not found in prog's BTF\n", name);
5274 static int libbpf_find_attach_btf_id(const char *name,
5275 enum bpf_attach_type attach_type,
5276 __u32 attach_prog_fd)
5283 for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
5284 if (!section_defs[i].is_attach_btf)
5286 if (strncmp(name, section_defs[i].sec, section_defs[i].len))
5289 err = libbpf_find_prog_btf_id(name + section_defs[i].len,
5292 err = libbpf_find_vmlinux_btf_id(name + section_defs[i].len,
5295 pr_warn("%s is not found in vmlinux BTF\n", name);
5298 pr_warn("failed to identify btf_id based on ELF section name '%s'\n", name);
5302 int libbpf_attach_type_by_name(const char *name,
5303 enum bpf_attach_type *attach_type)
5311 for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
5312 if (strncmp(name, section_defs[i].sec, section_defs[i].len))
5314 if (!section_defs[i].is_attachable)
5316 *attach_type = section_defs[i].attach_type;
5319 pr_warn("failed to guess attach type based on ELF section name '%s'\n", name);
5320 type_names = libbpf_get_type_names(true);
5321 if (type_names != NULL) {
5322 pr_info("attachable section(type) names are:%s\n", type_names);
5329 int bpf_map__fd(const struct bpf_map *map)
5331 return map ? map->fd : -EINVAL;
5334 const struct bpf_map_def *bpf_map__def(const struct bpf_map *map)
5336 return map ? &map->def : ERR_PTR(-EINVAL);
5339 const char *bpf_map__name(const struct bpf_map *map)
5341 return map ? map->name : NULL;
5344 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
5346 return map ? map->btf_key_type_id : 0;
5349 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
5351 return map ? map->btf_value_type_id : 0;
5354 int bpf_map__set_priv(struct bpf_map *map, void *priv,
5355 bpf_map_clear_priv_t clear_priv)
5361 if (map->clear_priv)
5362 map->clear_priv(map, map->priv);
5366 map->clear_priv = clear_priv;
5370 void *bpf_map__priv(const struct bpf_map *map)
5372 return map ? map->priv : ERR_PTR(-EINVAL);
5375 bool bpf_map__is_offload_neutral(const struct bpf_map *map)
5377 return map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY;
5380 bool bpf_map__is_internal(const struct bpf_map *map)
5382 return map->libbpf_type != LIBBPF_MAP_UNSPEC;
5385 void bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
5387 map->map_ifindex = ifindex;
5390 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
5392 if (!bpf_map_type__is_map_in_map(map->def.type)) {
5393 pr_warn("error: unsupported map type\n");
5396 if (map->inner_map_fd != -1) {
5397 pr_warn("error: inner_map_fd already specified\n");
5400 map->inner_map_fd = fd;
5404 static struct bpf_map *
5405 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
5408 struct bpf_map *s, *e;
5410 if (!obj || !obj->maps)
5414 e = obj->maps + obj->nr_maps;
5416 if ((m < s) || (m >= e)) {
5417 pr_warn("error in %s: map handler doesn't belong to object\n",
5422 idx = (m - obj->maps) + i;
5423 if (idx >= obj->nr_maps || idx < 0)
5425 return &obj->maps[idx];
5429 bpf_map__next(const struct bpf_map *prev, const struct bpf_object *obj)
5434 return __bpf_map__iter(prev, obj, 1);
5438 bpf_map__prev(const struct bpf_map *next, const struct bpf_object *obj)
5443 return obj->maps + obj->nr_maps - 1;
5446 return __bpf_map__iter(next, obj, -1);
5450 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
5452 struct bpf_map *pos;
5454 bpf_object__for_each_map(pos, obj) {
5455 if (pos->name && !strcmp(pos->name, name))
5462 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
5464 return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
5468 bpf_object__find_map_by_offset(struct bpf_object *obj, size_t offset)
5470 return ERR_PTR(-ENOTSUP);
5473 long libbpf_get_error(const void *ptr)
5475 return PTR_ERR_OR_ZERO(ptr);
5478 int bpf_prog_load(const char *file, enum bpf_prog_type type,
5479 struct bpf_object **pobj, int *prog_fd)
5481 struct bpf_prog_load_attr attr;
5483 memset(&attr, 0, sizeof(struct bpf_prog_load_attr));
5485 attr.prog_type = type;
5486 attr.expected_attach_type = 0;
5488 return bpf_prog_load_xattr(&attr, pobj, prog_fd);
5491 int bpf_prog_load_xattr(const struct bpf_prog_load_attr *attr,
5492 struct bpf_object **pobj, int *prog_fd)
5494 struct bpf_object_open_attr open_attr = {};
5495 struct bpf_program *prog, *first_prog = NULL;
5496 struct bpf_object *obj;
5497 struct bpf_map *map;
5505 open_attr.file = attr->file;
5506 open_attr.prog_type = attr->prog_type;
5508 obj = bpf_object__open_xattr(&open_attr);
5509 if (IS_ERR_OR_NULL(obj))
5512 bpf_object__for_each_program(prog, obj) {
5513 enum bpf_attach_type attach_type = attr->expected_attach_type;
5515 * to preserve backwards compatibility, bpf_prog_load treats
5516 * attr->prog_type, if specified, as an override to whatever
5517 * bpf_object__open guessed
5519 if (attr->prog_type != BPF_PROG_TYPE_UNSPEC) {
5520 bpf_program__set_type(prog, attr->prog_type);
5521 bpf_program__set_expected_attach_type(prog,
5524 if (bpf_program__get_type(prog) == BPF_PROG_TYPE_UNSPEC) {
5526 * we haven't guessed from section name and user
5527 * didn't provide a fallback type, too bad...
5529 bpf_object__close(obj);
5533 prog->prog_ifindex = attr->ifindex;
5534 prog->log_level = attr->log_level;
5535 prog->prog_flags = attr->prog_flags;
5540 bpf_object__for_each_map(map, obj) {
5541 if (!bpf_map__is_offload_neutral(map))
5542 map->map_ifindex = attr->ifindex;
5546 pr_warn("object file doesn't contain bpf program\n");
5547 bpf_object__close(obj);
5551 err = bpf_object__load(obj);
5553 bpf_object__close(obj);
5558 *prog_fd = bpf_program__fd(first_prog);
5563 int (*destroy)(struct bpf_link *link);
5566 int bpf_link__destroy(struct bpf_link *link)
5573 err = link->destroy(link);
5579 struct bpf_link_fd {
5580 struct bpf_link link; /* has to be at the top of struct */
5581 int fd; /* hook FD */
5584 static int bpf_link__destroy_perf_event(struct bpf_link *link)
5586 struct bpf_link_fd *l = (void *)link;
5589 err = ioctl(l->fd, PERF_EVENT_IOC_DISABLE, 0);
5597 struct bpf_link *bpf_program__attach_perf_event(struct bpf_program *prog,
5600 char errmsg[STRERR_BUFSIZE];
5601 struct bpf_link_fd *link;
5605 pr_warn("program '%s': invalid perf event FD %d\n",
5606 bpf_program__title(prog, false), pfd);
5607 return ERR_PTR(-EINVAL);
5609 prog_fd = bpf_program__fd(prog);
5611 pr_warn("program '%s': can't attach BPF program w/o FD (did you load it?)\n",
5612 bpf_program__title(prog, false));
5613 return ERR_PTR(-EINVAL);
5616 link = malloc(sizeof(*link));
5618 return ERR_PTR(-ENOMEM);
5619 link->link.destroy = &bpf_link__destroy_perf_event;
5622 if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
5625 pr_warn("program '%s': failed to attach to pfd %d: %s\n",
5626 bpf_program__title(prog, false), pfd,
5627 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
5628 return ERR_PTR(err);
5630 if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
5633 pr_warn("program '%s': failed to enable pfd %d: %s\n",
5634 bpf_program__title(prog, false), pfd,
5635 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
5636 return ERR_PTR(err);
5638 return (struct bpf_link *)link;
5642 * this function is expected to parse integer in the range of [0, 2^31-1] from
5643 * given file using scanf format string fmt. If actual parsed value is
5644 * negative, the result might be indistinguishable from error
5646 static int parse_uint_from_file(const char *file, const char *fmt)
5648 char buf[STRERR_BUFSIZE];
5652 f = fopen(file, "r");
5655 pr_debug("failed to open '%s': %s\n", file,
5656 libbpf_strerror_r(err, buf, sizeof(buf)));
5659 err = fscanf(f, fmt, &ret);
5661 err = err == EOF ? -EIO : -errno;
5662 pr_debug("failed to parse '%s': %s\n", file,
5663 libbpf_strerror_r(err, buf, sizeof(buf)));
5671 static int determine_kprobe_perf_type(void)
5673 const char *file = "/sys/bus/event_source/devices/kprobe/type";
5675 return parse_uint_from_file(file, "%d\n");
5678 static int determine_uprobe_perf_type(void)
5680 const char *file = "/sys/bus/event_source/devices/uprobe/type";
5682 return parse_uint_from_file(file, "%d\n");
5685 static int determine_kprobe_retprobe_bit(void)
5687 const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
5689 return parse_uint_from_file(file, "config:%d\n");
5692 static int determine_uprobe_retprobe_bit(void)
5694 const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
5696 return parse_uint_from_file(file, "config:%d\n");
5699 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
5700 uint64_t offset, int pid)
5702 struct perf_event_attr attr = {};
5703 char errmsg[STRERR_BUFSIZE];
5706 type = uprobe ? determine_uprobe_perf_type()
5707 : determine_kprobe_perf_type();
5709 pr_warn("failed to determine %s perf type: %s\n",
5710 uprobe ? "uprobe" : "kprobe",
5711 libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
5715 int bit = uprobe ? determine_uprobe_retprobe_bit()
5716 : determine_kprobe_retprobe_bit();
5719 pr_warn("failed to determine %s retprobe bit: %s\n",
5720 uprobe ? "uprobe" : "kprobe",
5721 libbpf_strerror_r(bit, errmsg, sizeof(errmsg)));
5724 attr.config |= 1 << bit;
5726 attr.size = sizeof(attr);
5728 attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
5729 attr.config2 = offset; /* kprobe_addr or probe_offset */
5731 /* pid filter is meaningful only for uprobes */
5732 pfd = syscall(__NR_perf_event_open, &attr,
5733 pid < 0 ? -1 : pid /* pid */,
5734 pid == -1 ? 0 : -1 /* cpu */,
5735 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
5738 pr_warn("%s perf_event_open() failed: %s\n",
5739 uprobe ? "uprobe" : "kprobe",
5740 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
5746 struct bpf_link *bpf_program__attach_kprobe(struct bpf_program *prog,
5748 const char *func_name)
5750 char errmsg[STRERR_BUFSIZE];
5751 struct bpf_link *link;
5754 pfd = perf_event_open_probe(false /* uprobe */, retprobe, func_name,
5755 0 /* offset */, -1 /* pid */);
5757 pr_warn("program '%s': failed to create %s '%s' perf event: %s\n",
5758 bpf_program__title(prog, false),
5759 retprobe ? "kretprobe" : "kprobe", func_name,
5760 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
5761 return ERR_PTR(pfd);
5763 link = bpf_program__attach_perf_event(prog, pfd);
5766 err = PTR_ERR(link);
5767 pr_warn("program '%s': failed to attach to %s '%s': %s\n",
5768 bpf_program__title(prog, false),
5769 retprobe ? "kretprobe" : "kprobe", func_name,
5770 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
5776 static struct bpf_link *attach_kprobe(const struct bpf_sec_def *sec,
5777 struct bpf_program *prog)
5779 const char *func_name;
5782 func_name = bpf_program__title(prog, false) + sec->len;
5783 retprobe = strcmp(sec->sec, "kretprobe/") == 0;
5785 return bpf_program__attach_kprobe(prog, retprobe, func_name);
5788 struct bpf_link *bpf_program__attach_uprobe(struct bpf_program *prog,
5789 bool retprobe, pid_t pid,
5790 const char *binary_path,
5793 char errmsg[STRERR_BUFSIZE];
5794 struct bpf_link *link;
5797 pfd = perf_event_open_probe(true /* uprobe */, retprobe,
5798 binary_path, func_offset, pid);
5800 pr_warn("program '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
5801 bpf_program__title(prog, false),
5802 retprobe ? "uretprobe" : "uprobe",
5803 binary_path, func_offset,
5804 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
5805 return ERR_PTR(pfd);
5807 link = bpf_program__attach_perf_event(prog, pfd);
5810 err = PTR_ERR(link);
5811 pr_warn("program '%s': failed to attach to %s '%s:0x%zx': %s\n",
5812 bpf_program__title(prog, false),
5813 retprobe ? "uretprobe" : "uprobe",
5814 binary_path, func_offset,
5815 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
5821 static int determine_tracepoint_id(const char *tp_category,
5822 const char *tp_name)
5824 char file[PATH_MAX];
5827 ret = snprintf(file, sizeof(file),
5828 "/sys/kernel/debug/tracing/events/%s/%s/id",
5829 tp_category, tp_name);
5832 if (ret >= sizeof(file)) {
5833 pr_debug("tracepoint %s/%s path is too long\n",
5834 tp_category, tp_name);
5837 return parse_uint_from_file(file, "%d\n");
5840 static int perf_event_open_tracepoint(const char *tp_category,
5841 const char *tp_name)
5843 struct perf_event_attr attr = {};
5844 char errmsg[STRERR_BUFSIZE];
5845 int tp_id, pfd, err;
5847 tp_id = determine_tracepoint_id(tp_category, tp_name);
5849 pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
5850 tp_category, tp_name,
5851 libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
5855 attr.type = PERF_TYPE_TRACEPOINT;
5856 attr.size = sizeof(attr);
5857 attr.config = tp_id;
5859 pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
5860 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
5863 pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
5864 tp_category, tp_name,
5865 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
5871 struct bpf_link *bpf_program__attach_tracepoint(struct bpf_program *prog,
5872 const char *tp_category,
5873 const char *tp_name)
5875 char errmsg[STRERR_BUFSIZE];
5876 struct bpf_link *link;
5879 pfd = perf_event_open_tracepoint(tp_category, tp_name);
5881 pr_warn("program '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
5882 bpf_program__title(prog, false),
5883 tp_category, tp_name,
5884 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
5885 return ERR_PTR(pfd);
5887 link = bpf_program__attach_perf_event(prog, pfd);
5890 err = PTR_ERR(link);
5891 pr_warn("program '%s': failed to attach to tracepoint '%s/%s': %s\n",
5892 bpf_program__title(prog, false),
5893 tp_category, tp_name,
5894 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
5900 static struct bpf_link *attach_tp(const struct bpf_sec_def *sec,
5901 struct bpf_program *prog)
5903 char *sec_name, *tp_cat, *tp_name;
5904 struct bpf_link *link;
5906 sec_name = strdup(bpf_program__title(prog, false));
5908 return ERR_PTR(-ENOMEM);
5910 /* extract "tp/<category>/<name>" */
5911 tp_cat = sec_name + sec->len;
5912 tp_name = strchr(tp_cat, '/');
5914 link = ERR_PTR(-EINVAL);
5920 link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
5926 static int bpf_link__destroy_fd(struct bpf_link *link)
5928 struct bpf_link_fd *l = (void *)link;
5930 return close(l->fd);
5933 struct bpf_link *bpf_program__attach_raw_tracepoint(struct bpf_program *prog,
5934 const char *tp_name)
5936 char errmsg[STRERR_BUFSIZE];
5937 struct bpf_link_fd *link;
5940 prog_fd = bpf_program__fd(prog);
5942 pr_warn("program '%s': can't attach before loaded\n",
5943 bpf_program__title(prog, false));
5944 return ERR_PTR(-EINVAL);
5947 link = malloc(sizeof(*link));
5949 return ERR_PTR(-ENOMEM);
5950 link->link.destroy = &bpf_link__destroy_fd;
5952 pfd = bpf_raw_tracepoint_open(tp_name, prog_fd);
5956 pr_warn("program '%s': failed to attach to raw tracepoint '%s': %s\n",
5957 bpf_program__title(prog, false), tp_name,
5958 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
5959 return ERR_PTR(pfd);
5962 return (struct bpf_link *)link;
5965 static struct bpf_link *attach_raw_tp(const struct bpf_sec_def *sec,
5966 struct bpf_program *prog)
5968 const char *tp_name = bpf_program__title(prog, false) + sec->len;
5970 return bpf_program__attach_raw_tracepoint(prog, tp_name);
5973 struct bpf_link *bpf_program__attach_trace(struct bpf_program *prog)
5975 char errmsg[STRERR_BUFSIZE];
5976 struct bpf_link_fd *link;
5979 prog_fd = bpf_program__fd(prog);
5981 pr_warn("program '%s': can't attach before loaded\n",
5982 bpf_program__title(prog, false));
5983 return ERR_PTR(-EINVAL);
5986 link = malloc(sizeof(*link));
5988 return ERR_PTR(-ENOMEM);
5989 link->link.destroy = &bpf_link__destroy_fd;
5991 pfd = bpf_raw_tracepoint_open(NULL, prog_fd);
5995 pr_warn("program '%s': failed to attach to trace: %s\n",
5996 bpf_program__title(prog, false),
5997 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
5998 return ERR_PTR(pfd);
6001 return (struct bpf_link *)link;
6004 static struct bpf_link *attach_trace(const struct bpf_sec_def *sec,
6005 struct bpf_program *prog)
6007 return bpf_program__attach_trace(prog);
6010 struct bpf_link *bpf_program__attach(struct bpf_program *prog)
6012 const struct bpf_sec_def *sec_def;
6014 sec_def = find_sec_def(bpf_program__title(prog, false));
6015 if (!sec_def || !sec_def->attach_fn)
6016 return ERR_PTR(-ESRCH);
6018 return sec_def->attach_fn(sec_def, prog);
6021 enum bpf_perf_event_ret
6022 bpf_perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
6023 void **copy_mem, size_t *copy_size,
6024 bpf_perf_event_print_t fn, void *private_data)
6026 struct perf_event_mmap_page *header = mmap_mem;
6027 __u64 data_head = ring_buffer_read_head(header);
6028 __u64 data_tail = header->data_tail;
6029 void *base = ((__u8 *)header) + page_size;
6030 int ret = LIBBPF_PERF_EVENT_CONT;
6031 struct perf_event_header *ehdr;
6034 while (data_head != data_tail) {
6035 ehdr = base + (data_tail & (mmap_size - 1));
6036 ehdr_size = ehdr->size;
6038 if (((void *)ehdr) + ehdr_size > base + mmap_size) {
6039 void *copy_start = ehdr;
6040 size_t len_first = base + mmap_size - copy_start;
6041 size_t len_secnd = ehdr_size - len_first;
6043 if (*copy_size < ehdr_size) {
6045 *copy_mem = malloc(ehdr_size);
6048 ret = LIBBPF_PERF_EVENT_ERROR;
6051 *copy_size = ehdr_size;
6054 memcpy(*copy_mem, copy_start, len_first);
6055 memcpy(*copy_mem + len_first, base, len_secnd);
6059 ret = fn(ehdr, private_data);
6060 data_tail += ehdr_size;
6061 if (ret != LIBBPF_PERF_EVENT_CONT)
6065 ring_buffer_write_tail(header, data_tail);
6071 struct perf_buffer_params {
6072 struct perf_event_attr *attr;
6073 /* if event_cb is specified, it takes precendence */
6074 perf_buffer_event_fn event_cb;
6075 /* sample_cb and lost_cb are higher-level common-case callbacks */
6076 perf_buffer_sample_fn sample_cb;
6077 perf_buffer_lost_fn lost_cb;
6084 struct perf_cpu_buf {
6085 struct perf_buffer *pb;
6086 void *base; /* mmap()'ed memory */
6087 void *buf; /* for reconstructing segmented data */
6094 struct perf_buffer {
6095 perf_buffer_event_fn event_cb;
6096 perf_buffer_sample_fn sample_cb;
6097 perf_buffer_lost_fn lost_cb;
6098 void *ctx; /* passed into callbacks */
6102 struct perf_cpu_buf **cpu_bufs;
6103 struct epoll_event *events;
6104 int cpu_cnt; /* number of allocated CPU buffers */
6105 int epoll_fd; /* perf event FD */
6106 int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
6109 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
6110 struct perf_cpu_buf *cpu_buf)
6114 if (cpu_buf->base &&
6115 munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
6116 pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
6117 if (cpu_buf->fd >= 0) {
6118 ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
6125 void perf_buffer__free(struct perf_buffer *pb)
6132 for (i = 0; i < pb->cpu_cnt && pb->cpu_bufs[i]; i++) {
6133 struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
6135 bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
6136 perf_buffer__free_cpu_buf(pb, cpu_buf);
6140 if (pb->epoll_fd >= 0)
6141 close(pb->epoll_fd);
6146 static struct perf_cpu_buf *
6147 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
6148 int cpu, int map_key)
6150 struct perf_cpu_buf *cpu_buf;
6151 char msg[STRERR_BUFSIZE];
6154 cpu_buf = calloc(1, sizeof(*cpu_buf));
6156 return ERR_PTR(-ENOMEM);
6160 cpu_buf->map_key = map_key;
6162 cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
6163 -1, PERF_FLAG_FD_CLOEXEC);
6164 if (cpu_buf->fd < 0) {
6166 pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
6167 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
6171 cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
6172 PROT_READ | PROT_WRITE, MAP_SHARED,
6174 if (cpu_buf->base == MAP_FAILED) {
6175 cpu_buf->base = NULL;
6177 pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
6178 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
6182 if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
6184 pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
6185 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
6192 perf_buffer__free_cpu_buf(pb, cpu_buf);
6193 return (struct perf_cpu_buf *)ERR_PTR(err);
6196 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
6197 struct perf_buffer_params *p);
6199 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
6200 const struct perf_buffer_opts *opts)
6202 struct perf_buffer_params p = {};
6203 struct perf_event_attr attr = { 0, };
6205 attr.config = PERF_COUNT_SW_BPF_OUTPUT,
6206 attr.type = PERF_TYPE_SOFTWARE;
6207 attr.sample_type = PERF_SAMPLE_RAW;
6208 attr.sample_period = 1;
6209 attr.wakeup_events = 1;
6212 p.sample_cb = opts ? opts->sample_cb : NULL;
6213 p.lost_cb = opts ? opts->lost_cb : NULL;
6214 p.ctx = opts ? opts->ctx : NULL;
6216 return __perf_buffer__new(map_fd, page_cnt, &p);
6219 struct perf_buffer *
6220 perf_buffer__new_raw(int map_fd, size_t page_cnt,
6221 const struct perf_buffer_raw_opts *opts)
6223 struct perf_buffer_params p = {};
6225 p.attr = opts->attr;
6226 p.event_cb = opts->event_cb;
6228 p.cpu_cnt = opts->cpu_cnt;
6229 p.cpus = opts->cpus;
6230 p.map_keys = opts->map_keys;
6232 return __perf_buffer__new(map_fd, page_cnt, &p);
6235 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
6236 struct perf_buffer_params *p)
6238 const char *online_cpus_file = "/sys/devices/system/cpu/online";
6239 struct bpf_map_info map = {};
6240 char msg[STRERR_BUFSIZE];
6241 struct perf_buffer *pb;
6242 bool *online = NULL;
6246 if (page_cnt & (page_cnt - 1)) {
6247 pr_warn("page count should be power of two, but is %zu\n",
6249 return ERR_PTR(-EINVAL);
6252 map_info_len = sizeof(map);
6253 err = bpf_obj_get_info_by_fd(map_fd, &map, &map_info_len);
6256 pr_warn("failed to get map info for map FD %d: %s\n",
6257 map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
6258 return ERR_PTR(err);
6261 if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
6262 pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
6264 return ERR_PTR(-EINVAL);
6267 pb = calloc(1, sizeof(*pb));
6269 return ERR_PTR(-ENOMEM);
6271 pb->event_cb = p->event_cb;
6272 pb->sample_cb = p->sample_cb;
6273 pb->lost_cb = p->lost_cb;
6276 pb->page_size = getpagesize();
6277 pb->mmap_size = pb->page_size * page_cnt;
6278 pb->map_fd = map_fd;
6280 pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
6281 if (pb->epoll_fd < 0) {
6283 pr_warn("failed to create epoll instance: %s\n",
6284 libbpf_strerror_r(err, msg, sizeof(msg)));
6288 if (p->cpu_cnt > 0) {
6289 pb->cpu_cnt = p->cpu_cnt;
6291 pb->cpu_cnt = libbpf_num_possible_cpus();
6292 if (pb->cpu_cnt < 0) {
6296 if (map.max_entries < pb->cpu_cnt)
6297 pb->cpu_cnt = map.max_entries;
6300 pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
6303 pr_warn("failed to allocate events: out of memory\n");
6306 pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
6307 if (!pb->cpu_bufs) {
6309 pr_warn("failed to allocate buffers: out of memory\n");
6313 err = parse_cpu_mask_file(online_cpus_file, &online, &n);
6315 pr_warn("failed to get online CPU mask: %d\n", err);
6319 for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
6320 struct perf_cpu_buf *cpu_buf;
6323 cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
6324 map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
6326 /* in case user didn't explicitly requested particular CPUs to
6327 * be attached to, skip offline/not present CPUs
6329 if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
6332 cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
6333 if (IS_ERR(cpu_buf)) {
6334 err = PTR_ERR(cpu_buf);
6338 pb->cpu_bufs[j] = cpu_buf;
6340 err = bpf_map_update_elem(pb->map_fd, &map_key,
6344 pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
6345 cpu, map_key, cpu_buf->fd,
6346 libbpf_strerror_r(err, msg, sizeof(msg)));
6350 pb->events[j].events = EPOLLIN;
6351 pb->events[j].data.ptr = cpu_buf;
6352 if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
6353 &pb->events[j]) < 0) {
6355 pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
6357 libbpf_strerror_r(err, msg, sizeof(msg)));
6370 perf_buffer__free(pb);
6371 return ERR_PTR(err);
6374 struct perf_sample_raw {
6375 struct perf_event_header header;
6380 struct perf_sample_lost {
6381 struct perf_event_header header;
6387 static enum bpf_perf_event_ret
6388 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
6390 struct perf_cpu_buf *cpu_buf = ctx;
6391 struct perf_buffer *pb = cpu_buf->pb;
6394 /* user wants full control over parsing perf event */
6396 return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
6399 case PERF_RECORD_SAMPLE: {
6400 struct perf_sample_raw *s = data;
6403 pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
6406 case PERF_RECORD_LOST: {
6407 struct perf_sample_lost *s = data;
6410 pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
6414 pr_warn("unknown perf sample type %d\n", e->type);
6415 return LIBBPF_PERF_EVENT_ERROR;
6417 return LIBBPF_PERF_EVENT_CONT;
6420 static int perf_buffer__process_records(struct perf_buffer *pb,
6421 struct perf_cpu_buf *cpu_buf)
6423 enum bpf_perf_event_ret ret;
6425 ret = bpf_perf_event_read_simple(cpu_buf->base, pb->mmap_size,
6426 pb->page_size, &cpu_buf->buf,
6428 perf_buffer__process_record, cpu_buf);
6429 if (ret != LIBBPF_PERF_EVENT_CONT)
6434 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
6438 cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
6439 for (i = 0; i < cnt; i++) {
6440 struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
6442 err = perf_buffer__process_records(pb, cpu_buf);
6444 pr_warn("error while processing records: %d\n", err);
6448 return cnt < 0 ? -errno : cnt;
6451 struct bpf_prog_info_array_desc {
6452 int array_offset; /* e.g. offset of jited_prog_insns */
6453 int count_offset; /* e.g. offset of jited_prog_len */
6454 int size_offset; /* > 0: offset of rec size,
6455 * < 0: fix size of -size_offset
6459 static struct bpf_prog_info_array_desc bpf_prog_info_array_desc[] = {
6460 [BPF_PROG_INFO_JITED_INSNS] = {
6461 offsetof(struct bpf_prog_info, jited_prog_insns),
6462 offsetof(struct bpf_prog_info, jited_prog_len),
6465 [BPF_PROG_INFO_XLATED_INSNS] = {
6466 offsetof(struct bpf_prog_info, xlated_prog_insns),
6467 offsetof(struct bpf_prog_info, xlated_prog_len),
6470 [BPF_PROG_INFO_MAP_IDS] = {
6471 offsetof(struct bpf_prog_info, map_ids),
6472 offsetof(struct bpf_prog_info, nr_map_ids),
6473 -(int)sizeof(__u32),
6475 [BPF_PROG_INFO_JITED_KSYMS] = {
6476 offsetof(struct bpf_prog_info, jited_ksyms),
6477 offsetof(struct bpf_prog_info, nr_jited_ksyms),
6478 -(int)sizeof(__u64),
6480 [BPF_PROG_INFO_JITED_FUNC_LENS] = {
6481 offsetof(struct bpf_prog_info, jited_func_lens),
6482 offsetof(struct bpf_prog_info, nr_jited_func_lens),
6483 -(int)sizeof(__u32),
6485 [BPF_PROG_INFO_FUNC_INFO] = {
6486 offsetof(struct bpf_prog_info, func_info),
6487 offsetof(struct bpf_prog_info, nr_func_info),
6488 offsetof(struct bpf_prog_info, func_info_rec_size),
6490 [BPF_PROG_INFO_LINE_INFO] = {
6491 offsetof(struct bpf_prog_info, line_info),
6492 offsetof(struct bpf_prog_info, nr_line_info),
6493 offsetof(struct bpf_prog_info, line_info_rec_size),
6495 [BPF_PROG_INFO_JITED_LINE_INFO] = {
6496 offsetof(struct bpf_prog_info, jited_line_info),
6497 offsetof(struct bpf_prog_info, nr_jited_line_info),
6498 offsetof(struct bpf_prog_info, jited_line_info_rec_size),
6500 [BPF_PROG_INFO_PROG_TAGS] = {
6501 offsetof(struct bpf_prog_info, prog_tags),
6502 offsetof(struct bpf_prog_info, nr_prog_tags),
6503 -(int)sizeof(__u8) * BPF_TAG_SIZE,
6508 static __u32 bpf_prog_info_read_offset_u32(struct bpf_prog_info *info,
6511 __u32 *array = (__u32 *)info;
6514 return array[offset / sizeof(__u32)];
6515 return -(int)offset;
6518 static __u64 bpf_prog_info_read_offset_u64(struct bpf_prog_info *info,
6521 __u64 *array = (__u64 *)info;
6524 return array[offset / sizeof(__u64)];
6525 return -(int)offset;
6528 static void bpf_prog_info_set_offset_u32(struct bpf_prog_info *info, int offset,
6531 __u32 *array = (__u32 *)info;
6534 array[offset / sizeof(__u32)] = val;
6537 static void bpf_prog_info_set_offset_u64(struct bpf_prog_info *info, int offset,
6540 __u64 *array = (__u64 *)info;
6543 array[offset / sizeof(__u64)] = val;
6546 struct bpf_prog_info_linear *
6547 bpf_program__get_prog_info_linear(int fd, __u64 arrays)
6549 struct bpf_prog_info_linear *info_linear;
6550 struct bpf_prog_info info = {};
6551 __u32 info_len = sizeof(info);
6556 if (arrays >> BPF_PROG_INFO_LAST_ARRAY)
6557 return ERR_PTR(-EINVAL);
6559 /* step 1: get array dimensions */
6560 err = bpf_obj_get_info_by_fd(fd, &info, &info_len);
6562 pr_debug("can't get prog info: %s", strerror(errno));
6563 return ERR_PTR(-EFAULT);
6566 /* step 2: calculate total size of all arrays */
6567 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
6568 bool include_array = (arrays & (1UL << i)) > 0;
6569 struct bpf_prog_info_array_desc *desc;
6572 desc = bpf_prog_info_array_desc + i;
6574 /* kernel is too old to support this field */
6575 if (info_len < desc->array_offset + sizeof(__u32) ||
6576 info_len < desc->count_offset + sizeof(__u32) ||
6577 (desc->size_offset > 0 && info_len < desc->size_offset))
6578 include_array = false;
6580 if (!include_array) {
6581 arrays &= ~(1UL << i); /* clear the bit */
6585 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
6586 size = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
6588 data_len += count * size;
6591 /* step 3: allocate continuous memory */
6592 data_len = roundup(data_len, sizeof(__u64));
6593 info_linear = malloc(sizeof(struct bpf_prog_info_linear) + data_len);
6595 return ERR_PTR(-ENOMEM);
6597 /* step 4: fill data to info_linear->info */
6598 info_linear->arrays = arrays;
6599 memset(&info_linear->info, 0, sizeof(info));
6600 ptr = info_linear->data;
6602 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
6603 struct bpf_prog_info_array_desc *desc;
6606 if ((arrays & (1UL << i)) == 0)
6609 desc = bpf_prog_info_array_desc + i;
6610 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
6611 size = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
6612 bpf_prog_info_set_offset_u32(&info_linear->info,
6613 desc->count_offset, count);
6614 bpf_prog_info_set_offset_u32(&info_linear->info,
6615 desc->size_offset, size);
6616 bpf_prog_info_set_offset_u64(&info_linear->info,
6619 ptr += count * size;
6622 /* step 5: call syscall again to get required arrays */
6623 err = bpf_obj_get_info_by_fd(fd, &info_linear->info, &info_len);
6625 pr_debug("can't get prog info: %s", strerror(errno));
6627 return ERR_PTR(-EFAULT);
6630 /* step 6: verify the data */
6631 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
6632 struct bpf_prog_info_array_desc *desc;
6635 if ((arrays & (1UL << i)) == 0)
6638 desc = bpf_prog_info_array_desc + i;
6639 v1 = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
6640 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
6641 desc->count_offset);
6643 pr_warn("%s: mismatch in element count\n", __func__);
6645 v1 = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
6646 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
6649 pr_warn("%s: mismatch in rec size\n", __func__);
6652 /* step 7: update info_len and data_len */
6653 info_linear->info_len = sizeof(struct bpf_prog_info);
6654 info_linear->data_len = data_len;
6659 void bpf_program__bpil_addr_to_offs(struct bpf_prog_info_linear *info_linear)
6663 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
6664 struct bpf_prog_info_array_desc *desc;
6667 if ((info_linear->arrays & (1UL << i)) == 0)
6670 desc = bpf_prog_info_array_desc + i;
6671 addr = bpf_prog_info_read_offset_u64(&info_linear->info,
6672 desc->array_offset);
6673 offs = addr - ptr_to_u64(info_linear->data);
6674 bpf_prog_info_set_offset_u64(&info_linear->info,
6675 desc->array_offset, offs);
6679 void bpf_program__bpil_offs_to_addr(struct bpf_prog_info_linear *info_linear)
6683 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
6684 struct bpf_prog_info_array_desc *desc;
6687 if ((info_linear->arrays & (1UL << i)) == 0)
6690 desc = bpf_prog_info_array_desc + i;
6691 offs = bpf_prog_info_read_offset_u64(&info_linear->info,
6692 desc->array_offset);
6693 addr = offs + ptr_to_u64(info_linear->data);
6694 bpf_prog_info_set_offset_u64(&info_linear->info,
6695 desc->array_offset, addr);
6699 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
6701 int err = 0, n, len, start, end = -1;
6707 /* Each sub string separated by ',' has format \d+-\d+ or \d+ */
6709 if (*s == ',' || *s == '\n') {
6713 n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
6714 if (n <= 0 || n > 2) {
6715 pr_warn("Failed to get CPU range %s: %d\n", s, n);
6718 } else if (n == 1) {
6721 if (start < 0 || start > end) {
6722 pr_warn("Invalid CPU range [%d,%d] in %s\n",
6727 tmp = realloc(*mask, end + 1);
6733 memset(tmp + *mask_sz, 0, start - *mask_sz);
6734 memset(tmp + start, 1, end - start + 1);
6739 pr_warn("Empty CPU range\n");
6749 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
6751 int fd, err = 0, len;
6754 fd = open(fcpu, O_RDONLY);
6757 pr_warn("Failed to open cpu mask file %s: %d\n", fcpu, err);
6760 len = read(fd, buf, sizeof(buf));
6763 err = len ? -errno : -EINVAL;
6764 pr_warn("Failed to read cpu mask from %s: %d\n", fcpu, err);
6767 if (len >= sizeof(buf)) {
6768 pr_warn("CPU mask is too big in file %s\n", fcpu);
6773 return parse_cpu_mask_str(buf, mask, mask_sz);
6776 int libbpf_num_possible_cpus(void)
6778 static const char *fcpu = "/sys/devices/system/cpu/possible";
6780 int err, n, i, tmp_cpus;
6783 tmp_cpus = READ_ONCE(cpus);
6787 err = parse_cpu_mask_file(fcpu, &mask, &n);
6792 for (i = 0; i < n; i++) {
6798 WRITE_ONCE(cpus, tmp_cpus);
6802 int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
6803 const struct bpf_object_open_opts *opts)
6805 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, skel_opts,
6806 .object_name = s->name,
6808 struct bpf_object *obj;
6811 /* Attempt to preserve opts->object_name, unless overriden by user
6812 * explicitly. Overwriting object name for skeletons is discouraged,
6813 * as it breaks global data maps, because they contain object name
6814 * prefix as their own map name prefix. When skeleton is generated,
6815 * bpftool is making an assumption that this name will stay the same.
6818 memcpy(&skel_opts, opts, sizeof(*opts));
6819 if (!opts->object_name)
6820 skel_opts.object_name = s->name;
6823 obj = bpf_object__open_mem(s->data, s->data_sz, &skel_opts);
6825 pr_warn("failed to initialize skeleton BPF object '%s': %ld\n",
6826 s->name, PTR_ERR(obj));
6827 return PTR_ERR(obj);
6832 for (i = 0; i < s->map_cnt; i++) {
6833 struct bpf_map **map = s->maps[i].map;
6834 const char *name = s->maps[i].name;
6835 void **mmaped = s->maps[i].mmaped;
6837 *map = bpf_object__find_map_by_name(obj, name);
6839 pr_warn("failed to find skeleton map '%s'\n", name);
6844 *mmaped = (*map)->mmaped;
6847 for (i = 0; i < s->prog_cnt; i++) {
6848 struct bpf_program **prog = s->progs[i].prog;
6849 const char *name = s->progs[i].name;
6851 *prog = bpf_object__find_program_by_name(obj, name);
6853 pr_warn("failed to find skeleton program '%s'\n", name);
6861 int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
6865 err = bpf_object__load(*s->obj);
6867 pr_warn("failed to load BPF skeleton '%s': %d\n", s->name, err);
6871 for (i = 0; i < s->map_cnt; i++) {
6872 struct bpf_map *map = *s->maps[i].map;
6873 size_t mmap_sz = bpf_map_mmap_sz(map);
6874 int prot, map_fd = bpf_map__fd(map);
6875 void **mmaped = s->maps[i].mmaped;
6881 if (!(map->def.map_flags & BPF_F_MMAPABLE)) {
6886 if (map->def.map_flags & BPF_F_RDONLY_PROG)
6889 prot = PROT_READ | PROT_WRITE;
6891 /* Remap anonymous mmap()-ed "map initialization image" as
6892 * a BPF map-backed mmap()-ed memory, but preserving the same
6893 * memory address. This will cause kernel to change process'
6894 * page table to point to a different piece of kernel memory,
6895 * but from userspace point of view memory address (and its
6896 * contents, being identical at this point) will stay the
6897 * same. This mapping will be released by bpf_object__close()
6898 * as per normal clean up procedure, so we don't need to worry
6899 * about it from skeleton's clean up perspective.
6901 remapped = mmap(*mmaped, mmap_sz, prot, MAP_SHARED | MAP_FIXED,
6903 if (remapped == MAP_FAILED) {
6906 pr_warn("failed to re-mmap() map '%s': %d\n",
6907 bpf_map__name(map), err);
6915 int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
6919 for (i = 0; i < s->prog_cnt; i++) {
6920 struct bpf_program *prog = *s->progs[i].prog;
6921 struct bpf_link **link = s->progs[i].link;
6922 const struct bpf_sec_def *sec_def;
6923 const char *sec_name = bpf_program__title(prog, false);
6925 sec_def = find_sec_def(sec_name);
6926 if (!sec_def || !sec_def->attach_fn)
6929 *link = sec_def->attach_fn(sec_def, prog);
6930 if (IS_ERR(*link)) {
6931 pr_warn("failed to auto-attach program '%s': %ld\n",
6932 bpf_program__name(prog), PTR_ERR(*link));
6933 return PTR_ERR(*link);
6940 void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
6944 for (i = 0; i < s->prog_cnt; i++) {
6945 struct bpf_link **link = s->progs[i].link;
6947 if (!IS_ERR_OR_NULL(*link))
6948 bpf_link__destroy(*link);
6953 void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
6956 bpf_object__detach_skeleton(s);
6958 bpf_object__close(*s->obj);