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 #define CHECK_ERR(action, err, out) do { \
111 /* Copied from tools/perf/util/util.h */
113 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
117 # define zclose(fd) ({ \
120 ___err = close((fd)); \
125 #ifdef HAVE_LIBELF_MMAP_SUPPORT
126 # define LIBBPF_ELF_C_READ_MMAP ELF_C_READ_MMAP
128 # define LIBBPF_ELF_C_READ_MMAP ELF_C_READ
131 static inline __u64 ptr_to_u64(const void *ptr)
133 return (__u64) (unsigned long) ptr;
136 struct bpf_capabilities {
137 /* v4.14: kernel support for program & map names. */
139 /* v5.2: kernel support for global data sections. */
141 /* BTF_KIND_FUNC and BTF_KIND_FUNC_PROTO support */
143 /* BTF_KIND_VAR and BTF_KIND_DATASEC support */
145 /* BPF_F_MMAPABLE is supported for arrays */
150 * bpf_prog should be a better name but it has been used in
154 /* Index in elf obj file, for relocation use. */
159 /* section_name with / replaced by _; makes recursive pinning
160 * in bpf_object__pin_programs easier
163 struct bpf_insn *insns;
164 size_t insns_cnt, main_prog_cnt;
165 enum bpf_prog_type type;
184 bpf_program_prep_t preprocessor;
186 struct bpf_object *obj;
188 bpf_program_clear_priv_t clear_priv;
190 enum bpf_attach_type expected_attach_type;
192 __u32 attach_prog_fd;
194 __u32 func_info_rec_size;
197 struct bpf_capabilities *caps;
200 __u32 line_info_rec_size;
205 enum libbpf_map_type {
212 static const char * const libbpf_type_to_btf_name[] = {
213 [LIBBPF_MAP_DATA] = ".data",
214 [LIBBPF_MAP_BSS] = ".bss",
215 [LIBBPF_MAP_RODATA] = ".rodata",
225 struct bpf_map_def def;
226 __u32 btf_key_type_id;
227 __u32 btf_value_type_id;
229 bpf_map_clear_priv_t clear_priv;
230 enum libbpf_map_type libbpf_type;
241 static LIST_HEAD(bpf_objects_list);
244 char name[BPF_OBJ_NAME_LEN];
248 struct bpf_program *programs;
250 struct bpf_map *maps;
253 struct bpf_secdata sections;
256 bool has_pseudo_calls;
257 bool relaxed_core_relocs;
260 * Information when doing elf related work. Only valid if fd
287 * All loaded bpf_object is linked in a list, which is
288 * hidden to caller. bpf_objects__<func> handlers deal with
291 struct list_head list;
294 struct btf_ext *btf_ext;
297 bpf_object_clear_priv_t clear_priv;
299 struct bpf_capabilities caps;
303 #define obj_elf_valid(o) ((o)->efile.elf)
305 void bpf_program__unload(struct bpf_program *prog)
313 * If the object is opened but the program was never loaded,
314 * it is possible that prog->instances.nr == -1.
316 if (prog->instances.nr > 0) {
317 for (i = 0; i < prog->instances.nr; i++)
318 zclose(prog->instances.fds[i]);
319 } else if (prog->instances.nr != -1) {
320 pr_warn("Internal error: instances.nr is %d\n",
324 prog->instances.nr = -1;
325 zfree(&prog->instances.fds);
327 zfree(&prog->func_info);
328 zfree(&prog->line_info);
331 static void bpf_program__exit(struct bpf_program *prog)
336 if (prog->clear_priv)
337 prog->clear_priv(prog, prog->priv);
340 prog->clear_priv = NULL;
342 bpf_program__unload(prog);
344 zfree(&prog->section_name);
345 zfree(&prog->pin_name);
347 zfree(&prog->reloc_desc);
354 static char *__bpf_program__pin_name(struct bpf_program *prog)
358 name = p = strdup(prog->section_name);
359 while ((p = strchr(p, '/')))
366 bpf_program__init(void *data, size_t size, char *section_name, int idx,
367 struct bpf_program *prog)
369 const size_t bpf_insn_sz = sizeof(struct bpf_insn);
371 if (size == 0 || size % bpf_insn_sz) {
372 pr_warn("corrupted section '%s', size: %zu\n",
377 memset(prog, 0, sizeof(*prog));
379 prog->section_name = strdup(section_name);
380 if (!prog->section_name) {
381 pr_warn("failed to alloc name for prog under section(%d) %s\n",
386 prog->pin_name = __bpf_program__pin_name(prog);
387 if (!prog->pin_name) {
388 pr_warn("failed to alloc pin name for prog under section(%d) %s\n",
393 prog->insns = malloc(size);
395 pr_warn("failed to alloc insns for prog under section %s\n",
399 prog->insns_cnt = size / bpf_insn_sz;
400 memcpy(prog->insns, data, size);
402 prog->instances.fds = NULL;
403 prog->instances.nr = -1;
404 prog->type = BPF_PROG_TYPE_UNSPEC;
408 bpf_program__exit(prog);
413 bpf_object__add_program(struct bpf_object *obj, void *data, size_t size,
414 char *section_name, int idx)
416 struct bpf_program prog, *progs;
419 err = bpf_program__init(data, size, section_name, idx, &prog);
423 prog.caps = &obj->caps;
424 progs = obj->programs;
425 nr_progs = obj->nr_programs;
427 progs = reallocarray(progs, nr_progs + 1, sizeof(progs[0]));
430 * In this case the original obj->programs
431 * is still valid, so don't need special treat for
432 * bpf_close_object().
434 pr_warn("failed to alloc a new program under section '%s'\n",
436 bpf_program__exit(&prog);
440 pr_debug("found program %s\n", prog.section_name);
441 obj->programs = progs;
442 obj->nr_programs = nr_progs + 1;
444 progs[nr_progs] = prog;
449 bpf_object__init_prog_names(struct bpf_object *obj)
451 Elf_Data *symbols = obj->efile.symbols;
452 struct bpf_program *prog;
455 for (pi = 0; pi < obj->nr_programs; pi++) {
456 const char *name = NULL;
458 prog = &obj->programs[pi];
460 for (si = 0; si < symbols->d_size / sizeof(GElf_Sym) && !name;
464 if (!gelf_getsym(symbols, si, &sym))
466 if (sym.st_shndx != prog->idx)
468 if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL)
471 name = elf_strptr(obj->efile.elf,
472 obj->efile.strtabidx,
475 pr_warn("failed to get sym name string for prog %s\n",
477 return -LIBBPF_ERRNO__LIBELF;
481 if (!name && prog->idx == obj->efile.text_shndx)
485 pr_warn("failed to find sym for prog %s\n",
490 prog->name = strdup(name);
492 pr_warn("failed to allocate memory for prog sym %s\n",
501 static __u32 get_kernel_version(void)
503 __u32 major, minor, patch;
507 if (sscanf(info.release, "%u.%u.%u", &major, &minor, &patch) != 3)
509 return KERNEL_VERSION(major, minor, patch);
512 static struct bpf_object *bpf_object__new(const char *path,
515 const char *obj_name)
517 struct bpf_object *obj;
520 obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
522 pr_warn("alloc memory failed for %s\n", path);
523 return ERR_PTR(-ENOMEM);
526 strcpy(obj->path, path);
528 strncpy(obj->name, obj_name, sizeof(obj->name) - 1);
529 obj->name[sizeof(obj->name) - 1] = 0;
531 /* Using basename() GNU version which doesn't modify arg. */
532 strncpy(obj->name, basename((void *)path),
533 sizeof(obj->name) - 1);
534 end = strchr(obj->name, '.');
541 * Caller of this function should also call
542 * bpf_object__elf_finish() after data collection to return
543 * obj_buf to user. If not, we should duplicate the buffer to
544 * avoid user freeing them before elf finish.
546 obj->efile.obj_buf = obj_buf;
547 obj->efile.obj_buf_sz = obj_buf_sz;
548 obj->efile.maps_shndx = -1;
549 obj->efile.btf_maps_shndx = -1;
550 obj->efile.data_shndx = -1;
551 obj->efile.rodata_shndx = -1;
552 obj->efile.bss_shndx = -1;
554 obj->kern_version = get_kernel_version();
557 INIT_LIST_HEAD(&obj->list);
558 list_add(&obj->list, &bpf_objects_list);
562 static void bpf_object__elf_finish(struct bpf_object *obj)
564 if (!obj_elf_valid(obj))
567 if (obj->efile.elf) {
568 elf_end(obj->efile.elf);
569 obj->efile.elf = NULL;
571 obj->efile.symbols = NULL;
572 obj->efile.data = NULL;
573 obj->efile.rodata = NULL;
574 obj->efile.bss = NULL;
576 zfree(&obj->efile.reloc_sects);
577 obj->efile.nr_reloc_sects = 0;
578 zclose(obj->efile.fd);
579 obj->efile.obj_buf = NULL;
580 obj->efile.obj_buf_sz = 0;
583 static int bpf_object__elf_init(struct bpf_object *obj)
588 if (obj_elf_valid(obj)) {
589 pr_warn("elf init: internal error\n");
590 return -LIBBPF_ERRNO__LIBELF;
593 if (obj->efile.obj_buf_sz > 0) {
595 * obj_buf should have been validated by
596 * bpf_object__open_buffer().
598 obj->efile.elf = elf_memory((char *)obj->efile.obj_buf,
599 obj->efile.obj_buf_sz);
601 obj->efile.fd = open(obj->path, O_RDONLY);
602 if (obj->efile.fd < 0) {
603 char errmsg[STRERR_BUFSIZE], *cp;
606 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
607 pr_warn("failed to open %s: %s\n", obj->path, cp);
611 obj->efile.elf = elf_begin(obj->efile.fd,
612 LIBBPF_ELF_C_READ_MMAP, NULL);
615 if (!obj->efile.elf) {
616 pr_warn("failed to open %s as ELF file\n", obj->path);
617 err = -LIBBPF_ERRNO__LIBELF;
621 if (!gelf_getehdr(obj->efile.elf, &obj->efile.ehdr)) {
622 pr_warn("failed to get EHDR from %s\n", obj->path);
623 err = -LIBBPF_ERRNO__FORMAT;
626 ep = &obj->efile.ehdr;
628 /* Old LLVM set e_machine to EM_NONE */
629 if (ep->e_type != ET_REL ||
630 (ep->e_machine && ep->e_machine != EM_BPF)) {
631 pr_warn("%s is not an eBPF object file\n", obj->path);
632 err = -LIBBPF_ERRNO__FORMAT;
638 bpf_object__elf_finish(obj);
642 static int bpf_object__check_endianness(struct bpf_object *obj)
644 #if __BYTE_ORDER == __LITTLE_ENDIAN
645 if (obj->efile.ehdr.e_ident[EI_DATA] == ELFDATA2LSB)
647 #elif __BYTE_ORDER == __BIG_ENDIAN
648 if (obj->efile.ehdr.e_ident[EI_DATA] == ELFDATA2MSB)
651 # error "Unrecognized __BYTE_ORDER__"
653 pr_warn("endianness mismatch.\n");
654 return -LIBBPF_ERRNO__ENDIAN;
658 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
660 memcpy(obj->license, data, min(size, sizeof(obj->license) - 1));
661 pr_debug("license of %s is %s\n", obj->path, obj->license);
666 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
670 if (size != sizeof(kver)) {
671 pr_warn("invalid kver section in %s\n", obj->path);
672 return -LIBBPF_ERRNO__FORMAT;
674 memcpy(&kver, data, sizeof(kver));
675 obj->kern_version = kver;
676 pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
680 static int compare_bpf_map(const void *_a, const void *_b)
682 const struct bpf_map *a = _a;
683 const struct bpf_map *b = _b;
685 if (a->sec_idx != b->sec_idx)
686 return a->sec_idx - b->sec_idx;
687 return a->sec_offset - b->sec_offset;
690 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
692 if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
693 type == BPF_MAP_TYPE_HASH_OF_MAPS)
698 static int bpf_object_search_section_size(const struct bpf_object *obj,
699 const char *name, size_t *d_size)
701 const GElf_Ehdr *ep = &obj->efile.ehdr;
702 Elf *elf = obj->efile.elf;
706 while ((scn = elf_nextscn(elf, scn)) != NULL) {
707 const char *sec_name;
712 if (gelf_getshdr(scn, &sh) != &sh) {
713 pr_warn("failed to get section(%d) header from %s\n",
718 sec_name = elf_strptr(elf, ep->e_shstrndx, sh.sh_name);
720 pr_warn("failed to get section(%d) name from %s\n",
725 if (strcmp(name, sec_name))
728 data = elf_getdata(scn, 0);
730 pr_warn("failed to get section(%d) data from %s(%s)\n",
731 idx, name, obj->path);
735 *d_size = data->d_size;
742 int bpf_object__section_size(const struct bpf_object *obj, const char *name,
751 } else if (!strcmp(name, ".data")) {
753 *size = obj->efile.data->d_size;
754 } else if (!strcmp(name, ".bss")) {
756 *size = obj->efile.bss->d_size;
757 } else if (!strcmp(name, ".rodata")) {
758 if (obj->efile.rodata)
759 *size = obj->efile.rodata->d_size;
761 ret = bpf_object_search_section_size(obj, name, &d_size);
766 return *size ? 0 : ret;
769 int bpf_object__variable_offset(const struct bpf_object *obj, const char *name,
772 Elf_Data *symbols = obj->efile.symbols;
779 for (si = 0; si < symbols->d_size / sizeof(GElf_Sym); si++) {
782 if (!gelf_getsym(symbols, si, &sym))
784 if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL ||
785 GELF_ST_TYPE(sym.st_info) != STT_OBJECT)
788 sname = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
791 pr_warn("failed to get sym name string for var %s\n",
795 if (strcmp(name, sname) == 0) {
804 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
806 struct bpf_map *new_maps;
810 if (obj->nr_maps < obj->maps_cap)
811 return &obj->maps[obj->nr_maps++];
813 new_cap = max((size_t)4, obj->maps_cap * 3 / 2);
814 new_maps = realloc(obj->maps, new_cap * sizeof(*obj->maps));
816 pr_warn("alloc maps for object failed\n");
817 return ERR_PTR(-ENOMEM);
820 obj->maps_cap = new_cap;
821 obj->maps = new_maps;
823 /* zero out new maps */
824 memset(obj->maps + obj->nr_maps, 0,
825 (obj->maps_cap - obj->nr_maps) * sizeof(*obj->maps));
827 * fill all fd with -1 so won't close incorrect fd (fd=0 is stdin)
828 * when failure (zclose won't close negative fd)).
830 for (i = obj->nr_maps; i < obj->maps_cap; i++) {
831 obj->maps[i].fd = -1;
832 obj->maps[i].inner_map_fd = -1;
835 return &obj->maps[obj->nr_maps++];
839 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
840 int sec_idx, Elf_Data *data, void **data_buff)
842 char map_name[BPF_OBJ_NAME_LEN];
843 struct bpf_map_def *def;
846 map = bpf_object__add_map(obj);
850 map->libbpf_type = type;
851 map->sec_idx = sec_idx;
853 snprintf(map_name, sizeof(map_name), "%.8s%.7s", obj->name,
854 libbpf_type_to_btf_name[type]);
855 map->name = strdup(map_name);
857 pr_warn("failed to alloc map name\n");
862 def->type = BPF_MAP_TYPE_ARRAY;
863 def->key_size = sizeof(int);
864 def->value_size = data->d_size;
865 def->max_entries = 1;
866 def->map_flags = type == LIBBPF_MAP_RODATA ? BPF_F_RDONLY_PROG : 0;
867 if (obj->caps.array_mmap)
868 def->map_flags |= BPF_F_MMAPABLE;
870 pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
871 map_name, map->sec_idx, map->sec_offset, def->map_flags);
874 *data_buff = malloc(data->d_size);
877 pr_warn("failed to alloc map content buffer\n");
880 memcpy(*data_buff, data->d_buf, data->d_size);
883 pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
887 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
891 if (!obj->caps.global_data)
894 * Populate obj->maps with libbpf internal maps.
896 if (obj->efile.data_shndx >= 0) {
897 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
898 obj->efile.data_shndx,
900 &obj->sections.data);
904 if (obj->efile.rodata_shndx >= 0) {
905 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
906 obj->efile.rodata_shndx,
908 &obj->sections.rodata);
912 if (obj->efile.bss_shndx >= 0) {
913 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
914 obj->efile.bss_shndx,
915 obj->efile.bss, NULL);
922 static int bpf_object__init_user_maps(struct bpf_object *obj, bool strict)
924 Elf_Data *symbols = obj->efile.symbols;
925 int i, map_def_sz = 0, nr_maps = 0, nr_syms;
926 Elf_Data *data = NULL;
929 if (obj->efile.maps_shndx < 0)
935 scn = elf_getscn(obj->efile.elf, obj->efile.maps_shndx);
937 data = elf_getdata(scn, NULL);
939 pr_warn("failed to get Elf_Data from map section %d\n",
940 obj->efile.maps_shndx);
945 * Count number of maps. Each map has a name.
946 * Array of maps is not supported: only the first element is
949 * TODO: Detect array of map and report error.
951 nr_syms = symbols->d_size / sizeof(GElf_Sym);
952 for (i = 0; i < nr_syms; i++) {
955 if (!gelf_getsym(symbols, i, &sym))
957 if (sym.st_shndx != obj->efile.maps_shndx)
961 /* Assume equally sized map definitions */
962 pr_debug("maps in %s: %d maps in %zd bytes\n",
963 obj->path, nr_maps, data->d_size);
965 if (!data->d_size || nr_maps == 0 || (data->d_size % nr_maps) != 0) {
966 pr_warn("unable to determine map definition size section %s, %d maps in %zd bytes\n",
967 obj->path, nr_maps, data->d_size);
970 map_def_sz = data->d_size / nr_maps;
972 /* Fill obj->maps using data in "maps" section. */
973 for (i = 0; i < nr_syms; i++) {
975 const char *map_name;
976 struct bpf_map_def *def;
979 if (!gelf_getsym(symbols, i, &sym))
981 if (sym.st_shndx != obj->efile.maps_shndx)
984 map = bpf_object__add_map(obj);
988 map_name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
991 pr_warn("failed to get map #%d name sym string for obj %s\n",
993 return -LIBBPF_ERRNO__FORMAT;
996 map->libbpf_type = LIBBPF_MAP_UNSPEC;
997 map->sec_idx = sym.st_shndx;
998 map->sec_offset = sym.st_value;
999 pr_debug("map '%s' (legacy): at sec_idx %d, offset %zu.\n",
1000 map_name, map->sec_idx, map->sec_offset);
1001 if (sym.st_value + map_def_sz > data->d_size) {
1002 pr_warn("corrupted maps section in %s: last map \"%s\" too small\n",
1003 obj->path, map_name);
1007 map->name = strdup(map_name);
1009 pr_warn("failed to alloc map name\n");
1012 pr_debug("map %d is \"%s\"\n", i, map->name);
1013 def = (struct bpf_map_def *)(data->d_buf + sym.st_value);
1015 * If the definition of the map in the object file fits in
1016 * bpf_map_def, copy it. Any extra fields in our version
1017 * of bpf_map_def will default to zero as a result of the
1020 if (map_def_sz <= sizeof(struct bpf_map_def)) {
1021 memcpy(&map->def, def, map_def_sz);
1024 * Here the map structure being read is bigger than what
1025 * we expect, truncate if the excess bits are all zero.
1026 * If they are not zero, reject this map as
1031 for (b = ((char *)def) + sizeof(struct bpf_map_def);
1032 b < ((char *)def) + map_def_sz; b++) {
1034 pr_warn("maps section in %s: \"%s\" has unrecognized, non-zero options\n",
1035 obj->path, map_name);
1040 memcpy(&map->def, def, sizeof(struct bpf_map_def));
1046 static const struct btf_type *
1047 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
1049 const struct btf_type *t = btf__type_by_id(btf, id);
1054 while (btf_is_mod(t) || btf_is_typedef(t)) {
1057 t = btf__type_by_id(btf, t->type);
1064 * Fetch integer attribute of BTF map definition. Such attributes are
1065 * represented using a pointer to an array, in which dimensionality of array
1066 * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
1067 * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
1068 * type definition, while using only sizeof(void *) space in ELF data section.
1070 static bool get_map_field_int(const char *map_name, const struct btf *btf,
1071 const struct btf_type *def,
1072 const struct btf_member *m, __u32 *res)
1074 const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
1075 const char *name = btf__name_by_offset(btf, m->name_off);
1076 const struct btf_array *arr_info;
1077 const struct btf_type *arr_t;
1079 if (!btf_is_ptr(t)) {
1080 pr_warn("map '%s': attr '%s': expected PTR, got %u.\n",
1081 map_name, name, btf_kind(t));
1085 arr_t = btf__type_by_id(btf, t->type);
1087 pr_warn("map '%s': attr '%s': type [%u] not found.\n",
1088 map_name, name, t->type);
1091 if (!btf_is_array(arr_t)) {
1092 pr_warn("map '%s': attr '%s': expected ARRAY, got %u.\n",
1093 map_name, name, btf_kind(arr_t));
1096 arr_info = btf_array(arr_t);
1097 *res = arr_info->nelems;
1101 static int build_map_pin_path(struct bpf_map *map, const char *path)
1107 path = "/sys/fs/bpf";
1109 len = snprintf(buf, PATH_MAX, "%s/%s", path, bpf_map__name(map));
1112 else if (len >= PATH_MAX)
1113 return -ENAMETOOLONG;
1115 err = bpf_map__set_pin_path(map, buf);
1122 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
1123 const struct btf_type *sec,
1124 int var_idx, int sec_idx,
1125 const Elf_Data *data, bool strict,
1126 const char *pin_root_path)
1128 const struct btf_type *var, *def, *t;
1129 const struct btf_var_secinfo *vi;
1130 const struct btf_var *var_extra;
1131 const struct btf_member *m;
1132 const char *map_name;
1133 struct bpf_map *map;
1136 vi = btf_var_secinfos(sec) + var_idx;
1137 var = btf__type_by_id(obj->btf, vi->type);
1138 var_extra = btf_var(var);
1139 map_name = btf__name_by_offset(obj->btf, var->name_off);
1140 vlen = btf_vlen(var);
1142 if (map_name == NULL || map_name[0] == '\0') {
1143 pr_warn("map #%d: empty name.\n", var_idx);
1146 if ((__u64)vi->offset + vi->size > data->d_size) {
1147 pr_warn("map '%s' BTF data is corrupted.\n", map_name);
1150 if (!btf_is_var(var)) {
1151 pr_warn("map '%s': unexpected var kind %u.\n",
1152 map_name, btf_kind(var));
1155 if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED &&
1156 var_extra->linkage != BTF_VAR_STATIC) {
1157 pr_warn("map '%s': unsupported var linkage %u.\n",
1158 map_name, var_extra->linkage);
1162 def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
1163 if (!btf_is_struct(def)) {
1164 pr_warn("map '%s': unexpected def kind %u.\n",
1165 map_name, btf_kind(var));
1168 if (def->size > vi->size) {
1169 pr_warn("map '%s': invalid def size.\n", map_name);
1173 map = bpf_object__add_map(obj);
1175 return PTR_ERR(map);
1176 map->name = strdup(map_name);
1178 pr_warn("map '%s': failed to alloc map name.\n", map_name);
1181 map->libbpf_type = LIBBPF_MAP_UNSPEC;
1182 map->def.type = BPF_MAP_TYPE_UNSPEC;
1183 map->sec_idx = sec_idx;
1184 map->sec_offset = vi->offset;
1185 pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
1186 map_name, map->sec_idx, map->sec_offset);
1188 vlen = btf_vlen(def);
1189 m = btf_members(def);
1190 for (i = 0; i < vlen; i++, m++) {
1191 const char *name = btf__name_by_offset(obj->btf, m->name_off);
1194 pr_warn("map '%s': invalid field #%d.\n", map_name, i);
1197 if (strcmp(name, "type") == 0) {
1198 if (!get_map_field_int(map_name, obj->btf, def, m,
1201 pr_debug("map '%s': found type = %u.\n",
1202 map_name, map->def.type);
1203 } else if (strcmp(name, "max_entries") == 0) {
1204 if (!get_map_field_int(map_name, obj->btf, def, m,
1205 &map->def.max_entries))
1207 pr_debug("map '%s': found max_entries = %u.\n",
1208 map_name, map->def.max_entries);
1209 } else if (strcmp(name, "map_flags") == 0) {
1210 if (!get_map_field_int(map_name, obj->btf, def, m,
1211 &map->def.map_flags))
1213 pr_debug("map '%s': found map_flags = %u.\n",
1214 map_name, map->def.map_flags);
1215 } else if (strcmp(name, "key_size") == 0) {
1218 if (!get_map_field_int(map_name, obj->btf, def, m,
1221 pr_debug("map '%s': found key_size = %u.\n",
1223 if (map->def.key_size && map->def.key_size != sz) {
1224 pr_warn("map '%s': conflicting key size %u != %u.\n",
1225 map_name, map->def.key_size, sz);
1228 map->def.key_size = sz;
1229 } else if (strcmp(name, "key") == 0) {
1232 t = btf__type_by_id(obj->btf, m->type);
1234 pr_warn("map '%s': key type [%d] not found.\n",
1238 if (!btf_is_ptr(t)) {
1239 pr_warn("map '%s': key spec is not PTR: %u.\n",
1240 map_name, btf_kind(t));
1243 sz = btf__resolve_size(obj->btf, t->type);
1245 pr_warn("map '%s': can't determine key size for type [%u]: %lld.\n",
1246 map_name, t->type, sz);
1249 pr_debug("map '%s': found key [%u], sz = %lld.\n",
1250 map_name, t->type, sz);
1251 if (map->def.key_size && map->def.key_size != sz) {
1252 pr_warn("map '%s': conflicting key size %u != %lld.\n",
1253 map_name, map->def.key_size, sz);
1256 map->def.key_size = sz;
1257 map->btf_key_type_id = t->type;
1258 } else if (strcmp(name, "value_size") == 0) {
1261 if (!get_map_field_int(map_name, obj->btf, def, m,
1264 pr_debug("map '%s': found value_size = %u.\n",
1266 if (map->def.value_size && map->def.value_size != sz) {
1267 pr_warn("map '%s': conflicting value size %u != %u.\n",
1268 map_name, map->def.value_size, sz);
1271 map->def.value_size = sz;
1272 } else if (strcmp(name, "value") == 0) {
1275 t = btf__type_by_id(obj->btf, m->type);
1277 pr_warn("map '%s': value type [%d] not found.\n",
1281 if (!btf_is_ptr(t)) {
1282 pr_warn("map '%s': value spec is not PTR: %u.\n",
1283 map_name, btf_kind(t));
1286 sz = btf__resolve_size(obj->btf, t->type);
1288 pr_warn("map '%s': can't determine value size for type [%u]: %lld.\n",
1289 map_name, t->type, sz);
1292 pr_debug("map '%s': found value [%u], sz = %lld.\n",
1293 map_name, t->type, sz);
1294 if (map->def.value_size && map->def.value_size != sz) {
1295 pr_warn("map '%s': conflicting value size %u != %lld.\n",
1296 map_name, map->def.value_size, sz);
1299 map->def.value_size = sz;
1300 map->btf_value_type_id = t->type;
1301 } else if (strcmp(name, "pinning") == 0) {
1305 if (!get_map_field_int(map_name, obj->btf, def, m,
1308 pr_debug("map '%s': found pinning = %u.\n",
1311 if (val != LIBBPF_PIN_NONE &&
1312 val != LIBBPF_PIN_BY_NAME) {
1313 pr_warn("map '%s': invalid pinning value %u.\n",
1317 if (val == LIBBPF_PIN_BY_NAME) {
1318 err = build_map_pin_path(map, pin_root_path);
1320 pr_warn("map '%s': couldn't build pin path.\n",
1327 pr_warn("map '%s': unknown field '%s'.\n",
1331 pr_debug("map '%s': ignoring unknown field '%s'.\n",
1336 if (map->def.type == BPF_MAP_TYPE_UNSPEC) {
1337 pr_warn("map '%s': map type isn't specified.\n", map_name);
1344 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
1345 const char *pin_root_path)
1347 const struct btf_type *sec = NULL;
1348 int nr_types, i, vlen, err;
1349 const struct btf_type *t;
1354 if (obj->efile.btf_maps_shndx < 0)
1357 scn = elf_getscn(obj->efile.elf, obj->efile.btf_maps_shndx);
1359 data = elf_getdata(scn, NULL);
1360 if (!scn || !data) {
1361 pr_warn("failed to get Elf_Data from map section %d (%s)\n",
1362 obj->efile.maps_shndx, MAPS_ELF_SEC);
1366 nr_types = btf__get_nr_types(obj->btf);
1367 for (i = 1; i <= nr_types; i++) {
1368 t = btf__type_by_id(obj->btf, i);
1369 if (!btf_is_datasec(t))
1371 name = btf__name_by_offset(obj->btf, t->name_off);
1372 if (strcmp(name, MAPS_ELF_SEC) == 0) {
1379 pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
1383 vlen = btf_vlen(sec);
1384 for (i = 0; i < vlen; i++) {
1385 err = bpf_object__init_user_btf_map(obj, sec, i,
1386 obj->efile.btf_maps_shndx,
1396 static int bpf_object__init_maps(struct bpf_object *obj, bool relaxed_maps,
1397 const char *pin_root_path)
1399 bool strict = !relaxed_maps;
1402 err = bpf_object__init_user_maps(obj, strict);
1406 err = bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
1410 err = bpf_object__init_global_data_maps(obj);
1415 qsort(obj->maps, obj->nr_maps, sizeof(obj->maps[0]),
1421 static bool section_have_execinstr(struct bpf_object *obj, int idx)
1426 scn = elf_getscn(obj->efile.elf, idx);
1430 if (gelf_getshdr(scn, &sh) != &sh)
1433 if (sh.sh_flags & SHF_EXECINSTR)
1439 static void bpf_object__sanitize_btf(struct bpf_object *obj)
1441 bool has_datasec = obj->caps.btf_datasec;
1442 bool has_func = obj->caps.btf_func;
1443 struct btf *btf = obj->btf;
1447 if (!obj->btf || (has_func && has_datasec))
1450 for (i = 1; i <= btf__get_nr_types(btf); i++) {
1451 t = (struct btf_type *)btf__type_by_id(btf, i);
1453 if (!has_datasec && btf_is_var(t)) {
1454 /* replace VAR with INT */
1455 t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
1457 * using size = 1 is the safest choice, 4 will be too
1458 * big and cause kernel BTF validation failure if
1459 * original variable took less than 4 bytes
1462 *(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
1463 } else if (!has_datasec && btf_is_datasec(t)) {
1464 /* replace DATASEC with STRUCT */
1465 const struct btf_var_secinfo *v = btf_var_secinfos(t);
1466 struct btf_member *m = btf_members(t);
1467 struct btf_type *vt;
1470 name = (char *)btf__name_by_offset(btf, t->name_off);
1478 t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
1479 for (j = 0; j < vlen; j++, v++, m++) {
1480 /* order of field assignments is important */
1481 m->offset = v->offset * 8;
1483 /* preserve variable name as member name */
1484 vt = (void *)btf__type_by_id(btf, v->type);
1485 m->name_off = vt->name_off;
1487 } else if (!has_func && btf_is_func_proto(t)) {
1488 /* replace FUNC_PROTO with ENUM */
1490 t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
1491 t->size = sizeof(__u32); /* kernel enforced */
1492 } else if (!has_func && btf_is_func(t)) {
1493 /* replace FUNC with TYPEDEF */
1494 t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
1499 static void bpf_object__sanitize_btf_ext(struct bpf_object *obj)
1504 if (!obj->caps.btf_func) {
1505 btf_ext__free(obj->btf_ext);
1506 obj->btf_ext = NULL;
1510 static bool bpf_object__is_btf_mandatory(const struct bpf_object *obj)
1512 return obj->efile.btf_maps_shndx >= 0;
1515 static int bpf_object__init_btf(struct bpf_object *obj,
1517 Elf_Data *btf_ext_data)
1519 bool btf_required = bpf_object__is_btf_mandatory(obj);
1523 obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
1524 if (IS_ERR(obj->btf)) {
1525 pr_warn("Error loading ELF section %s: %d.\n",
1529 err = btf__finalize_data(obj, obj->btf);
1531 pr_warn("Error finalizing %s: %d.\n", BTF_ELF_SEC, err);
1537 pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
1538 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
1541 obj->btf_ext = btf_ext__new(btf_ext_data->d_buf,
1542 btf_ext_data->d_size);
1543 if (IS_ERR(obj->btf_ext)) {
1544 pr_warn("Error loading ELF section %s: %ld. Ignored and continue.\n",
1545 BTF_EXT_ELF_SEC, PTR_ERR(obj->btf_ext));
1546 obj->btf_ext = NULL;
1551 if (err || IS_ERR(obj->btf)) {
1553 err = err ? : PTR_ERR(obj->btf);
1556 if (!IS_ERR_OR_NULL(obj->btf))
1557 btf__free(obj->btf);
1560 if (btf_required && !obj->btf) {
1561 pr_warn("BTF is required, but is missing or corrupted.\n");
1562 return err == 0 ? -ENOENT : err;
1567 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
1574 bpf_object__sanitize_btf(obj);
1575 bpf_object__sanitize_btf_ext(obj);
1577 err = btf__load(obj->btf);
1579 pr_warn("Error loading %s into kernel: %d.\n",
1581 btf__free(obj->btf);
1583 /* btf_ext can't exist without btf, so free it as well */
1585 btf_ext__free(obj->btf_ext);
1586 obj->btf_ext = NULL;
1589 if (bpf_object__is_btf_mandatory(obj))
1595 static int bpf_object__elf_collect(struct bpf_object *obj, bool relaxed_maps,
1596 const char *pin_root_path)
1598 Elf *elf = obj->efile.elf;
1599 GElf_Ehdr *ep = &obj->efile.ehdr;
1600 Elf_Data *btf_ext_data = NULL;
1601 Elf_Data *btf_data = NULL;
1602 Elf_Scn *scn = NULL;
1603 int idx = 0, err = 0;
1605 /* Elf is corrupted/truncated, avoid calling elf_strptr. */
1606 if (!elf_rawdata(elf_getscn(elf, ep->e_shstrndx), NULL)) {
1607 pr_warn("failed to get e_shstrndx from %s\n", obj->path);
1608 return -LIBBPF_ERRNO__FORMAT;
1611 while ((scn = elf_nextscn(elf, scn)) != NULL) {
1617 if (gelf_getshdr(scn, &sh) != &sh) {
1618 pr_warn("failed to get section(%d) header from %s\n",
1620 return -LIBBPF_ERRNO__FORMAT;
1623 name = elf_strptr(elf, ep->e_shstrndx, sh.sh_name);
1625 pr_warn("failed to get section(%d) name from %s\n",
1627 return -LIBBPF_ERRNO__FORMAT;
1630 data = elf_getdata(scn, 0);
1632 pr_warn("failed to get section(%d) data from %s(%s)\n",
1633 idx, name, obj->path);
1634 return -LIBBPF_ERRNO__FORMAT;
1636 pr_debug("section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
1637 idx, name, (unsigned long)data->d_size,
1638 (int)sh.sh_link, (unsigned long)sh.sh_flags,
1641 if (strcmp(name, "license") == 0) {
1642 err = bpf_object__init_license(obj,
1647 } else if (strcmp(name, "version") == 0) {
1648 err = bpf_object__init_kversion(obj,
1653 } else if (strcmp(name, "maps") == 0) {
1654 obj->efile.maps_shndx = idx;
1655 } else if (strcmp(name, MAPS_ELF_SEC) == 0) {
1656 obj->efile.btf_maps_shndx = idx;
1657 } else if (strcmp(name, BTF_ELF_SEC) == 0) {
1659 } else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
1660 btf_ext_data = data;
1661 } else if (sh.sh_type == SHT_SYMTAB) {
1662 if (obj->efile.symbols) {
1663 pr_warn("bpf: multiple SYMTAB in %s\n",
1665 return -LIBBPF_ERRNO__FORMAT;
1667 obj->efile.symbols = data;
1668 obj->efile.strtabidx = sh.sh_link;
1669 } else if (sh.sh_type == SHT_PROGBITS && data->d_size > 0) {
1670 if (sh.sh_flags & SHF_EXECINSTR) {
1671 if (strcmp(name, ".text") == 0)
1672 obj->efile.text_shndx = idx;
1673 err = bpf_object__add_program(obj, data->d_buf,
1677 char errmsg[STRERR_BUFSIZE];
1680 cp = libbpf_strerror_r(-err, errmsg,
1682 pr_warn("failed to alloc program %s (%s): %s",
1683 name, obj->path, cp);
1686 } else if (strcmp(name, ".data") == 0) {
1687 obj->efile.data = data;
1688 obj->efile.data_shndx = idx;
1689 } else if (strcmp(name, ".rodata") == 0) {
1690 obj->efile.rodata = data;
1691 obj->efile.rodata_shndx = idx;
1693 pr_debug("skip section(%d) %s\n", idx, name);
1695 } else if (sh.sh_type == SHT_REL) {
1696 int nr_sects = obj->efile.nr_reloc_sects;
1697 void *sects = obj->efile.reloc_sects;
1698 int sec = sh.sh_info; /* points to other section */
1700 /* Only do relo for section with exec instructions */
1701 if (!section_have_execinstr(obj, sec)) {
1702 pr_debug("skip relo %s(%d) for section(%d)\n",
1707 sects = reallocarray(sects, nr_sects + 1,
1708 sizeof(*obj->efile.reloc_sects));
1710 pr_warn("reloc_sects realloc failed\n");
1714 obj->efile.reloc_sects = sects;
1715 obj->efile.nr_reloc_sects++;
1717 obj->efile.reloc_sects[nr_sects].shdr = sh;
1718 obj->efile.reloc_sects[nr_sects].data = data;
1719 } else if (sh.sh_type == SHT_NOBITS && strcmp(name, ".bss") == 0) {
1720 obj->efile.bss = data;
1721 obj->efile.bss_shndx = idx;
1723 pr_debug("skip section(%d) %s\n", idx, name);
1727 if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
1728 pr_warn("Corrupted ELF file: index of strtab invalid\n");
1729 return -LIBBPF_ERRNO__FORMAT;
1731 err = bpf_object__init_btf(obj, btf_data, btf_ext_data);
1733 err = bpf_object__init_maps(obj, relaxed_maps, pin_root_path);
1735 err = bpf_object__sanitize_and_load_btf(obj);
1737 err = bpf_object__init_prog_names(obj);
1741 static struct bpf_program *
1742 bpf_object__find_prog_by_idx(struct bpf_object *obj, int idx)
1744 struct bpf_program *prog;
1747 for (i = 0; i < obj->nr_programs; i++) {
1748 prog = &obj->programs[i];
1749 if (prog->idx == idx)
1755 struct bpf_program *
1756 bpf_object__find_program_by_title(const struct bpf_object *obj,
1759 struct bpf_program *pos;
1761 bpf_object__for_each_program(pos, obj) {
1762 if (pos->section_name && !strcmp(pos->section_name, title))
1768 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
1771 return shndx == obj->efile.data_shndx ||
1772 shndx == obj->efile.bss_shndx ||
1773 shndx == obj->efile.rodata_shndx;
1776 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
1779 return shndx == obj->efile.maps_shndx ||
1780 shndx == obj->efile.btf_maps_shndx;
1783 static enum libbpf_map_type
1784 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
1786 if (shndx == obj->efile.data_shndx)
1787 return LIBBPF_MAP_DATA;
1788 else if (shndx == obj->efile.bss_shndx)
1789 return LIBBPF_MAP_BSS;
1790 else if (shndx == obj->efile.rodata_shndx)
1791 return LIBBPF_MAP_RODATA;
1793 return LIBBPF_MAP_UNSPEC;
1796 static int bpf_program__record_reloc(struct bpf_program *prog,
1797 struct reloc_desc *reloc_desc,
1798 __u32 insn_idx, const char *name,
1799 const GElf_Sym *sym, const GElf_Rel *rel)
1801 struct bpf_insn *insn = &prog->insns[insn_idx];
1802 size_t map_idx, nr_maps = prog->obj->nr_maps;
1803 struct bpf_object *obj = prog->obj;
1804 __u32 shdr_idx = sym->st_shndx;
1805 enum libbpf_map_type type;
1806 struct bpf_map *map;
1808 /* sub-program call relocation */
1809 if (insn->code == (BPF_JMP | BPF_CALL)) {
1810 if (insn->src_reg != BPF_PSEUDO_CALL) {
1811 pr_warn("incorrect bpf_call opcode\n");
1812 return -LIBBPF_ERRNO__RELOC;
1814 /* text_shndx can be 0, if no default "main" program exists */
1815 if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
1816 pr_warn("bad call relo against section %u\n", shdr_idx);
1817 return -LIBBPF_ERRNO__RELOC;
1819 if (sym->st_value % 8) {
1820 pr_warn("bad call relo offset: %llu\n", (__u64)sym->st_value);
1821 return -LIBBPF_ERRNO__RELOC;
1823 reloc_desc->type = RELO_CALL;
1824 reloc_desc->insn_idx = insn_idx;
1825 reloc_desc->sym_off = sym->st_value;
1826 obj->has_pseudo_calls = true;
1830 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) {
1831 pr_warn("invalid relo for insns[%d].code 0x%x\n",
1832 insn_idx, insn->code);
1833 return -LIBBPF_ERRNO__RELOC;
1835 if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
1836 pr_warn("invalid relo for \'%s\' in special section 0x%x; forgot to initialize global var?..\n",
1838 return -LIBBPF_ERRNO__RELOC;
1841 type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
1843 /* generic map reference relocation */
1844 if (type == LIBBPF_MAP_UNSPEC) {
1845 if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
1846 pr_warn("bad map relo against section %u\n",
1848 return -LIBBPF_ERRNO__RELOC;
1850 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
1851 map = &obj->maps[map_idx];
1852 if (map->libbpf_type != type ||
1853 map->sec_idx != sym->st_shndx ||
1854 map->sec_offset != sym->st_value)
1856 pr_debug("found map %zd (%s, sec %d, off %zu) for insn %u\n",
1857 map_idx, map->name, map->sec_idx,
1858 map->sec_offset, insn_idx);
1861 if (map_idx >= nr_maps) {
1862 pr_warn("map relo failed to find map for sec %u, off %llu\n",
1863 shdr_idx, (__u64)sym->st_value);
1864 return -LIBBPF_ERRNO__RELOC;
1866 reloc_desc->type = RELO_LD64;
1867 reloc_desc->insn_idx = insn_idx;
1868 reloc_desc->map_idx = map_idx;
1869 reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
1873 /* global data map relocation */
1874 if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
1875 pr_warn("bad data relo against section %u\n", shdr_idx);
1876 return -LIBBPF_ERRNO__RELOC;
1878 if (!obj->caps.global_data) {
1879 pr_warn("relocation: kernel does not support global \'%s\' variable access in insns[%d]\n",
1881 return -LIBBPF_ERRNO__RELOC;
1883 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
1884 map = &obj->maps[map_idx];
1885 if (map->libbpf_type != type)
1887 pr_debug("found data map %zd (%s, sec %d, off %zu) for insn %u\n",
1888 map_idx, map->name, map->sec_idx, map->sec_offset,
1892 if (map_idx >= nr_maps) {
1893 pr_warn("data relo failed to find map for sec %u\n",
1895 return -LIBBPF_ERRNO__RELOC;
1898 reloc_desc->type = RELO_DATA;
1899 reloc_desc->insn_idx = insn_idx;
1900 reloc_desc->map_idx = map_idx;
1901 reloc_desc->sym_off = sym->st_value;
1906 bpf_program__collect_reloc(struct bpf_program *prog, GElf_Shdr *shdr,
1907 Elf_Data *data, struct bpf_object *obj)
1909 Elf_Data *symbols = obj->efile.symbols;
1912 pr_debug("collecting relocating info for: '%s'\n", prog->section_name);
1913 nrels = shdr->sh_size / shdr->sh_entsize;
1915 prog->reloc_desc = malloc(sizeof(*prog->reloc_desc) * nrels);
1916 if (!prog->reloc_desc) {
1917 pr_warn("failed to alloc memory in relocation\n");
1920 prog->nr_reloc = nrels;
1922 for (i = 0; i < nrels; i++) {
1928 if (!gelf_getrel(data, i, &rel)) {
1929 pr_warn("relocation: failed to get %d reloc\n", i);
1930 return -LIBBPF_ERRNO__FORMAT;
1932 if (!gelf_getsym(symbols, GELF_R_SYM(rel.r_info), &sym)) {
1933 pr_warn("relocation: symbol %"PRIx64" not found\n",
1934 GELF_R_SYM(rel.r_info));
1935 return -LIBBPF_ERRNO__FORMAT;
1937 if (rel.r_offset % sizeof(struct bpf_insn))
1938 return -LIBBPF_ERRNO__FORMAT;
1940 insn_idx = rel.r_offset / sizeof(struct bpf_insn);
1941 name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
1942 sym.st_name) ? : "<?>";
1944 pr_debug("relo for shdr %u, symb %llu, value %llu, type %d, bind %d, name %d (\'%s\'), insn %u\n",
1945 (__u32)sym.st_shndx, (__u64)GELF_R_SYM(rel.r_info),
1946 (__u64)sym.st_value, GELF_ST_TYPE(sym.st_info),
1947 GELF_ST_BIND(sym.st_info), sym.st_name, name,
1950 err = bpf_program__record_reloc(prog, &prog->reloc_desc[i],
1951 insn_idx, name, &sym, &rel);
1958 static int bpf_map_find_btf_info(struct bpf_object *obj, struct bpf_map *map)
1960 struct bpf_map_def *def = &map->def;
1961 __u32 key_type_id = 0, value_type_id = 0;
1964 /* if it's BTF-defined map, we don't need to search for type IDs */
1965 if (map->sec_idx == obj->efile.btf_maps_shndx)
1968 if (!bpf_map__is_internal(map)) {
1969 ret = btf__get_map_kv_tids(obj->btf, map->name, def->key_size,
1970 def->value_size, &key_type_id,
1974 * LLVM annotates global data differently in BTF, that is,
1975 * only as '.data', '.bss' or '.rodata'.
1977 ret = btf__find_by_name(obj->btf,
1978 libbpf_type_to_btf_name[map->libbpf_type]);
1983 map->btf_key_type_id = key_type_id;
1984 map->btf_value_type_id = bpf_map__is_internal(map) ?
1985 ret : value_type_id;
1989 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
1991 struct bpf_map_info info = {};
1992 __u32 len = sizeof(info);
1996 err = bpf_obj_get_info_by_fd(fd, &info, &len);
2000 new_name = strdup(info.name);
2004 new_fd = open("/", O_RDONLY | O_CLOEXEC);
2007 goto err_free_new_name;
2010 new_fd = dup3(fd, new_fd, O_CLOEXEC);
2013 goto err_close_new_fd;
2016 err = zclose(map->fd);
2019 goto err_close_new_fd;
2024 map->name = new_name;
2025 map->def.type = info.type;
2026 map->def.key_size = info.key_size;
2027 map->def.value_size = info.value_size;
2028 map->def.max_entries = info.max_entries;
2029 map->def.map_flags = info.map_flags;
2030 map->btf_key_type_id = info.btf_key_type_id;
2031 map->btf_value_type_id = info.btf_value_type_id;
2043 int bpf_map__resize(struct bpf_map *map, __u32 max_entries)
2045 if (!map || !max_entries)
2048 /* If map already created, its attributes can't be changed. */
2052 map->def.max_entries = max_entries;
2058 bpf_object__probe_name(struct bpf_object *obj)
2060 struct bpf_load_program_attr attr;
2061 char *cp, errmsg[STRERR_BUFSIZE];
2062 struct bpf_insn insns[] = {
2063 BPF_MOV64_IMM(BPF_REG_0, 0),
2068 /* make sure basic loading works */
2070 memset(&attr, 0, sizeof(attr));
2071 attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
2073 attr.insns_cnt = ARRAY_SIZE(insns);
2074 attr.license = "GPL";
2076 ret = bpf_load_program_xattr(&attr, NULL, 0);
2078 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
2079 pr_warn("Error in %s():%s(%d). Couldn't load basic 'r0 = 0' BPF program.\n",
2080 __func__, cp, errno);
2085 /* now try the same program, but with the name */
2088 ret = bpf_load_program_xattr(&attr, NULL, 0);
2098 bpf_object__probe_global_data(struct bpf_object *obj)
2100 struct bpf_load_program_attr prg_attr;
2101 struct bpf_create_map_attr map_attr;
2102 char *cp, errmsg[STRERR_BUFSIZE];
2103 struct bpf_insn insns[] = {
2104 BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16),
2105 BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42),
2106 BPF_MOV64_IMM(BPF_REG_0, 0),
2111 memset(&map_attr, 0, sizeof(map_attr));
2112 map_attr.map_type = BPF_MAP_TYPE_ARRAY;
2113 map_attr.key_size = sizeof(int);
2114 map_attr.value_size = 32;
2115 map_attr.max_entries = 1;
2117 map = bpf_create_map_xattr(&map_attr);
2119 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
2120 pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
2121 __func__, cp, errno);
2127 memset(&prg_attr, 0, sizeof(prg_attr));
2128 prg_attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
2129 prg_attr.insns = insns;
2130 prg_attr.insns_cnt = ARRAY_SIZE(insns);
2131 prg_attr.license = "GPL";
2133 ret = bpf_load_program_xattr(&prg_attr, NULL, 0);
2135 obj->caps.global_data = 1;
2143 static int bpf_object__probe_btf_func(struct bpf_object *obj)
2145 static const char strs[] = "\0int\0x\0a";
2146 /* void x(int a) {} */
2149 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
2150 /* FUNC_PROTO */ /* [2] */
2151 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
2152 BTF_PARAM_ENC(7, 1),
2153 /* FUNC x */ /* [3] */
2154 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0), 2),
2158 btf_fd = libbpf__load_raw_btf((char *)types, sizeof(types),
2159 strs, sizeof(strs));
2161 obj->caps.btf_func = 1;
2169 static int bpf_object__probe_btf_datasec(struct bpf_object *obj)
2171 static const char strs[] = "\0x\0.data";
2175 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
2176 /* VAR x */ /* [2] */
2177 BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
2179 /* DATASEC val */ /* [3] */
2180 BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC, 0, 1), 4),
2181 BTF_VAR_SECINFO_ENC(2, 0, 4),
2185 btf_fd = libbpf__load_raw_btf((char *)types, sizeof(types),
2186 strs, sizeof(strs));
2188 obj->caps.btf_datasec = 1;
2196 static int bpf_object__probe_array_mmap(struct bpf_object *obj)
2198 struct bpf_create_map_attr attr = {
2199 .map_type = BPF_MAP_TYPE_ARRAY,
2200 .map_flags = BPF_F_MMAPABLE,
2201 .key_size = sizeof(int),
2202 .value_size = sizeof(int),
2207 fd = bpf_create_map_xattr(&attr);
2209 obj->caps.array_mmap = 1;
2218 bpf_object__probe_caps(struct bpf_object *obj)
2220 int (*probe_fn[])(struct bpf_object *obj) = {
2221 bpf_object__probe_name,
2222 bpf_object__probe_global_data,
2223 bpf_object__probe_btf_func,
2224 bpf_object__probe_btf_datasec,
2225 bpf_object__probe_array_mmap,
2229 for (i = 0; i < ARRAY_SIZE(probe_fn); i++) {
2230 ret = probe_fn[i](obj);
2232 pr_debug("Probe #%d failed with %d.\n", i, ret);
2238 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
2240 struct bpf_map_info map_info = {};
2241 char msg[STRERR_BUFSIZE];
2244 map_info_len = sizeof(map_info);
2246 if (bpf_obj_get_info_by_fd(map_fd, &map_info, &map_info_len)) {
2247 pr_warn("failed to get map info for map FD %d: %s\n",
2248 map_fd, libbpf_strerror_r(errno, msg, sizeof(msg)));
2252 return (map_info.type == map->def.type &&
2253 map_info.key_size == map->def.key_size &&
2254 map_info.value_size == map->def.value_size &&
2255 map_info.max_entries == map->def.max_entries &&
2256 map_info.map_flags == map->def.map_flags);
2260 bpf_object__reuse_map(struct bpf_map *map)
2262 char *cp, errmsg[STRERR_BUFSIZE];
2265 pin_fd = bpf_obj_get(map->pin_path);
2268 if (err == -ENOENT) {
2269 pr_debug("found no pinned map to reuse at '%s'\n",
2274 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
2275 pr_warn("couldn't retrieve pinned map '%s': %s\n",
2280 if (!map_is_reuse_compat(map, pin_fd)) {
2281 pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
2287 err = bpf_map__reuse_fd(map, pin_fd);
2293 pr_debug("reused pinned map at '%s'\n", map->pin_path);
2299 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
2301 char *cp, errmsg[STRERR_BUFSIZE];
2305 /* Nothing to do here since kernel already zero-initializes .bss map. */
2306 if (map->libbpf_type == LIBBPF_MAP_BSS)
2309 data = map->libbpf_type == LIBBPF_MAP_DATA ?
2310 obj->sections.data : obj->sections.rodata;
2312 err = bpf_map_update_elem(map->fd, &zero, data, 0);
2313 /* Freeze .rodata map as read-only from syscall side. */
2314 if (!err && map->libbpf_type == LIBBPF_MAP_RODATA) {
2315 err = bpf_map_freeze(map->fd);
2317 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
2318 pr_warn("Error freezing map(%s) as read-only: %s\n",
2327 bpf_object__create_maps(struct bpf_object *obj)
2329 struct bpf_create_map_attr create_attr = {};
2334 for (i = 0; i < obj->nr_maps; i++) {
2335 struct bpf_map *map = &obj->maps[i];
2336 struct bpf_map_def *def = &map->def;
2337 char *cp, errmsg[STRERR_BUFSIZE];
2338 int *pfd = &map->fd;
2340 if (map->pin_path) {
2341 err = bpf_object__reuse_map(map);
2343 pr_warn("error reusing pinned map %s\n",
2350 pr_debug("skip map create (preset) %s: fd=%d\n",
2351 map->name, map->fd);
2356 create_attr.name = map->name;
2357 create_attr.map_ifindex = map->map_ifindex;
2358 create_attr.map_type = def->type;
2359 create_attr.map_flags = def->map_flags;
2360 create_attr.key_size = def->key_size;
2361 create_attr.value_size = def->value_size;
2362 if (def->type == BPF_MAP_TYPE_PERF_EVENT_ARRAY &&
2363 !def->max_entries) {
2365 nr_cpus = libbpf_num_possible_cpus();
2367 pr_warn("failed to determine number of system CPUs: %d\n",
2372 pr_debug("map '%s': setting size to %d\n",
2373 map->name, nr_cpus);
2374 create_attr.max_entries = nr_cpus;
2376 create_attr.max_entries = def->max_entries;
2378 create_attr.btf_fd = 0;
2379 create_attr.btf_key_type_id = 0;
2380 create_attr.btf_value_type_id = 0;
2381 if (bpf_map_type__is_map_in_map(def->type) &&
2382 map->inner_map_fd >= 0)
2383 create_attr.inner_map_fd = map->inner_map_fd;
2385 if (obj->btf && !bpf_map_find_btf_info(obj, map)) {
2386 create_attr.btf_fd = btf__fd(obj->btf);
2387 create_attr.btf_key_type_id = map->btf_key_type_id;
2388 create_attr.btf_value_type_id = map->btf_value_type_id;
2391 *pfd = bpf_create_map_xattr(&create_attr);
2392 if (*pfd < 0 && (create_attr.btf_key_type_id ||
2393 create_attr.btf_value_type_id)) {
2395 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
2396 pr_warn("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
2397 map->name, cp, err);
2398 create_attr.btf_fd = 0;
2399 create_attr.btf_key_type_id = 0;
2400 create_attr.btf_value_type_id = 0;
2401 map->btf_key_type_id = 0;
2402 map->btf_value_type_id = 0;
2403 *pfd = bpf_create_map_xattr(&create_attr);
2411 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
2412 pr_warn("failed to create map (name: '%s'): %s(%d)\n",
2413 map->name, cp, err);
2414 for (j = 0; j < i; j++)
2415 zclose(obj->maps[j].fd);
2419 if (bpf_map__is_internal(map)) {
2420 err = bpf_object__populate_internal_map(obj, map);
2427 if (map->pin_path && !map->pinned) {
2428 err = bpf_map__pin(map, NULL);
2430 pr_warn("failed to auto-pin map name '%s' at '%s'\n",
2431 map->name, map->pin_path);
2436 pr_debug("created map %s: fd=%d\n", map->name, *pfd);
2443 check_btf_ext_reloc_err(struct bpf_program *prog, int err,
2444 void *btf_prog_info, const char *info_name)
2446 if (err != -ENOENT) {
2447 pr_warn("Error in loading %s for sec %s.\n",
2448 info_name, prog->section_name);
2452 /* err == -ENOENT (i.e. prog->section_name not found in btf_ext) */
2454 if (btf_prog_info) {
2456 * Some info has already been found but has problem
2457 * in the last btf_ext reloc. Must have to error out.
2459 pr_warn("Error in relocating %s for sec %s.\n",
2460 info_name, prog->section_name);
2464 /* Have problem loading the very first info. Ignore the rest. */
2465 pr_warn("Cannot find %s for main program sec %s. Ignore all %s.\n",
2466 info_name, prog->section_name, info_name);
2471 bpf_program_reloc_btf_ext(struct bpf_program *prog, struct bpf_object *obj,
2472 const char *section_name, __u32 insn_offset)
2476 if (!insn_offset || prog->func_info) {
2478 * !insn_offset => main program
2480 * For sub prog, the main program's func_info has to
2481 * be loaded first (i.e. prog->func_info != NULL)
2483 err = btf_ext__reloc_func_info(obj->btf, obj->btf_ext,
2484 section_name, insn_offset,
2486 &prog->func_info_cnt);
2488 return check_btf_ext_reloc_err(prog, err,
2492 prog->func_info_rec_size = btf_ext__func_info_rec_size(obj->btf_ext);
2495 if (!insn_offset || prog->line_info) {
2496 err = btf_ext__reloc_line_info(obj->btf, obj->btf_ext,
2497 section_name, insn_offset,
2499 &prog->line_info_cnt);
2501 return check_btf_ext_reloc_err(prog, err,
2505 prog->line_info_rec_size = btf_ext__line_info_rec_size(obj->btf_ext);
2511 #define BPF_CORE_SPEC_MAX_LEN 64
2513 /* represents BPF CO-RE field or array element accessor */
2514 struct bpf_core_accessor {
2515 __u32 type_id; /* struct/union type or array element type */
2516 __u32 idx; /* field index or array index */
2517 const char *name; /* field name or NULL for array accessor */
2520 struct bpf_core_spec {
2521 const struct btf *btf;
2522 /* high-level spec: named fields and array indices only */
2523 struct bpf_core_accessor spec[BPF_CORE_SPEC_MAX_LEN];
2524 /* high-level spec length */
2526 /* raw, low-level spec: 1-to-1 with accessor spec string */
2527 int raw_spec[BPF_CORE_SPEC_MAX_LEN];
2528 /* raw spec length */
2530 /* field bit offset represented by spec */
2534 static bool str_is_empty(const char *s)
2540 * Turn bpf_field_reloc into a low- and high-level spec representation,
2541 * validating correctness along the way, as well as calculating resulting
2542 * field bit offset, specified by accessor string. Low-level spec captures
2543 * every single level of nestedness, including traversing anonymous
2544 * struct/union members. High-level one only captures semantically meaningful
2545 * "turning points": named fields and array indicies.
2546 * E.g., for this case:
2549 * int __unimportant;
2557 * struct sample *s = ...;
2559 * int x = &s->a[3]; // access string = '0:1:2:3'
2561 * Low-level spec has 1:1 mapping with each element of access string (it's
2562 * just a parsed access string representation): [0, 1, 2, 3].
2564 * High-level spec will capture only 3 points:
2565 * - intial zero-index access by pointer (&s->... is the same as &s[0]...);
2566 * - field 'a' access (corresponds to '2' in low-level spec);
2567 * - array element #3 access (corresponds to '3' in low-level spec).
2570 static int bpf_core_spec_parse(const struct btf *btf,
2572 const char *spec_str,
2573 struct bpf_core_spec *spec)
2575 int access_idx, parsed_len, i;
2576 const struct btf_type *t;
2581 if (str_is_empty(spec_str) || *spec_str == ':')
2584 memset(spec, 0, sizeof(*spec));
2587 /* parse spec_str="0:1:2:3:4" into array raw_spec=[0, 1, 2, 3, 4] */
2589 if (*spec_str == ':')
2591 if (sscanf(spec_str, "%d%n", &access_idx, &parsed_len) != 1)
2593 if (spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
2595 spec_str += parsed_len;
2596 spec->raw_spec[spec->raw_len++] = access_idx;
2599 if (spec->raw_len == 0)
2602 /* first spec value is always reloc type array index */
2603 t = skip_mods_and_typedefs(btf, type_id, &id);
2607 access_idx = spec->raw_spec[0];
2608 spec->spec[0].type_id = id;
2609 spec->spec[0].idx = access_idx;
2612 sz = btf__resolve_size(btf, id);
2615 spec->bit_offset = access_idx * sz * 8;
2617 for (i = 1; i < spec->raw_len; i++) {
2618 t = skip_mods_and_typedefs(btf, id, &id);
2622 access_idx = spec->raw_spec[i];
2624 if (btf_is_composite(t)) {
2625 const struct btf_member *m;
2628 if (access_idx >= btf_vlen(t))
2631 bit_offset = btf_member_bit_offset(t, access_idx);
2632 spec->bit_offset += bit_offset;
2634 m = btf_members(t) + access_idx;
2636 name = btf__name_by_offset(btf, m->name_off);
2637 if (str_is_empty(name))
2640 spec->spec[spec->len].type_id = id;
2641 spec->spec[spec->len].idx = access_idx;
2642 spec->spec[spec->len].name = name;
2647 } else if (btf_is_array(t)) {
2648 const struct btf_array *a = btf_array(t);
2650 t = skip_mods_and_typedefs(btf, a->type, &id);
2651 if (!t || access_idx >= a->nelems)
2654 spec->spec[spec->len].type_id = id;
2655 spec->spec[spec->len].idx = access_idx;
2658 sz = btf__resolve_size(btf, id);
2661 spec->bit_offset += access_idx * sz * 8;
2663 pr_warn("relo for [%u] %s (at idx %d) captures type [%d] of unexpected kind %d\n",
2664 type_id, spec_str, i, id, btf_kind(t));
2672 static bool bpf_core_is_flavor_sep(const char *s)
2674 /* check X___Y name pattern, where X and Y are not underscores */
2675 return s[0] != '_' && /* X */
2676 s[1] == '_' && s[2] == '_' && s[3] == '_' && /* ___ */
2677 s[4] != '_'; /* Y */
2680 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
2681 * before last triple underscore. Struct name part after last triple
2682 * underscore is ignored by BPF CO-RE relocation during relocation matching.
2684 static size_t bpf_core_essential_name_len(const char *name)
2686 size_t n = strlen(name);
2689 for (i = n - 5; i >= 0; i--) {
2690 if (bpf_core_is_flavor_sep(name + i))
2696 /* dynamically sized list of type IDs */
2702 static void bpf_core_free_cands(struct ids_vec *cand_ids)
2704 free(cand_ids->data);
2708 static struct ids_vec *bpf_core_find_cands(const struct btf *local_btf,
2709 __u32 local_type_id,
2710 const struct btf *targ_btf)
2712 size_t local_essent_len, targ_essent_len;
2713 const char *local_name, *targ_name;
2714 const struct btf_type *t;
2715 struct ids_vec *cand_ids;
2719 t = btf__type_by_id(local_btf, local_type_id);
2721 return ERR_PTR(-EINVAL);
2723 local_name = btf__name_by_offset(local_btf, t->name_off);
2724 if (str_is_empty(local_name))
2725 return ERR_PTR(-EINVAL);
2726 local_essent_len = bpf_core_essential_name_len(local_name);
2728 cand_ids = calloc(1, sizeof(*cand_ids));
2730 return ERR_PTR(-ENOMEM);
2732 n = btf__get_nr_types(targ_btf);
2733 for (i = 1; i <= n; i++) {
2734 t = btf__type_by_id(targ_btf, i);
2735 targ_name = btf__name_by_offset(targ_btf, t->name_off);
2736 if (str_is_empty(targ_name))
2739 targ_essent_len = bpf_core_essential_name_len(targ_name);
2740 if (targ_essent_len != local_essent_len)
2743 if (strncmp(local_name, targ_name, local_essent_len) == 0) {
2744 pr_debug("[%d] %s: found candidate [%d] %s\n",
2745 local_type_id, local_name, i, targ_name);
2746 new_ids = realloc(cand_ids->data, cand_ids->len + 1);
2751 cand_ids->data = new_ids;
2752 cand_ids->data[cand_ids->len++] = i;
2757 bpf_core_free_cands(cand_ids);
2758 return ERR_PTR(err);
2761 /* Check two types for compatibility, skipping const/volatile/restrict and
2762 * typedefs, to ensure we are relocating compatible entities:
2763 * - any two STRUCTs/UNIONs are compatible and can be mixed;
2764 * - any two FWDs are compatible, if their names match (modulo flavor suffix);
2765 * - any two PTRs are always compatible;
2766 * - for ENUMs, names should be the same (ignoring flavor suffix) or at
2767 * least one of enums should be anonymous;
2768 * - for ENUMs, check sizes, names are ignored;
2769 * - for INT, size and signedness are ignored;
2770 * - for ARRAY, dimensionality is ignored, element types are checked for
2771 * compatibility recursively;
2772 * - everything else shouldn't be ever a target of relocation.
2773 * These rules are not set in stone and probably will be adjusted as we get
2774 * more experience with using BPF CO-RE relocations.
2776 static int bpf_core_fields_are_compat(const struct btf *local_btf,
2778 const struct btf *targ_btf,
2781 const struct btf_type *local_type, *targ_type;
2784 local_type = skip_mods_and_typedefs(local_btf, local_id, &local_id);
2785 targ_type = skip_mods_and_typedefs(targ_btf, targ_id, &targ_id);
2786 if (!local_type || !targ_type)
2789 if (btf_is_composite(local_type) && btf_is_composite(targ_type))
2791 if (btf_kind(local_type) != btf_kind(targ_type))
2794 switch (btf_kind(local_type)) {
2798 case BTF_KIND_ENUM: {
2799 const char *local_name, *targ_name;
2800 size_t local_len, targ_len;
2802 local_name = btf__name_by_offset(local_btf,
2803 local_type->name_off);
2804 targ_name = btf__name_by_offset(targ_btf, targ_type->name_off);
2805 local_len = bpf_core_essential_name_len(local_name);
2806 targ_len = bpf_core_essential_name_len(targ_name);
2807 /* one of them is anonymous or both w/ same flavor-less names */
2808 return local_len == 0 || targ_len == 0 ||
2809 (local_len == targ_len &&
2810 strncmp(local_name, targ_name, local_len) == 0);
2813 /* just reject deprecated bitfield-like integers; all other
2814 * integers are by default compatible between each other
2816 return btf_int_offset(local_type) == 0 &&
2817 btf_int_offset(targ_type) == 0;
2818 case BTF_KIND_ARRAY:
2819 local_id = btf_array(local_type)->type;
2820 targ_id = btf_array(targ_type)->type;
2823 pr_warn("unexpected kind %d relocated, local [%d], target [%d]\n",
2824 btf_kind(local_type), local_id, targ_id);
2830 * Given single high-level named field accessor in local type, find
2831 * corresponding high-level accessor for a target type. Along the way,
2832 * maintain low-level spec for target as well. Also keep updating target
2835 * Searching is performed through recursive exhaustive enumeration of all
2836 * fields of a struct/union. If there are any anonymous (embedded)
2837 * structs/unions, they are recursively searched as well. If field with
2838 * desired name is found, check compatibility between local and target types,
2839 * before returning result.
2841 * 1 is returned, if field is found.
2842 * 0 is returned if no compatible field is found.
2843 * <0 is returned on error.
2845 static int bpf_core_match_member(const struct btf *local_btf,
2846 const struct bpf_core_accessor *local_acc,
2847 const struct btf *targ_btf,
2849 struct bpf_core_spec *spec,
2850 __u32 *next_targ_id)
2852 const struct btf_type *local_type, *targ_type;
2853 const struct btf_member *local_member, *m;
2854 const char *local_name, *targ_name;
2858 targ_type = skip_mods_and_typedefs(targ_btf, targ_id, &targ_id);
2861 if (!btf_is_composite(targ_type))
2864 local_id = local_acc->type_id;
2865 local_type = btf__type_by_id(local_btf, local_id);
2866 local_member = btf_members(local_type) + local_acc->idx;
2867 local_name = btf__name_by_offset(local_btf, local_member->name_off);
2869 n = btf_vlen(targ_type);
2870 m = btf_members(targ_type);
2871 for (i = 0; i < n; i++, m++) {
2874 bit_offset = btf_member_bit_offset(targ_type, i);
2876 /* too deep struct/union/array nesting */
2877 if (spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
2880 /* speculate this member will be the good one */
2881 spec->bit_offset += bit_offset;
2882 spec->raw_spec[spec->raw_len++] = i;
2884 targ_name = btf__name_by_offset(targ_btf, m->name_off);
2885 if (str_is_empty(targ_name)) {
2886 /* embedded struct/union, we need to go deeper */
2887 found = bpf_core_match_member(local_btf, local_acc,
2889 spec, next_targ_id);
2890 if (found) /* either found or error */
2892 } else if (strcmp(local_name, targ_name) == 0) {
2893 /* matching named field */
2894 struct bpf_core_accessor *targ_acc;
2896 targ_acc = &spec->spec[spec->len++];
2897 targ_acc->type_id = targ_id;
2899 targ_acc->name = targ_name;
2901 *next_targ_id = m->type;
2902 found = bpf_core_fields_are_compat(local_btf,
2906 spec->len--; /* pop accessor */
2909 /* member turned out not to be what we looked for */
2910 spec->bit_offset -= bit_offset;
2918 * Try to match local spec to a target type and, if successful, produce full
2919 * target spec (high-level, low-level + bit offset).
2921 static int bpf_core_spec_match(struct bpf_core_spec *local_spec,
2922 const struct btf *targ_btf, __u32 targ_id,
2923 struct bpf_core_spec *targ_spec)
2925 const struct btf_type *targ_type;
2926 const struct bpf_core_accessor *local_acc;
2927 struct bpf_core_accessor *targ_acc;
2930 memset(targ_spec, 0, sizeof(*targ_spec));
2931 targ_spec->btf = targ_btf;
2933 local_acc = &local_spec->spec[0];
2934 targ_acc = &targ_spec->spec[0];
2936 for (i = 0; i < local_spec->len; i++, local_acc++, targ_acc++) {
2937 targ_type = skip_mods_and_typedefs(targ_spec->btf, targ_id,
2942 if (local_acc->name) {
2943 matched = bpf_core_match_member(local_spec->btf,
2946 targ_spec, &targ_id);
2950 /* for i=0, targ_id is already treated as array element
2951 * type (because it's the original struct), for others
2952 * we should find array element type first
2955 const struct btf_array *a;
2957 if (!btf_is_array(targ_type))
2960 a = btf_array(targ_type);
2961 if (local_acc->idx >= a->nelems)
2963 if (!skip_mods_and_typedefs(targ_btf, a->type,
2968 /* too deep struct/union/array nesting */
2969 if (targ_spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
2972 targ_acc->type_id = targ_id;
2973 targ_acc->idx = local_acc->idx;
2974 targ_acc->name = NULL;
2976 targ_spec->raw_spec[targ_spec->raw_len] = targ_acc->idx;
2977 targ_spec->raw_len++;
2979 sz = btf__resolve_size(targ_btf, targ_id);
2982 targ_spec->bit_offset += local_acc->idx * sz * 8;
2989 static int bpf_core_calc_field_relo(const struct bpf_program *prog,
2990 const struct bpf_field_reloc *relo,
2991 const struct bpf_core_spec *spec,
2992 __u32 *val, bool *validate)
2994 const struct bpf_core_accessor *acc = &spec->spec[spec->len - 1];
2995 const struct btf_type *t = btf__type_by_id(spec->btf, acc->type_id);
2996 __u32 byte_off, byte_sz, bit_off, bit_sz;
2997 const struct btf_member *m;
2998 const struct btf_type *mt;
3002 /* a[n] accessor needs special handling */
3004 if (relo->kind == BPF_FIELD_BYTE_OFFSET) {
3005 *val = spec->bit_offset / 8;
3006 } else if (relo->kind == BPF_FIELD_BYTE_SIZE) {
3007 sz = btf__resolve_size(spec->btf, acc->type_id);
3012 pr_warn("prog '%s': relo %d at insn #%d can't be applied to array access\n",
3013 bpf_program__title(prog, false),
3014 relo->kind, relo->insn_off / 8);
3022 m = btf_members(t) + acc->idx;
3023 mt = skip_mods_and_typedefs(spec->btf, m->type, NULL);
3024 bit_off = spec->bit_offset;
3025 bit_sz = btf_member_bitfield_size(t, acc->idx);
3027 bitfield = bit_sz > 0;
3030 byte_off = bit_off / 8 / byte_sz * byte_sz;
3031 /* figure out smallest int size necessary for bitfield load */
3032 while (bit_off + bit_sz - byte_off * 8 > byte_sz * 8) {
3034 /* bitfield can't be read with 64-bit read */
3035 pr_warn("prog '%s': relo %d at insn #%d can't be satisfied for bitfield\n",
3036 bpf_program__title(prog, false),
3037 relo->kind, relo->insn_off / 8);
3041 byte_off = bit_off / 8 / byte_sz * byte_sz;
3044 sz = btf__resolve_size(spec->btf, m->type);
3048 byte_off = spec->bit_offset / 8;
3049 bit_sz = byte_sz * 8;
3052 /* for bitfields, all the relocatable aspects are ambiguous and we
3053 * might disagree with compiler, so turn off validation of expected
3054 * value, except for signedness
3057 *validate = !bitfield;
3059 switch (relo->kind) {
3060 case BPF_FIELD_BYTE_OFFSET:
3063 case BPF_FIELD_BYTE_SIZE:
3066 case BPF_FIELD_SIGNED:
3067 /* enums will be assumed unsigned */
3068 *val = btf_is_enum(mt) ||
3069 (btf_int_encoding(mt) & BTF_INT_SIGNED);
3071 *validate = true; /* signedness is never ambiguous */
3073 case BPF_FIELD_LSHIFT_U64:
3074 #if __BYTE_ORDER == __LITTLE_ENDIAN
3075 *val = 64 - (bit_off + bit_sz - byte_off * 8);
3077 *val = (8 - byte_sz) * 8 + (bit_off - byte_off * 8);
3080 case BPF_FIELD_RSHIFT_U64:
3083 *validate = true; /* right shift is never ambiguous */
3085 case BPF_FIELD_EXISTS:
3087 pr_warn("prog '%s': unknown relo %d at insn #%d\n",
3088 bpf_program__title(prog, false),
3089 relo->kind, relo->insn_off / 8);
3097 * Patch relocatable BPF instruction.
3099 * Patched value is determined by relocation kind and target specification.
3100 * For field existence relocation target spec will be NULL if field is not
3102 * Expected insn->imm value is determined using relocation kind and local
3103 * spec, and is checked before patching instruction. If actual insn->imm value
3104 * is wrong, bail out with error.
3106 * Currently three kinds of BPF instructions are supported:
3107 * 1. rX = <imm> (assignment with immediate operand);
3108 * 2. rX += <imm> (arithmetic operations with immediate operand);
3110 static int bpf_core_reloc_insn(struct bpf_program *prog,
3111 const struct bpf_field_reloc *relo,
3112 const struct bpf_core_spec *local_spec,
3113 const struct bpf_core_spec *targ_spec)
3115 bool failed = false, validate = true;
3116 __u32 orig_val, new_val;
3117 struct bpf_insn *insn;
3121 if (relo->insn_off % sizeof(struct bpf_insn))
3123 insn_idx = relo->insn_off / sizeof(struct bpf_insn);
3125 if (relo->kind == BPF_FIELD_EXISTS) {
3126 orig_val = 1; /* can't generate EXISTS relo w/o local field */
3127 new_val = targ_spec ? 1 : 0;
3128 } else if (!targ_spec) {
3130 new_val = (__u32)-1;
3132 err = bpf_core_calc_field_relo(prog, relo, local_spec,
3133 &orig_val, &validate);
3136 err = bpf_core_calc_field_relo(prog, relo, targ_spec,
3142 insn = &prog->insns[insn_idx];
3143 class = BPF_CLASS(insn->code);
3145 if (class == BPF_ALU || class == BPF_ALU64) {
3146 if (BPF_SRC(insn->code) != BPF_K)
3148 if (!failed && validate && insn->imm != orig_val) {
3149 pr_warn("prog '%s': unexpected insn #%d value: got %u, exp %u -> %u\n",
3150 bpf_program__title(prog, false), insn_idx,
3151 insn->imm, orig_val, new_val);
3154 orig_val = insn->imm;
3155 insn->imm = new_val;
3156 pr_debug("prog '%s': patched insn #%d (ALU/ALU64)%s imm %u -> %u\n",
3157 bpf_program__title(prog, false), insn_idx,
3158 failed ? " w/ failed reloc" : "", orig_val, new_val);
3160 pr_warn("prog '%s': trying to relocate unrecognized insn #%d, code:%x, src:%x, dst:%x, off:%x, imm:%x\n",
3161 bpf_program__title(prog, false),
3162 insn_idx, insn->code, insn->src_reg, insn->dst_reg,
3163 insn->off, insn->imm);
3170 static struct btf *btf_load_raw(const char *path)
3178 if (stat(path, &st))
3179 return ERR_PTR(-errno);
3181 data = malloc(st.st_size);
3183 return ERR_PTR(-ENOMEM);
3185 f = fopen(path, "rb");
3187 btf = ERR_PTR(-errno);
3191 read_cnt = fread(data, 1, st.st_size, f);
3193 if (read_cnt < st.st_size) {
3194 btf = ERR_PTR(-EBADF);
3198 btf = btf__new(data, read_cnt);
3206 * Probe few well-known locations for vmlinux kernel image and try to load BTF
3207 * data out of it to use for target BTF.
3209 static struct btf *bpf_core_find_kernel_btf(void)
3212 const char *path_fmt;
3215 /* try canonical vmlinux BTF through sysfs first */
3216 { "/sys/kernel/btf/vmlinux", true /* raw BTF */ },
3217 /* fall back to trying to find vmlinux ELF on disk otherwise */
3218 { "/boot/vmlinux-%1$s" },
3219 { "/lib/modules/%1$s/vmlinux-%1$s" },
3220 { "/lib/modules/%1$s/build/vmlinux" },
3221 { "/usr/lib/modules/%1$s/kernel/vmlinux" },
3222 { "/usr/lib/debug/boot/vmlinux-%1$s" },
3223 { "/usr/lib/debug/boot/vmlinux-%1$s.debug" },
3224 { "/usr/lib/debug/lib/modules/%1$s/vmlinux" },
3226 char path[PATH_MAX + 1];
3233 for (i = 0; i < ARRAY_SIZE(locations); i++) {
3234 snprintf(path, PATH_MAX, locations[i].path_fmt, buf.release);
3236 if (access(path, R_OK))
3239 if (locations[i].raw_btf)
3240 btf = btf_load_raw(path);
3242 btf = btf__parse_elf(path, NULL);
3244 pr_debug("loading kernel BTF '%s': %ld\n",
3245 path, IS_ERR(btf) ? PTR_ERR(btf) : 0);
3252 pr_warn("failed to find valid kernel BTF\n");
3253 return ERR_PTR(-ESRCH);
3256 /* Output spec definition in the format:
3257 * [<type-id>] (<type-name>) + <raw-spec> => <offset>@<spec>,
3258 * where <spec> is a C-syntax view of recorded field access, e.g.: x.a[3].b
3260 static void bpf_core_dump_spec(int level, const struct bpf_core_spec *spec)
3262 const struct btf_type *t;
3267 type_id = spec->spec[0].type_id;
3268 t = btf__type_by_id(spec->btf, type_id);
3269 s = btf__name_by_offset(spec->btf, t->name_off);
3270 libbpf_print(level, "[%u] %s + ", type_id, s);
3272 for (i = 0; i < spec->raw_len; i++)
3273 libbpf_print(level, "%d%s", spec->raw_spec[i],
3274 i == spec->raw_len - 1 ? " => " : ":");
3276 libbpf_print(level, "%u.%u @ &x",
3277 spec->bit_offset / 8, spec->bit_offset % 8);
3279 for (i = 0; i < spec->len; i++) {
3280 if (spec->spec[i].name)
3281 libbpf_print(level, ".%s", spec->spec[i].name);
3283 libbpf_print(level, "[%u]", spec->spec[i].idx);
3288 static size_t bpf_core_hash_fn(const void *key, void *ctx)
3293 static bool bpf_core_equal_fn(const void *k1, const void *k2, void *ctx)
3298 static void *u32_as_hash_key(__u32 x)
3300 return (void *)(uintptr_t)x;
3304 * CO-RE relocate single instruction.
3306 * The outline and important points of the algorithm:
3307 * 1. For given local type, find corresponding candidate target types.
3308 * Candidate type is a type with the same "essential" name, ignoring
3309 * everything after last triple underscore (___). E.g., `sample`,
3310 * `sample___flavor_one`, `sample___flavor_another_one`, are all candidates
3311 * for each other. Names with triple underscore are referred to as
3312 * "flavors" and are useful, among other things, to allow to
3313 * specify/support incompatible variations of the same kernel struct, which
3314 * might differ between different kernel versions and/or build
3317 * N.B. Struct "flavors" could be generated by bpftool's BTF-to-C
3318 * converter, when deduplicated BTF of a kernel still contains more than
3319 * one different types with the same name. In that case, ___2, ___3, etc
3320 * are appended starting from second name conflict. But start flavors are
3321 * also useful to be defined "locally", in BPF program, to extract same
3322 * data from incompatible changes between different kernel
3323 * versions/configurations. For instance, to handle field renames between
3324 * kernel versions, one can use two flavors of the struct name with the
3325 * same common name and use conditional relocations to extract that field,
3326 * depending on target kernel version.
3327 * 2. For each candidate type, try to match local specification to this
3328 * candidate target type. Matching involves finding corresponding
3329 * high-level spec accessors, meaning that all named fields should match,
3330 * as well as all array accesses should be within the actual bounds. Also,
3331 * types should be compatible (see bpf_core_fields_are_compat for details).
3332 * 3. It is supported and expected that there might be multiple flavors
3333 * matching the spec. As long as all the specs resolve to the same set of
3334 * offsets across all candidates, there is no error. If there is any
3335 * ambiguity, CO-RE relocation will fail. This is necessary to accomodate
3336 * imprefection of BTF deduplication, which can cause slight duplication of
3337 * the same BTF type, if some directly or indirectly referenced (by
3338 * pointer) type gets resolved to different actual types in different
3339 * object files. If such situation occurs, deduplicated BTF will end up
3340 * with two (or more) structurally identical types, which differ only in
3341 * types they refer to through pointer. This should be OK in most cases and
3343 * 4. Candidate types search is performed by linearly scanning through all
3344 * types in target BTF. It is anticipated that this is overall more
3345 * efficient memory-wise and not significantly worse (if not better)
3346 * CPU-wise compared to prebuilding a map from all local type names to
3347 * a list of candidate type names. It's also sped up by caching resolved
3348 * list of matching candidates per each local "root" type ID, that has at
3349 * least one bpf_field_reloc associated with it. This list is shared
3350 * between multiple relocations for the same type ID and is updated as some
3351 * of the candidates are pruned due to structural incompatibility.
3353 static int bpf_core_reloc_field(struct bpf_program *prog,
3354 const struct bpf_field_reloc *relo,
3356 const struct btf *local_btf,
3357 const struct btf *targ_btf,
3358 struct hashmap *cand_cache)
3360 const char *prog_name = bpf_program__title(prog, false);
3361 struct bpf_core_spec local_spec, cand_spec, targ_spec;
3362 const void *type_key = u32_as_hash_key(relo->type_id);
3363 const struct btf_type *local_type, *cand_type;
3364 const char *local_name, *cand_name;
3365 struct ids_vec *cand_ids;
3366 __u32 local_id, cand_id;
3367 const char *spec_str;
3370 local_id = relo->type_id;
3371 local_type = btf__type_by_id(local_btf, local_id);
3375 local_name = btf__name_by_offset(local_btf, local_type->name_off);
3376 if (str_is_empty(local_name))
3379 spec_str = btf__name_by_offset(local_btf, relo->access_str_off);
3380 if (str_is_empty(spec_str))
3383 err = bpf_core_spec_parse(local_btf, local_id, spec_str, &local_spec);
3385 pr_warn("prog '%s': relo #%d: parsing [%d] %s + %s failed: %d\n",
3386 prog_name, relo_idx, local_id, local_name, spec_str,
3391 pr_debug("prog '%s': relo #%d: kind %d, spec is ", prog_name, relo_idx,
3393 bpf_core_dump_spec(LIBBPF_DEBUG, &local_spec);
3394 libbpf_print(LIBBPF_DEBUG, "\n");
3396 if (!hashmap__find(cand_cache, type_key, (void **)&cand_ids)) {
3397 cand_ids = bpf_core_find_cands(local_btf, local_id, targ_btf);
3398 if (IS_ERR(cand_ids)) {
3399 pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s: %ld",
3400 prog_name, relo_idx, local_id, local_name,
3402 return PTR_ERR(cand_ids);
3404 err = hashmap__set(cand_cache, type_key, cand_ids, NULL, NULL);
3406 bpf_core_free_cands(cand_ids);
3411 for (i = 0, j = 0; i < cand_ids->len; i++) {
3412 cand_id = cand_ids->data[i];
3413 cand_type = btf__type_by_id(targ_btf, cand_id);
3414 cand_name = btf__name_by_offset(targ_btf, cand_type->name_off);
3416 err = bpf_core_spec_match(&local_spec, targ_btf,
3417 cand_id, &cand_spec);
3418 pr_debug("prog '%s': relo #%d: matching candidate #%d %s against spec ",
3419 prog_name, relo_idx, i, cand_name);
3420 bpf_core_dump_spec(LIBBPF_DEBUG, &cand_spec);
3421 libbpf_print(LIBBPF_DEBUG, ": %d\n", err);
3423 pr_warn("prog '%s': relo #%d: matching error: %d\n",
3424 prog_name, relo_idx, err);
3431 targ_spec = cand_spec;
3432 } else if (cand_spec.bit_offset != targ_spec.bit_offset) {
3433 /* if there are many candidates, they should all
3434 * resolve to the same bit offset
3436 pr_warn("prog '%s': relo #%d: offset ambiguity: %u != %u\n",
3437 prog_name, relo_idx, cand_spec.bit_offset,
3438 targ_spec.bit_offset);
3442 cand_ids->data[j++] = cand_spec.spec[0].type_id;
3446 * For BPF_FIELD_EXISTS relo or when relaxed CO-RE reloc mode is
3447 * requested, it's expected that we might not find any candidates.
3448 * In this case, if field wasn't found in any candidate, the list of
3449 * candidates shouldn't change at all, we'll just handle relocating
3450 * appropriately, depending on relo's kind.
3455 if (j == 0 && !prog->obj->relaxed_core_relocs &&
3456 relo->kind != BPF_FIELD_EXISTS) {
3457 pr_warn("prog '%s': relo #%d: no matching targets found for [%d] %s + %s\n",
3458 prog_name, relo_idx, local_id, local_name, spec_str);
3462 /* bpf_core_reloc_insn should know how to handle missing targ_spec */
3463 err = bpf_core_reloc_insn(prog, relo, &local_spec,
3464 j ? &targ_spec : NULL);
3466 pr_warn("prog '%s': relo #%d: failed to patch insn at offset %d: %d\n",
3467 prog_name, relo_idx, relo->insn_off, err);
3475 bpf_core_reloc_fields(struct bpf_object *obj, const char *targ_btf_path)
3477 const struct btf_ext_info_sec *sec;
3478 const struct bpf_field_reloc *rec;
3479 const struct btf_ext_info *seg;
3480 struct hashmap_entry *entry;
3481 struct hashmap *cand_cache = NULL;
3482 struct bpf_program *prog;
3483 struct btf *targ_btf;
3484 const char *sec_name;
3488 targ_btf = btf__parse_elf(targ_btf_path, NULL);
3490 targ_btf = bpf_core_find_kernel_btf();
3491 if (IS_ERR(targ_btf)) {
3492 pr_warn("failed to get target BTF: %ld\n", PTR_ERR(targ_btf));
3493 return PTR_ERR(targ_btf);
3496 cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
3497 if (IS_ERR(cand_cache)) {
3498 err = PTR_ERR(cand_cache);
3502 seg = &obj->btf_ext->field_reloc_info;
3503 for_each_btf_ext_sec(seg, sec) {
3504 sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
3505 if (str_is_empty(sec_name)) {
3509 prog = bpf_object__find_program_by_title(obj, sec_name);
3511 pr_warn("failed to find program '%s' for CO-RE offset relocation\n",
3517 pr_debug("prog '%s': performing %d CO-RE offset relocs\n",
3518 sec_name, sec->num_info);
3520 for_each_btf_ext_rec(seg, sec, i, rec) {
3521 err = bpf_core_reloc_field(prog, rec, i, obj->btf,
3522 targ_btf, cand_cache);
3524 pr_warn("prog '%s': relo #%d: failed to relocate: %d\n",
3532 btf__free(targ_btf);
3533 if (!IS_ERR_OR_NULL(cand_cache)) {
3534 hashmap__for_each_entry(cand_cache, entry, i) {
3535 bpf_core_free_cands(entry->value);
3537 hashmap__free(cand_cache);
3543 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
3547 if (obj->btf_ext->field_reloc_info.len)
3548 err = bpf_core_reloc_fields(obj, targ_btf_path);
3554 bpf_program__reloc_text(struct bpf_program *prog, struct bpf_object *obj,
3555 struct reloc_desc *relo)
3557 struct bpf_insn *insn, *new_insn;
3558 struct bpf_program *text;
3562 if (relo->type != RELO_CALL)
3563 return -LIBBPF_ERRNO__RELOC;
3565 if (prog->idx == obj->efile.text_shndx) {
3566 pr_warn("relo in .text insn %d into off %d (insn #%d)\n",
3567 relo->insn_idx, relo->sym_off, relo->sym_off / 8);
3568 return -LIBBPF_ERRNO__RELOC;
3571 if (prog->main_prog_cnt == 0) {
3572 text = bpf_object__find_prog_by_idx(obj, obj->efile.text_shndx);
3574 pr_warn("no .text section found yet relo into text exist\n");
3575 return -LIBBPF_ERRNO__RELOC;
3577 new_cnt = prog->insns_cnt + text->insns_cnt;
3578 new_insn = reallocarray(prog->insns, new_cnt, sizeof(*insn));
3580 pr_warn("oom in prog realloc\n");
3583 prog->insns = new_insn;
3586 err = bpf_program_reloc_btf_ext(prog, obj,
3593 memcpy(new_insn + prog->insns_cnt, text->insns,
3594 text->insns_cnt * sizeof(*insn));
3595 prog->main_prog_cnt = prog->insns_cnt;
3596 prog->insns_cnt = new_cnt;
3597 pr_debug("added %zd insn from %s to prog %s\n",
3598 text->insns_cnt, text->section_name,
3599 prog->section_name);
3601 insn = &prog->insns[relo->insn_idx];
3602 insn->imm += relo->sym_off / 8 + prog->main_prog_cnt - relo->insn_idx;
3607 bpf_program__relocate(struct bpf_program *prog, struct bpf_object *obj)
3615 err = bpf_program_reloc_btf_ext(prog, obj,
3616 prog->section_name, 0);
3621 if (!prog->reloc_desc)
3624 for (i = 0; i < prog->nr_reloc; i++) {
3625 struct reloc_desc *relo = &prog->reloc_desc[i];
3627 if (relo->type == RELO_LD64 || relo->type == RELO_DATA) {
3628 struct bpf_insn *insn = &prog->insns[relo->insn_idx];
3630 if (relo->insn_idx + 1 >= (int)prog->insns_cnt) {
3631 pr_warn("relocation out of range: '%s'\n",
3632 prog->section_name);
3633 return -LIBBPF_ERRNO__RELOC;
3636 if (relo->type != RELO_DATA) {
3637 insn[0].src_reg = BPF_PSEUDO_MAP_FD;
3639 insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
3640 insn[1].imm = insn[0].imm + relo->sym_off;
3642 insn[0].imm = obj->maps[relo->map_idx].fd;
3643 } else if (relo->type == RELO_CALL) {
3644 err = bpf_program__reloc_text(prog, obj, relo);
3650 zfree(&prog->reloc_desc);
3656 bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
3658 struct bpf_program *prog;
3663 err = bpf_object__relocate_core(obj, targ_btf_path);
3665 pr_warn("failed to perform CO-RE relocations: %d\n",
3670 for (i = 0; i < obj->nr_programs; i++) {
3671 prog = &obj->programs[i];
3673 err = bpf_program__relocate(prog, obj);
3675 pr_warn("failed to relocate '%s'\n", prog->section_name);
3682 static int bpf_object__collect_reloc(struct bpf_object *obj)
3686 if (!obj_elf_valid(obj)) {
3687 pr_warn("Internal error: elf object is closed\n");
3688 return -LIBBPF_ERRNO__INTERNAL;
3691 for (i = 0; i < obj->efile.nr_reloc_sects; i++) {
3692 GElf_Shdr *shdr = &obj->efile.reloc_sects[i].shdr;
3693 Elf_Data *data = obj->efile.reloc_sects[i].data;
3694 int idx = shdr->sh_info;
3695 struct bpf_program *prog;
3697 if (shdr->sh_type != SHT_REL) {
3698 pr_warn("internal error at %d\n", __LINE__);
3699 return -LIBBPF_ERRNO__INTERNAL;
3702 prog = bpf_object__find_prog_by_idx(obj, idx);
3704 pr_warn("relocation failed: no section(%d)\n", idx);
3705 return -LIBBPF_ERRNO__RELOC;
3708 err = bpf_program__collect_reloc(prog, shdr, data, obj);
3716 load_program(struct bpf_program *prog, struct bpf_insn *insns, int insns_cnt,
3717 char *license, __u32 kern_version, int *pfd)
3719 struct bpf_load_program_attr load_attr;
3720 char *cp, errmsg[STRERR_BUFSIZE];
3721 int log_buf_size = BPF_LOG_BUF_SIZE;
3725 if (!insns || !insns_cnt)
3728 memset(&load_attr, 0, sizeof(struct bpf_load_program_attr));
3729 load_attr.prog_type = prog->type;
3730 load_attr.expected_attach_type = prog->expected_attach_type;
3731 if (prog->caps->name)
3732 load_attr.name = prog->name;
3733 load_attr.insns = insns;
3734 load_attr.insns_cnt = insns_cnt;
3735 load_attr.license = license;
3736 if (prog->type == BPF_PROG_TYPE_TRACING) {
3737 load_attr.attach_prog_fd = prog->attach_prog_fd;
3738 load_attr.attach_btf_id = prog->attach_btf_id;
3740 load_attr.kern_version = kern_version;
3741 load_attr.prog_ifindex = prog->prog_ifindex;
3743 /* if .BTF.ext was loaded, kernel supports associated BTF for prog */
3744 if (prog->obj->btf_ext)
3745 btf_fd = bpf_object__btf_fd(prog->obj);
3748 load_attr.prog_btf_fd = btf_fd >= 0 ? btf_fd : 0;
3749 load_attr.func_info = prog->func_info;
3750 load_attr.func_info_rec_size = prog->func_info_rec_size;
3751 load_attr.func_info_cnt = prog->func_info_cnt;
3752 load_attr.line_info = prog->line_info;
3753 load_attr.line_info_rec_size = prog->line_info_rec_size;
3754 load_attr.line_info_cnt = prog->line_info_cnt;
3755 load_attr.log_level = prog->log_level;
3756 load_attr.prog_flags = prog->prog_flags;
3759 log_buf = malloc(log_buf_size);
3761 pr_warn("Alloc log buffer for bpf loader error, continue without log\n");
3763 ret = bpf_load_program_xattr(&load_attr, log_buf, log_buf_size);
3766 if (load_attr.log_level)
3767 pr_debug("verifier log:\n%s", log_buf);
3773 if (errno == ENOSPC) {
3779 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
3780 pr_warn("load bpf program failed: %s\n", cp);
3782 if (log_buf && log_buf[0] != '\0') {
3783 ret = -LIBBPF_ERRNO__VERIFY;
3784 pr_warn("-- BEGIN DUMP LOG ---\n");
3785 pr_warn("\n%s\n", log_buf);
3786 pr_warn("-- END LOG --\n");
3787 } else if (load_attr.insns_cnt >= BPF_MAXINSNS) {
3788 pr_warn("Program too large (%zu insns), at most %d insns\n",
3789 load_attr.insns_cnt, BPF_MAXINSNS);
3790 ret = -LIBBPF_ERRNO__PROG2BIG;
3791 } else if (load_attr.prog_type != BPF_PROG_TYPE_KPROBE) {
3792 /* Wrong program type? */
3795 load_attr.prog_type = BPF_PROG_TYPE_KPROBE;
3796 load_attr.expected_attach_type = 0;
3797 fd = bpf_load_program_xattr(&load_attr, NULL, 0);
3800 ret = -LIBBPF_ERRNO__PROGTYPE;
3811 bpf_program__load(struct bpf_program *prog,
3812 char *license, __u32 kern_version)
3816 if (prog->instances.nr < 0 || !prog->instances.fds) {
3817 if (prog->preprocessor) {
3818 pr_warn("Internal error: can't load program '%s'\n",
3819 prog->section_name);
3820 return -LIBBPF_ERRNO__INTERNAL;
3823 prog->instances.fds = malloc(sizeof(int));
3824 if (!prog->instances.fds) {
3825 pr_warn("Not enough memory for BPF fds\n");
3828 prog->instances.nr = 1;
3829 prog->instances.fds[0] = -1;
3832 if (!prog->preprocessor) {
3833 if (prog->instances.nr != 1) {
3834 pr_warn("Program '%s' is inconsistent: nr(%d) != 1\n",
3835 prog->section_name, prog->instances.nr);
3837 err = load_program(prog, prog->insns, prog->insns_cnt,
3838 license, kern_version, &fd);
3840 prog->instances.fds[0] = fd;
3844 for (i = 0; i < prog->instances.nr; i++) {
3845 struct bpf_prog_prep_result result;
3846 bpf_program_prep_t preprocessor = prog->preprocessor;
3848 memset(&result, 0, sizeof(result));
3849 err = preprocessor(prog, i, prog->insns,
3850 prog->insns_cnt, &result);
3852 pr_warn("Preprocessing the %dth instance of program '%s' failed\n",
3853 i, prog->section_name);
3857 if (!result.new_insn_ptr || !result.new_insn_cnt) {
3858 pr_debug("Skip loading the %dth instance of program '%s'\n",
3859 i, prog->section_name);
3860 prog->instances.fds[i] = -1;
3866 err = load_program(prog, result.new_insn_ptr,
3867 result.new_insn_cnt,
3868 license, kern_version, &fd);
3871 pr_warn("Loading the %dth instance of program '%s' failed\n",
3872 i, prog->section_name);
3878 prog->instances.fds[i] = fd;
3882 pr_warn("failed to load program '%s'\n", prog->section_name);
3883 zfree(&prog->insns);
3884 prog->insns_cnt = 0;
3888 static bool bpf_program__is_function_storage(const struct bpf_program *prog,
3889 const struct bpf_object *obj)
3891 return prog->idx == obj->efile.text_shndx && obj->has_pseudo_calls;
3895 bpf_object__load_progs(struct bpf_object *obj, int log_level)
3900 for (i = 0; i < obj->nr_programs; i++) {
3901 if (bpf_program__is_function_storage(&obj->programs[i], obj))
3903 obj->programs[i].log_level |= log_level;
3904 err = bpf_program__load(&obj->programs[i],
3913 static int libbpf_find_attach_btf_id(const char *name,
3914 enum bpf_attach_type attach_type,
3915 __u32 attach_prog_fd);
3916 static struct bpf_object *
3917 __bpf_object__open(const char *path, const void *obj_buf, size_t obj_buf_sz,
3918 struct bpf_object_open_opts *opts)
3920 const char *pin_root_path;
3921 struct bpf_program *prog;
3922 struct bpf_object *obj;
3923 const char *obj_name;
3926 __u32 attach_prog_fd;
3929 if (elf_version(EV_CURRENT) == EV_NONE) {
3930 pr_warn("failed to init libelf for %s\n",
3931 path ? : "(mem buf)");
3932 return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
3935 if (!OPTS_VALID(opts, bpf_object_open_opts))
3936 return ERR_PTR(-EINVAL);
3938 obj_name = OPTS_GET(opts, object_name, NULL);
3941 snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
3942 (unsigned long)obj_buf,
3943 (unsigned long)obj_buf_sz);
3944 obj_name = tmp_name;
3947 pr_debug("loading object '%s' from buffer\n", obj_name);
3950 obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
3954 obj->relaxed_core_relocs = OPTS_GET(opts, relaxed_core_relocs, false);
3955 relaxed_maps = OPTS_GET(opts, relaxed_maps, false);
3956 pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
3957 attach_prog_fd = OPTS_GET(opts, attach_prog_fd, 0);
3959 CHECK_ERR(bpf_object__elf_init(obj), err, out);
3960 CHECK_ERR(bpf_object__check_endianness(obj), err, out);
3961 CHECK_ERR(bpf_object__probe_caps(obj), err, out);
3962 CHECK_ERR(bpf_object__elf_collect(obj, relaxed_maps, pin_root_path),
3964 CHECK_ERR(bpf_object__collect_reloc(obj), err, out);
3965 bpf_object__elf_finish(obj);
3967 bpf_object__for_each_program(prog, obj) {
3968 enum bpf_prog_type prog_type;
3969 enum bpf_attach_type attach_type;
3971 err = libbpf_prog_type_by_name(prog->section_name, &prog_type,
3974 /* couldn't guess, but user might manually specify */
3979 bpf_program__set_type(prog, prog_type);
3980 bpf_program__set_expected_attach_type(prog, attach_type);
3981 if (prog_type == BPF_PROG_TYPE_TRACING) {
3982 err = libbpf_find_attach_btf_id(prog->section_name,
3987 prog->attach_btf_id = err;
3988 prog->attach_prog_fd = attach_prog_fd;
3994 bpf_object__close(obj);
3995 return ERR_PTR(err);
3998 static struct bpf_object *
3999 __bpf_object__open_xattr(struct bpf_object_open_attr *attr, int flags)
4001 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts,
4002 .relaxed_maps = flags & MAPS_RELAX_COMPAT,
4005 /* param validation */
4009 pr_debug("loading %s\n", attr->file);
4010 return __bpf_object__open(attr->file, NULL, 0, &opts);
4013 struct bpf_object *bpf_object__open_xattr(struct bpf_object_open_attr *attr)
4015 return __bpf_object__open_xattr(attr, 0);
4018 struct bpf_object *bpf_object__open(const char *path)
4020 struct bpf_object_open_attr attr = {
4022 .prog_type = BPF_PROG_TYPE_UNSPEC,
4025 return bpf_object__open_xattr(&attr);
4029 bpf_object__open_file(const char *path, struct bpf_object_open_opts *opts)
4032 return ERR_PTR(-EINVAL);
4034 pr_debug("loading %s\n", path);
4036 return __bpf_object__open(path, NULL, 0, opts);
4040 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
4041 struct bpf_object_open_opts *opts)
4043 if (!obj_buf || obj_buf_sz == 0)
4044 return ERR_PTR(-EINVAL);
4046 return __bpf_object__open(NULL, obj_buf, obj_buf_sz, opts);
4050 bpf_object__open_buffer(const void *obj_buf, size_t obj_buf_sz,
4053 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts,
4054 .object_name = name,
4055 /* wrong default, but backwards-compatible */
4056 .relaxed_maps = true,
4059 /* returning NULL is wrong, but backwards-compatible */
4060 if (!obj_buf || obj_buf_sz == 0)
4063 return bpf_object__open_mem(obj_buf, obj_buf_sz, &opts);
4066 int bpf_object__unload(struct bpf_object *obj)
4073 for (i = 0; i < obj->nr_maps; i++)
4074 zclose(obj->maps[i].fd);
4076 for (i = 0; i < obj->nr_programs; i++)
4077 bpf_program__unload(&obj->programs[i]);
4082 int bpf_object__load_xattr(struct bpf_object_load_attr *attr)
4084 struct bpf_object *obj;
4094 pr_warn("object should not be loaded twice\n");
4100 CHECK_ERR(bpf_object__create_maps(obj), err, out);
4101 CHECK_ERR(bpf_object__relocate(obj, attr->target_btf_path), err, out);
4102 CHECK_ERR(bpf_object__load_progs(obj, attr->log_level), err, out);
4106 /* unpin any maps that were auto-pinned during load */
4107 for (i = 0; i < obj->nr_maps; i++)
4108 if (obj->maps[i].pinned && !obj->maps[i].reused)
4109 bpf_map__unpin(&obj->maps[i], NULL);
4111 bpf_object__unload(obj);
4112 pr_warn("failed to load object '%s'\n", obj->path);
4116 int bpf_object__load(struct bpf_object *obj)
4118 struct bpf_object_load_attr attr = {
4122 return bpf_object__load_xattr(&attr);
4125 static int make_parent_dir(const char *path)
4127 char *cp, errmsg[STRERR_BUFSIZE];
4131 dname = strdup(path);
4135 dir = dirname(dname);
4136 if (mkdir(dir, 0700) && errno != EEXIST)
4141 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
4142 pr_warn("failed to mkdir %s: %s\n", path, cp);
4147 static int check_path(const char *path)
4149 char *cp, errmsg[STRERR_BUFSIZE];
4150 struct statfs st_fs;
4157 dname = strdup(path);
4161 dir = dirname(dname);
4162 if (statfs(dir, &st_fs)) {
4163 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
4164 pr_warn("failed to statfs %s: %s\n", dir, cp);
4169 if (!err && st_fs.f_type != BPF_FS_MAGIC) {
4170 pr_warn("specified path %s is not on BPF FS\n", path);
4177 int bpf_program__pin_instance(struct bpf_program *prog, const char *path,
4180 char *cp, errmsg[STRERR_BUFSIZE];
4183 err = make_parent_dir(path);
4187 err = check_path(path);
4192 pr_warn("invalid program pointer\n");
4196 if (instance < 0 || instance >= prog->instances.nr) {
4197 pr_warn("invalid prog instance %d of prog %s (max %d)\n",
4198 instance, prog->section_name, prog->instances.nr);
4202 if (bpf_obj_pin(prog->instances.fds[instance], path)) {
4203 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
4204 pr_warn("failed to pin program: %s\n", cp);
4207 pr_debug("pinned program '%s'\n", path);
4212 int bpf_program__unpin_instance(struct bpf_program *prog, const char *path,
4217 err = check_path(path);
4222 pr_warn("invalid program pointer\n");
4226 if (instance < 0 || instance >= prog->instances.nr) {
4227 pr_warn("invalid prog instance %d of prog %s (max %d)\n",
4228 instance, prog->section_name, prog->instances.nr);
4235 pr_debug("unpinned program '%s'\n", path);
4240 int bpf_program__pin(struct bpf_program *prog, const char *path)
4244 err = make_parent_dir(path);
4248 err = check_path(path);
4253 pr_warn("invalid program pointer\n");
4257 if (prog->instances.nr <= 0) {
4258 pr_warn("no instances of prog %s to pin\n",
4259 prog->section_name);
4263 if (prog->instances.nr == 1) {
4264 /* don't create subdirs when pinning single instance */
4265 return bpf_program__pin_instance(prog, path, 0);
4268 for (i = 0; i < prog->instances.nr; i++) {
4272 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
4276 } else if (len >= PATH_MAX) {
4277 err = -ENAMETOOLONG;
4281 err = bpf_program__pin_instance(prog, buf, i);
4289 for (i = i - 1; i >= 0; i--) {
4293 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
4296 else if (len >= PATH_MAX)
4299 bpf_program__unpin_instance(prog, buf, i);
4307 int bpf_program__unpin(struct bpf_program *prog, const char *path)
4311 err = check_path(path);
4316 pr_warn("invalid program pointer\n");
4320 if (prog->instances.nr <= 0) {
4321 pr_warn("no instances of prog %s to pin\n",
4322 prog->section_name);
4326 if (prog->instances.nr == 1) {
4327 /* don't create subdirs when pinning single instance */
4328 return bpf_program__unpin_instance(prog, path, 0);
4331 for (i = 0; i < prog->instances.nr; i++) {
4335 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
4338 else if (len >= PATH_MAX)
4339 return -ENAMETOOLONG;
4341 err = bpf_program__unpin_instance(prog, buf, i);
4353 int bpf_map__pin(struct bpf_map *map, const char *path)
4355 char *cp, errmsg[STRERR_BUFSIZE];
4359 pr_warn("invalid map pointer\n");
4363 if (map->pin_path) {
4364 if (path && strcmp(path, map->pin_path)) {
4365 pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
4366 bpf_map__name(map), map->pin_path, path);
4368 } else if (map->pinned) {
4369 pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
4370 bpf_map__name(map), map->pin_path);
4375 pr_warn("missing a path to pin map '%s' at\n",
4376 bpf_map__name(map));
4378 } else if (map->pinned) {
4379 pr_warn("map '%s' already pinned\n", bpf_map__name(map));
4383 map->pin_path = strdup(path);
4384 if (!map->pin_path) {
4390 err = make_parent_dir(map->pin_path);
4394 err = check_path(map->pin_path);
4398 if (bpf_obj_pin(map->fd, map->pin_path)) {
4404 pr_debug("pinned map '%s'\n", map->pin_path);
4409 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
4410 pr_warn("failed to pin map: %s\n", cp);
4414 int bpf_map__unpin(struct bpf_map *map, const char *path)
4419 pr_warn("invalid map pointer\n");
4423 if (map->pin_path) {
4424 if (path && strcmp(path, map->pin_path)) {
4425 pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
4426 bpf_map__name(map), map->pin_path, path);
4429 path = map->pin_path;
4431 pr_warn("no path to unpin map '%s' from\n",
4432 bpf_map__name(map));
4436 err = check_path(path);
4444 map->pinned = false;
4445 pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
4450 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
4460 free(map->pin_path);
4461 map->pin_path = new;
4465 const char *bpf_map__get_pin_path(const struct bpf_map *map)
4467 return map->pin_path;
4470 bool bpf_map__is_pinned(const struct bpf_map *map)
4475 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
4477 struct bpf_map *map;
4484 pr_warn("object not yet loaded; load it first\n");
4488 bpf_object__for_each_map(map, obj) {
4489 char *pin_path = NULL;
4495 len = snprintf(buf, PATH_MAX, "%s/%s", path,
4496 bpf_map__name(map));
4499 goto err_unpin_maps;
4500 } else if (len >= PATH_MAX) {
4501 err = -ENAMETOOLONG;
4502 goto err_unpin_maps;
4505 } else if (!map->pin_path) {
4509 err = bpf_map__pin(map, pin_path);
4511 goto err_unpin_maps;
4517 while ((map = bpf_map__prev(map, obj))) {
4521 bpf_map__unpin(map, NULL);
4527 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
4529 struct bpf_map *map;
4535 bpf_object__for_each_map(map, obj) {
4536 char *pin_path = NULL;
4542 len = snprintf(buf, PATH_MAX, "%s/%s", path,
4543 bpf_map__name(map));
4546 else if (len >= PATH_MAX)
4547 return -ENAMETOOLONG;
4549 } else if (!map->pin_path) {
4553 err = bpf_map__unpin(map, pin_path);
4561 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
4563 struct bpf_program *prog;
4570 pr_warn("object not yet loaded; load it first\n");
4574 bpf_object__for_each_program(prog, obj) {
4578 len = snprintf(buf, PATH_MAX, "%s/%s", path,
4582 goto err_unpin_programs;
4583 } else if (len >= PATH_MAX) {
4584 err = -ENAMETOOLONG;
4585 goto err_unpin_programs;
4588 err = bpf_program__pin(prog, buf);
4590 goto err_unpin_programs;
4596 while ((prog = bpf_program__prev(prog, obj))) {
4600 len = snprintf(buf, PATH_MAX, "%s/%s", path,
4604 else if (len >= PATH_MAX)
4607 bpf_program__unpin(prog, buf);
4613 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
4615 struct bpf_program *prog;
4621 bpf_object__for_each_program(prog, obj) {
4625 len = snprintf(buf, PATH_MAX, "%s/%s", path,
4629 else if (len >= PATH_MAX)
4630 return -ENAMETOOLONG;
4632 err = bpf_program__unpin(prog, buf);
4640 int bpf_object__pin(struct bpf_object *obj, const char *path)
4644 err = bpf_object__pin_maps(obj, path);
4648 err = bpf_object__pin_programs(obj, path);
4650 bpf_object__unpin_maps(obj, path);
4657 void bpf_object__close(struct bpf_object *obj)
4664 if (obj->clear_priv)
4665 obj->clear_priv(obj, obj->priv);
4667 bpf_object__elf_finish(obj);
4668 bpf_object__unload(obj);
4669 btf__free(obj->btf);
4670 btf_ext__free(obj->btf_ext);
4672 for (i = 0; i < obj->nr_maps; i++) {
4673 zfree(&obj->maps[i].name);
4674 zfree(&obj->maps[i].pin_path);
4675 if (obj->maps[i].clear_priv)
4676 obj->maps[i].clear_priv(&obj->maps[i],
4678 obj->maps[i].priv = NULL;
4679 obj->maps[i].clear_priv = NULL;
4682 zfree(&obj->sections.rodata);
4683 zfree(&obj->sections.data);
4687 if (obj->programs && obj->nr_programs) {
4688 for (i = 0; i < obj->nr_programs; i++)
4689 bpf_program__exit(&obj->programs[i]);
4691 zfree(&obj->programs);
4693 list_del(&obj->list);
4698 bpf_object__next(struct bpf_object *prev)
4700 struct bpf_object *next;
4703 next = list_first_entry(&bpf_objects_list,
4707 next = list_next_entry(prev, list);
4709 /* Empty list is noticed here so don't need checking on entry. */
4710 if (&next->list == &bpf_objects_list)
4716 const char *bpf_object__name(const struct bpf_object *obj)
4718 return obj ? obj->name : ERR_PTR(-EINVAL);
4721 unsigned int bpf_object__kversion(const struct bpf_object *obj)
4723 return obj ? obj->kern_version : 0;
4726 struct btf *bpf_object__btf(const struct bpf_object *obj)
4728 return obj ? obj->btf : NULL;
4731 int bpf_object__btf_fd(const struct bpf_object *obj)
4733 return obj->btf ? btf__fd(obj->btf) : -1;
4736 int bpf_object__set_priv(struct bpf_object *obj, void *priv,
4737 bpf_object_clear_priv_t clear_priv)
4739 if (obj->priv && obj->clear_priv)
4740 obj->clear_priv(obj, obj->priv);
4743 obj->clear_priv = clear_priv;
4747 void *bpf_object__priv(const struct bpf_object *obj)
4749 return obj ? obj->priv : ERR_PTR(-EINVAL);
4752 static struct bpf_program *
4753 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
4756 size_t nr_programs = obj->nr_programs;
4763 /* Iter from the beginning */
4764 return forward ? &obj->programs[0] :
4765 &obj->programs[nr_programs - 1];
4767 if (p->obj != obj) {
4768 pr_warn("error: program handler doesn't match object\n");
4772 idx = (p - obj->programs) + (forward ? 1 : -1);
4773 if (idx >= obj->nr_programs || idx < 0)
4775 return &obj->programs[idx];
4778 struct bpf_program *
4779 bpf_program__next(struct bpf_program *prev, const struct bpf_object *obj)
4781 struct bpf_program *prog = prev;
4784 prog = __bpf_program__iter(prog, obj, true);
4785 } while (prog && bpf_program__is_function_storage(prog, obj));
4790 struct bpf_program *
4791 bpf_program__prev(struct bpf_program *next, const struct bpf_object *obj)
4793 struct bpf_program *prog = next;
4796 prog = __bpf_program__iter(prog, obj, false);
4797 } while (prog && bpf_program__is_function_storage(prog, obj));
4802 int bpf_program__set_priv(struct bpf_program *prog, void *priv,
4803 bpf_program_clear_priv_t clear_priv)
4805 if (prog->priv && prog->clear_priv)
4806 prog->clear_priv(prog, prog->priv);
4809 prog->clear_priv = clear_priv;
4813 void *bpf_program__priv(const struct bpf_program *prog)
4815 return prog ? prog->priv : ERR_PTR(-EINVAL);
4818 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
4820 prog->prog_ifindex = ifindex;
4823 const char *bpf_program__title(const struct bpf_program *prog, bool needs_copy)
4827 title = prog->section_name;
4829 title = strdup(title);
4831 pr_warn("failed to strdup program title\n");
4832 return ERR_PTR(-ENOMEM);
4839 int bpf_program__fd(const struct bpf_program *prog)
4841 return bpf_program__nth_fd(prog, 0);
4844 size_t bpf_program__size(const struct bpf_program *prog)
4846 return prog->insns_cnt * sizeof(struct bpf_insn);
4849 int bpf_program__set_prep(struct bpf_program *prog, int nr_instances,
4850 bpf_program_prep_t prep)
4854 if (nr_instances <= 0 || !prep)
4857 if (prog->instances.nr > 0 || prog->instances.fds) {
4858 pr_warn("Can't set pre-processor after loading\n");
4862 instances_fds = malloc(sizeof(int) * nr_instances);
4863 if (!instances_fds) {
4864 pr_warn("alloc memory failed for fds\n");
4868 /* fill all fd with -1 */
4869 memset(instances_fds, -1, sizeof(int) * nr_instances);
4871 prog->instances.nr = nr_instances;
4872 prog->instances.fds = instances_fds;
4873 prog->preprocessor = prep;
4877 int bpf_program__nth_fd(const struct bpf_program *prog, int n)
4884 if (n >= prog->instances.nr || n < 0) {
4885 pr_warn("Can't get the %dth fd from program %s: only %d instances\n",
4886 n, prog->section_name, prog->instances.nr);
4890 fd = prog->instances.fds[n];
4892 pr_warn("%dth instance of program '%s' is invalid\n",
4893 n, prog->section_name);
4900 enum bpf_prog_type bpf_program__get_type(struct bpf_program *prog)
4905 void bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
4910 static bool bpf_program__is_type(const struct bpf_program *prog,
4911 enum bpf_prog_type type)
4913 return prog ? (prog->type == type) : false;
4916 #define BPF_PROG_TYPE_FNS(NAME, TYPE) \
4917 int bpf_program__set_##NAME(struct bpf_program *prog) \
4921 bpf_program__set_type(prog, TYPE); \
4925 bool bpf_program__is_##NAME(const struct bpf_program *prog) \
4927 return bpf_program__is_type(prog, TYPE); \
4930 BPF_PROG_TYPE_FNS(socket_filter, BPF_PROG_TYPE_SOCKET_FILTER);
4931 BPF_PROG_TYPE_FNS(kprobe, BPF_PROG_TYPE_KPROBE);
4932 BPF_PROG_TYPE_FNS(sched_cls, BPF_PROG_TYPE_SCHED_CLS);
4933 BPF_PROG_TYPE_FNS(sched_act, BPF_PROG_TYPE_SCHED_ACT);
4934 BPF_PROG_TYPE_FNS(tracepoint, BPF_PROG_TYPE_TRACEPOINT);
4935 BPF_PROG_TYPE_FNS(raw_tracepoint, BPF_PROG_TYPE_RAW_TRACEPOINT);
4936 BPF_PROG_TYPE_FNS(xdp, BPF_PROG_TYPE_XDP);
4937 BPF_PROG_TYPE_FNS(perf_event, BPF_PROG_TYPE_PERF_EVENT);
4938 BPF_PROG_TYPE_FNS(tracing, BPF_PROG_TYPE_TRACING);
4940 enum bpf_attach_type
4941 bpf_program__get_expected_attach_type(struct bpf_program *prog)
4943 return prog->expected_attach_type;
4946 void bpf_program__set_expected_attach_type(struct bpf_program *prog,
4947 enum bpf_attach_type type)
4949 prog->expected_attach_type = type;
4952 #define BPF_PROG_SEC_IMPL(string, ptype, eatype, is_attachable, btf, atype) \
4953 { string, sizeof(string) - 1, ptype, eatype, is_attachable, btf, atype }
4955 /* Programs that can NOT be attached. */
4956 #define BPF_PROG_SEC(string, ptype) BPF_PROG_SEC_IMPL(string, ptype, 0, 0, 0, 0)
4958 /* Programs that can be attached. */
4959 #define BPF_APROG_SEC(string, ptype, atype) \
4960 BPF_PROG_SEC_IMPL(string, ptype, 0, 1, 0, atype)
4962 /* Programs that must specify expected attach type at load time. */
4963 #define BPF_EAPROG_SEC(string, ptype, eatype) \
4964 BPF_PROG_SEC_IMPL(string, ptype, eatype, 1, 0, eatype)
4966 /* Programs that use BTF to identify attach point */
4967 #define BPF_PROG_BTF(string, ptype, eatype) \
4968 BPF_PROG_SEC_IMPL(string, ptype, eatype, 0, 1, 0)
4970 /* Programs that can be attached but attach type can't be identified by section
4971 * name. Kept for backward compatibility.
4973 #define BPF_APROG_COMPAT(string, ptype) BPF_PROG_SEC(string, ptype)
4975 static const struct {
4978 enum bpf_prog_type prog_type;
4979 enum bpf_attach_type expected_attach_type;
4982 enum bpf_attach_type attach_type;
4983 } section_names[] = {
4984 BPF_PROG_SEC("socket", BPF_PROG_TYPE_SOCKET_FILTER),
4985 BPF_PROG_SEC("kprobe/", BPF_PROG_TYPE_KPROBE),
4986 BPF_PROG_SEC("uprobe/", BPF_PROG_TYPE_KPROBE),
4987 BPF_PROG_SEC("kretprobe/", BPF_PROG_TYPE_KPROBE),
4988 BPF_PROG_SEC("uretprobe/", BPF_PROG_TYPE_KPROBE),
4989 BPF_PROG_SEC("classifier", BPF_PROG_TYPE_SCHED_CLS),
4990 BPF_PROG_SEC("action", BPF_PROG_TYPE_SCHED_ACT),
4991 BPF_PROG_SEC("tracepoint/", BPF_PROG_TYPE_TRACEPOINT),
4992 BPF_PROG_SEC("tp/", BPF_PROG_TYPE_TRACEPOINT),
4993 BPF_PROG_SEC("raw_tracepoint/", BPF_PROG_TYPE_RAW_TRACEPOINT),
4994 BPF_PROG_SEC("raw_tp/", BPF_PROG_TYPE_RAW_TRACEPOINT),
4995 BPF_PROG_BTF("tp_btf/", BPF_PROG_TYPE_TRACING,
4997 BPF_PROG_BTF("fentry/", BPF_PROG_TYPE_TRACING,
4999 BPF_PROG_BTF("fexit/", BPF_PROG_TYPE_TRACING,
5001 BPF_PROG_SEC("xdp", BPF_PROG_TYPE_XDP),
5002 BPF_PROG_SEC("perf_event", BPF_PROG_TYPE_PERF_EVENT),
5003 BPF_PROG_SEC("lwt_in", BPF_PROG_TYPE_LWT_IN),
5004 BPF_PROG_SEC("lwt_out", BPF_PROG_TYPE_LWT_OUT),
5005 BPF_PROG_SEC("lwt_xmit", BPF_PROG_TYPE_LWT_XMIT),
5006 BPF_PROG_SEC("lwt_seg6local", BPF_PROG_TYPE_LWT_SEG6LOCAL),
5007 BPF_APROG_SEC("cgroup_skb/ingress", BPF_PROG_TYPE_CGROUP_SKB,
5008 BPF_CGROUP_INET_INGRESS),
5009 BPF_APROG_SEC("cgroup_skb/egress", BPF_PROG_TYPE_CGROUP_SKB,
5010 BPF_CGROUP_INET_EGRESS),
5011 BPF_APROG_COMPAT("cgroup/skb", BPF_PROG_TYPE_CGROUP_SKB),
5012 BPF_APROG_SEC("cgroup/sock", BPF_PROG_TYPE_CGROUP_SOCK,
5013 BPF_CGROUP_INET_SOCK_CREATE),
5014 BPF_EAPROG_SEC("cgroup/post_bind4", BPF_PROG_TYPE_CGROUP_SOCK,
5015 BPF_CGROUP_INET4_POST_BIND),
5016 BPF_EAPROG_SEC("cgroup/post_bind6", BPF_PROG_TYPE_CGROUP_SOCK,
5017 BPF_CGROUP_INET6_POST_BIND),
5018 BPF_APROG_SEC("cgroup/dev", BPF_PROG_TYPE_CGROUP_DEVICE,
5020 BPF_APROG_SEC("sockops", BPF_PROG_TYPE_SOCK_OPS,
5021 BPF_CGROUP_SOCK_OPS),
5022 BPF_APROG_SEC("sk_skb/stream_parser", BPF_PROG_TYPE_SK_SKB,
5023 BPF_SK_SKB_STREAM_PARSER),
5024 BPF_APROG_SEC("sk_skb/stream_verdict", BPF_PROG_TYPE_SK_SKB,
5025 BPF_SK_SKB_STREAM_VERDICT),
5026 BPF_APROG_COMPAT("sk_skb", BPF_PROG_TYPE_SK_SKB),
5027 BPF_APROG_SEC("sk_msg", BPF_PROG_TYPE_SK_MSG,
5028 BPF_SK_MSG_VERDICT),
5029 BPF_APROG_SEC("lirc_mode2", BPF_PROG_TYPE_LIRC_MODE2,
5031 BPF_APROG_SEC("flow_dissector", BPF_PROG_TYPE_FLOW_DISSECTOR,
5032 BPF_FLOW_DISSECTOR),
5033 BPF_EAPROG_SEC("cgroup/bind4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
5034 BPF_CGROUP_INET4_BIND),
5035 BPF_EAPROG_SEC("cgroup/bind6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
5036 BPF_CGROUP_INET6_BIND),
5037 BPF_EAPROG_SEC("cgroup/connect4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
5038 BPF_CGROUP_INET4_CONNECT),
5039 BPF_EAPROG_SEC("cgroup/connect6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
5040 BPF_CGROUP_INET6_CONNECT),
5041 BPF_EAPROG_SEC("cgroup/sendmsg4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
5042 BPF_CGROUP_UDP4_SENDMSG),
5043 BPF_EAPROG_SEC("cgroup/sendmsg6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
5044 BPF_CGROUP_UDP6_SENDMSG),
5045 BPF_EAPROG_SEC("cgroup/recvmsg4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
5046 BPF_CGROUP_UDP4_RECVMSG),
5047 BPF_EAPROG_SEC("cgroup/recvmsg6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
5048 BPF_CGROUP_UDP6_RECVMSG),
5049 BPF_EAPROG_SEC("cgroup/sysctl", BPF_PROG_TYPE_CGROUP_SYSCTL,
5051 BPF_EAPROG_SEC("cgroup/getsockopt", BPF_PROG_TYPE_CGROUP_SOCKOPT,
5052 BPF_CGROUP_GETSOCKOPT),
5053 BPF_EAPROG_SEC("cgroup/setsockopt", BPF_PROG_TYPE_CGROUP_SOCKOPT,
5054 BPF_CGROUP_SETSOCKOPT),
5057 #undef BPF_PROG_SEC_IMPL
5059 #undef BPF_APROG_SEC
5060 #undef BPF_EAPROG_SEC
5061 #undef BPF_APROG_COMPAT
5063 #define MAX_TYPE_NAME_SIZE 32
5065 static char *libbpf_get_type_names(bool attach_type)
5067 int i, len = ARRAY_SIZE(section_names) * MAX_TYPE_NAME_SIZE;
5075 /* Forge string buf with all available names */
5076 for (i = 0; i < ARRAY_SIZE(section_names); i++) {
5077 if (attach_type && !section_names[i].is_attachable)
5080 if (strlen(buf) + strlen(section_names[i].sec) + 2 > len) {
5085 strcat(buf, section_names[i].sec);
5091 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
5092 enum bpf_attach_type *expected_attach_type)
5100 for (i = 0; i < ARRAY_SIZE(section_names); i++) {
5101 if (strncmp(name, section_names[i].sec, section_names[i].len))
5103 *prog_type = section_names[i].prog_type;
5104 *expected_attach_type = section_names[i].expected_attach_type;
5107 pr_warn("failed to guess program type from ELF section '%s'\n", name);
5108 type_names = libbpf_get_type_names(false);
5109 if (type_names != NULL) {
5110 pr_info("supported section(type) names are:%s\n", type_names);
5117 #define BTF_PREFIX "btf_trace_"
5118 int libbpf_find_vmlinux_btf_id(const char *name,
5119 enum bpf_attach_type attach_type)
5121 struct btf *btf = bpf_core_find_kernel_btf();
5122 char raw_tp_btf[128] = BTF_PREFIX;
5123 char *dst = raw_tp_btf + sizeof(BTF_PREFIX) - 1;
5124 const char *btf_name;
5129 pr_warn("vmlinux BTF is not found\n");
5133 if (attach_type == BPF_TRACE_RAW_TP) {
5134 /* prepend "btf_trace_" prefix per kernel convention */
5135 strncat(dst, name, sizeof(raw_tp_btf) - sizeof(BTF_PREFIX));
5136 btf_name = raw_tp_btf;
5137 kind = BTF_KIND_TYPEDEF;
5140 kind = BTF_KIND_FUNC;
5142 err = btf__find_by_name_kind(btf, btf_name, kind);
5147 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd)
5149 struct bpf_prog_info_linear *info_linear;
5150 struct bpf_prog_info *info;
5151 struct btf *btf = NULL;
5154 info_linear = bpf_program__get_prog_info_linear(attach_prog_fd, 0);
5155 if (IS_ERR_OR_NULL(info_linear)) {
5156 pr_warn("failed get_prog_info_linear for FD %d\n",
5160 info = &info_linear->info;
5161 if (!info->btf_id) {
5162 pr_warn("The target program doesn't have BTF\n");
5165 if (btf__get_from_id(info->btf_id, &btf)) {
5166 pr_warn("Failed to get BTF of the program\n");
5169 err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
5172 pr_warn("%s is not found in prog's BTF\n", name);
5180 static int libbpf_find_attach_btf_id(const char *name,
5181 enum bpf_attach_type attach_type,
5182 __u32 attach_prog_fd)
5189 for (i = 0; i < ARRAY_SIZE(section_names); i++) {
5190 if (!section_names[i].is_attach_btf)
5192 if (strncmp(name, section_names[i].sec, section_names[i].len))
5195 err = libbpf_find_prog_btf_id(name + section_names[i].len,
5198 err = libbpf_find_vmlinux_btf_id(name + section_names[i].len,
5201 pr_warn("%s is not found in vmlinux BTF\n", name);
5204 pr_warn("failed to identify btf_id based on ELF section name '%s'\n", name);
5208 int libbpf_attach_type_by_name(const char *name,
5209 enum bpf_attach_type *attach_type)
5217 for (i = 0; i < ARRAY_SIZE(section_names); i++) {
5218 if (strncmp(name, section_names[i].sec, section_names[i].len))
5220 if (!section_names[i].is_attachable)
5222 *attach_type = section_names[i].attach_type;
5225 pr_warn("failed to guess attach type based on ELF section name '%s'\n", name);
5226 type_names = libbpf_get_type_names(true);
5227 if (type_names != NULL) {
5228 pr_info("attachable section(type) names are:%s\n", type_names);
5235 int bpf_map__fd(const struct bpf_map *map)
5237 return map ? map->fd : -EINVAL;
5240 const struct bpf_map_def *bpf_map__def(const struct bpf_map *map)
5242 return map ? &map->def : ERR_PTR(-EINVAL);
5245 const char *bpf_map__name(const struct bpf_map *map)
5247 return map ? map->name : NULL;
5250 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
5252 return map ? map->btf_key_type_id : 0;
5255 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
5257 return map ? map->btf_value_type_id : 0;
5260 int bpf_map__set_priv(struct bpf_map *map, void *priv,
5261 bpf_map_clear_priv_t clear_priv)
5267 if (map->clear_priv)
5268 map->clear_priv(map, map->priv);
5272 map->clear_priv = clear_priv;
5276 void *bpf_map__priv(const struct bpf_map *map)
5278 return map ? map->priv : ERR_PTR(-EINVAL);
5281 bool bpf_map__is_offload_neutral(const struct bpf_map *map)
5283 return map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY;
5286 bool bpf_map__is_internal(const struct bpf_map *map)
5288 return map->libbpf_type != LIBBPF_MAP_UNSPEC;
5291 void bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
5293 map->map_ifindex = ifindex;
5296 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
5298 if (!bpf_map_type__is_map_in_map(map->def.type)) {
5299 pr_warn("error: unsupported map type\n");
5302 if (map->inner_map_fd != -1) {
5303 pr_warn("error: inner_map_fd already specified\n");
5306 map->inner_map_fd = fd;
5310 static struct bpf_map *
5311 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
5314 struct bpf_map *s, *e;
5316 if (!obj || !obj->maps)
5320 e = obj->maps + obj->nr_maps;
5322 if ((m < s) || (m >= e)) {
5323 pr_warn("error in %s: map handler doesn't belong to object\n",
5328 idx = (m - obj->maps) + i;
5329 if (idx >= obj->nr_maps || idx < 0)
5331 return &obj->maps[idx];
5335 bpf_map__next(const struct bpf_map *prev, const struct bpf_object *obj)
5340 return __bpf_map__iter(prev, obj, 1);
5344 bpf_map__prev(const struct bpf_map *next, const struct bpf_object *obj)
5349 return obj->maps + obj->nr_maps - 1;
5352 return __bpf_map__iter(next, obj, -1);
5356 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
5358 struct bpf_map *pos;
5360 bpf_object__for_each_map(pos, obj) {
5361 if (pos->name && !strcmp(pos->name, name))
5368 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
5370 return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
5374 bpf_object__find_map_by_offset(struct bpf_object *obj, size_t offset)
5376 return ERR_PTR(-ENOTSUP);
5379 long libbpf_get_error(const void *ptr)
5381 return PTR_ERR_OR_ZERO(ptr);
5384 int bpf_prog_load(const char *file, enum bpf_prog_type type,
5385 struct bpf_object **pobj, int *prog_fd)
5387 struct bpf_prog_load_attr attr;
5389 memset(&attr, 0, sizeof(struct bpf_prog_load_attr));
5391 attr.prog_type = type;
5392 attr.expected_attach_type = 0;
5394 return bpf_prog_load_xattr(&attr, pobj, prog_fd);
5397 int bpf_prog_load_xattr(const struct bpf_prog_load_attr *attr,
5398 struct bpf_object **pobj, int *prog_fd)
5400 struct bpf_object_open_attr open_attr = {};
5401 struct bpf_program *prog, *first_prog = NULL;
5402 struct bpf_object *obj;
5403 struct bpf_map *map;
5411 open_attr.file = attr->file;
5412 open_attr.prog_type = attr->prog_type;
5414 obj = bpf_object__open_xattr(&open_attr);
5415 if (IS_ERR_OR_NULL(obj))
5418 bpf_object__for_each_program(prog, obj) {
5419 enum bpf_attach_type attach_type = attr->expected_attach_type;
5421 * to preserve backwards compatibility, bpf_prog_load treats
5422 * attr->prog_type, if specified, as an override to whatever
5423 * bpf_object__open guessed
5425 if (attr->prog_type != BPF_PROG_TYPE_UNSPEC) {
5426 bpf_program__set_type(prog, attr->prog_type);
5427 bpf_program__set_expected_attach_type(prog,
5430 if (bpf_program__get_type(prog) == BPF_PROG_TYPE_UNSPEC) {
5432 * we haven't guessed from section name and user
5433 * didn't provide a fallback type, too bad...
5435 bpf_object__close(obj);
5439 prog->prog_ifindex = attr->ifindex;
5440 prog->log_level = attr->log_level;
5441 prog->prog_flags = attr->prog_flags;
5446 bpf_object__for_each_map(map, obj) {
5447 if (!bpf_map__is_offload_neutral(map))
5448 map->map_ifindex = attr->ifindex;
5452 pr_warn("object file doesn't contain bpf program\n");
5453 bpf_object__close(obj);
5457 err = bpf_object__load(obj);
5459 bpf_object__close(obj);
5464 *prog_fd = bpf_program__fd(first_prog);
5469 int (*destroy)(struct bpf_link *link);
5472 int bpf_link__destroy(struct bpf_link *link)
5479 err = link->destroy(link);
5485 struct bpf_link_fd {
5486 struct bpf_link link; /* has to be at the top of struct */
5487 int fd; /* hook FD */
5490 static int bpf_link__destroy_perf_event(struct bpf_link *link)
5492 struct bpf_link_fd *l = (void *)link;
5495 err = ioctl(l->fd, PERF_EVENT_IOC_DISABLE, 0);
5503 struct bpf_link *bpf_program__attach_perf_event(struct bpf_program *prog,
5506 char errmsg[STRERR_BUFSIZE];
5507 struct bpf_link_fd *link;
5511 pr_warn("program '%s': invalid perf event FD %d\n",
5512 bpf_program__title(prog, false), pfd);
5513 return ERR_PTR(-EINVAL);
5515 prog_fd = bpf_program__fd(prog);
5517 pr_warn("program '%s': can't attach BPF program w/o FD (did you load it?)\n",
5518 bpf_program__title(prog, false));
5519 return ERR_PTR(-EINVAL);
5522 link = malloc(sizeof(*link));
5524 return ERR_PTR(-ENOMEM);
5525 link->link.destroy = &bpf_link__destroy_perf_event;
5528 if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
5531 pr_warn("program '%s': failed to attach to pfd %d: %s\n",
5532 bpf_program__title(prog, false), pfd,
5533 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
5534 return ERR_PTR(err);
5536 if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
5539 pr_warn("program '%s': failed to enable pfd %d: %s\n",
5540 bpf_program__title(prog, false), pfd,
5541 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
5542 return ERR_PTR(err);
5544 return (struct bpf_link *)link;
5548 * this function is expected to parse integer in the range of [0, 2^31-1] from
5549 * given file using scanf format string fmt. If actual parsed value is
5550 * negative, the result might be indistinguishable from error
5552 static int parse_uint_from_file(const char *file, const char *fmt)
5554 char buf[STRERR_BUFSIZE];
5558 f = fopen(file, "r");
5561 pr_debug("failed to open '%s': %s\n", file,
5562 libbpf_strerror_r(err, buf, sizeof(buf)));
5565 err = fscanf(f, fmt, &ret);
5567 err = err == EOF ? -EIO : -errno;
5568 pr_debug("failed to parse '%s': %s\n", file,
5569 libbpf_strerror_r(err, buf, sizeof(buf)));
5577 static int determine_kprobe_perf_type(void)
5579 const char *file = "/sys/bus/event_source/devices/kprobe/type";
5581 return parse_uint_from_file(file, "%d\n");
5584 static int determine_uprobe_perf_type(void)
5586 const char *file = "/sys/bus/event_source/devices/uprobe/type";
5588 return parse_uint_from_file(file, "%d\n");
5591 static int determine_kprobe_retprobe_bit(void)
5593 const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
5595 return parse_uint_from_file(file, "config:%d\n");
5598 static int determine_uprobe_retprobe_bit(void)
5600 const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
5602 return parse_uint_from_file(file, "config:%d\n");
5605 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
5606 uint64_t offset, int pid)
5608 struct perf_event_attr attr = {};
5609 char errmsg[STRERR_BUFSIZE];
5612 type = uprobe ? determine_uprobe_perf_type()
5613 : determine_kprobe_perf_type();
5615 pr_warn("failed to determine %s perf type: %s\n",
5616 uprobe ? "uprobe" : "kprobe",
5617 libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
5621 int bit = uprobe ? determine_uprobe_retprobe_bit()
5622 : determine_kprobe_retprobe_bit();
5625 pr_warn("failed to determine %s retprobe bit: %s\n",
5626 uprobe ? "uprobe" : "kprobe",
5627 libbpf_strerror_r(bit, errmsg, sizeof(errmsg)));
5630 attr.config |= 1 << bit;
5632 attr.size = sizeof(attr);
5634 attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
5635 attr.config2 = offset; /* kprobe_addr or probe_offset */
5637 /* pid filter is meaningful only for uprobes */
5638 pfd = syscall(__NR_perf_event_open, &attr,
5639 pid < 0 ? -1 : pid /* pid */,
5640 pid == -1 ? 0 : -1 /* cpu */,
5641 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
5644 pr_warn("%s perf_event_open() failed: %s\n",
5645 uprobe ? "uprobe" : "kprobe",
5646 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
5652 struct bpf_link *bpf_program__attach_kprobe(struct bpf_program *prog,
5654 const char *func_name)
5656 char errmsg[STRERR_BUFSIZE];
5657 struct bpf_link *link;
5660 pfd = perf_event_open_probe(false /* uprobe */, retprobe, func_name,
5661 0 /* offset */, -1 /* pid */);
5663 pr_warn("program '%s': failed to create %s '%s' perf event: %s\n",
5664 bpf_program__title(prog, false),
5665 retprobe ? "kretprobe" : "kprobe", func_name,
5666 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
5667 return ERR_PTR(pfd);
5669 link = bpf_program__attach_perf_event(prog, pfd);
5672 err = PTR_ERR(link);
5673 pr_warn("program '%s': failed to attach to %s '%s': %s\n",
5674 bpf_program__title(prog, false),
5675 retprobe ? "kretprobe" : "kprobe", func_name,
5676 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
5682 struct bpf_link *bpf_program__attach_uprobe(struct bpf_program *prog,
5683 bool retprobe, pid_t pid,
5684 const char *binary_path,
5687 char errmsg[STRERR_BUFSIZE];
5688 struct bpf_link *link;
5691 pfd = perf_event_open_probe(true /* uprobe */, retprobe,
5692 binary_path, func_offset, pid);
5694 pr_warn("program '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
5695 bpf_program__title(prog, false),
5696 retprobe ? "uretprobe" : "uprobe",
5697 binary_path, func_offset,
5698 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
5699 return ERR_PTR(pfd);
5701 link = bpf_program__attach_perf_event(prog, pfd);
5704 err = PTR_ERR(link);
5705 pr_warn("program '%s': failed to attach to %s '%s:0x%zx': %s\n",
5706 bpf_program__title(prog, false),
5707 retprobe ? "uretprobe" : "uprobe",
5708 binary_path, func_offset,
5709 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
5715 static int determine_tracepoint_id(const char *tp_category,
5716 const char *tp_name)
5718 char file[PATH_MAX];
5721 ret = snprintf(file, sizeof(file),
5722 "/sys/kernel/debug/tracing/events/%s/%s/id",
5723 tp_category, tp_name);
5726 if (ret >= sizeof(file)) {
5727 pr_debug("tracepoint %s/%s path is too long\n",
5728 tp_category, tp_name);
5731 return parse_uint_from_file(file, "%d\n");
5734 static int perf_event_open_tracepoint(const char *tp_category,
5735 const char *tp_name)
5737 struct perf_event_attr attr = {};
5738 char errmsg[STRERR_BUFSIZE];
5739 int tp_id, pfd, err;
5741 tp_id = determine_tracepoint_id(tp_category, tp_name);
5743 pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
5744 tp_category, tp_name,
5745 libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
5749 attr.type = PERF_TYPE_TRACEPOINT;
5750 attr.size = sizeof(attr);
5751 attr.config = tp_id;
5753 pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
5754 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
5757 pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
5758 tp_category, tp_name,
5759 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
5765 struct bpf_link *bpf_program__attach_tracepoint(struct bpf_program *prog,
5766 const char *tp_category,
5767 const char *tp_name)
5769 char errmsg[STRERR_BUFSIZE];
5770 struct bpf_link *link;
5773 pfd = perf_event_open_tracepoint(tp_category, tp_name);
5775 pr_warn("program '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
5776 bpf_program__title(prog, false),
5777 tp_category, tp_name,
5778 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
5779 return ERR_PTR(pfd);
5781 link = bpf_program__attach_perf_event(prog, pfd);
5784 err = PTR_ERR(link);
5785 pr_warn("program '%s': failed to attach to tracepoint '%s/%s': %s\n",
5786 bpf_program__title(prog, false),
5787 tp_category, tp_name,
5788 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
5794 static int bpf_link__destroy_fd(struct bpf_link *link)
5796 struct bpf_link_fd *l = (void *)link;
5798 return close(l->fd);
5801 struct bpf_link *bpf_program__attach_raw_tracepoint(struct bpf_program *prog,
5802 const char *tp_name)
5804 char errmsg[STRERR_BUFSIZE];
5805 struct bpf_link_fd *link;
5808 prog_fd = bpf_program__fd(prog);
5810 pr_warn("program '%s': can't attach before loaded\n",
5811 bpf_program__title(prog, false));
5812 return ERR_PTR(-EINVAL);
5815 link = malloc(sizeof(*link));
5817 return ERR_PTR(-ENOMEM);
5818 link->link.destroy = &bpf_link__destroy_fd;
5820 pfd = bpf_raw_tracepoint_open(tp_name, prog_fd);
5824 pr_warn("program '%s': failed to attach to raw tracepoint '%s': %s\n",
5825 bpf_program__title(prog, false), tp_name,
5826 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
5827 return ERR_PTR(pfd);
5830 return (struct bpf_link *)link;
5833 struct bpf_link *bpf_program__attach_trace(struct bpf_program *prog)
5835 char errmsg[STRERR_BUFSIZE];
5836 struct bpf_link_fd *link;
5839 prog_fd = bpf_program__fd(prog);
5841 pr_warn("program '%s': can't attach before loaded\n",
5842 bpf_program__title(prog, false));
5843 return ERR_PTR(-EINVAL);
5846 link = malloc(sizeof(*link));
5848 return ERR_PTR(-ENOMEM);
5849 link->link.destroy = &bpf_link__destroy_fd;
5851 pfd = bpf_raw_tracepoint_open(NULL, prog_fd);
5855 pr_warn("program '%s': failed to attach to trace: %s\n",
5856 bpf_program__title(prog, false),
5857 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
5858 return ERR_PTR(pfd);
5861 return (struct bpf_link *)link;
5864 enum bpf_perf_event_ret
5865 bpf_perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
5866 void **copy_mem, size_t *copy_size,
5867 bpf_perf_event_print_t fn, void *private_data)
5869 struct perf_event_mmap_page *header = mmap_mem;
5870 __u64 data_head = ring_buffer_read_head(header);
5871 __u64 data_tail = header->data_tail;
5872 void *base = ((__u8 *)header) + page_size;
5873 int ret = LIBBPF_PERF_EVENT_CONT;
5874 struct perf_event_header *ehdr;
5877 while (data_head != data_tail) {
5878 ehdr = base + (data_tail & (mmap_size - 1));
5879 ehdr_size = ehdr->size;
5881 if (((void *)ehdr) + ehdr_size > base + mmap_size) {
5882 void *copy_start = ehdr;
5883 size_t len_first = base + mmap_size - copy_start;
5884 size_t len_secnd = ehdr_size - len_first;
5886 if (*copy_size < ehdr_size) {
5888 *copy_mem = malloc(ehdr_size);
5891 ret = LIBBPF_PERF_EVENT_ERROR;
5894 *copy_size = ehdr_size;
5897 memcpy(*copy_mem, copy_start, len_first);
5898 memcpy(*copy_mem + len_first, base, len_secnd);
5902 ret = fn(ehdr, private_data);
5903 data_tail += ehdr_size;
5904 if (ret != LIBBPF_PERF_EVENT_CONT)
5908 ring_buffer_write_tail(header, data_tail);
5914 struct perf_buffer_params {
5915 struct perf_event_attr *attr;
5916 /* if event_cb is specified, it takes precendence */
5917 perf_buffer_event_fn event_cb;
5918 /* sample_cb and lost_cb are higher-level common-case callbacks */
5919 perf_buffer_sample_fn sample_cb;
5920 perf_buffer_lost_fn lost_cb;
5927 struct perf_cpu_buf {
5928 struct perf_buffer *pb;
5929 void *base; /* mmap()'ed memory */
5930 void *buf; /* for reconstructing segmented data */
5937 struct perf_buffer {
5938 perf_buffer_event_fn event_cb;
5939 perf_buffer_sample_fn sample_cb;
5940 perf_buffer_lost_fn lost_cb;
5941 void *ctx; /* passed into callbacks */
5945 struct perf_cpu_buf **cpu_bufs;
5946 struct epoll_event *events;
5948 int epoll_fd; /* perf event FD */
5949 int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
5952 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
5953 struct perf_cpu_buf *cpu_buf)
5957 if (cpu_buf->base &&
5958 munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
5959 pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
5960 if (cpu_buf->fd >= 0) {
5961 ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
5968 void perf_buffer__free(struct perf_buffer *pb)
5975 for (i = 0; i < pb->cpu_cnt && pb->cpu_bufs[i]; i++) {
5976 struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
5978 bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
5979 perf_buffer__free_cpu_buf(pb, cpu_buf);
5983 if (pb->epoll_fd >= 0)
5984 close(pb->epoll_fd);
5989 static struct perf_cpu_buf *
5990 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
5991 int cpu, int map_key)
5993 struct perf_cpu_buf *cpu_buf;
5994 char msg[STRERR_BUFSIZE];
5997 cpu_buf = calloc(1, sizeof(*cpu_buf));
5999 return ERR_PTR(-ENOMEM);
6003 cpu_buf->map_key = map_key;
6005 cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
6006 -1, PERF_FLAG_FD_CLOEXEC);
6007 if (cpu_buf->fd < 0) {
6009 pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
6010 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
6014 cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
6015 PROT_READ | PROT_WRITE, MAP_SHARED,
6017 if (cpu_buf->base == MAP_FAILED) {
6018 cpu_buf->base = NULL;
6020 pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
6021 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
6025 if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
6027 pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
6028 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
6035 perf_buffer__free_cpu_buf(pb, cpu_buf);
6036 return (struct perf_cpu_buf *)ERR_PTR(err);
6039 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
6040 struct perf_buffer_params *p);
6042 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
6043 const struct perf_buffer_opts *opts)
6045 struct perf_buffer_params p = {};
6046 struct perf_event_attr attr = { 0, };
6048 attr.config = PERF_COUNT_SW_BPF_OUTPUT,
6049 attr.type = PERF_TYPE_SOFTWARE;
6050 attr.sample_type = PERF_SAMPLE_RAW;
6051 attr.sample_period = 1;
6052 attr.wakeup_events = 1;
6055 p.sample_cb = opts ? opts->sample_cb : NULL;
6056 p.lost_cb = opts ? opts->lost_cb : NULL;
6057 p.ctx = opts ? opts->ctx : NULL;
6059 return __perf_buffer__new(map_fd, page_cnt, &p);
6062 struct perf_buffer *
6063 perf_buffer__new_raw(int map_fd, size_t page_cnt,
6064 const struct perf_buffer_raw_opts *opts)
6066 struct perf_buffer_params p = {};
6068 p.attr = opts->attr;
6069 p.event_cb = opts->event_cb;
6071 p.cpu_cnt = opts->cpu_cnt;
6072 p.cpus = opts->cpus;
6073 p.map_keys = opts->map_keys;
6075 return __perf_buffer__new(map_fd, page_cnt, &p);
6078 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
6079 struct perf_buffer_params *p)
6081 struct bpf_map_info map = {};
6082 char msg[STRERR_BUFSIZE];
6083 struct perf_buffer *pb;
6087 if (page_cnt & (page_cnt - 1)) {
6088 pr_warn("page count should be power of two, but is %zu\n",
6090 return ERR_PTR(-EINVAL);
6093 map_info_len = sizeof(map);
6094 err = bpf_obj_get_info_by_fd(map_fd, &map, &map_info_len);
6097 pr_warn("failed to get map info for map FD %d: %s\n",
6098 map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
6099 return ERR_PTR(err);
6102 if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
6103 pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
6105 return ERR_PTR(-EINVAL);
6108 pb = calloc(1, sizeof(*pb));
6110 return ERR_PTR(-ENOMEM);
6112 pb->event_cb = p->event_cb;
6113 pb->sample_cb = p->sample_cb;
6114 pb->lost_cb = p->lost_cb;
6117 pb->page_size = getpagesize();
6118 pb->mmap_size = pb->page_size * page_cnt;
6119 pb->map_fd = map_fd;
6121 pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
6122 if (pb->epoll_fd < 0) {
6124 pr_warn("failed to create epoll instance: %s\n",
6125 libbpf_strerror_r(err, msg, sizeof(msg)));
6129 if (p->cpu_cnt > 0) {
6130 pb->cpu_cnt = p->cpu_cnt;
6132 pb->cpu_cnt = libbpf_num_possible_cpus();
6133 if (pb->cpu_cnt < 0) {
6137 if (map.max_entries < pb->cpu_cnt)
6138 pb->cpu_cnt = map.max_entries;
6141 pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
6144 pr_warn("failed to allocate events: out of memory\n");
6147 pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
6148 if (!pb->cpu_bufs) {
6150 pr_warn("failed to allocate buffers: out of memory\n");
6154 for (i = 0; i < pb->cpu_cnt; i++) {
6155 struct perf_cpu_buf *cpu_buf;
6158 cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
6159 map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
6161 cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
6162 if (IS_ERR(cpu_buf)) {
6163 err = PTR_ERR(cpu_buf);
6167 pb->cpu_bufs[i] = cpu_buf;
6169 err = bpf_map_update_elem(pb->map_fd, &map_key,
6173 pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
6174 cpu, map_key, cpu_buf->fd,
6175 libbpf_strerror_r(err, msg, sizeof(msg)));
6179 pb->events[i].events = EPOLLIN;
6180 pb->events[i].data.ptr = cpu_buf;
6181 if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
6182 &pb->events[i]) < 0) {
6184 pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
6186 libbpf_strerror_r(err, msg, sizeof(msg)));
6195 perf_buffer__free(pb);
6196 return ERR_PTR(err);
6199 struct perf_sample_raw {
6200 struct perf_event_header header;
6205 struct perf_sample_lost {
6206 struct perf_event_header header;
6212 static enum bpf_perf_event_ret
6213 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
6215 struct perf_cpu_buf *cpu_buf = ctx;
6216 struct perf_buffer *pb = cpu_buf->pb;
6219 /* user wants full control over parsing perf event */
6221 return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
6224 case PERF_RECORD_SAMPLE: {
6225 struct perf_sample_raw *s = data;
6228 pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
6231 case PERF_RECORD_LOST: {
6232 struct perf_sample_lost *s = data;
6235 pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
6239 pr_warn("unknown perf sample type %d\n", e->type);
6240 return LIBBPF_PERF_EVENT_ERROR;
6242 return LIBBPF_PERF_EVENT_CONT;
6245 static int perf_buffer__process_records(struct perf_buffer *pb,
6246 struct perf_cpu_buf *cpu_buf)
6248 enum bpf_perf_event_ret ret;
6250 ret = bpf_perf_event_read_simple(cpu_buf->base, pb->mmap_size,
6251 pb->page_size, &cpu_buf->buf,
6253 perf_buffer__process_record, cpu_buf);
6254 if (ret != LIBBPF_PERF_EVENT_CONT)
6259 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
6263 cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
6264 for (i = 0; i < cnt; i++) {
6265 struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
6267 err = perf_buffer__process_records(pb, cpu_buf);
6269 pr_warn("error while processing records: %d\n", err);
6273 return cnt < 0 ? -errno : cnt;
6276 struct bpf_prog_info_array_desc {
6277 int array_offset; /* e.g. offset of jited_prog_insns */
6278 int count_offset; /* e.g. offset of jited_prog_len */
6279 int size_offset; /* > 0: offset of rec size,
6280 * < 0: fix size of -size_offset
6284 static struct bpf_prog_info_array_desc bpf_prog_info_array_desc[] = {
6285 [BPF_PROG_INFO_JITED_INSNS] = {
6286 offsetof(struct bpf_prog_info, jited_prog_insns),
6287 offsetof(struct bpf_prog_info, jited_prog_len),
6290 [BPF_PROG_INFO_XLATED_INSNS] = {
6291 offsetof(struct bpf_prog_info, xlated_prog_insns),
6292 offsetof(struct bpf_prog_info, xlated_prog_len),
6295 [BPF_PROG_INFO_MAP_IDS] = {
6296 offsetof(struct bpf_prog_info, map_ids),
6297 offsetof(struct bpf_prog_info, nr_map_ids),
6298 -(int)sizeof(__u32),
6300 [BPF_PROG_INFO_JITED_KSYMS] = {
6301 offsetof(struct bpf_prog_info, jited_ksyms),
6302 offsetof(struct bpf_prog_info, nr_jited_ksyms),
6303 -(int)sizeof(__u64),
6305 [BPF_PROG_INFO_JITED_FUNC_LENS] = {
6306 offsetof(struct bpf_prog_info, jited_func_lens),
6307 offsetof(struct bpf_prog_info, nr_jited_func_lens),
6308 -(int)sizeof(__u32),
6310 [BPF_PROG_INFO_FUNC_INFO] = {
6311 offsetof(struct bpf_prog_info, func_info),
6312 offsetof(struct bpf_prog_info, nr_func_info),
6313 offsetof(struct bpf_prog_info, func_info_rec_size),
6315 [BPF_PROG_INFO_LINE_INFO] = {
6316 offsetof(struct bpf_prog_info, line_info),
6317 offsetof(struct bpf_prog_info, nr_line_info),
6318 offsetof(struct bpf_prog_info, line_info_rec_size),
6320 [BPF_PROG_INFO_JITED_LINE_INFO] = {
6321 offsetof(struct bpf_prog_info, jited_line_info),
6322 offsetof(struct bpf_prog_info, nr_jited_line_info),
6323 offsetof(struct bpf_prog_info, jited_line_info_rec_size),
6325 [BPF_PROG_INFO_PROG_TAGS] = {
6326 offsetof(struct bpf_prog_info, prog_tags),
6327 offsetof(struct bpf_prog_info, nr_prog_tags),
6328 -(int)sizeof(__u8) * BPF_TAG_SIZE,
6333 static __u32 bpf_prog_info_read_offset_u32(struct bpf_prog_info *info,
6336 __u32 *array = (__u32 *)info;
6339 return array[offset / sizeof(__u32)];
6340 return -(int)offset;
6343 static __u64 bpf_prog_info_read_offset_u64(struct bpf_prog_info *info,
6346 __u64 *array = (__u64 *)info;
6349 return array[offset / sizeof(__u64)];
6350 return -(int)offset;
6353 static void bpf_prog_info_set_offset_u32(struct bpf_prog_info *info, int offset,
6356 __u32 *array = (__u32 *)info;
6359 array[offset / sizeof(__u32)] = val;
6362 static void bpf_prog_info_set_offset_u64(struct bpf_prog_info *info, int offset,
6365 __u64 *array = (__u64 *)info;
6368 array[offset / sizeof(__u64)] = val;
6371 struct bpf_prog_info_linear *
6372 bpf_program__get_prog_info_linear(int fd, __u64 arrays)
6374 struct bpf_prog_info_linear *info_linear;
6375 struct bpf_prog_info info = {};
6376 __u32 info_len = sizeof(info);
6381 if (arrays >> BPF_PROG_INFO_LAST_ARRAY)
6382 return ERR_PTR(-EINVAL);
6384 /* step 1: get array dimensions */
6385 err = bpf_obj_get_info_by_fd(fd, &info, &info_len);
6387 pr_debug("can't get prog info: %s", strerror(errno));
6388 return ERR_PTR(-EFAULT);
6391 /* step 2: calculate total size of all arrays */
6392 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
6393 bool include_array = (arrays & (1UL << i)) > 0;
6394 struct bpf_prog_info_array_desc *desc;
6397 desc = bpf_prog_info_array_desc + i;
6399 /* kernel is too old to support this field */
6400 if (info_len < desc->array_offset + sizeof(__u32) ||
6401 info_len < desc->count_offset + sizeof(__u32) ||
6402 (desc->size_offset > 0 && info_len < desc->size_offset))
6403 include_array = false;
6405 if (!include_array) {
6406 arrays &= ~(1UL << i); /* clear the bit */
6410 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
6411 size = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
6413 data_len += count * size;
6416 /* step 3: allocate continuous memory */
6417 data_len = roundup(data_len, sizeof(__u64));
6418 info_linear = malloc(sizeof(struct bpf_prog_info_linear) + data_len);
6420 return ERR_PTR(-ENOMEM);
6422 /* step 4: fill data to info_linear->info */
6423 info_linear->arrays = arrays;
6424 memset(&info_linear->info, 0, sizeof(info));
6425 ptr = info_linear->data;
6427 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
6428 struct bpf_prog_info_array_desc *desc;
6431 if ((arrays & (1UL << i)) == 0)
6434 desc = bpf_prog_info_array_desc + i;
6435 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
6436 size = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
6437 bpf_prog_info_set_offset_u32(&info_linear->info,
6438 desc->count_offset, count);
6439 bpf_prog_info_set_offset_u32(&info_linear->info,
6440 desc->size_offset, size);
6441 bpf_prog_info_set_offset_u64(&info_linear->info,
6444 ptr += count * size;
6447 /* step 5: call syscall again to get required arrays */
6448 err = bpf_obj_get_info_by_fd(fd, &info_linear->info, &info_len);
6450 pr_debug("can't get prog info: %s", strerror(errno));
6452 return ERR_PTR(-EFAULT);
6455 /* step 6: verify the data */
6456 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
6457 struct bpf_prog_info_array_desc *desc;
6460 if ((arrays & (1UL << i)) == 0)
6463 desc = bpf_prog_info_array_desc + i;
6464 v1 = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
6465 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
6466 desc->count_offset);
6468 pr_warn("%s: mismatch in element count\n", __func__);
6470 v1 = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
6471 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
6474 pr_warn("%s: mismatch in rec size\n", __func__);
6477 /* step 7: update info_len and data_len */
6478 info_linear->info_len = sizeof(struct bpf_prog_info);
6479 info_linear->data_len = data_len;
6484 void bpf_program__bpil_addr_to_offs(struct bpf_prog_info_linear *info_linear)
6488 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
6489 struct bpf_prog_info_array_desc *desc;
6492 if ((info_linear->arrays & (1UL << i)) == 0)
6495 desc = bpf_prog_info_array_desc + i;
6496 addr = bpf_prog_info_read_offset_u64(&info_linear->info,
6497 desc->array_offset);
6498 offs = addr - ptr_to_u64(info_linear->data);
6499 bpf_prog_info_set_offset_u64(&info_linear->info,
6500 desc->array_offset, offs);
6504 void bpf_program__bpil_offs_to_addr(struct bpf_prog_info_linear *info_linear)
6508 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
6509 struct bpf_prog_info_array_desc *desc;
6512 if ((info_linear->arrays & (1UL << i)) == 0)
6515 desc = bpf_prog_info_array_desc + i;
6516 offs = bpf_prog_info_read_offset_u64(&info_linear->info,
6517 desc->array_offset);
6518 addr = offs + ptr_to_u64(info_linear->data);
6519 bpf_prog_info_set_offset_u64(&info_linear->info,
6520 desc->array_offset, addr);
6524 int libbpf_num_possible_cpus(void)
6526 static const char *fcpu = "/sys/devices/system/cpu/possible";
6527 int len = 0, n = 0, il = 0, ir = 0;
6528 unsigned int start = 0, end = 0;
6535 tmp_cpus = READ_ONCE(cpus);
6539 fd = open(fcpu, O_RDONLY);
6542 pr_warn("Failed to open file %s: %s\n", fcpu, strerror(error));
6545 len = read(fd, buf, sizeof(buf));
6548 error = len ? errno : EINVAL;
6549 pr_warn("Failed to read # of possible cpus from %s: %s\n",
6550 fcpu, strerror(error));
6553 if (len == sizeof(buf)) {
6554 pr_warn("File %s size overflow\n", fcpu);
6559 for (ir = 0, tmp_cpus = 0; ir <= len; ir++) {
6560 /* Each sub string separated by ',' has format \d+-\d+ or \d+ */
6561 if (buf[ir] == ',' || buf[ir] == '\0') {
6563 n = sscanf(&buf[il], "%u-%u", &start, &end);
6565 pr_warn("Failed to get # CPUs from %s\n",
6568 } else if (n == 1) {
6571 tmp_cpus += end - start + 1;
6575 if (tmp_cpus <= 0) {
6576 pr_warn("Invalid #CPUs %d from %s\n", tmp_cpus, fcpu);
6580 WRITE_ONCE(cpus, tmp_cpus);