1 // SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
4 * Common eBPF ELF object loading operations.
6 * Copyright (C) 2013-2015 Alexei Starovoitov <ast@kernel.org>
7 * Copyright (C) 2015 Wang Nan <wangnan0@huawei.com>
8 * Copyright (C) 2015 Huawei Inc.
9 * Copyright (C) 2017 Nicira, Inc.
10 * Copyright (C) 2019 Isovalent, Inc.
26 #include <asm/unistd.h>
27 #include <linux/err.h>
28 #include <linux/kernel.h>
29 #include <linux/bpf.h>
30 #include <linux/btf.h>
31 #include <linux/filter.h>
32 #include <linux/list.h>
33 #include <linux/limits.h>
34 #include <linux/perf_event.h>
35 #include <linux/ring_buffer.h>
36 #include <linux/version.h>
37 #include <sys/epoll.h>
38 #include <sys/ioctl.h>
41 #include <sys/types.h>
43 #include <sys/utsname.h>
44 #include <tools/libc_compat.h>
51 #include "str_error.h"
52 #include "libbpf_internal.h"
60 #define BPF_FS_MAGIC 0xcafe4a11
63 /* vsprintf() in __base_pr() uses nonliteral format string. It may break
64 * compilation if user enables corresponding warning. Disable it explicitly.
66 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
68 #define __printf(a, b) __attribute__((format(printf, a, b)))
70 static int __base_pr(enum libbpf_print_level level, const char *format,
73 if (level == LIBBPF_DEBUG)
76 return vfprintf(stderr, format, args);
79 static libbpf_print_fn_t __libbpf_pr = __base_pr;
81 libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn)
83 libbpf_print_fn_t old_print_fn = __libbpf_pr;
90 void libbpf_print(enum libbpf_print_level level, const char *format, ...)
97 va_start(args, format);
98 __libbpf_pr(level, format, args);
102 #define STRERR_BUFSIZE 128
104 /* Copied from tools/perf/util/util.h */
106 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
110 # define zclose(fd) ({ \
113 ___err = close((fd)); \
118 #ifdef HAVE_LIBELF_MMAP_SUPPORT
119 # define LIBBPF_ELF_C_READ_MMAP ELF_C_READ_MMAP
121 # define LIBBPF_ELF_C_READ_MMAP ELF_C_READ
124 static inline __u64 ptr_to_u64(const void *ptr)
126 return (__u64) (unsigned long) ptr;
129 struct bpf_capabilities {
130 /* v4.14: kernel support for program & map names. */
132 /* v5.2: kernel support for global data sections. */
134 /* BTF_KIND_FUNC and BTF_KIND_FUNC_PROTO support */
136 /* BTF_KIND_VAR and BTF_KIND_DATASEC support */
138 /* BPF_F_MMAPABLE is supported for arrays */
143 * bpf_prog should be a better name but it has been used in
147 /* Index in elf obj file, for relocation use. */
152 /* section_name with / replaced by _; makes recursive pinning
153 * in bpf_object__pin_programs easier
156 struct bpf_insn *insns;
157 size_t insns_cnt, main_prog_cnt;
158 enum bpf_prog_type type;
177 bpf_program_prep_t preprocessor;
179 struct bpf_object *obj;
181 bpf_program_clear_priv_t clear_priv;
183 enum bpf_attach_type expected_attach_type;
185 __u32 attach_prog_fd;
187 __u32 func_info_rec_size;
190 struct bpf_capabilities *caps;
193 __u32 line_info_rec_size;
198 enum libbpf_map_type {
205 static const char * const libbpf_type_to_btf_name[] = {
206 [LIBBPF_MAP_DATA] = ".data",
207 [LIBBPF_MAP_BSS] = ".bss",
208 [LIBBPF_MAP_RODATA] = ".rodata",
218 struct bpf_map_def def;
219 __u32 btf_key_type_id;
220 __u32 btf_value_type_id;
222 bpf_map_clear_priv_t clear_priv;
223 enum libbpf_map_type libbpf_type;
234 static LIST_HEAD(bpf_objects_list);
237 char name[BPF_OBJ_NAME_LEN];
241 struct bpf_program *programs;
243 struct bpf_map *maps;
246 struct bpf_secdata sections;
249 bool has_pseudo_calls;
250 bool relaxed_core_relocs;
253 * Information when doing elf related work. Only valid if fd
280 * All loaded bpf_object is linked in a list, which is
281 * hidden to caller. bpf_objects__<func> handlers deal with
284 struct list_head list;
287 struct btf_ext *btf_ext;
290 bpf_object_clear_priv_t clear_priv;
292 struct bpf_capabilities caps;
296 #define obj_elf_valid(o) ((o)->efile.elf)
298 void bpf_program__unload(struct bpf_program *prog)
306 * If the object is opened but the program was never loaded,
307 * it is possible that prog->instances.nr == -1.
309 if (prog->instances.nr > 0) {
310 for (i = 0; i < prog->instances.nr; i++)
311 zclose(prog->instances.fds[i]);
312 } else if (prog->instances.nr != -1) {
313 pr_warn("Internal error: instances.nr is %d\n",
317 prog->instances.nr = -1;
318 zfree(&prog->instances.fds);
320 zfree(&prog->func_info);
321 zfree(&prog->line_info);
324 static void bpf_program__exit(struct bpf_program *prog)
329 if (prog->clear_priv)
330 prog->clear_priv(prog, prog->priv);
333 prog->clear_priv = NULL;
335 bpf_program__unload(prog);
337 zfree(&prog->section_name);
338 zfree(&prog->pin_name);
340 zfree(&prog->reloc_desc);
347 static char *__bpf_program__pin_name(struct bpf_program *prog)
351 name = p = strdup(prog->section_name);
352 while ((p = strchr(p, '/')))
359 bpf_program__init(void *data, size_t size, char *section_name, int idx,
360 struct bpf_program *prog)
362 const size_t bpf_insn_sz = sizeof(struct bpf_insn);
364 if (size == 0 || size % bpf_insn_sz) {
365 pr_warn("corrupted section '%s', size: %zu\n",
370 memset(prog, 0, sizeof(*prog));
372 prog->section_name = strdup(section_name);
373 if (!prog->section_name) {
374 pr_warn("failed to alloc name for prog under section(%d) %s\n",
379 prog->pin_name = __bpf_program__pin_name(prog);
380 if (!prog->pin_name) {
381 pr_warn("failed to alloc pin name for prog under section(%d) %s\n",
386 prog->insns = malloc(size);
388 pr_warn("failed to alloc insns for prog under section %s\n",
392 prog->insns_cnt = size / bpf_insn_sz;
393 memcpy(prog->insns, data, size);
395 prog->instances.fds = NULL;
396 prog->instances.nr = -1;
397 prog->type = BPF_PROG_TYPE_UNSPEC;
401 bpf_program__exit(prog);
406 bpf_object__add_program(struct bpf_object *obj, void *data, size_t size,
407 char *section_name, int idx)
409 struct bpf_program prog, *progs;
412 err = bpf_program__init(data, size, section_name, idx, &prog);
416 prog.caps = &obj->caps;
417 progs = obj->programs;
418 nr_progs = obj->nr_programs;
420 progs = reallocarray(progs, nr_progs + 1, sizeof(progs[0]));
423 * In this case the original obj->programs
424 * is still valid, so don't need special treat for
425 * bpf_close_object().
427 pr_warn("failed to alloc a new program under section '%s'\n",
429 bpf_program__exit(&prog);
433 pr_debug("found program %s\n", prog.section_name);
434 obj->programs = progs;
435 obj->nr_programs = nr_progs + 1;
437 progs[nr_progs] = prog;
442 bpf_object__init_prog_names(struct bpf_object *obj)
444 Elf_Data *symbols = obj->efile.symbols;
445 struct bpf_program *prog;
448 for (pi = 0; pi < obj->nr_programs; pi++) {
449 const char *name = NULL;
451 prog = &obj->programs[pi];
453 for (si = 0; si < symbols->d_size / sizeof(GElf_Sym) && !name;
457 if (!gelf_getsym(symbols, si, &sym))
459 if (sym.st_shndx != prog->idx)
461 if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL)
464 name = elf_strptr(obj->efile.elf,
465 obj->efile.strtabidx,
468 pr_warn("failed to get sym name string for prog %s\n",
470 return -LIBBPF_ERRNO__LIBELF;
474 if (!name && prog->idx == obj->efile.text_shndx)
478 pr_warn("failed to find sym for prog %s\n",
483 prog->name = strdup(name);
485 pr_warn("failed to allocate memory for prog sym %s\n",
494 static __u32 get_kernel_version(void)
496 __u32 major, minor, patch;
500 if (sscanf(info.release, "%u.%u.%u", &major, &minor, &patch) != 3)
502 return KERNEL_VERSION(major, minor, patch);
505 static struct bpf_object *bpf_object__new(const char *path,
508 const char *obj_name)
510 struct bpf_object *obj;
513 obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
515 pr_warn("alloc memory failed for %s\n", path);
516 return ERR_PTR(-ENOMEM);
519 strcpy(obj->path, path);
521 strncpy(obj->name, obj_name, sizeof(obj->name) - 1);
522 obj->name[sizeof(obj->name) - 1] = 0;
524 /* Using basename() GNU version which doesn't modify arg. */
525 strncpy(obj->name, basename((void *)path),
526 sizeof(obj->name) - 1);
527 end = strchr(obj->name, '.');
534 * Caller of this function should also call
535 * bpf_object__elf_finish() after data collection to return
536 * obj_buf to user. If not, we should duplicate the buffer to
537 * avoid user freeing them before elf finish.
539 obj->efile.obj_buf = obj_buf;
540 obj->efile.obj_buf_sz = obj_buf_sz;
541 obj->efile.maps_shndx = -1;
542 obj->efile.btf_maps_shndx = -1;
543 obj->efile.data_shndx = -1;
544 obj->efile.rodata_shndx = -1;
545 obj->efile.bss_shndx = -1;
547 obj->kern_version = get_kernel_version();
550 INIT_LIST_HEAD(&obj->list);
551 list_add(&obj->list, &bpf_objects_list);
555 static void bpf_object__elf_finish(struct bpf_object *obj)
557 if (!obj_elf_valid(obj))
560 if (obj->efile.elf) {
561 elf_end(obj->efile.elf);
562 obj->efile.elf = NULL;
564 obj->efile.symbols = NULL;
565 obj->efile.data = NULL;
566 obj->efile.rodata = NULL;
567 obj->efile.bss = NULL;
569 zfree(&obj->efile.reloc_sects);
570 obj->efile.nr_reloc_sects = 0;
571 zclose(obj->efile.fd);
572 obj->efile.obj_buf = NULL;
573 obj->efile.obj_buf_sz = 0;
576 static int bpf_object__elf_init(struct bpf_object *obj)
581 if (obj_elf_valid(obj)) {
582 pr_warn("elf init: internal error\n");
583 return -LIBBPF_ERRNO__LIBELF;
586 if (obj->efile.obj_buf_sz > 0) {
588 * obj_buf should have been validated by
589 * bpf_object__open_buffer().
591 obj->efile.elf = elf_memory((char *)obj->efile.obj_buf,
592 obj->efile.obj_buf_sz);
594 obj->efile.fd = open(obj->path, O_RDONLY);
595 if (obj->efile.fd < 0) {
596 char errmsg[STRERR_BUFSIZE], *cp;
599 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
600 pr_warn("failed to open %s: %s\n", obj->path, cp);
604 obj->efile.elf = elf_begin(obj->efile.fd,
605 LIBBPF_ELF_C_READ_MMAP, NULL);
608 if (!obj->efile.elf) {
609 pr_warn("failed to open %s as ELF file\n", obj->path);
610 err = -LIBBPF_ERRNO__LIBELF;
614 if (!gelf_getehdr(obj->efile.elf, &obj->efile.ehdr)) {
615 pr_warn("failed to get EHDR from %s\n", obj->path);
616 err = -LIBBPF_ERRNO__FORMAT;
619 ep = &obj->efile.ehdr;
621 /* Old LLVM set e_machine to EM_NONE */
622 if (ep->e_type != ET_REL ||
623 (ep->e_machine && ep->e_machine != EM_BPF)) {
624 pr_warn("%s is not an eBPF object file\n", obj->path);
625 err = -LIBBPF_ERRNO__FORMAT;
631 bpf_object__elf_finish(obj);
635 static int bpf_object__check_endianness(struct bpf_object *obj)
637 #if __BYTE_ORDER == __LITTLE_ENDIAN
638 if (obj->efile.ehdr.e_ident[EI_DATA] == ELFDATA2LSB)
640 #elif __BYTE_ORDER == __BIG_ENDIAN
641 if (obj->efile.ehdr.e_ident[EI_DATA] == ELFDATA2MSB)
644 # error "Unrecognized __BYTE_ORDER__"
646 pr_warn("endianness mismatch.\n");
647 return -LIBBPF_ERRNO__ENDIAN;
651 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
653 memcpy(obj->license, data, min(size, sizeof(obj->license) - 1));
654 pr_debug("license of %s is %s\n", obj->path, obj->license);
659 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
663 if (size != sizeof(kver)) {
664 pr_warn("invalid kver section in %s\n", obj->path);
665 return -LIBBPF_ERRNO__FORMAT;
667 memcpy(&kver, data, sizeof(kver));
668 obj->kern_version = kver;
669 pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
673 static int compare_bpf_map(const void *_a, const void *_b)
675 const struct bpf_map *a = _a;
676 const struct bpf_map *b = _b;
678 if (a->sec_idx != b->sec_idx)
679 return a->sec_idx - b->sec_idx;
680 return a->sec_offset - b->sec_offset;
683 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
685 if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
686 type == BPF_MAP_TYPE_HASH_OF_MAPS)
691 static int bpf_object_search_section_size(const struct bpf_object *obj,
692 const char *name, size_t *d_size)
694 const GElf_Ehdr *ep = &obj->efile.ehdr;
695 Elf *elf = obj->efile.elf;
699 while ((scn = elf_nextscn(elf, scn)) != NULL) {
700 const char *sec_name;
705 if (gelf_getshdr(scn, &sh) != &sh) {
706 pr_warn("failed to get section(%d) header from %s\n",
711 sec_name = elf_strptr(elf, ep->e_shstrndx, sh.sh_name);
713 pr_warn("failed to get section(%d) name from %s\n",
718 if (strcmp(name, sec_name))
721 data = elf_getdata(scn, 0);
723 pr_warn("failed to get section(%d) data from %s(%s)\n",
724 idx, name, obj->path);
728 *d_size = data->d_size;
735 int bpf_object__section_size(const struct bpf_object *obj, const char *name,
744 } else if (!strcmp(name, ".data")) {
746 *size = obj->efile.data->d_size;
747 } else if (!strcmp(name, ".bss")) {
749 *size = obj->efile.bss->d_size;
750 } else if (!strcmp(name, ".rodata")) {
751 if (obj->efile.rodata)
752 *size = obj->efile.rodata->d_size;
754 ret = bpf_object_search_section_size(obj, name, &d_size);
759 return *size ? 0 : ret;
762 int bpf_object__variable_offset(const struct bpf_object *obj, const char *name,
765 Elf_Data *symbols = obj->efile.symbols;
772 for (si = 0; si < symbols->d_size / sizeof(GElf_Sym); si++) {
775 if (!gelf_getsym(symbols, si, &sym))
777 if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL ||
778 GELF_ST_TYPE(sym.st_info) != STT_OBJECT)
781 sname = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
784 pr_warn("failed to get sym name string for var %s\n",
788 if (strcmp(name, sname) == 0) {
797 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
799 struct bpf_map *new_maps;
803 if (obj->nr_maps < obj->maps_cap)
804 return &obj->maps[obj->nr_maps++];
806 new_cap = max((size_t)4, obj->maps_cap * 3 / 2);
807 new_maps = realloc(obj->maps, new_cap * sizeof(*obj->maps));
809 pr_warn("alloc maps for object failed\n");
810 return ERR_PTR(-ENOMEM);
813 obj->maps_cap = new_cap;
814 obj->maps = new_maps;
816 /* zero out new maps */
817 memset(obj->maps + obj->nr_maps, 0,
818 (obj->maps_cap - obj->nr_maps) * sizeof(*obj->maps));
820 * fill all fd with -1 so won't close incorrect fd (fd=0 is stdin)
821 * when failure (zclose won't close negative fd)).
823 for (i = obj->nr_maps; i < obj->maps_cap; i++) {
824 obj->maps[i].fd = -1;
825 obj->maps[i].inner_map_fd = -1;
828 return &obj->maps[obj->nr_maps++];
832 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
833 int sec_idx, Elf_Data *data, void **data_buff)
835 char map_name[BPF_OBJ_NAME_LEN];
836 struct bpf_map_def *def;
839 map = bpf_object__add_map(obj);
843 map->libbpf_type = type;
844 map->sec_idx = sec_idx;
846 snprintf(map_name, sizeof(map_name), "%.8s%.7s", obj->name,
847 libbpf_type_to_btf_name[type]);
848 map->name = strdup(map_name);
850 pr_warn("failed to alloc map name\n");
855 def->type = BPF_MAP_TYPE_ARRAY;
856 def->key_size = sizeof(int);
857 def->value_size = data->d_size;
858 def->max_entries = 1;
859 def->map_flags = type == LIBBPF_MAP_RODATA ? BPF_F_RDONLY_PROG : 0;
860 def->map_flags |= BPF_F_MMAPABLE;
862 pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
863 map_name, map->sec_idx, map->sec_offset, def->map_flags);
866 *data_buff = malloc(data->d_size);
869 pr_warn("failed to alloc map content buffer\n");
872 memcpy(*data_buff, data->d_buf, data->d_size);
875 pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
879 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
884 * Populate obj->maps with libbpf internal maps.
886 if (obj->efile.data_shndx >= 0) {
887 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
888 obj->efile.data_shndx,
890 &obj->sections.data);
894 if (obj->efile.rodata_shndx >= 0) {
895 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
896 obj->efile.rodata_shndx,
898 &obj->sections.rodata);
902 if (obj->efile.bss_shndx >= 0) {
903 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
904 obj->efile.bss_shndx,
905 obj->efile.bss, NULL);
912 static int bpf_object__init_user_maps(struct bpf_object *obj, bool strict)
914 Elf_Data *symbols = obj->efile.symbols;
915 int i, map_def_sz = 0, nr_maps = 0, nr_syms;
916 Elf_Data *data = NULL;
919 if (obj->efile.maps_shndx < 0)
925 scn = elf_getscn(obj->efile.elf, obj->efile.maps_shndx);
927 data = elf_getdata(scn, NULL);
929 pr_warn("failed to get Elf_Data from map section %d\n",
930 obj->efile.maps_shndx);
935 * Count number of maps. Each map has a name.
936 * Array of maps is not supported: only the first element is
939 * TODO: Detect array of map and report error.
941 nr_syms = symbols->d_size / sizeof(GElf_Sym);
942 for (i = 0; i < nr_syms; i++) {
945 if (!gelf_getsym(symbols, i, &sym))
947 if (sym.st_shndx != obj->efile.maps_shndx)
951 /* Assume equally sized map definitions */
952 pr_debug("maps in %s: %d maps in %zd bytes\n",
953 obj->path, nr_maps, data->d_size);
955 if (!data->d_size || nr_maps == 0 || (data->d_size % nr_maps) != 0) {
956 pr_warn("unable to determine map definition size section %s, %d maps in %zd bytes\n",
957 obj->path, nr_maps, data->d_size);
960 map_def_sz = data->d_size / nr_maps;
962 /* Fill obj->maps using data in "maps" section. */
963 for (i = 0; i < nr_syms; i++) {
965 const char *map_name;
966 struct bpf_map_def *def;
969 if (!gelf_getsym(symbols, i, &sym))
971 if (sym.st_shndx != obj->efile.maps_shndx)
974 map = bpf_object__add_map(obj);
978 map_name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
981 pr_warn("failed to get map #%d name sym string for obj %s\n",
983 return -LIBBPF_ERRNO__FORMAT;
986 map->libbpf_type = LIBBPF_MAP_UNSPEC;
987 map->sec_idx = sym.st_shndx;
988 map->sec_offset = sym.st_value;
989 pr_debug("map '%s' (legacy): at sec_idx %d, offset %zu.\n",
990 map_name, map->sec_idx, map->sec_offset);
991 if (sym.st_value + map_def_sz > data->d_size) {
992 pr_warn("corrupted maps section in %s: last map \"%s\" too small\n",
993 obj->path, map_name);
997 map->name = strdup(map_name);
999 pr_warn("failed to alloc map name\n");
1002 pr_debug("map %d is \"%s\"\n", i, map->name);
1003 def = (struct bpf_map_def *)(data->d_buf + sym.st_value);
1005 * If the definition of the map in the object file fits in
1006 * bpf_map_def, copy it. Any extra fields in our version
1007 * of bpf_map_def will default to zero as a result of the
1010 if (map_def_sz <= sizeof(struct bpf_map_def)) {
1011 memcpy(&map->def, def, map_def_sz);
1014 * Here the map structure being read is bigger than what
1015 * we expect, truncate if the excess bits are all zero.
1016 * If they are not zero, reject this map as
1021 for (b = ((char *)def) + sizeof(struct bpf_map_def);
1022 b < ((char *)def) + map_def_sz; b++) {
1024 pr_warn("maps section in %s: \"%s\" has unrecognized, non-zero options\n",
1025 obj->path, map_name);
1030 memcpy(&map->def, def, sizeof(struct bpf_map_def));
1036 static const struct btf_type *
1037 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
1039 const struct btf_type *t = btf__type_by_id(btf, id);
1044 while (btf_is_mod(t) || btf_is_typedef(t)) {
1047 t = btf__type_by_id(btf, t->type);
1054 * Fetch integer attribute of BTF map definition. Such attributes are
1055 * represented using a pointer to an array, in which dimensionality of array
1056 * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
1057 * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
1058 * type definition, while using only sizeof(void *) space in ELF data section.
1060 static bool get_map_field_int(const char *map_name, const struct btf *btf,
1061 const struct btf_type *def,
1062 const struct btf_member *m, __u32 *res)
1064 const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
1065 const char *name = btf__name_by_offset(btf, m->name_off);
1066 const struct btf_array *arr_info;
1067 const struct btf_type *arr_t;
1069 if (!btf_is_ptr(t)) {
1070 pr_warn("map '%s': attr '%s': expected PTR, got %u.\n",
1071 map_name, name, btf_kind(t));
1075 arr_t = btf__type_by_id(btf, t->type);
1077 pr_warn("map '%s': attr '%s': type [%u] not found.\n",
1078 map_name, name, t->type);
1081 if (!btf_is_array(arr_t)) {
1082 pr_warn("map '%s': attr '%s': expected ARRAY, got %u.\n",
1083 map_name, name, btf_kind(arr_t));
1086 arr_info = btf_array(arr_t);
1087 *res = arr_info->nelems;
1091 static int build_map_pin_path(struct bpf_map *map, const char *path)
1097 path = "/sys/fs/bpf";
1099 len = snprintf(buf, PATH_MAX, "%s/%s", path, bpf_map__name(map));
1102 else if (len >= PATH_MAX)
1103 return -ENAMETOOLONG;
1105 err = bpf_map__set_pin_path(map, buf);
1112 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
1113 const struct btf_type *sec,
1114 int var_idx, int sec_idx,
1115 const Elf_Data *data, bool strict,
1116 const char *pin_root_path)
1118 const struct btf_type *var, *def, *t;
1119 const struct btf_var_secinfo *vi;
1120 const struct btf_var *var_extra;
1121 const struct btf_member *m;
1122 const char *map_name;
1123 struct bpf_map *map;
1126 vi = btf_var_secinfos(sec) + var_idx;
1127 var = btf__type_by_id(obj->btf, vi->type);
1128 var_extra = btf_var(var);
1129 map_name = btf__name_by_offset(obj->btf, var->name_off);
1130 vlen = btf_vlen(var);
1132 if (map_name == NULL || map_name[0] == '\0') {
1133 pr_warn("map #%d: empty name.\n", var_idx);
1136 if ((__u64)vi->offset + vi->size > data->d_size) {
1137 pr_warn("map '%s' BTF data is corrupted.\n", map_name);
1140 if (!btf_is_var(var)) {
1141 pr_warn("map '%s': unexpected var kind %u.\n",
1142 map_name, btf_kind(var));
1145 if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED &&
1146 var_extra->linkage != BTF_VAR_STATIC) {
1147 pr_warn("map '%s': unsupported var linkage %u.\n",
1148 map_name, var_extra->linkage);
1152 def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
1153 if (!btf_is_struct(def)) {
1154 pr_warn("map '%s': unexpected def kind %u.\n",
1155 map_name, btf_kind(var));
1158 if (def->size > vi->size) {
1159 pr_warn("map '%s': invalid def size.\n", map_name);
1163 map = bpf_object__add_map(obj);
1165 return PTR_ERR(map);
1166 map->name = strdup(map_name);
1168 pr_warn("map '%s': failed to alloc map name.\n", map_name);
1171 map->libbpf_type = LIBBPF_MAP_UNSPEC;
1172 map->def.type = BPF_MAP_TYPE_UNSPEC;
1173 map->sec_idx = sec_idx;
1174 map->sec_offset = vi->offset;
1175 pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
1176 map_name, map->sec_idx, map->sec_offset);
1178 vlen = btf_vlen(def);
1179 m = btf_members(def);
1180 for (i = 0; i < vlen; i++, m++) {
1181 const char *name = btf__name_by_offset(obj->btf, m->name_off);
1184 pr_warn("map '%s': invalid field #%d.\n", map_name, i);
1187 if (strcmp(name, "type") == 0) {
1188 if (!get_map_field_int(map_name, obj->btf, def, m,
1191 pr_debug("map '%s': found type = %u.\n",
1192 map_name, map->def.type);
1193 } else if (strcmp(name, "max_entries") == 0) {
1194 if (!get_map_field_int(map_name, obj->btf, def, m,
1195 &map->def.max_entries))
1197 pr_debug("map '%s': found max_entries = %u.\n",
1198 map_name, map->def.max_entries);
1199 } else if (strcmp(name, "map_flags") == 0) {
1200 if (!get_map_field_int(map_name, obj->btf, def, m,
1201 &map->def.map_flags))
1203 pr_debug("map '%s': found map_flags = %u.\n",
1204 map_name, map->def.map_flags);
1205 } else if (strcmp(name, "key_size") == 0) {
1208 if (!get_map_field_int(map_name, obj->btf, def, m,
1211 pr_debug("map '%s': found key_size = %u.\n",
1213 if (map->def.key_size && map->def.key_size != sz) {
1214 pr_warn("map '%s': conflicting key size %u != %u.\n",
1215 map_name, map->def.key_size, sz);
1218 map->def.key_size = sz;
1219 } else if (strcmp(name, "key") == 0) {
1222 t = btf__type_by_id(obj->btf, m->type);
1224 pr_warn("map '%s': key type [%d] not found.\n",
1228 if (!btf_is_ptr(t)) {
1229 pr_warn("map '%s': key spec is not PTR: %u.\n",
1230 map_name, btf_kind(t));
1233 sz = btf__resolve_size(obj->btf, t->type);
1235 pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
1236 map_name, t->type, (ssize_t)sz);
1239 pr_debug("map '%s': found key [%u], sz = %zd.\n",
1240 map_name, t->type, (ssize_t)sz);
1241 if (map->def.key_size && map->def.key_size != sz) {
1242 pr_warn("map '%s': conflicting key size %u != %zd.\n",
1243 map_name, map->def.key_size, (ssize_t)sz);
1246 map->def.key_size = sz;
1247 map->btf_key_type_id = t->type;
1248 } else if (strcmp(name, "value_size") == 0) {
1251 if (!get_map_field_int(map_name, obj->btf, def, m,
1254 pr_debug("map '%s': found value_size = %u.\n",
1256 if (map->def.value_size && map->def.value_size != sz) {
1257 pr_warn("map '%s': conflicting value size %u != %u.\n",
1258 map_name, map->def.value_size, sz);
1261 map->def.value_size = sz;
1262 } else if (strcmp(name, "value") == 0) {
1265 t = btf__type_by_id(obj->btf, m->type);
1267 pr_warn("map '%s': value type [%d] not found.\n",
1271 if (!btf_is_ptr(t)) {
1272 pr_warn("map '%s': value spec is not PTR: %u.\n",
1273 map_name, btf_kind(t));
1276 sz = btf__resolve_size(obj->btf, t->type);
1278 pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
1279 map_name, t->type, (ssize_t)sz);
1282 pr_debug("map '%s': found value [%u], sz = %zd.\n",
1283 map_name, t->type, (ssize_t)sz);
1284 if (map->def.value_size && map->def.value_size != sz) {
1285 pr_warn("map '%s': conflicting value size %u != %zd.\n",
1286 map_name, map->def.value_size, (ssize_t)sz);
1289 map->def.value_size = sz;
1290 map->btf_value_type_id = t->type;
1291 } else if (strcmp(name, "pinning") == 0) {
1295 if (!get_map_field_int(map_name, obj->btf, def, m,
1298 pr_debug("map '%s': found pinning = %u.\n",
1301 if (val != LIBBPF_PIN_NONE &&
1302 val != LIBBPF_PIN_BY_NAME) {
1303 pr_warn("map '%s': invalid pinning value %u.\n",
1307 if (val == LIBBPF_PIN_BY_NAME) {
1308 err = build_map_pin_path(map, pin_root_path);
1310 pr_warn("map '%s': couldn't build pin path.\n",
1317 pr_warn("map '%s': unknown field '%s'.\n",
1321 pr_debug("map '%s': ignoring unknown field '%s'.\n",
1326 if (map->def.type == BPF_MAP_TYPE_UNSPEC) {
1327 pr_warn("map '%s': map type isn't specified.\n", map_name);
1334 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
1335 const char *pin_root_path)
1337 const struct btf_type *sec = NULL;
1338 int nr_types, i, vlen, err;
1339 const struct btf_type *t;
1344 if (obj->efile.btf_maps_shndx < 0)
1347 scn = elf_getscn(obj->efile.elf, obj->efile.btf_maps_shndx);
1349 data = elf_getdata(scn, NULL);
1350 if (!scn || !data) {
1351 pr_warn("failed to get Elf_Data from map section %d (%s)\n",
1352 obj->efile.maps_shndx, MAPS_ELF_SEC);
1356 nr_types = btf__get_nr_types(obj->btf);
1357 for (i = 1; i <= nr_types; i++) {
1358 t = btf__type_by_id(obj->btf, i);
1359 if (!btf_is_datasec(t))
1361 name = btf__name_by_offset(obj->btf, t->name_off);
1362 if (strcmp(name, MAPS_ELF_SEC) == 0) {
1369 pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
1373 vlen = btf_vlen(sec);
1374 for (i = 0; i < vlen; i++) {
1375 err = bpf_object__init_user_btf_map(obj, sec, i,
1376 obj->efile.btf_maps_shndx,
1386 static int bpf_object__init_maps(struct bpf_object *obj,
1387 struct bpf_object_open_opts *opts)
1389 const char *pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
1390 bool strict = !OPTS_GET(opts, relaxed_maps, false);
1393 err = bpf_object__init_user_maps(obj, strict);
1397 err = bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
1401 err = bpf_object__init_global_data_maps(obj);
1406 qsort(obj->maps, obj->nr_maps, sizeof(obj->maps[0]),
1412 static bool section_have_execinstr(struct bpf_object *obj, int idx)
1417 scn = elf_getscn(obj->efile.elf, idx);
1421 if (gelf_getshdr(scn, &sh) != &sh)
1424 if (sh.sh_flags & SHF_EXECINSTR)
1430 static void bpf_object__sanitize_btf(struct bpf_object *obj)
1432 bool has_datasec = obj->caps.btf_datasec;
1433 bool has_func = obj->caps.btf_func;
1434 struct btf *btf = obj->btf;
1438 if (!obj->btf || (has_func && has_datasec))
1441 for (i = 1; i <= btf__get_nr_types(btf); i++) {
1442 t = (struct btf_type *)btf__type_by_id(btf, i);
1444 if (!has_datasec && btf_is_var(t)) {
1445 /* replace VAR with INT */
1446 t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
1448 * using size = 1 is the safest choice, 4 will be too
1449 * big and cause kernel BTF validation failure if
1450 * original variable took less than 4 bytes
1453 *(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
1454 } else if (!has_datasec && btf_is_datasec(t)) {
1455 /* replace DATASEC with STRUCT */
1456 const struct btf_var_secinfo *v = btf_var_secinfos(t);
1457 struct btf_member *m = btf_members(t);
1458 struct btf_type *vt;
1461 name = (char *)btf__name_by_offset(btf, t->name_off);
1469 t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
1470 for (j = 0; j < vlen; j++, v++, m++) {
1471 /* order of field assignments is important */
1472 m->offset = v->offset * 8;
1474 /* preserve variable name as member name */
1475 vt = (void *)btf__type_by_id(btf, v->type);
1476 m->name_off = vt->name_off;
1478 } else if (!has_func && btf_is_func_proto(t)) {
1479 /* replace FUNC_PROTO with ENUM */
1481 t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
1482 t->size = sizeof(__u32); /* kernel enforced */
1483 } else if (!has_func && btf_is_func(t)) {
1484 /* replace FUNC with TYPEDEF */
1485 t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
1490 static void bpf_object__sanitize_btf_ext(struct bpf_object *obj)
1495 if (!obj->caps.btf_func) {
1496 btf_ext__free(obj->btf_ext);
1497 obj->btf_ext = NULL;
1501 static bool bpf_object__is_btf_mandatory(const struct bpf_object *obj)
1503 return obj->efile.btf_maps_shndx >= 0;
1506 static int bpf_object__init_btf(struct bpf_object *obj,
1508 Elf_Data *btf_ext_data)
1510 bool btf_required = bpf_object__is_btf_mandatory(obj);
1514 obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
1515 if (IS_ERR(obj->btf)) {
1516 pr_warn("Error loading ELF section %s: %d.\n",
1520 err = btf__finalize_data(obj, obj->btf);
1522 pr_warn("Error finalizing %s: %d.\n", BTF_ELF_SEC, err);
1528 pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
1529 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
1532 obj->btf_ext = btf_ext__new(btf_ext_data->d_buf,
1533 btf_ext_data->d_size);
1534 if (IS_ERR(obj->btf_ext)) {
1535 pr_warn("Error loading ELF section %s: %ld. Ignored and continue.\n",
1536 BTF_EXT_ELF_SEC, PTR_ERR(obj->btf_ext));
1537 obj->btf_ext = NULL;
1542 if (err || IS_ERR(obj->btf)) {
1544 err = err ? : PTR_ERR(obj->btf);
1547 if (!IS_ERR_OR_NULL(obj->btf))
1548 btf__free(obj->btf);
1551 if (btf_required && !obj->btf) {
1552 pr_warn("BTF is required, but is missing or corrupted.\n");
1553 return err == 0 ? -ENOENT : err;
1558 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
1565 bpf_object__sanitize_btf(obj);
1566 bpf_object__sanitize_btf_ext(obj);
1568 err = btf__load(obj->btf);
1570 pr_warn("Error loading %s into kernel: %d.\n",
1572 btf__free(obj->btf);
1574 /* btf_ext can't exist without btf, so free it as well */
1576 btf_ext__free(obj->btf_ext);
1577 obj->btf_ext = NULL;
1580 if (bpf_object__is_btf_mandatory(obj))
1586 static int bpf_object__elf_collect(struct bpf_object *obj)
1588 Elf *elf = obj->efile.elf;
1589 GElf_Ehdr *ep = &obj->efile.ehdr;
1590 Elf_Data *btf_ext_data = NULL;
1591 Elf_Data *btf_data = NULL;
1592 Elf_Scn *scn = NULL;
1593 int idx = 0, err = 0;
1595 /* Elf is corrupted/truncated, avoid calling elf_strptr. */
1596 if (!elf_rawdata(elf_getscn(elf, ep->e_shstrndx), NULL)) {
1597 pr_warn("failed to get e_shstrndx from %s\n", obj->path);
1598 return -LIBBPF_ERRNO__FORMAT;
1601 while ((scn = elf_nextscn(elf, scn)) != NULL) {
1607 if (gelf_getshdr(scn, &sh) != &sh) {
1608 pr_warn("failed to get section(%d) header from %s\n",
1610 return -LIBBPF_ERRNO__FORMAT;
1613 name = elf_strptr(elf, ep->e_shstrndx, sh.sh_name);
1615 pr_warn("failed to get section(%d) name from %s\n",
1617 return -LIBBPF_ERRNO__FORMAT;
1620 data = elf_getdata(scn, 0);
1622 pr_warn("failed to get section(%d) data from %s(%s)\n",
1623 idx, name, obj->path);
1624 return -LIBBPF_ERRNO__FORMAT;
1626 pr_debug("section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
1627 idx, name, (unsigned long)data->d_size,
1628 (int)sh.sh_link, (unsigned long)sh.sh_flags,
1631 if (strcmp(name, "license") == 0) {
1632 err = bpf_object__init_license(obj,
1637 } else if (strcmp(name, "version") == 0) {
1638 err = bpf_object__init_kversion(obj,
1643 } else if (strcmp(name, "maps") == 0) {
1644 obj->efile.maps_shndx = idx;
1645 } else if (strcmp(name, MAPS_ELF_SEC) == 0) {
1646 obj->efile.btf_maps_shndx = idx;
1647 } else if (strcmp(name, BTF_ELF_SEC) == 0) {
1649 } else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
1650 btf_ext_data = data;
1651 } else if (sh.sh_type == SHT_SYMTAB) {
1652 if (obj->efile.symbols) {
1653 pr_warn("bpf: multiple SYMTAB in %s\n",
1655 return -LIBBPF_ERRNO__FORMAT;
1657 obj->efile.symbols = data;
1658 obj->efile.strtabidx = sh.sh_link;
1659 } else if (sh.sh_type == SHT_PROGBITS && data->d_size > 0) {
1660 if (sh.sh_flags & SHF_EXECINSTR) {
1661 if (strcmp(name, ".text") == 0)
1662 obj->efile.text_shndx = idx;
1663 err = bpf_object__add_program(obj, data->d_buf,
1667 char errmsg[STRERR_BUFSIZE];
1670 cp = libbpf_strerror_r(-err, errmsg,
1672 pr_warn("failed to alloc program %s (%s): %s",
1673 name, obj->path, cp);
1676 } else if (strcmp(name, ".data") == 0) {
1677 obj->efile.data = data;
1678 obj->efile.data_shndx = idx;
1679 } else if (strcmp(name, ".rodata") == 0) {
1680 obj->efile.rodata = data;
1681 obj->efile.rodata_shndx = idx;
1683 pr_debug("skip section(%d) %s\n", idx, name);
1685 } else if (sh.sh_type == SHT_REL) {
1686 int nr_sects = obj->efile.nr_reloc_sects;
1687 void *sects = obj->efile.reloc_sects;
1688 int sec = sh.sh_info; /* points to other section */
1690 /* Only do relo for section with exec instructions */
1691 if (!section_have_execinstr(obj, sec)) {
1692 pr_debug("skip relo %s(%d) for section(%d)\n",
1697 sects = reallocarray(sects, nr_sects + 1,
1698 sizeof(*obj->efile.reloc_sects));
1700 pr_warn("reloc_sects realloc failed\n");
1704 obj->efile.reloc_sects = sects;
1705 obj->efile.nr_reloc_sects++;
1707 obj->efile.reloc_sects[nr_sects].shdr = sh;
1708 obj->efile.reloc_sects[nr_sects].data = data;
1709 } else if (sh.sh_type == SHT_NOBITS && strcmp(name, ".bss") == 0) {
1710 obj->efile.bss = data;
1711 obj->efile.bss_shndx = idx;
1713 pr_debug("skip section(%d) %s\n", idx, name);
1717 if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
1718 pr_warn("Corrupted ELF file: index of strtab invalid\n");
1719 return -LIBBPF_ERRNO__FORMAT;
1721 return bpf_object__init_btf(obj, btf_data, btf_ext_data);
1724 static struct bpf_program *
1725 bpf_object__find_prog_by_idx(struct bpf_object *obj, int idx)
1727 struct bpf_program *prog;
1730 for (i = 0; i < obj->nr_programs; i++) {
1731 prog = &obj->programs[i];
1732 if (prog->idx == idx)
1738 struct bpf_program *
1739 bpf_object__find_program_by_title(const struct bpf_object *obj,
1742 struct bpf_program *pos;
1744 bpf_object__for_each_program(pos, obj) {
1745 if (pos->section_name && !strcmp(pos->section_name, title))
1751 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
1754 return shndx == obj->efile.data_shndx ||
1755 shndx == obj->efile.bss_shndx ||
1756 shndx == obj->efile.rodata_shndx;
1759 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
1762 return shndx == obj->efile.maps_shndx ||
1763 shndx == obj->efile.btf_maps_shndx;
1766 static enum libbpf_map_type
1767 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
1769 if (shndx == obj->efile.data_shndx)
1770 return LIBBPF_MAP_DATA;
1771 else if (shndx == obj->efile.bss_shndx)
1772 return LIBBPF_MAP_BSS;
1773 else if (shndx == obj->efile.rodata_shndx)
1774 return LIBBPF_MAP_RODATA;
1776 return LIBBPF_MAP_UNSPEC;
1779 static int bpf_program__record_reloc(struct bpf_program *prog,
1780 struct reloc_desc *reloc_desc,
1781 __u32 insn_idx, const char *name,
1782 const GElf_Sym *sym, const GElf_Rel *rel)
1784 struct bpf_insn *insn = &prog->insns[insn_idx];
1785 size_t map_idx, nr_maps = prog->obj->nr_maps;
1786 struct bpf_object *obj = prog->obj;
1787 __u32 shdr_idx = sym->st_shndx;
1788 enum libbpf_map_type type;
1789 struct bpf_map *map;
1791 /* sub-program call relocation */
1792 if (insn->code == (BPF_JMP | BPF_CALL)) {
1793 if (insn->src_reg != BPF_PSEUDO_CALL) {
1794 pr_warn("incorrect bpf_call opcode\n");
1795 return -LIBBPF_ERRNO__RELOC;
1797 /* text_shndx can be 0, if no default "main" program exists */
1798 if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
1799 pr_warn("bad call relo against section %u\n", shdr_idx);
1800 return -LIBBPF_ERRNO__RELOC;
1802 if (sym->st_value % 8) {
1803 pr_warn("bad call relo offset: %zu\n",
1804 (size_t)sym->st_value);
1805 return -LIBBPF_ERRNO__RELOC;
1807 reloc_desc->type = RELO_CALL;
1808 reloc_desc->insn_idx = insn_idx;
1809 reloc_desc->sym_off = sym->st_value;
1810 obj->has_pseudo_calls = true;
1814 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) {
1815 pr_warn("invalid relo for insns[%d].code 0x%x\n",
1816 insn_idx, insn->code);
1817 return -LIBBPF_ERRNO__RELOC;
1819 if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
1820 pr_warn("invalid relo for \'%s\' in special section 0x%x; forgot to initialize global var?..\n",
1822 return -LIBBPF_ERRNO__RELOC;
1825 type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
1827 /* generic map reference relocation */
1828 if (type == LIBBPF_MAP_UNSPEC) {
1829 if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
1830 pr_warn("bad map relo against section %u\n",
1832 return -LIBBPF_ERRNO__RELOC;
1834 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
1835 map = &obj->maps[map_idx];
1836 if (map->libbpf_type != type ||
1837 map->sec_idx != sym->st_shndx ||
1838 map->sec_offset != sym->st_value)
1840 pr_debug("found map %zd (%s, sec %d, off %zu) for insn %u\n",
1841 map_idx, map->name, map->sec_idx,
1842 map->sec_offset, insn_idx);
1845 if (map_idx >= nr_maps) {
1846 pr_warn("map relo failed to find map for sec %u, off %zu\n",
1847 shdr_idx, (size_t)sym->st_value);
1848 return -LIBBPF_ERRNO__RELOC;
1850 reloc_desc->type = RELO_LD64;
1851 reloc_desc->insn_idx = insn_idx;
1852 reloc_desc->map_idx = map_idx;
1853 reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
1857 /* global data map relocation */
1858 if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
1859 pr_warn("bad data relo against section %u\n", shdr_idx);
1860 return -LIBBPF_ERRNO__RELOC;
1862 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
1863 map = &obj->maps[map_idx];
1864 if (map->libbpf_type != type)
1866 pr_debug("found data map %zd (%s, sec %d, off %zu) for insn %u\n",
1867 map_idx, map->name, map->sec_idx, map->sec_offset,
1871 if (map_idx >= nr_maps) {
1872 pr_warn("data relo failed to find map for sec %u\n",
1874 return -LIBBPF_ERRNO__RELOC;
1877 reloc_desc->type = RELO_DATA;
1878 reloc_desc->insn_idx = insn_idx;
1879 reloc_desc->map_idx = map_idx;
1880 reloc_desc->sym_off = sym->st_value;
1885 bpf_program__collect_reloc(struct bpf_program *prog, GElf_Shdr *shdr,
1886 Elf_Data *data, struct bpf_object *obj)
1888 Elf_Data *symbols = obj->efile.symbols;
1891 pr_debug("collecting relocating info for: '%s'\n", prog->section_name);
1892 nrels = shdr->sh_size / shdr->sh_entsize;
1894 prog->reloc_desc = malloc(sizeof(*prog->reloc_desc) * nrels);
1895 if (!prog->reloc_desc) {
1896 pr_warn("failed to alloc memory in relocation\n");
1899 prog->nr_reloc = nrels;
1901 for (i = 0; i < nrels; i++) {
1907 if (!gelf_getrel(data, i, &rel)) {
1908 pr_warn("relocation: failed to get %d reloc\n", i);
1909 return -LIBBPF_ERRNO__FORMAT;
1911 if (!gelf_getsym(symbols, GELF_R_SYM(rel.r_info), &sym)) {
1912 pr_warn("relocation: symbol %"PRIx64" not found\n",
1913 GELF_R_SYM(rel.r_info));
1914 return -LIBBPF_ERRNO__FORMAT;
1916 if (rel.r_offset % sizeof(struct bpf_insn))
1917 return -LIBBPF_ERRNO__FORMAT;
1919 insn_idx = rel.r_offset / sizeof(struct bpf_insn);
1920 name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
1921 sym.st_name) ? : "<?>";
1923 pr_debug("relo for shdr %u, symb %zu, value %zu, type %d, bind %d, name %d (\'%s\'), insn %u\n",
1924 (__u32)sym.st_shndx, (size_t)GELF_R_SYM(rel.r_info),
1925 (size_t)sym.st_value, GELF_ST_TYPE(sym.st_info),
1926 GELF_ST_BIND(sym.st_info), sym.st_name, name,
1929 err = bpf_program__record_reloc(prog, &prog->reloc_desc[i],
1930 insn_idx, name, &sym, &rel);
1937 static int bpf_map_find_btf_info(struct bpf_object *obj, struct bpf_map *map)
1939 struct bpf_map_def *def = &map->def;
1940 __u32 key_type_id = 0, value_type_id = 0;
1943 /* if it's BTF-defined map, we don't need to search for type IDs */
1944 if (map->sec_idx == obj->efile.btf_maps_shndx)
1947 if (!bpf_map__is_internal(map)) {
1948 ret = btf__get_map_kv_tids(obj->btf, map->name, def->key_size,
1949 def->value_size, &key_type_id,
1953 * LLVM annotates global data differently in BTF, that is,
1954 * only as '.data', '.bss' or '.rodata'.
1956 ret = btf__find_by_name(obj->btf,
1957 libbpf_type_to_btf_name[map->libbpf_type]);
1962 map->btf_key_type_id = key_type_id;
1963 map->btf_value_type_id = bpf_map__is_internal(map) ?
1964 ret : value_type_id;
1968 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
1970 struct bpf_map_info info = {};
1971 __u32 len = sizeof(info);
1975 err = bpf_obj_get_info_by_fd(fd, &info, &len);
1979 new_name = strdup(info.name);
1983 new_fd = open("/", O_RDONLY | O_CLOEXEC);
1986 goto err_free_new_name;
1989 new_fd = dup3(fd, new_fd, O_CLOEXEC);
1992 goto err_close_new_fd;
1995 err = zclose(map->fd);
1998 goto err_close_new_fd;
2003 map->name = new_name;
2004 map->def.type = info.type;
2005 map->def.key_size = info.key_size;
2006 map->def.value_size = info.value_size;
2007 map->def.max_entries = info.max_entries;
2008 map->def.map_flags = info.map_flags;
2009 map->btf_key_type_id = info.btf_key_type_id;
2010 map->btf_value_type_id = info.btf_value_type_id;
2022 int bpf_map__resize(struct bpf_map *map, __u32 max_entries)
2024 if (!map || !max_entries)
2027 /* If map already created, its attributes can't be changed. */
2031 map->def.max_entries = max_entries;
2037 bpf_object__probe_name(struct bpf_object *obj)
2039 struct bpf_load_program_attr attr;
2040 char *cp, errmsg[STRERR_BUFSIZE];
2041 struct bpf_insn insns[] = {
2042 BPF_MOV64_IMM(BPF_REG_0, 0),
2047 /* make sure basic loading works */
2049 memset(&attr, 0, sizeof(attr));
2050 attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
2052 attr.insns_cnt = ARRAY_SIZE(insns);
2053 attr.license = "GPL";
2055 ret = bpf_load_program_xattr(&attr, NULL, 0);
2057 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
2058 pr_warn("Error in %s():%s(%d). Couldn't load basic 'r0 = 0' BPF program.\n",
2059 __func__, cp, errno);
2064 /* now try the same program, but with the name */
2067 ret = bpf_load_program_xattr(&attr, NULL, 0);
2077 bpf_object__probe_global_data(struct bpf_object *obj)
2079 struct bpf_load_program_attr prg_attr;
2080 struct bpf_create_map_attr map_attr;
2081 char *cp, errmsg[STRERR_BUFSIZE];
2082 struct bpf_insn insns[] = {
2083 BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16),
2084 BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42),
2085 BPF_MOV64_IMM(BPF_REG_0, 0),
2090 memset(&map_attr, 0, sizeof(map_attr));
2091 map_attr.map_type = BPF_MAP_TYPE_ARRAY;
2092 map_attr.key_size = sizeof(int);
2093 map_attr.value_size = 32;
2094 map_attr.max_entries = 1;
2096 map = bpf_create_map_xattr(&map_attr);
2098 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
2099 pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
2100 __func__, cp, errno);
2106 memset(&prg_attr, 0, sizeof(prg_attr));
2107 prg_attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
2108 prg_attr.insns = insns;
2109 prg_attr.insns_cnt = ARRAY_SIZE(insns);
2110 prg_attr.license = "GPL";
2112 ret = bpf_load_program_xattr(&prg_attr, NULL, 0);
2114 obj->caps.global_data = 1;
2122 static int bpf_object__probe_btf_func(struct bpf_object *obj)
2124 static const char strs[] = "\0int\0x\0a";
2125 /* void x(int a) {} */
2128 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
2129 /* FUNC_PROTO */ /* [2] */
2130 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
2131 BTF_PARAM_ENC(7, 1),
2132 /* FUNC x */ /* [3] */
2133 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0), 2),
2137 btf_fd = libbpf__load_raw_btf((char *)types, sizeof(types),
2138 strs, sizeof(strs));
2140 obj->caps.btf_func = 1;
2148 static int bpf_object__probe_btf_datasec(struct bpf_object *obj)
2150 static const char strs[] = "\0x\0.data";
2154 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
2155 /* VAR x */ /* [2] */
2156 BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
2158 /* DATASEC val */ /* [3] */
2159 BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC, 0, 1), 4),
2160 BTF_VAR_SECINFO_ENC(2, 0, 4),
2164 btf_fd = libbpf__load_raw_btf((char *)types, sizeof(types),
2165 strs, sizeof(strs));
2167 obj->caps.btf_datasec = 1;
2175 static int bpf_object__probe_array_mmap(struct bpf_object *obj)
2177 struct bpf_create_map_attr attr = {
2178 .map_type = BPF_MAP_TYPE_ARRAY,
2179 .map_flags = BPF_F_MMAPABLE,
2180 .key_size = sizeof(int),
2181 .value_size = sizeof(int),
2186 fd = bpf_create_map_xattr(&attr);
2188 obj->caps.array_mmap = 1;
2197 bpf_object__probe_caps(struct bpf_object *obj)
2199 int (*probe_fn[])(struct bpf_object *obj) = {
2200 bpf_object__probe_name,
2201 bpf_object__probe_global_data,
2202 bpf_object__probe_btf_func,
2203 bpf_object__probe_btf_datasec,
2204 bpf_object__probe_array_mmap,
2208 for (i = 0; i < ARRAY_SIZE(probe_fn); i++) {
2209 ret = probe_fn[i](obj);
2211 pr_debug("Probe #%d failed with %d.\n", i, ret);
2217 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
2219 struct bpf_map_info map_info = {};
2220 char msg[STRERR_BUFSIZE];
2223 map_info_len = sizeof(map_info);
2225 if (bpf_obj_get_info_by_fd(map_fd, &map_info, &map_info_len)) {
2226 pr_warn("failed to get map info for map FD %d: %s\n",
2227 map_fd, libbpf_strerror_r(errno, msg, sizeof(msg)));
2231 return (map_info.type == map->def.type &&
2232 map_info.key_size == map->def.key_size &&
2233 map_info.value_size == map->def.value_size &&
2234 map_info.max_entries == map->def.max_entries &&
2235 map_info.map_flags == map->def.map_flags);
2239 bpf_object__reuse_map(struct bpf_map *map)
2241 char *cp, errmsg[STRERR_BUFSIZE];
2244 pin_fd = bpf_obj_get(map->pin_path);
2247 if (err == -ENOENT) {
2248 pr_debug("found no pinned map to reuse at '%s'\n",
2253 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
2254 pr_warn("couldn't retrieve pinned map '%s': %s\n",
2259 if (!map_is_reuse_compat(map, pin_fd)) {
2260 pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
2266 err = bpf_map__reuse_fd(map, pin_fd);
2272 pr_debug("reused pinned map at '%s'\n", map->pin_path);
2278 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
2280 char *cp, errmsg[STRERR_BUFSIZE];
2284 /* Nothing to do here since kernel already zero-initializes .bss map. */
2285 if (map->libbpf_type == LIBBPF_MAP_BSS)
2288 data = map->libbpf_type == LIBBPF_MAP_DATA ?
2289 obj->sections.data : obj->sections.rodata;
2291 err = bpf_map_update_elem(map->fd, &zero, data, 0);
2292 /* Freeze .rodata map as read-only from syscall side. */
2293 if (!err && map->libbpf_type == LIBBPF_MAP_RODATA) {
2294 err = bpf_map_freeze(map->fd);
2296 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
2297 pr_warn("Error freezing map(%s) as read-only: %s\n",
2306 bpf_object__create_maps(struct bpf_object *obj)
2308 struct bpf_create_map_attr create_attr = {};
2313 for (i = 0; i < obj->nr_maps; i++) {
2314 struct bpf_map *map = &obj->maps[i];
2315 struct bpf_map_def *def = &map->def;
2316 char *cp, errmsg[STRERR_BUFSIZE];
2317 int *pfd = &map->fd;
2319 if (map->pin_path) {
2320 err = bpf_object__reuse_map(map);
2322 pr_warn("error reusing pinned map %s\n",
2329 pr_debug("skip map create (preset) %s: fd=%d\n",
2330 map->name, map->fd);
2335 create_attr.name = map->name;
2336 create_attr.map_ifindex = map->map_ifindex;
2337 create_attr.map_type = def->type;
2338 create_attr.map_flags = def->map_flags;
2339 create_attr.key_size = def->key_size;
2340 create_attr.value_size = def->value_size;
2341 if (def->type == BPF_MAP_TYPE_PERF_EVENT_ARRAY &&
2342 !def->max_entries) {
2344 nr_cpus = libbpf_num_possible_cpus();
2346 pr_warn("failed to determine number of system CPUs: %d\n",
2351 pr_debug("map '%s': setting size to %d\n",
2352 map->name, nr_cpus);
2353 create_attr.max_entries = nr_cpus;
2355 create_attr.max_entries = def->max_entries;
2357 create_attr.btf_fd = 0;
2358 create_attr.btf_key_type_id = 0;
2359 create_attr.btf_value_type_id = 0;
2360 if (bpf_map_type__is_map_in_map(def->type) &&
2361 map->inner_map_fd >= 0)
2362 create_attr.inner_map_fd = map->inner_map_fd;
2364 if (obj->btf && !bpf_map_find_btf_info(obj, map)) {
2365 create_attr.btf_fd = btf__fd(obj->btf);
2366 create_attr.btf_key_type_id = map->btf_key_type_id;
2367 create_attr.btf_value_type_id = map->btf_value_type_id;
2370 *pfd = bpf_create_map_xattr(&create_attr);
2371 if (*pfd < 0 && (create_attr.btf_key_type_id ||
2372 create_attr.btf_value_type_id)) {
2374 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
2375 pr_warn("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
2376 map->name, cp, err);
2377 create_attr.btf_fd = 0;
2378 create_attr.btf_key_type_id = 0;
2379 create_attr.btf_value_type_id = 0;
2380 map->btf_key_type_id = 0;
2381 map->btf_value_type_id = 0;
2382 *pfd = bpf_create_map_xattr(&create_attr);
2390 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
2391 pr_warn("failed to create map (name: '%s'): %s(%d)\n",
2392 map->name, cp, err);
2393 for (j = 0; j < i; j++)
2394 zclose(obj->maps[j].fd);
2398 if (bpf_map__is_internal(map)) {
2399 err = bpf_object__populate_internal_map(obj, map);
2406 if (map->pin_path && !map->pinned) {
2407 err = bpf_map__pin(map, NULL);
2409 pr_warn("failed to auto-pin map name '%s' at '%s'\n",
2410 map->name, map->pin_path);
2415 pr_debug("created map %s: fd=%d\n", map->name, *pfd);
2422 check_btf_ext_reloc_err(struct bpf_program *prog, int err,
2423 void *btf_prog_info, const char *info_name)
2425 if (err != -ENOENT) {
2426 pr_warn("Error in loading %s for sec %s.\n",
2427 info_name, prog->section_name);
2431 /* err == -ENOENT (i.e. prog->section_name not found in btf_ext) */
2433 if (btf_prog_info) {
2435 * Some info has already been found but has problem
2436 * in the last btf_ext reloc. Must have to error out.
2438 pr_warn("Error in relocating %s for sec %s.\n",
2439 info_name, prog->section_name);
2443 /* Have problem loading the very first info. Ignore the rest. */
2444 pr_warn("Cannot find %s for main program sec %s. Ignore all %s.\n",
2445 info_name, prog->section_name, info_name);
2450 bpf_program_reloc_btf_ext(struct bpf_program *prog, struct bpf_object *obj,
2451 const char *section_name, __u32 insn_offset)
2455 if (!insn_offset || prog->func_info) {
2457 * !insn_offset => main program
2459 * For sub prog, the main program's func_info has to
2460 * be loaded first (i.e. prog->func_info != NULL)
2462 err = btf_ext__reloc_func_info(obj->btf, obj->btf_ext,
2463 section_name, insn_offset,
2465 &prog->func_info_cnt);
2467 return check_btf_ext_reloc_err(prog, err,
2471 prog->func_info_rec_size = btf_ext__func_info_rec_size(obj->btf_ext);
2474 if (!insn_offset || prog->line_info) {
2475 err = btf_ext__reloc_line_info(obj->btf, obj->btf_ext,
2476 section_name, insn_offset,
2478 &prog->line_info_cnt);
2480 return check_btf_ext_reloc_err(prog, err,
2484 prog->line_info_rec_size = btf_ext__line_info_rec_size(obj->btf_ext);
2490 #define BPF_CORE_SPEC_MAX_LEN 64
2492 /* represents BPF CO-RE field or array element accessor */
2493 struct bpf_core_accessor {
2494 __u32 type_id; /* struct/union type or array element type */
2495 __u32 idx; /* field index or array index */
2496 const char *name; /* field name or NULL for array accessor */
2499 struct bpf_core_spec {
2500 const struct btf *btf;
2501 /* high-level spec: named fields and array indices only */
2502 struct bpf_core_accessor spec[BPF_CORE_SPEC_MAX_LEN];
2503 /* high-level spec length */
2505 /* raw, low-level spec: 1-to-1 with accessor spec string */
2506 int raw_spec[BPF_CORE_SPEC_MAX_LEN];
2507 /* raw spec length */
2509 /* field bit offset represented by spec */
2513 static bool str_is_empty(const char *s)
2519 * Turn bpf_field_reloc into a low- and high-level spec representation,
2520 * validating correctness along the way, as well as calculating resulting
2521 * field bit offset, specified by accessor string. Low-level spec captures
2522 * every single level of nestedness, including traversing anonymous
2523 * struct/union members. High-level one only captures semantically meaningful
2524 * "turning points": named fields and array indicies.
2525 * E.g., for this case:
2528 * int __unimportant;
2536 * struct sample *s = ...;
2538 * int x = &s->a[3]; // access string = '0:1:2:3'
2540 * Low-level spec has 1:1 mapping with each element of access string (it's
2541 * just a parsed access string representation): [0, 1, 2, 3].
2543 * High-level spec will capture only 3 points:
2544 * - intial zero-index access by pointer (&s->... is the same as &s[0]...);
2545 * - field 'a' access (corresponds to '2' in low-level spec);
2546 * - array element #3 access (corresponds to '3' in low-level spec).
2549 static int bpf_core_spec_parse(const struct btf *btf,
2551 const char *spec_str,
2552 struct bpf_core_spec *spec)
2554 int access_idx, parsed_len, i;
2555 const struct btf_type *t;
2560 if (str_is_empty(spec_str) || *spec_str == ':')
2563 memset(spec, 0, sizeof(*spec));
2566 /* parse spec_str="0:1:2:3:4" into array raw_spec=[0, 1, 2, 3, 4] */
2568 if (*spec_str == ':')
2570 if (sscanf(spec_str, "%d%n", &access_idx, &parsed_len) != 1)
2572 if (spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
2574 spec_str += parsed_len;
2575 spec->raw_spec[spec->raw_len++] = access_idx;
2578 if (spec->raw_len == 0)
2581 /* first spec value is always reloc type array index */
2582 t = skip_mods_and_typedefs(btf, type_id, &id);
2586 access_idx = spec->raw_spec[0];
2587 spec->spec[0].type_id = id;
2588 spec->spec[0].idx = access_idx;
2591 sz = btf__resolve_size(btf, id);
2594 spec->bit_offset = access_idx * sz * 8;
2596 for (i = 1; i < spec->raw_len; i++) {
2597 t = skip_mods_and_typedefs(btf, id, &id);
2601 access_idx = spec->raw_spec[i];
2603 if (btf_is_composite(t)) {
2604 const struct btf_member *m;
2607 if (access_idx >= btf_vlen(t))
2610 bit_offset = btf_member_bit_offset(t, access_idx);
2611 spec->bit_offset += bit_offset;
2613 m = btf_members(t) + access_idx;
2615 name = btf__name_by_offset(btf, m->name_off);
2616 if (str_is_empty(name))
2619 spec->spec[spec->len].type_id = id;
2620 spec->spec[spec->len].idx = access_idx;
2621 spec->spec[spec->len].name = name;
2626 } else if (btf_is_array(t)) {
2627 const struct btf_array *a = btf_array(t);
2629 t = skip_mods_and_typedefs(btf, a->type, &id);
2630 if (!t || access_idx >= a->nelems)
2633 spec->spec[spec->len].type_id = id;
2634 spec->spec[spec->len].idx = access_idx;
2637 sz = btf__resolve_size(btf, id);
2640 spec->bit_offset += access_idx * sz * 8;
2642 pr_warn("relo for [%u] %s (at idx %d) captures type [%d] of unexpected kind %d\n",
2643 type_id, spec_str, i, id, btf_kind(t));
2651 static bool bpf_core_is_flavor_sep(const char *s)
2653 /* check X___Y name pattern, where X and Y are not underscores */
2654 return s[0] != '_' && /* X */
2655 s[1] == '_' && s[2] == '_' && s[3] == '_' && /* ___ */
2656 s[4] != '_'; /* Y */
2659 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
2660 * before last triple underscore. Struct name part after last triple
2661 * underscore is ignored by BPF CO-RE relocation during relocation matching.
2663 static size_t bpf_core_essential_name_len(const char *name)
2665 size_t n = strlen(name);
2668 for (i = n - 5; i >= 0; i--) {
2669 if (bpf_core_is_flavor_sep(name + i))
2675 /* dynamically sized list of type IDs */
2681 static void bpf_core_free_cands(struct ids_vec *cand_ids)
2683 free(cand_ids->data);
2687 static struct ids_vec *bpf_core_find_cands(const struct btf *local_btf,
2688 __u32 local_type_id,
2689 const struct btf *targ_btf)
2691 size_t local_essent_len, targ_essent_len;
2692 const char *local_name, *targ_name;
2693 const struct btf_type *t;
2694 struct ids_vec *cand_ids;
2698 t = btf__type_by_id(local_btf, local_type_id);
2700 return ERR_PTR(-EINVAL);
2702 local_name = btf__name_by_offset(local_btf, t->name_off);
2703 if (str_is_empty(local_name))
2704 return ERR_PTR(-EINVAL);
2705 local_essent_len = bpf_core_essential_name_len(local_name);
2707 cand_ids = calloc(1, sizeof(*cand_ids));
2709 return ERR_PTR(-ENOMEM);
2711 n = btf__get_nr_types(targ_btf);
2712 for (i = 1; i <= n; i++) {
2713 t = btf__type_by_id(targ_btf, i);
2714 targ_name = btf__name_by_offset(targ_btf, t->name_off);
2715 if (str_is_empty(targ_name))
2718 targ_essent_len = bpf_core_essential_name_len(targ_name);
2719 if (targ_essent_len != local_essent_len)
2722 if (strncmp(local_name, targ_name, local_essent_len) == 0) {
2723 pr_debug("[%d] %s: found candidate [%d] %s\n",
2724 local_type_id, local_name, i, targ_name);
2725 new_ids = realloc(cand_ids->data, cand_ids->len + 1);
2730 cand_ids->data = new_ids;
2731 cand_ids->data[cand_ids->len++] = i;
2736 bpf_core_free_cands(cand_ids);
2737 return ERR_PTR(err);
2740 /* Check two types for compatibility, skipping const/volatile/restrict and
2741 * typedefs, to ensure we are relocating compatible entities:
2742 * - any two STRUCTs/UNIONs are compatible and can be mixed;
2743 * - any two FWDs are compatible, if their names match (modulo flavor suffix);
2744 * - any two PTRs are always compatible;
2745 * - for ENUMs, names should be the same (ignoring flavor suffix) or at
2746 * least one of enums should be anonymous;
2747 * - for ENUMs, check sizes, names are ignored;
2748 * - for INT, size and signedness are ignored;
2749 * - for ARRAY, dimensionality is ignored, element types are checked for
2750 * compatibility recursively;
2751 * - everything else shouldn't be ever a target of relocation.
2752 * These rules are not set in stone and probably will be adjusted as we get
2753 * more experience with using BPF CO-RE relocations.
2755 static int bpf_core_fields_are_compat(const struct btf *local_btf,
2757 const struct btf *targ_btf,
2760 const struct btf_type *local_type, *targ_type;
2763 local_type = skip_mods_and_typedefs(local_btf, local_id, &local_id);
2764 targ_type = skip_mods_and_typedefs(targ_btf, targ_id, &targ_id);
2765 if (!local_type || !targ_type)
2768 if (btf_is_composite(local_type) && btf_is_composite(targ_type))
2770 if (btf_kind(local_type) != btf_kind(targ_type))
2773 switch (btf_kind(local_type)) {
2777 case BTF_KIND_ENUM: {
2778 const char *local_name, *targ_name;
2779 size_t local_len, targ_len;
2781 local_name = btf__name_by_offset(local_btf,
2782 local_type->name_off);
2783 targ_name = btf__name_by_offset(targ_btf, targ_type->name_off);
2784 local_len = bpf_core_essential_name_len(local_name);
2785 targ_len = bpf_core_essential_name_len(targ_name);
2786 /* one of them is anonymous or both w/ same flavor-less names */
2787 return local_len == 0 || targ_len == 0 ||
2788 (local_len == targ_len &&
2789 strncmp(local_name, targ_name, local_len) == 0);
2792 /* just reject deprecated bitfield-like integers; all other
2793 * integers are by default compatible between each other
2795 return btf_int_offset(local_type) == 0 &&
2796 btf_int_offset(targ_type) == 0;
2797 case BTF_KIND_ARRAY:
2798 local_id = btf_array(local_type)->type;
2799 targ_id = btf_array(targ_type)->type;
2802 pr_warn("unexpected kind %d relocated, local [%d], target [%d]\n",
2803 btf_kind(local_type), local_id, targ_id);
2809 * Given single high-level named field accessor in local type, find
2810 * corresponding high-level accessor for a target type. Along the way,
2811 * maintain low-level spec for target as well. Also keep updating target
2814 * Searching is performed through recursive exhaustive enumeration of all
2815 * fields of a struct/union. If there are any anonymous (embedded)
2816 * structs/unions, they are recursively searched as well. If field with
2817 * desired name is found, check compatibility between local and target types,
2818 * before returning result.
2820 * 1 is returned, if field is found.
2821 * 0 is returned if no compatible field is found.
2822 * <0 is returned on error.
2824 static int bpf_core_match_member(const struct btf *local_btf,
2825 const struct bpf_core_accessor *local_acc,
2826 const struct btf *targ_btf,
2828 struct bpf_core_spec *spec,
2829 __u32 *next_targ_id)
2831 const struct btf_type *local_type, *targ_type;
2832 const struct btf_member *local_member, *m;
2833 const char *local_name, *targ_name;
2837 targ_type = skip_mods_and_typedefs(targ_btf, targ_id, &targ_id);
2840 if (!btf_is_composite(targ_type))
2843 local_id = local_acc->type_id;
2844 local_type = btf__type_by_id(local_btf, local_id);
2845 local_member = btf_members(local_type) + local_acc->idx;
2846 local_name = btf__name_by_offset(local_btf, local_member->name_off);
2848 n = btf_vlen(targ_type);
2849 m = btf_members(targ_type);
2850 for (i = 0; i < n; i++, m++) {
2853 bit_offset = btf_member_bit_offset(targ_type, i);
2855 /* too deep struct/union/array nesting */
2856 if (spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
2859 /* speculate this member will be the good one */
2860 spec->bit_offset += bit_offset;
2861 spec->raw_spec[spec->raw_len++] = i;
2863 targ_name = btf__name_by_offset(targ_btf, m->name_off);
2864 if (str_is_empty(targ_name)) {
2865 /* embedded struct/union, we need to go deeper */
2866 found = bpf_core_match_member(local_btf, local_acc,
2868 spec, next_targ_id);
2869 if (found) /* either found or error */
2871 } else if (strcmp(local_name, targ_name) == 0) {
2872 /* matching named field */
2873 struct bpf_core_accessor *targ_acc;
2875 targ_acc = &spec->spec[spec->len++];
2876 targ_acc->type_id = targ_id;
2878 targ_acc->name = targ_name;
2880 *next_targ_id = m->type;
2881 found = bpf_core_fields_are_compat(local_btf,
2885 spec->len--; /* pop accessor */
2888 /* member turned out not to be what we looked for */
2889 spec->bit_offset -= bit_offset;
2897 * Try to match local spec to a target type and, if successful, produce full
2898 * target spec (high-level, low-level + bit offset).
2900 static int bpf_core_spec_match(struct bpf_core_spec *local_spec,
2901 const struct btf *targ_btf, __u32 targ_id,
2902 struct bpf_core_spec *targ_spec)
2904 const struct btf_type *targ_type;
2905 const struct bpf_core_accessor *local_acc;
2906 struct bpf_core_accessor *targ_acc;
2909 memset(targ_spec, 0, sizeof(*targ_spec));
2910 targ_spec->btf = targ_btf;
2912 local_acc = &local_spec->spec[0];
2913 targ_acc = &targ_spec->spec[0];
2915 for (i = 0; i < local_spec->len; i++, local_acc++, targ_acc++) {
2916 targ_type = skip_mods_and_typedefs(targ_spec->btf, targ_id,
2921 if (local_acc->name) {
2922 matched = bpf_core_match_member(local_spec->btf,
2925 targ_spec, &targ_id);
2929 /* for i=0, targ_id is already treated as array element
2930 * type (because it's the original struct), for others
2931 * we should find array element type first
2934 const struct btf_array *a;
2936 if (!btf_is_array(targ_type))
2939 a = btf_array(targ_type);
2940 if (local_acc->idx >= a->nelems)
2942 if (!skip_mods_and_typedefs(targ_btf, a->type,
2947 /* too deep struct/union/array nesting */
2948 if (targ_spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
2951 targ_acc->type_id = targ_id;
2952 targ_acc->idx = local_acc->idx;
2953 targ_acc->name = NULL;
2955 targ_spec->raw_spec[targ_spec->raw_len] = targ_acc->idx;
2956 targ_spec->raw_len++;
2958 sz = btf__resolve_size(targ_btf, targ_id);
2961 targ_spec->bit_offset += local_acc->idx * sz * 8;
2968 static int bpf_core_calc_field_relo(const struct bpf_program *prog,
2969 const struct bpf_field_reloc *relo,
2970 const struct bpf_core_spec *spec,
2971 __u32 *val, bool *validate)
2973 const struct bpf_core_accessor *acc = &spec->spec[spec->len - 1];
2974 const struct btf_type *t = btf__type_by_id(spec->btf, acc->type_id);
2975 __u32 byte_off, byte_sz, bit_off, bit_sz;
2976 const struct btf_member *m;
2977 const struct btf_type *mt;
2981 /* a[n] accessor needs special handling */
2983 if (relo->kind == BPF_FIELD_BYTE_OFFSET) {
2984 *val = spec->bit_offset / 8;
2985 } else if (relo->kind == BPF_FIELD_BYTE_SIZE) {
2986 sz = btf__resolve_size(spec->btf, acc->type_id);
2991 pr_warn("prog '%s': relo %d at insn #%d can't be applied to array access\n",
2992 bpf_program__title(prog, false),
2993 relo->kind, relo->insn_off / 8);
3001 m = btf_members(t) + acc->idx;
3002 mt = skip_mods_and_typedefs(spec->btf, m->type, NULL);
3003 bit_off = spec->bit_offset;
3004 bit_sz = btf_member_bitfield_size(t, acc->idx);
3006 bitfield = bit_sz > 0;
3009 byte_off = bit_off / 8 / byte_sz * byte_sz;
3010 /* figure out smallest int size necessary for bitfield load */
3011 while (bit_off + bit_sz - byte_off * 8 > byte_sz * 8) {
3013 /* bitfield can't be read with 64-bit read */
3014 pr_warn("prog '%s': relo %d at insn #%d can't be satisfied for bitfield\n",
3015 bpf_program__title(prog, false),
3016 relo->kind, relo->insn_off / 8);
3020 byte_off = bit_off / 8 / byte_sz * byte_sz;
3023 sz = btf__resolve_size(spec->btf, m->type);
3027 byte_off = spec->bit_offset / 8;
3028 bit_sz = byte_sz * 8;
3031 /* for bitfields, all the relocatable aspects are ambiguous and we
3032 * might disagree with compiler, so turn off validation of expected
3033 * value, except for signedness
3036 *validate = !bitfield;
3038 switch (relo->kind) {
3039 case BPF_FIELD_BYTE_OFFSET:
3042 case BPF_FIELD_BYTE_SIZE:
3045 case BPF_FIELD_SIGNED:
3046 /* enums will be assumed unsigned */
3047 *val = btf_is_enum(mt) ||
3048 (btf_int_encoding(mt) & BTF_INT_SIGNED);
3050 *validate = true; /* signedness is never ambiguous */
3052 case BPF_FIELD_LSHIFT_U64:
3053 #if __BYTE_ORDER == __LITTLE_ENDIAN
3054 *val = 64 - (bit_off + bit_sz - byte_off * 8);
3056 *val = (8 - byte_sz) * 8 + (bit_off - byte_off * 8);
3059 case BPF_FIELD_RSHIFT_U64:
3062 *validate = true; /* right shift is never ambiguous */
3064 case BPF_FIELD_EXISTS:
3066 pr_warn("prog '%s': unknown relo %d at insn #%d\n",
3067 bpf_program__title(prog, false),
3068 relo->kind, relo->insn_off / 8);
3076 * Patch relocatable BPF instruction.
3078 * Patched value is determined by relocation kind and target specification.
3079 * For field existence relocation target spec will be NULL if field is not
3081 * Expected insn->imm value is determined using relocation kind and local
3082 * spec, and is checked before patching instruction. If actual insn->imm value
3083 * is wrong, bail out with error.
3085 * Currently three kinds of BPF instructions are supported:
3086 * 1. rX = <imm> (assignment with immediate operand);
3087 * 2. rX += <imm> (arithmetic operations with immediate operand);
3089 static int bpf_core_reloc_insn(struct bpf_program *prog,
3090 const struct bpf_field_reloc *relo,
3091 const struct bpf_core_spec *local_spec,
3092 const struct bpf_core_spec *targ_spec)
3094 bool failed = false, validate = true;
3095 __u32 orig_val, new_val;
3096 struct bpf_insn *insn;
3100 if (relo->insn_off % sizeof(struct bpf_insn))
3102 insn_idx = relo->insn_off / sizeof(struct bpf_insn);
3104 if (relo->kind == BPF_FIELD_EXISTS) {
3105 orig_val = 1; /* can't generate EXISTS relo w/o local field */
3106 new_val = targ_spec ? 1 : 0;
3107 } else if (!targ_spec) {
3109 new_val = (__u32)-1;
3111 err = bpf_core_calc_field_relo(prog, relo, local_spec,
3112 &orig_val, &validate);
3115 err = bpf_core_calc_field_relo(prog, relo, targ_spec,
3121 insn = &prog->insns[insn_idx];
3122 class = BPF_CLASS(insn->code);
3124 if (class == BPF_ALU || class == BPF_ALU64) {
3125 if (BPF_SRC(insn->code) != BPF_K)
3127 if (!failed && validate && insn->imm != orig_val) {
3128 pr_warn("prog '%s': unexpected insn #%d value: got %u, exp %u -> %u\n",
3129 bpf_program__title(prog, false), insn_idx,
3130 insn->imm, orig_val, new_val);
3133 orig_val = insn->imm;
3134 insn->imm = new_val;
3135 pr_debug("prog '%s': patched insn #%d (ALU/ALU64)%s imm %u -> %u\n",
3136 bpf_program__title(prog, false), insn_idx,
3137 failed ? " w/ failed reloc" : "", orig_val, new_val);
3139 pr_warn("prog '%s': trying to relocate unrecognized insn #%d, code:%x, src:%x, dst:%x, off:%x, imm:%x\n",
3140 bpf_program__title(prog, false),
3141 insn_idx, insn->code, insn->src_reg, insn->dst_reg,
3142 insn->off, insn->imm);
3149 static struct btf *btf_load_raw(const char *path)
3157 if (stat(path, &st))
3158 return ERR_PTR(-errno);
3160 data = malloc(st.st_size);
3162 return ERR_PTR(-ENOMEM);
3164 f = fopen(path, "rb");
3166 btf = ERR_PTR(-errno);
3170 read_cnt = fread(data, 1, st.st_size, f);
3172 if (read_cnt < st.st_size) {
3173 btf = ERR_PTR(-EBADF);
3177 btf = btf__new(data, read_cnt);
3185 * Probe few well-known locations for vmlinux kernel image and try to load BTF
3186 * data out of it to use for target BTF.
3188 static struct btf *bpf_core_find_kernel_btf(void)
3191 const char *path_fmt;
3194 /* try canonical vmlinux BTF through sysfs first */
3195 { "/sys/kernel/btf/vmlinux", true /* raw BTF */ },
3196 /* fall back to trying to find vmlinux ELF on disk otherwise */
3197 { "/boot/vmlinux-%1$s" },
3198 { "/lib/modules/%1$s/vmlinux-%1$s" },
3199 { "/lib/modules/%1$s/build/vmlinux" },
3200 { "/usr/lib/modules/%1$s/kernel/vmlinux" },
3201 { "/usr/lib/debug/boot/vmlinux-%1$s" },
3202 { "/usr/lib/debug/boot/vmlinux-%1$s.debug" },
3203 { "/usr/lib/debug/lib/modules/%1$s/vmlinux" },
3205 char path[PATH_MAX + 1];
3212 for (i = 0; i < ARRAY_SIZE(locations); i++) {
3213 snprintf(path, PATH_MAX, locations[i].path_fmt, buf.release);
3215 if (access(path, R_OK))
3218 if (locations[i].raw_btf)
3219 btf = btf_load_raw(path);
3221 btf = btf__parse_elf(path, NULL);
3223 pr_debug("loading kernel BTF '%s': %ld\n",
3224 path, IS_ERR(btf) ? PTR_ERR(btf) : 0);
3231 pr_warn("failed to find valid kernel BTF\n");
3232 return ERR_PTR(-ESRCH);
3235 /* Output spec definition in the format:
3236 * [<type-id>] (<type-name>) + <raw-spec> => <offset>@<spec>,
3237 * where <spec> is a C-syntax view of recorded field access, e.g.: x.a[3].b
3239 static void bpf_core_dump_spec(int level, const struct bpf_core_spec *spec)
3241 const struct btf_type *t;
3246 type_id = spec->spec[0].type_id;
3247 t = btf__type_by_id(spec->btf, type_id);
3248 s = btf__name_by_offset(spec->btf, t->name_off);
3249 libbpf_print(level, "[%u] %s + ", type_id, s);
3251 for (i = 0; i < spec->raw_len; i++)
3252 libbpf_print(level, "%d%s", spec->raw_spec[i],
3253 i == spec->raw_len - 1 ? " => " : ":");
3255 libbpf_print(level, "%u.%u @ &x",
3256 spec->bit_offset / 8, spec->bit_offset % 8);
3258 for (i = 0; i < spec->len; i++) {
3259 if (spec->spec[i].name)
3260 libbpf_print(level, ".%s", spec->spec[i].name);
3262 libbpf_print(level, "[%u]", spec->spec[i].idx);
3267 static size_t bpf_core_hash_fn(const void *key, void *ctx)
3272 static bool bpf_core_equal_fn(const void *k1, const void *k2, void *ctx)
3277 static void *u32_as_hash_key(__u32 x)
3279 return (void *)(uintptr_t)x;
3283 * CO-RE relocate single instruction.
3285 * The outline and important points of the algorithm:
3286 * 1. For given local type, find corresponding candidate target types.
3287 * Candidate type is a type with the same "essential" name, ignoring
3288 * everything after last triple underscore (___). E.g., `sample`,
3289 * `sample___flavor_one`, `sample___flavor_another_one`, are all candidates
3290 * for each other. Names with triple underscore are referred to as
3291 * "flavors" and are useful, among other things, to allow to
3292 * specify/support incompatible variations of the same kernel struct, which
3293 * might differ between different kernel versions and/or build
3296 * N.B. Struct "flavors" could be generated by bpftool's BTF-to-C
3297 * converter, when deduplicated BTF of a kernel still contains more than
3298 * one different types with the same name. In that case, ___2, ___3, etc
3299 * are appended starting from second name conflict. But start flavors are
3300 * also useful to be defined "locally", in BPF program, to extract same
3301 * data from incompatible changes between different kernel
3302 * versions/configurations. For instance, to handle field renames between
3303 * kernel versions, one can use two flavors of the struct name with the
3304 * same common name and use conditional relocations to extract that field,
3305 * depending on target kernel version.
3306 * 2. For each candidate type, try to match local specification to this
3307 * candidate target type. Matching involves finding corresponding
3308 * high-level spec accessors, meaning that all named fields should match,
3309 * as well as all array accesses should be within the actual bounds. Also,
3310 * types should be compatible (see bpf_core_fields_are_compat for details).
3311 * 3. It is supported and expected that there might be multiple flavors
3312 * matching the spec. As long as all the specs resolve to the same set of
3313 * offsets across all candidates, there is no error. If there is any
3314 * ambiguity, CO-RE relocation will fail. This is necessary to accomodate
3315 * imprefection of BTF deduplication, which can cause slight duplication of
3316 * the same BTF type, if some directly or indirectly referenced (by
3317 * pointer) type gets resolved to different actual types in different
3318 * object files. If such situation occurs, deduplicated BTF will end up
3319 * with two (or more) structurally identical types, which differ only in
3320 * types they refer to through pointer. This should be OK in most cases and
3322 * 4. Candidate types search is performed by linearly scanning through all
3323 * types in target BTF. It is anticipated that this is overall more
3324 * efficient memory-wise and not significantly worse (if not better)
3325 * CPU-wise compared to prebuilding a map from all local type names to
3326 * a list of candidate type names. It's also sped up by caching resolved
3327 * list of matching candidates per each local "root" type ID, that has at
3328 * least one bpf_field_reloc associated with it. This list is shared
3329 * between multiple relocations for the same type ID and is updated as some
3330 * of the candidates are pruned due to structural incompatibility.
3332 static int bpf_core_reloc_field(struct bpf_program *prog,
3333 const struct bpf_field_reloc *relo,
3335 const struct btf *local_btf,
3336 const struct btf *targ_btf,
3337 struct hashmap *cand_cache)
3339 const char *prog_name = bpf_program__title(prog, false);
3340 struct bpf_core_spec local_spec, cand_spec, targ_spec;
3341 const void *type_key = u32_as_hash_key(relo->type_id);
3342 const struct btf_type *local_type, *cand_type;
3343 const char *local_name, *cand_name;
3344 struct ids_vec *cand_ids;
3345 __u32 local_id, cand_id;
3346 const char *spec_str;
3349 local_id = relo->type_id;
3350 local_type = btf__type_by_id(local_btf, local_id);
3354 local_name = btf__name_by_offset(local_btf, local_type->name_off);
3355 if (str_is_empty(local_name))
3358 spec_str = btf__name_by_offset(local_btf, relo->access_str_off);
3359 if (str_is_empty(spec_str))
3362 err = bpf_core_spec_parse(local_btf, local_id, spec_str, &local_spec);
3364 pr_warn("prog '%s': relo #%d: parsing [%d] %s + %s failed: %d\n",
3365 prog_name, relo_idx, local_id, local_name, spec_str,
3370 pr_debug("prog '%s': relo #%d: kind %d, spec is ", prog_name, relo_idx,
3372 bpf_core_dump_spec(LIBBPF_DEBUG, &local_spec);
3373 libbpf_print(LIBBPF_DEBUG, "\n");
3375 if (!hashmap__find(cand_cache, type_key, (void **)&cand_ids)) {
3376 cand_ids = bpf_core_find_cands(local_btf, local_id, targ_btf);
3377 if (IS_ERR(cand_ids)) {
3378 pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s: %ld",
3379 prog_name, relo_idx, local_id, local_name,
3381 return PTR_ERR(cand_ids);
3383 err = hashmap__set(cand_cache, type_key, cand_ids, NULL, NULL);
3385 bpf_core_free_cands(cand_ids);
3390 for (i = 0, j = 0; i < cand_ids->len; i++) {
3391 cand_id = cand_ids->data[i];
3392 cand_type = btf__type_by_id(targ_btf, cand_id);
3393 cand_name = btf__name_by_offset(targ_btf, cand_type->name_off);
3395 err = bpf_core_spec_match(&local_spec, targ_btf,
3396 cand_id, &cand_spec);
3397 pr_debug("prog '%s': relo #%d: matching candidate #%d %s against spec ",
3398 prog_name, relo_idx, i, cand_name);
3399 bpf_core_dump_spec(LIBBPF_DEBUG, &cand_spec);
3400 libbpf_print(LIBBPF_DEBUG, ": %d\n", err);
3402 pr_warn("prog '%s': relo #%d: matching error: %d\n",
3403 prog_name, relo_idx, err);
3410 targ_spec = cand_spec;
3411 } else if (cand_spec.bit_offset != targ_spec.bit_offset) {
3412 /* if there are many candidates, they should all
3413 * resolve to the same bit offset
3415 pr_warn("prog '%s': relo #%d: offset ambiguity: %u != %u\n",
3416 prog_name, relo_idx, cand_spec.bit_offset,
3417 targ_spec.bit_offset);
3421 cand_ids->data[j++] = cand_spec.spec[0].type_id;
3425 * For BPF_FIELD_EXISTS relo or when relaxed CO-RE reloc mode is
3426 * requested, it's expected that we might not find any candidates.
3427 * In this case, if field wasn't found in any candidate, the list of
3428 * candidates shouldn't change at all, we'll just handle relocating
3429 * appropriately, depending on relo's kind.
3434 if (j == 0 && !prog->obj->relaxed_core_relocs &&
3435 relo->kind != BPF_FIELD_EXISTS) {
3436 pr_warn("prog '%s': relo #%d: no matching targets found for [%d] %s + %s\n",
3437 prog_name, relo_idx, local_id, local_name, spec_str);
3441 /* bpf_core_reloc_insn should know how to handle missing targ_spec */
3442 err = bpf_core_reloc_insn(prog, relo, &local_spec,
3443 j ? &targ_spec : NULL);
3445 pr_warn("prog '%s': relo #%d: failed to patch insn at offset %d: %d\n",
3446 prog_name, relo_idx, relo->insn_off, err);
3454 bpf_core_reloc_fields(struct bpf_object *obj, const char *targ_btf_path)
3456 const struct btf_ext_info_sec *sec;
3457 const struct bpf_field_reloc *rec;
3458 const struct btf_ext_info *seg;
3459 struct hashmap_entry *entry;
3460 struct hashmap *cand_cache = NULL;
3461 struct bpf_program *prog;
3462 struct btf *targ_btf;
3463 const char *sec_name;
3467 targ_btf = btf__parse_elf(targ_btf_path, NULL);
3469 targ_btf = bpf_core_find_kernel_btf();
3470 if (IS_ERR(targ_btf)) {
3471 pr_warn("failed to get target BTF: %ld\n", PTR_ERR(targ_btf));
3472 return PTR_ERR(targ_btf);
3475 cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
3476 if (IS_ERR(cand_cache)) {
3477 err = PTR_ERR(cand_cache);
3481 seg = &obj->btf_ext->field_reloc_info;
3482 for_each_btf_ext_sec(seg, sec) {
3483 sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
3484 if (str_is_empty(sec_name)) {
3488 prog = bpf_object__find_program_by_title(obj, sec_name);
3490 pr_warn("failed to find program '%s' for CO-RE offset relocation\n",
3496 pr_debug("prog '%s': performing %d CO-RE offset relocs\n",
3497 sec_name, sec->num_info);
3499 for_each_btf_ext_rec(seg, sec, i, rec) {
3500 err = bpf_core_reloc_field(prog, rec, i, obj->btf,
3501 targ_btf, cand_cache);
3503 pr_warn("prog '%s': relo #%d: failed to relocate: %d\n",
3511 btf__free(targ_btf);
3512 if (!IS_ERR_OR_NULL(cand_cache)) {
3513 hashmap__for_each_entry(cand_cache, entry, i) {
3514 bpf_core_free_cands(entry->value);
3516 hashmap__free(cand_cache);
3522 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
3526 if (obj->btf_ext->field_reloc_info.len)
3527 err = bpf_core_reloc_fields(obj, targ_btf_path);
3533 bpf_program__reloc_text(struct bpf_program *prog, struct bpf_object *obj,
3534 struct reloc_desc *relo)
3536 struct bpf_insn *insn, *new_insn;
3537 struct bpf_program *text;
3541 if (relo->type != RELO_CALL)
3542 return -LIBBPF_ERRNO__RELOC;
3544 if (prog->idx == obj->efile.text_shndx) {
3545 pr_warn("relo in .text insn %d into off %d (insn #%d)\n",
3546 relo->insn_idx, relo->sym_off, relo->sym_off / 8);
3547 return -LIBBPF_ERRNO__RELOC;
3550 if (prog->main_prog_cnt == 0) {
3551 text = bpf_object__find_prog_by_idx(obj, obj->efile.text_shndx);
3553 pr_warn("no .text section found yet relo into text exist\n");
3554 return -LIBBPF_ERRNO__RELOC;
3556 new_cnt = prog->insns_cnt + text->insns_cnt;
3557 new_insn = reallocarray(prog->insns, new_cnt, sizeof(*insn));
3559 pr_warn("oom in prog realloc\n");
3562 prog->insns = new_insn;
3565 err = bpf_program_reloc_btf_ext(prog, obj,
3572 memcpy(new_insn + prog->insns_cnt, text->insns,
3573 text->insns_cnt * sizeof(*insn));
3574 prog->main_prog_cnt = prog->insns_cnt;
3575 prog->insns_cnt = new_cnt;
3576 pr_debug("added %zd insn from %s to prog %s\n",
3577 text->insns_cnt, text->section_name,
3578 prog->section_name);
3580 insn = &prog->insns[relo->insn_idx];
3581 insn->imm += relo->sym_off / 8 + prog->main_prog_cnt - relo->insn_idx;
3586 bpf_program__relocate(struct bpf_program *prog, struct bpf_object *obj)
3594 err = bpf_program_reloc_btf_ext(prog, obj,
3595 prog->section_name, 0);
3600 if (!prog->reloc_desc)
3603 for (i = 0; i < prog->nr_reloc; i++) {
3604 struct reloc_desc *relo = &prog->reloc_desc[i];
3606 if (relo->type == RELO_LD64 || relo->type == RELO_DATA) {
3607 struct bpf_insn *insn = &prog->insns[relo->insn_idx];
3609 if (relo->insn_idx + 1 >= (int)prog->insns_cnt) {
3610 pr_warn("relocation out of range: '%s'\n",
3611 prog->section_name);
3612 return -LIBBPF_ERRNO__RELOC;
3615 if (relo->type != RELO_DATA) {
3616 insn[0].src_reg = BPF_PSEUDO_MAP_FD;
3618 insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
3619 insn[1].imm = insn[0].imm + relo->sym_off;
3621 insn[0].imm = obj->maps[relo->map_idx].fd;
3622 } else if (relo->type == RELO_CALL) {
3623 err = bpf_program__reloc_text(prog, obj, relo);
3629 zfree(&prog->reloc_desc);
3635 bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
3637 struct bpf_program *prog;
3642 err = bpf_object__relocate_core(obj, targ_btf_path);
3644 pr_warn("failed to perform CO-RE relocations: %d\n",
3649 for (i = 0; i < obj->nr_programs; i++) {
3650 prog = &obj->programs[i];
3652 err = bpf_program__relocate(prog, obj);
3654 pr_warn("failed to relocate '%s'\n", prog->section_name);
3661 static int bpf_object__collect_reloc(struct bpf_object *obj)
3665 if (!obj_elf_valid(obj)) {
3666 pr_warn("Internal error: elf object is closed\n");
3667 return -LIBBPF_ERRNO__INTERNAL;
3670 for (i = 0; i < obj->efile.nr_reloc_sects; i++) {
3671 GElf_Shdr *shdr = &obj->efile.reloc_sects[i].shdr;
3672 Elf_Data *data = obj->efile.reloc_sects[i].data;
3673 int idx = shdr->sh_info;
3674 struct bpf_program *prog;
3676 if (shdr->sh_type != SHT_REL) {
3677 pr_warn("internal error at %d\n", __LINE__);
3678 return -LIBBPF_ERRNO__INTERNAL;
3681 prog = bpf_object__find_prog_by_idx(obj, idx);
3683 pr_warn("relocation failed: no section(%d)\n", idx);
3684 return -LIBBPF_ERRNO__RELOC;
3687 err = bpf_program__collect_reloc(prog, shdr, data, obj);
3695 load_program(struct bpf_program *prog, struct bpf_insn *insns, int insns_cnt,
3696 char *license, __u32 kern_version, int *pfd)
3698 struct bpf_load_program_attr load_attr;
3699 char *cp, errmsg[STRERR_BUFSIZE];
3700 int log_buf_size = BPF_LOG_BUF_SIZE;
3704 if (!insns || !insns_cnt)
3707 memset(&load_attr, 0, sizeof(struct bpf_load_program_attr));
3708 load_attr.prog_type = prog->type;
3709 load_attr.expected_attach_type = prog->expected_attach_type;
3710 if (prog->caps->name)
3711 load_attr.name = prog->name;
3712 load_attr.insns = insns;
3713 load_attr.insns_cnt = insns_cnt;
3714 load_attr.license = license;
3715 if (prog->type == BPF_PROG_TYPE_TRACING) {
3716 load_attr.attach_prog_fd = prog->attach_prog_fd;
3717 load_attr.attach_btf_id = prog->attach_btf_id;
3719 load_attr.kern_version = kern_version;
3720 load_attr.prog_ifindex = prog->prog_ifindex;
3722 /* if .BTF.ext was loaded, kernel supports associated BTF for prog */
3723 if (prog->obj->btf_ext)
3724 btf_fd = bpf_object__btf_fd(prog->obj);
3727 load_attr.prog_btf_fd = btf_fd >= 0 ? btf_fd : 0;
3728 load_attr.func_info = prog->func_info;
3729 load_attr.func_info_rec_size = prog->func_info_rec_size;
3730 load_attr.func_info_cnt = prog->func_info_cnt;
3731 load_attr.line_info = prog->line_info;
3732 load_attr.line_info_rec_size = prog->line_info_rec_size;
3733 load_attr.line_info_cnt = prog->line_info_cnt;
3734 load_attr.log_level = prog->log_level;
3735 load_attr.prog_flags = prog->prog_flags;
3738 log_buf = malloc(log_buf_size);
3740 pr_warn("Alloc log buffer for bpf loader error, continue without log\n");
3742 ret = bpf_load_program_xattr(&load_attr, log_buf, log_buf_size);
3745 if (load_attr.log_level)
3746 pr_debug("verifier log:\n%s", log_buf);
3752 if (errno == ENOSPC) {
3758 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
3759 pr_warn("load bpf program failed: %s\n", cp);
3761 if (log_buf && log_buf[0] != '\0') {
3762 ret = -LIBBPF_ERRNO__VERIFY;
3763 pr_warn("-- BEGIN DUMP LOG ---\n");
3764 pr_warn("\n%s\n", log_buf);
3765 pr_warn("-- END LOG --\n");
3766 } else if (load_attr.insns_cnt >= BPF_MAXINSNS) {
3767 pr_warn("Program too large (%zu insns), at most %d insns\n",
3768 load_attr.insns_cnt, BPF_MAXINSNS);
3769 ret = -LIBBPF_ERRNO__PROG2BIG;
3770 } else if (load_attr.prog_type != BPF_PROG_TYPE_KPROBE) {
3771 /* Wrong program type? */
3774 load_attr.prog_type = BPF_PROG_TYPE_KPROBE;
3775 load_attr.expected_attach_type = 0;
3776 fd = bpf_load_program_xattr(&load_attr, NULL, 0);
3779 ret = -LIBBPF_ERRNO__PROGTYPE;
3790 bpf_program__load(struct bpf_program *prog,
3791 char *license, __u32 kern_version)
3795 if (prog->instances.nr < 0 || !prog->instances.fds) {
3796 if (prog->preprocessor) {
3797 pr_warn("Internal error: can't load program '%s'\n",
3798 prog->section_name);
3799 return -LIBBPF_ERRNO__INTERNAL;
3802 prog->instances.fds = malloc(sizeof(int));
3803 if (!prog->instances.fds) {
3804 pr_warn("Not enough memory for BPF fds\n");
3807 prog->instances.nr = 1;
3808 prog->instances.fds[0] = -1;
3811 if (!prog->preprocessor) {
3812 if (prog->instances.nr != 1) {
3813 pr_warn("Program '%s' is inconsistent: nr(%d) != 1\n",
3814 prog->section_name, prog->instances.nr);
3816 err = load_program(prog, prog->insns, prog->insns_cnt,
3817 license, kern_version, &fd);
3819 prog->instances.fds[0] = fd;
3823 for (i = 0; i < prog->instances.nr; i++) {
3824 struct bpf_prog_prep_result result;
3825 bpf_program_prep_t preprocessor = prog->preprocessor;
3827 memset(&result, 0, sizeof(result));
3828 err = preprocessor(prog, i, prog->insns,
3829 prog->insns_cnt, &result);
3831 pr_warn("Preprocessing the %dth instance of program '%s' failed\n",
3832 i, prog->section_name);
3836 if (!result.new_insn_ptr || !result.new_insn_cnt) {
3837 pr_debug("Skip loading the %dth instance of program '%s'\n",
3838 i, prog->section_name);
3839 prog->instances.fds[i] = -1;
3845 err = load_program(prog, result.new_insn_ptr,
3846 result.new_insn_cnt,
3847 license, kern_version, &fd);
3850 pr_warn("Loading the %dth instance of program '%s' failed\n",
3851 i, prog->section_name);
3857 prog->instances.fds[i] = fd;
3861 pr_warn("failed to load program '%s'\n", prog->section_name);
3862 zfree(&prog->insns);
3863 prog->insns_cnt = 0;
3867 static bool bpf_program__is_function_storage(const struct bpf_program *prog,
3868 const struct bpf_object *obj)
3870 return prog->idx == obj->efile.text_shndx && obj->has_pseudo_calls;
3874 bpf_object__load_progs(struct bpf_object *obj, int log_level)
3879 for (i = 0; i < obj->nr_programs; i++) {
3880 if (bpf_program__is_function_storage(&obj->programs[i], obj))
3882 obj->programs[i].log_level |= log_level;
3883 err = bpf_program__load(&obj->programs[i],
3892 static int libbpf_find_attach_btf_id(const char *name,
3893 enum bpf_attach_type attach_type,
3894 __u32 attach_prog_fd);
3895 static struct bpf_object *
3896 __bpf_object__open(const char *path, const void *obj_buf, size_t obj_buf_sz,
3897 struct bpf_object_open_opts *opts)
3899 struct bpf_program *prog;
3900 struct bpf_object *obj;
3901 const char *obj_name;
3903 __u32 attach_prog_fd;
3906 if (elf_version(EV_CURRENT) == EV_NONE) {
3907 pr_warn("failed to init libelf for %s\n",
3908 path ? : "(mem buf)");
3909 return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
3912 if (!OPTS_VALID(opts, bpf_object_open_opts))
3913 return ERR_PTR(-EINVAL);
3915 obj_name = OPTS_GET(opts, object_name, NULL);
3918 snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
3919 (unsigned long)obj_buf,
3920 (unsigned long)obj_buf_sz);
3921 obj_name = tmp_name;
3924 pr_debug("loading object '%s' from buffer\n", obj_name);
3927 obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
3931 obj->relaxed_core_relocs = OPTS_GET(opts, relaxed_core_relocs, false);
3932 attach_prog_fd = OPTS_GET(opts, attach_prog_fd, 0);
3934 err = bpf_object__elf_init(obj);
3935 err = err ? : bpf_object__check_endianness(obj);
3936 err = err ? : bpf_object__elf_collect(obj);
3937 err = err ? : bpf_object__init_maps(obj, opts);
3938 err = err ? : bpf_object__init_prog_names(obj);
3939 err = err ? : bpf_object__collect_reloc(obj);
3942 bpf_object__elf_finish(obj);
3944 bpf_object__for_each_program(prog, obj) {
3945 enum bpf_prog_type prog_type;
3946 enum bpf_attach_type attach_type;
3948 err = libbpf_prog_type_by_name(prog->section_name, &prog_type,
3951 /* couldn't guess, but user might manually specify */
3956 bpf_program__set_type(prog, prog_type);
3957 bpf_program__set_expected_attach_type(prog, attach_type);
3958 if (prog_type == BPF_PROG_TYPE_TRACING) {
3959 err = libbpf_find_attach_btf_id(prog->section_name,
3964 prog->attach_btf_id = err;
3965 prog->attach_prog_fd = attach_prog_fd;
3971 bpf_object__close(obj);
3972 return ERR_PTR(err);
3975 static struct bpf_object *
3976 __bpf_object__open_xattr(struct bpf_object_open_attr *attr, int flags)
3978 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts,
3979 .relaxed_maps = flags & MAPS_RELAX_COMPAT,
3982 /* param validation */
3986 pr_debug("loading %s\n", attr->file);
3987 return __bpf_object__open(attr->file, NULL, 0, &opts);
3990 struct bpf_object *bpf_object__open_xattr(struct bpf_object_open_attr *attr)
3992 return __bpf_object__open_xattr(attr, 0);
3995 struct bpf_object *bpf_object__open(const char *path)
3997 struct bpf_object_open_attr attr = {
3999 .prog_type = BPF_PROG_TYPE_UNSPEC,
4002 return bpf_object__open_xattr(&attr);
4006 bpf_object__open_file(const char *path, struct bpf_object_open_opts *opts)
4009 return ERR_PTR(-EINVAL);
4011 pr_debug("loading %s\n", path);
4013 return __bpf_object__open(path, NULL, 0, opts);
4017 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
4018 struct bpf_object_open_opts *opts)
4020 if (!obj_buf || obj_buf_sz == 0)
4021 return ERR_PTR(-EINVAL);
4023 return __bpf_object__open(NULL, obj_buf, obj_buf_sz, opts);
4027 bpf_object__open_buffer(const void *obj_buf, size_t obj_buf_sz,
4030 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts,
4031 .object_name = name,
4032 /* wrong default, but backwards-compatible */
4033 .relaxed_maps = true,
4036 /* returning NULL is wrong, but backwards-compatible */
4037 if (!obj_buf || obj_buf_sz == 0)
4040 return bpf_object__open_mem(obj_buf, obj_buf_sz, &opts);
4043 int bpf_object__unload(struct bpf_object *obj)
4050 for (i = 0; i < obj->nr_maps; i++)
4051 zclose(obj->maps[i].fd);
4053 for (i = 0; i < obj->nr_programs; i++)
4054 bpf_program__unload(&obj->programs[i]);
4059 static int bpf_object__sanitize_maps(struct bpf_object *obj)
4063 bpf_object__for_each_map(m, obj) {
4064 if (!bpf_map__is_internal(m))
4066 if (!obj->caps.global_data) {
4067 pr_warn("kernel doesn't support global data\n");
4070 if (!obj->caps.array_mmap)
4071 m->def.map_flags ^= BPF_F_MMAPABLE;
4077 int bpf_object__load_xattr(struct bpf_object_load_attr *attr)
4079 struct bpf_object *obj;
4089 pr_warn("object should not be loaded twice\n");
4095 err = bpf_object__probe_caps(obj);
4096 err = err ? : bpf_object__sanitize_and_load_btf(obj);
4097 err = err ? : bpf_object__sanitize_maps(obj);
4098 err = err ? : bpf_object__create_maps(obj);
4099 err = err ? : bpf_object__relocate(obj, attr->target_btf_path);
4100 err = err ? : bpf_object__load_progs(obj, attr->log_level);
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 #define SEC_DEF(sec_pfx, ptype, ...) { \
4977 .len = sizeof(sec_pfx) - 1, \
4978 .prog_type = BPF_PROG_TYPE_##ptype, \
4984 typedef struct bpf_link *(*attach_fn_t)(const struct bpf_sec_def *sec,
4985 struct bpf_program *prog);
4987 static struct bpf_link *attach_kprobe(const struct bpf_sec_def *sec,
4988 struct bpf_program *prog);
4989 static struct bpf_link *attach_tp(const struct bpf_sec_def *sec,
4990 struct bpf_program *prog);
4991 static struct bpf_link *attach_raw_tp(const struct bpf_sec_def *sec,
4992 struct bpf_program *prog);
4993 static struct bpf_link *attach_trace(const struct bpf_sec_def *sec,
4994 struct bpf_program *prog);
4996 struct bpf_sec_def {
4999 enum bpf_prog_type prog_type;
5000 enum bpf_attach_type expected_attach_type;
5003 enum bpf_attach_type attach_type;
5004 attach_fn_t attach_fn;
5007 static const struct bpf_sec_def section_defs[] = {
5008 BPF_PROG_SEC("socket", BPF_PROG_TYPE_SOCKET_FILTER),
5009 BPF_PROG_SEC("sk_reuseport", BPF_PROG_TYPE_SK_REUSEPORT),
5010 SEC_DEF("kprobe/", KPROBE,
5011 .attach_fn = attach_kprobe),
5012 BPF_PROG_SEC("uprobe/", BPF_PROG_TYPE_KPROBE),
5013 SEC_DEF("kretprobe/", KPROBE,
5014 .attach_fn = attach_kprobe),
5015 BPF_PROG_SEC("uretprobe/", BPF_PROG_TYPE_KPROBE),
5016 BPF_PROG_SEC("classifier", BPF_PROG_TYPE_SCHED_CLS),
5017 BPF_PROG_SEC("action", BPF_PROG_TYPE_SCHED_ACT),
5018 SEC_DEF("tracepoint/", TRACEPOINT,
5019 .attach_fn = attach_tp),
5020 SEC_DEF("tp/", TRACEPOINT,
5021 .attach_fn = attach_tp),
5022 SEC_DEF("raw_tracepoint/", RAW_TRACEPOINT,
5023 .attach_fn = attach_raw_tp),
5024 SEC_DEF("raw_tp/", RAW_TRACEPOINT,
5025 .attach_fn = attach_raw_tp),
5026 SEC_DEF("tp_btf/", TRACING,
5027 .expected_attach_type = BPF_TRACE_RAW_TP,
5028 .is_attach_btf = true,
5029 .attach_fn = attach_trace),
5030 SEC_DEF("fentry/", TRACING,
5031 .expected_attach_type = BPF_TRACE_FENTRY,
5032 .is_attach_btf = true,
5033 .attach_fn = attach_trace),
5034 SEC_DEF("fexit/", TRACING,
5035 .expected_attach_type = BPF_TRACE_FEXIT,
5036 .is_attach_btf = true,
5037 .attach_fn = attach_trace),
5038 BPF_PROG_SEC("xdp", BPF_PROG_TYPE_XDP),
5039 BPF_PROG_SEC("perf_event", BPF_PROG_TYPE_PERF_EVENT),
5040 BPF_PROG_SEC("lwt_in", BPF_PROG_TYPE_LWT_IN),
5041 BPF_PROG_SEC("lwt_out", BPF_PROG_TYPE_LWT_OUT),
5042 BPF_PROG_SEC("lwt_xmit", BPF_PROG_TYPE_LWT_XMIT),
5043 BPF_PROG_SEC("lwt_seg6local", BPF_PROG_TYPE_LWT_SEG6LOCAL),
5044 BPF_APROG_SEC("cgroup_skb/ingress", BPF_PROG_TYPE_CGROUP_SKB,
5045 BPF_CGROUP_INET_INGRESS),
5046 BPF_APROG_SEC("cgroup_skb/egress", BPF_PROG_TYPE_CGROUP_SKB,
5047 BPF_CGROUP_INET_EGRESS),
5048 BPF_APROG_COMPAT("cgroup/skb", BPF_PROG_TYPE_CGROUP_SKB),
5049 BPF_APROG_SEC("cgroup/sock", BPF_PROG_TYPE_CGROUP_SOCK,
5050 BPF_CGROUP_INET_SOCK_CREATE),
5051 BPF_EAPROG_SEC("cgroup/post_bind4", BPF_PROG_TYPE_CGROUP_SOCK,
5052 BPF_CGROUP_INET4_POST_BIND),
5053 BPF_EAPROG_SEC("cgroup/post_bind6", BPF_PROG_TYPE_CGROUP_SOCK,
5054 BPF_CGROUP_INET6_POST_BIND),
5055 BPF_APROG_SEC("cgroup/dev", BPF_PROG_TYPE_CGROUP_DEVICE,
5057 BPF_APROG_SEC("sockops", BPF_PROG_TYPE_SOCK_OPS,
5058 BPF_CGROUP_SOCK_OPS),
5059 BPF_APROG_SEC("sk_skb/stream_parser", BPF_PROG_TYPE_SK_SKB,
5060 BPF_SK_SKB_STREAM_PARSER),
5061 BPF_APROG_SEC("sk_skb/stream_verdict", BPF_PROG_TYPE_SK_SKB,
5062 BPF_SK_SKB_STREAM_VERDICT),
5063 BPF_APROG_COMPAT("sk_skb", BPF_PROG_TYPE_SK_SKB),
5064 BPF_APROG_SEC("sk_msg", BPF_PROG_TYPE_SK_MSG,
5065 BPF_SK_MSG_VERDICT),
5066 BPF_APROG_SEC("lirc_mode2", BPF_PROG_TYPE_LIRC_MODE2,
5068 BPF_APROG_SEC("flow_dissector", BPF_PROG_TYPE_FLOW_DISSECTOR,
5069 BPF_FLOW_DISSECTOR),
5070 BPF_EAPROG_SEC("cgroup/bind4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
5071 BPF_CGROUP_INET4_BIND),
5072 BPF_EAPROG_SEC("cgroup/bind6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
5073 BPF_CGROUP_INET6_BIND),
5074 BPF_EAPROG_SEC("cgroup/connect4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
5075 BPF_CGROUP_INET4_CONNECT),
5076 BPF_EAPROG_SEC("cgroup/connect6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
5077 BPF_CGROUP_INET6_CONNECT),
5078 BPF_EAPROG_SEC("cgroup/sendmsg4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
5079 BPF_CGROUP_UDP4_SENDMSG),
5080 BPF_EAPROG_SEC("cgroup/sendmsg6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
5081 BPF_CGROUP_UDP6_SENDMSG),
5082 BPF_EAPROG_SEC("cgroup/recvmsg4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
5083 BPF_CGROUP_UDP4_RECVMSG),
5084 BPF_EAPROG_SEC("cgroup/recvmsg6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
5085 BPF_CGROUP_UDP6_RECVMSG),
5086 BPF_EAPROG_SEC("cgroup/sysctl", BPF_PROG_TYPE_CGROUP_SYSCTL,
5088 BPF_EAPROG_SEC("cgroup/getsockopt", BPF_PROG_TYPE_CGROUP_SOCKOPT,
5089 BPF_CGROUP_GETSOCKOPT),
5090 BPF_EAPROG_SEC("cgroup/setsockopt", BPF_PROG_TYPE_CGROUP_SOCKOPT,
5091 BPF_CGROUP_SETSOCKOPT),
5094 #undef BPF_PROG_SEC_IMPL
5096 #undef BPF_APROG_SEC
5097 #undef BPF_EAPROG_SEC
5098 #undef BPF_APROG_COMPAT
5101 #define MAX_TYPE_NAME_SIZE 32
5103 static const struct bpf_sec_def *find_sec_def(const char *sec_name)
5105 int i, n = ARRAY_SIZE(section_defs);
5107 for (i = 0; i < n; i++) {
5108 if (strncmp(sec_name,
5109 section_defs[i].sec, section_defs[i].len))
5111 return §ion_defs[i];
5116 static char *libbpf_get_type_names(bool attach_type)
5118 int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
5126 /* Forge string buf with all available names */
5127 for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
5128 if (attach_type && !section_defs[i].is_attachable)
5131 if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
5136 strcat(buf, section_defs[i].sec);
5142 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
5143 enum bpf_attach_type *expected_attach_type)
5145 const struct bpf_sec_def *sec_def;
5151 sec_def = find_sec_def(name);
5153 *prog_type = sec_def->prog_type;
5154 *expected_attach_type = sec_def->expected_attach_type;
5158 pr_warn("failed to guess program type from ELF section '%s'\n", name);
5159 type_names = libbpf_get_type_names(false);
5160 if (type_names != NULL) {
5161 pr_info("supported section(type) names are:%s\n", type_names);
5168 #define BTF_PREFIX "btf_trace_"
5169 int libbpf_find_vmlinux_btf_id(const char *name,
5170 enum bpf_attach_type attach_type)
5172 struct btf *btf = bpf_core_find_kernel_btf();
5173 char raw_tp_btf[128] = BTF_PREFIX;
5174 char *dst = raw_tp_btf + sizeof(BTF_PREFIX) - 1;
5175 const char *btf_name;
5180 pr_warn("vmlinux BTF is not found\n");
5184 if (attach_type == BPF_TRACE_RAW_TP) {
5185 /* prepend "btf_trace_" prefix per kernel convention */
5186 strncat(dst, name, sizeof(raw_tp_btf) - sizeof(BTF_PREFIX));
5187 btf_name = raw_tp_btf;
5188 kind = BTF_KIND_TYPEDEF;
5191 kind = BTF_KIND_FUNC;
5193 err = btf__find_by_name_kind(btf, btf_name, kind);
5198 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd)
5200 struct bpf_prog_info_linear *info_linear;
5201 struct bpf_prog_info *info;
5202 struct btf *btf = NULL;
5205 info_linear = bpf_program__get_prog_info_linear(attach_prog_fd, 0);
5206 if (IS_ERR_OR_NULL(info_linear)) {
5207 pr_warn("failed get_prog_info_linear for FD %d\n",
5211 info = &info_linear->info;
5212 if (!info->btf_id) {
5213 pr_warn("The target program doesn't have BTF\n");
5216 if (btf__get_from_id(info->btf_id, &btf)) {
5217 pr_warn("Failed to get BTF of the program\n");
5220 err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
5223 pr_warn("%s is not found in prog's BTF\n", name);
5231 static int libbpf_find_attach_btf_id(const char *name,
5232 enum bpf_attach_type attach_type,
5233 __u32 attach_prog_fd)
5240 for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
5241 if (!section_defs[i].is_attach_btf)
5243 if (strncmp(name, section_defs[i].sec, section_defs[i].len))
5246 err = libbpf_find_prog_btf_id(name + section_defs[i].len,
5249 err = libbpf_find_vmlinux_btf_id(name + section_defs[i].len,
5252 pr_warn("%s is not found in vmlinux BTF\n", name);
5255 pr_warn("failed to identify btf_id based on ELF section name '%s'\n", name);
5259 int libbpf_attach_type_by_name(const char *name,
5260 enum bpf_attach_type *attach_type)
5268 for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
5269 if (strncmp(name, section_defs[i].sec, section_defs[i].len))
5271 if (!section_defs[i].is_attachable)
5273 *attach_type = section_defs[i].attach_type;
5276 pr_warn("failed to guess attach type based on ELF section name '%s'\n", name);
5277 type_names = libbpf_get_type_names(true);
5278 if (type_names != NULL) {
5279 pr_info("attachable section(type) names are:%s\n", type_names);
5286 int bpf_map__fd(const struct bpf_map *map)
5288 return map ? map->fd : -EINVAL;
5291 const struct bpf_map_def *bpf_map__def(const struct bpf_map *map)
5293 return map ? &map->def : ERR_PTR(-EINVAL);
5296 const char *bpf_map__name(const struct bpf_map *map)
5298 return map ? map->name : NULL;
5301 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
5303 return map ? map->btf_key_type_id : 0;
5306 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
5308 return map ? map->btf_value_type_id : 0;
5311 int bpf_map__set_priv(struct bpf_map *map, void *priv,
5312 bpf_map_clear_priv_t clear_priv)
5318 if (map->clear_priv)
5319 map->clear_priv(map, map->priv);
5323 map->clear_priv = clear_priv;
5327 void *bpf_map__priv(const struct bpf_map *map)
5329 return map ? map->priv : ERR_PTR(-EINVAL);
5332 bool bpf_map__is_offload_neutral(const struct bpf_map *map)
5334 return map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY;
5337 bool bpf_map__is_internal(const struct bpf_map *map)
5339 return map->libbpf_type != LIBBPF_MAP_UNSPEC;
5342 void bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
5344 map->map_ifindex = ifindex;
5347 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
5349 if (!bpf_map_type__is_map_in_map(map->def.type)) {
5350 pr_warn("error: unsupported map type\n");
5353 if (map->inner_map_fd != -1) {
5354 pr_warn("error: inner_map_fd already specified\n");
5357 map->inner_map_fd = fd;
5361 static struct bpf_map *
5362 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
5365 struct bpf_map *s, *e;
5367 if (!obj || !obj->maps)
5371 e = obj->maps + obj->nr_maps;
5373 if ((m < s) || (m >= e)) {
5374 pr_warn("error in %s: map handler doesn't belong to object\n",
5379 idx = (m - obj->maps) + i;
5380 if (idx >= obj->nr_maps || idx < 0)
5382 return &obj->maps[idx];
5386 bpf_map__next(const struct bpf_map *prev, const struct bpf_object *obj)
5391 return __bpf_map__iter(prev, obj, 1);
5395 bpf_map__prev(const struct bpf_map *next, const struct bpf_object *obj)
5400 return obj->maps + obj->nr_maps - 1;
5403 return __bpf_map__iter(next, obj, -1);
5407 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
5409 struct bpf_map *pos;
5411 bpf_object__for_each_map(pos, obj) {
5412 if (pos->name && !strcmp(pos->name, name))
5419 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
5421 return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
5425 bpf_object__find_map_by_offset(struct bpf_object *obj, size_t offset)
5427 return ERR_PTR(-ENOTSUP);
5430 long libbpf_get_error(const void *ptr)
5432 return PTR_ERR_OR_ZERO(ptr);
5435 int bpf_prog_load(const char *file, enum bpf_prog_type type,
5436 struct bpf_object **pobj, int *prog_fd)
5438 struct bpf_prog_load_attr attr;
5440 memset(&attr, 0, sizeof(struct bpf_prog_load_attr));
5442 attr.prog_type = type;
5443 attr.expected_attach_type = 0;
5445 return bpf_prog_load_xattr(&attr, pobj, prog_fd);
5448 int bpf_prog_load_xattr(const struct bpf_prog_load_attr *attr,
5449 struct bpf_object **pobj, int *prog_fd)
5451 struct bpf_object_open_attr open_attr = {};
5452 struct bpf_program *prog, *first_prog = NULL;
5453 struct bpf_object *obj;
5454 struct bpf_map *map;
5462 open_attr.file = attr->file;
5463 open_attr.prog_type = attr->prog_type;
5465 obj = bpf_object__open_xattr(&open_attr);
5466 if (IS_ERR_OR_NULL(obj))
5469 bpf_object__for_each_program(prog, obj) {
5470 enum bpf_attach_type attach_type = attr->expected_attach_type;
5472 * to preserve backwards compatibility, bpf_prog_load treats
5473 * attr->prog_type, if specified, as an override to whatever
5474 * bpf_object__open guessed
5476 if (attr->prog_type != BPF_PROG_TYPE_UNSPEC) {
5477 bpf_program__set_type(prog, attr->prog_type);
5478 bpf_program__set_expected_attach_type(prog,
5481 if (bpf_program__get_type(prog) == BPF_PROG_TYPE_UNSPEC) {
5483 * we haven't guessed from section name and user
5484 * didn't provide a fallback type, too bad...
5486 bpf_object__close(obj);
5490 prog->prog_ifindex = attr->ifindex;
5491 prog->log_level = attr->log_level;
5492 prog->prog_flags = attr->prog_flags;
5497 bpf_object__for_each_map(map, obj) {
5498 if (!bpf_map__is_offload_neutral(map))
5499 map->map_ifindex = attr->ifindex;
5503 pr_warn("object file doesn't contain bpf program\n");
5504 bpf_object__close(obj);
5508 err = bpf_object__load(obj);
5510 bpf_object__close(obj);
5515 *prog_fd = bpf_program__fd(first_prog);
5520 int (*destroy)(struct bpf_link *link);
5523 int bpf_link__destroy(struct bpf_link *link)
5530 err = link->destroy(link);
5536 struct bpf_link_fd {
5537 struct bpf_link link; /* has to be at the top of struct */
5538 int fd; /* hook FD */
5541 static int bpf_link__destroy_perf_event(struct bpf_link *link)
5543 struct bpf_link_fd *l = (void *)link;
5546 err = ioctl(l->fd, PERF_EVENT_IOC_DISABLE, 0);
5554 struct bpf_link *bpf_program__attach_perf_event(struct bpf_program *prog,
5557 char errmsg[STRERR_BUFSIZE];
5558 struct bpf_link_fd *link;
5562 pr_warn("program '%s': invalid perf event FD %d\n",
5563 bpf_program__title(prog, false), pfd);
5564 return ERR_PTR(-EINVAL);
5566 prog_fd = bpf_program__fd(prog);
5568 pr_warn("program '%s': can't attach BPF program w/o FD (did you load it?)\n",
5569 bpf_program__title(prog, false));
5570 return ERR_PTR(-EINVAL);
5573 link = malloc(sizeof(*link));
5575 return ERR_PTR(-ENOMEM);
5576 link->link.destroy = &bpf_link__destroy_perf_event;
5579 if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
5582 pr_warn("program '%s': failed to attach to pfd %d: %s\n",
5583 bpf_program__title(prog, false), pfd,
5584 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
5585 return ERR_PTR(err);
5587 if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
5590 pr_warn("program '%s': failed to enable pfd %d: %s\n",
5591 bpf_program__title(prog, false), pfd,
5592 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
5593 return ERR_PTR(err);
5595 return (struct bpf_link *)link;
5599 * this function is expected to parse integer in the range of [0, 2^31-1] from
5600 * given file using scanf format string fmt. If actual parsed value is
5601 * negative, the result might be indistinguishable from error
5603 static int parse_uint_from_file(const char *file, const char *fmt)
5605 char buf[STRERR_BUFSIZE];
5609 f = fopen(file, "r");
5612 pr_debug("failed to open '%s': %s\n", file,
5613 libbpf_strerror_r(err, buf, sizeof(buf)));
5616 err = fscanf(f, fmt, &ret);
5618 err = err == EOF ? -EIO : -errno;
5619 pr_debug("failed to parse '%s': %s\n", file,
5620 libbpf_strerror_r(err, buf, sizeof(buf)));
5628 static int determine_kprobe_perf_type(void)
5630 const char *file = "/sys/bus/event_source/devices/kprobe/type";
5632 return parse_uint_from_file(file, "%d\n");
5635 static int determine_uprobe_perf_type(void)
5637 const char *file = "/sys/bus/event_source/devices/uprobe/type";
5639 return parse_uint_from_file(file, "%d\n");
5642 static int determine_kprobe_retprobe_bit(void)
5644 const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
5646 return parse_uint_from_file(file, "config:%d\n");
5649 static int determine_uprobe_retprobe_bit(void)
5651 const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
5653 return parse_uint_from_file(file, "config:%d\n");
5656 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
5657 uint64_t offset, int pid)
5659 struct perf_event_attr attr = {};
5660 char errmsg[STRERR_BUFSIZE];
5663 type = uprobe ? determine_uprobe_perf_type()
5664 : determine_kprobe_perf_type();
5666 pr_warn("failed to determine %s perf type: %s\n",
5667 uprobe ? "uprobe" : "kprobe",
5668 libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
5672 int bit = uprobe ? determine_uprobe_retprobe_bit()
5673 : determine_kprobe_retprobe_bit();
5676 pr_warn("failed to determine %s retprobe bit: %s\n",
5677 uprobe ? "uprobe" : "kprobe",
5678 libbpf_strerror_r(bit, errmsg, sizeof(errmsg)));
5681 attr.config |= 1 << bit;
5683 attr.size = sizeof(attr);
5685 attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
5686 attr.config2 = offset; /* kprobe_addr or probe_offset */
5688 /* pid filter is meaningful only for uprobes */
5689 pfd = syscall(__NR_perf_event_open, &attr,
5690 pid < 0 ? -1 : pid /* pid */,
5691 pid == -1 ? 0 : -1 /* cpu */,
5692 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
5695 pr_warn("%s perf_event_open() failed: %s\n",
5696 uprobe ? "uprobe" : "kprobe",
5697 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
5703 struct bpf_link *bpf_program__attach_kprobe(struct bpf_program *prog,
5705 const char *func_name)
5707 char errmsg[STRERR_BUFSIZE];
5708 struct bpf_link *link;
5711 pfd = perf_event_open_probe(false /* uprobe */, retprobe, func_name,
5712 0 /* offset */, -1 /* pid */);
5714 pr_warn("program '%s': failed to create %s '%s' perf event: %s\n",
5715 bpf_program__title(prog, false),
5716 retprobe ? "kretprobe" : "kprobe", func_name,
5717 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
5718 return ERR_PTR(pfd);
5720 link = bpf_program__attach_perf_event(prog, pfd);
5723 err = PTR_ERR(link);
5724 pr_warn("program '%s': failed to attach to %s '%s': %s\n",
5725 bpf_program__title(prog, false),
5726 retprobe ? "kretprobe" : "kprobe", func_name,
5727 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
5733 static struct bpf_link *attach_kprobe(const struct bpf_sec_def *sec,
5734 struct bpf_program *prog)
5736 const char *func_name;
5739 func_name = bpf_program__title(prog, false) + sec->len;
5740 retprobe = strcmp(sec->sec, "kretprobe/") == 0;
5742 return bpf_program__attach_kprobe(prog, retprobe, func_name);
5745 struct bpf_link *bpf_program__attach_uprobe(struct bpf_program *prog,
5746 bool retprobe, pid_t pid,
5747 const char *binary_path,
5750 char errmsg[STRERR_BUFSIZE];
5751 struct bpf_link *link;
5754 pfd = perf_event_open_probe(true /* uprobe */, retprobe,
5755 binary_path, func_offset, pid);
5757 pr_warn("program '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
5758 bpf_program__title(prog, false),
5759 retprobe ? "uretprobe" : "uprobe",
5760 binary_path, func_offset,
5761 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
5762 return ERR_PTR(pfd);
5764 link = bpf_program__attach_perf_event(prog, pfd);
5767 err = PTR_ERR(link);
5768 pr_warn("program '%s': failed to attach to %s '%s:0x%zx': %s\n",
5769 bpf_program__title(prog, false),
5770 retprobe ? "uretprobe" : "uprobe",
5771 binary_path, func_offset,
5772 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
5778 static int determine_tracepoint_id(const char *tp_category,
5779 const char *tp_name)
5781 char file[PATH_MAX];
5784 ret = snprintf(file, sizeof(file),
5785 "/sys/kernel/debug/tracing/events/%s/%s/id",
5786 tp_category, tp_name);
5789 if (ret >= sizeof(file)) {
5790 pr_debug("tracepoint %s/%s path is too long\n",
5791 tp_category, tp_name);
5794 return parse_uint_from_file(file, "%d\n");
5797 static int perf_event_open_tracepoint(const char *tp_category,
5798 const char *tp_name)
5800 struct perf_event_attr attr = {};
5801 char errmsg[STRERR_BUFSIZE];
5802 int tp_id, pfd, err;
5804 tp_id = determine_tracepoint_id(tp_category, tp_name);
5806 pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
5807 tp_category, tp_name,
5808 libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
5812 attr.type = PERF_TYPE_TRACEPOINT;
5813 attr.size = sizeof(attr);
5814 attr.config = tp_id;
5816 pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
5817 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
5820 pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
5821 tp_category, tp_name,
5822 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
5828 struct bpf_link *bpf_program__attach_tracepoint(struct bpf_program *prog,
5829 const char *tp_category,
5830 const char *tp_name)
5832 char errmsg[STRERR_BUFSIZE];
5833 struct bpf_link *link;
5836 pfd = perf_event_open_tracepoint(tp_category, tp_name);
5838 pr_warn("program '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
5839 bpf_program__title(prog, false),
5840 tp_category, tp_name,
5841 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
5842 return ERR_PTR(pfd);
5844 link = bpf_program__attach_perf_event(prog, pfd);
5847 err = PTR_ERR(link);
5848 pr_warn("program '%s': failed to attach to tracepoint '%s/%s': %s\n",
5849 bpf_program__title(prog, false),
5850 tp_category, tp_name,
5851 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
5857 static struct bpf_link *attach_tp(const struct bpf_sec_def *sec,
5858 struct bpf_program *prog)
5860 char *sec_name, *tp_cat, *tp_name;
5861 struct bpf_link *link;
5863 sec_name = strdup(bpf_program__title(prog, false));
5865 return ERR_PTR(-ENOMEM);
5867 /* extract "tp/<category>/<name>" */
5868 tp_cat = sec_name + sec->len;
5869 tp_name = strchr(tp_cat, '/');
5871 link = ERR_PTR(-EINVAL);
5877 link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
5883 static int bpf_link__destroy_fd(struct bpf_link *link)
5885 struct bpf_link_fd *l = (void *)link;
5887 return close(l->fd);
5890 struct bpf_link *bpf_program__attach_raw_tracepoint(struct bpf_program *prog,
5891 const char *tp_name)
5893 char errmsg[STRERR_BUFSIZE];
5894 struct bpf_link_fd *link;
5897 prog_fd = bpf_program__fd(prog);
5899 pr_warn("program '%s': can't attach before loaded\n",
5900 bpf_program__title(prog, false));
5901 return ERR_PTR(-EINVAL);
5904 link = malloc(sizeof(*link));
5906 return ERR_PTR(-ENOMEM);
5907 link->link.destroy = &bpf_link__destroy_fd;
5909 pfd = bpf_raw_tracepoint_open(tp_name, prog_fd);
5913 pr_warn("program '%s': failed to attach to raw tracepoint '%s': %s\n",
5914 bpf_program__title(prog, false), tp_name,
5915 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
5916 return ERR_PTR(pfd);
5919 return (struct bpf_link *)link;
5922 static struct bpf_link *attach_raw_tp(const struct bpf_sec_def *sec,
5923 struct bpf_program *prog)
5925 const char *tp_name = bpf_program__title(prog, false) + sec->len;
5927 return bpf_program__attach_raw_tracepoint(prog, tp_name);
5930 struct bpf_link *bpf_program__attach_trace(struct bpf_program *prog)
5932 char errmsg[STRERR_BUFSIZE];
5933 struct bpf_link_fd *link;
5936 prog_fd = bpf_program__fd(prog);
5938 pr_warn("program '%s': can't attach before loaded\n",
5939 bpf_program__title(prog, false));
5940 return ERR_PTR(-EINVAL);
5943 link = malloc(sizeof(*link));
5945 return ERR_PTR(-ENOMEM);
5946 link->link.destroy = &bpf_link__destroy_fd;
5948 pfd = bpf_raw_tracepoint_open(NULL, prog_fd);
5952 pr_warn("program '%s': failed to attach to trace: %s\n",
5953 bpf_program__title(prog, false),
5954 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
5955 return ERR_PTR(pfd);
5958 return (struct bpf_link *)link;
5961 static struct bpf_link *attach_trace(const struct bpf_sec_def *sec,
5962 struct bpf_program *prog)
5964 return bpf_program__attach_trace(prog);
5967 struct bpf_link *bpf_program__attach(struct bpf_program *prog)
5969 const struct bpf_sec_def *sec_def;
5971 sec_def = find_sec_def(bpf_program__title(prog, false));
5972 if (!sec_def || !sec_def->attach_fn)
5973 return ERR_PTR(-ESRCH);
5975 return sec_def->attach_fn(sec_def, prog);
5978 enum bpf_perf_event_ret
5979 bpf_perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
5980 void **copy_mem, size_t *copy_size,
5981 bpf_perf_event_print_t fn, void *private_data)
5983 struct perf_event_mmap_page *header = mmap_mem;
5984 __u64 data_head = ring_buffer_read_head(header);
5985 __u64 data_tail = header->data_tail;
5986 void *base = ((__u8 *)header) + page_size;
5987 int ret = LIBBPF_PERF_EVENT_CONT;
5988 struct perf_event_header *ehdr;
5991 while (data_head != data_tail) {
5992 ehdr = base + (data_tail & (mmap_size - 1));
5993 ehdr_size = ehdr->size;
5995 if (((void *)ehdr) + ehdr_size > base + mmap_size) {
5996 void *copy_start = ehdr;
5997 size_t len_first = base + mmap_size - copy_start;
5998 size_t len_secnd = ehdr_size - len_first;
6000 if (*copy_size < ehdr_size) {
6002 *copy_mem = malloc(ehdr_size);
6005 ret = LIBBPF_PERF_EVENT_ERROR;
6008 *copy_size = ehdr_size;
6011 memcpy(*copy_mem, copy_start, len_first);
6012 memcpy(*copy_mem + len_first, base, len_secnd);
6016 ret = fn(ehdr, private_data);
6017 data_tail += ehdr_size;
6018 if (ret != LIBBPF_PERF_EVENT_CONT)
6022 ring_buffer_write_tail(header, data_tail);
6028 struct perf_buffer_params {
6029 struct perf_event_attr *attr;
6030 /* if event_cb is specified, it takes precendence */
6031 perf_buffer_event_fn event_cb;
6032 /* sample_cb and lost_cb are higher-level common-case callbacks */
6033 perf_buffer_sample_fn sample_cb;
6034 perf_buffer_lost_fn lost_cb;
6041 struct perf_cpu_buf {
6042 struct perf_buffer *pb;
6043 void *base; /* mmap()'ed memory */
6044 void *buf; /* for reconstructing segmented data */
6051 struct perf_buffer {
6052 perf_buffer_event_fn event_cb;
6053 perf_buffer_sample_fn sample_cb;
6054 perf_buffer_lost_fn lost_cb;
6055 void *ctx; /* passed into callbacks */
6059 struct perf_cpu_buf **cpu_bufs;
6060 struct epoll_event *events;
6061 int cpu_cnt; /* number of allocated CPU buffers */
6062 int epoll_fd; /* perf event FD */
6063 int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
6066 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
6067 struct perf_cpu_buf *cpu_buf)
6071 if (cpu_buf->base &&
6072 munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
6073 pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
6074 if (cpu_buf->fd >= 0) {
6075 ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
6082 void perf_buffer__free(struct perf_buffer *pb)
6089 for (i = 0; i < pb->cpu_cnt && pb->cpu_bufs[i]; i++) {
6090 struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
6092 bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
6093 perf_buffer__free_cpu_buf(pb, cpu_buf);
6097 if (pb->epoll_fd >= 0)
6098 close(pb->epoll_fd);
6103 static struct perf_cpu_buf *
6104 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
6105 int cpu, int map_key)
6107 struct perf_cpu_buf *cpu_buf;
6108 char msg[STRERR_BUFSIZE];
6111 cpu_buf = calloc(1, sizeof(*cpu_buf));
6113 return ERR_PTR(-ENOMEM);
6117 cpu_buf->map_key = map_key;
6119 cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
6120 -1, PERF_FLAG_FD_CLOEXEC);
6121 if (cpu_buf->fd < 0) {
6123 pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
6124 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
6128 cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
6129 PROT_READ | PROT_WRITE, MAP_SHARED,
6131 if (cpu_buf->base == MAP_FAILED) {
6132 cpu_buf->base = NULL;
6134 pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
6135 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
6139 if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
6141 pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
6142 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
6149 perf_buffer__free_cpu_buf(pb, cpu_buf);
6150 return (struct perf_cpu_buf *)ERR_PTR(err);
6153 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
6154 struct perf_buffer_params *p);
6156 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
6157 const struct perf_buffer_opts *opts)
6159 struct perf_buffer_params p = {};
6160 struct perf_event_attr attr = { 0, };
6162 attr.config = PERF_COUNT_SW_BPF_OUTPUT,
6163 attr.type = PERF_TYPE_SOFTWARE;
6164 attr.sample_type = PERF_SAMPLE_RAW;
6165 attr.sample_period = 1;
6166 attr.wakeup_events = 1;
6169 p.sample_cb = opts ? opts->sample_cb : NULL;
6170 p.lost_cb = opts ? opts->lost_cb : NULL;
6171 p.ctx = opts ? opts->ctx : NULL;
6173 return __perf_buffer__new(map_fd, page_cnt, &p);
6176 struct perf_buffer *
6177 perf_buffer__new_raw(int map_fd, size_t page_cnt,
6178 const struct perf_buffer_raw_opts *opts)
6180 struct perf_buffer_params p = {};
6182 p.attr = opts->attr;
6183 p.event_cb = opts->event_cb;
6185 p.cpu_cnt = opts->cpu_cnt;
6186 p.cpus = opts->cpus;
6187 p.map_keys = opts->map_keys;
6189 return __perf_buffer__new(map_fd, page_cnt, &p);
6192 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
6193 struct perf_buffer_params *p)
6195 const char *online_cpus_file = "/sys/devices/system/cpu/online";
6196 struct bpf_map_info map = {};
6197 char msg[STRERR_BUFSIZE];
6198 struct perf_buffer *pb;
6199 bool *online = NULL;
6203 if (page_cnt & (page_cnt - 1)) {
6204 pr_warn("page count should be power of two, but is %zu\n",
6206 return ERR_PTR(-EINVAL);
6209 map_info_len = sizeof(map);
6210 err = bpf_obj_get_info_by_fd(map_fd, &map, &map_info_len);
6213 pr_warn("failed to get map info for map FD %d: %s\n",
6214 map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
6215 return ERR_PTR(err);
6218 if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
6219 pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
6221 return ERR_PTR(-EINVAL);
6224 pb = calloc(1, sizeof(*pb));
6226 return ERR_PTR(-ENOMEM);
6228 pb->event_cb = p->event_cb;
6229 pb->sample_cb = p->sample_cb;
6230 pb->lost_cb = p->lost_cb;
6233 pb->page_size = getpagesize();
6234 pb->mmap_size = pb->page_size * page_cnt;
6235 pb->map_fd = map_fd;
6237 pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
6238 if (pb->epoll_fd < 0) {
6240 pr_warn("failed to create epoll instance: %s\n",
6241 libbpf_strerror_r(err, msg, sizeof(msg)));
6245 if (p->cpu_cnt > 0) {
6246 pb->cpu_cnt = p->cpu_cnt;
6248 pb->cpu_cnt = libbpf_num_possible_cpus();
6249 if (pb->cpu_cnt < 0) {
6253 if (map.max_entries < pb->cpu_cnt)
6254 pb->cpu_cnt = map.max_entries;
6257 pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
6260 pr_warn("failed to allocate events: out of memory\n");
6263 pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
6264 if (!pb->cpu_bufs) {
6266 pr_warn("failed to allocate buffers: out of memory\n");
6270 err = parse_cpu_mask_file(online_cpus_file, &online, &n);
6272 pr_warn("failed to get online CPU mask: %d\n", err);
6276 for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
6277 struct perf_cpu_buf *cpu_buf;
6280 cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
6281 map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
6283 /* in case user didn't explicitly requested particular CPUs to
6284 * be attached to, skip offline/not present CPUs
6286 if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
6289 cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
6290 if (IS_ERR(cpu_buf)) {
6291 err = PTR_ERR(cpu_buf);
6295 pb->cpu_bufs[j] = cpu_buf;
6297 err = bpf_map_update_elem(pb->map_fd, &map_key,
6301 pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
6302 cpu, map_key, cpu_buf->fd,
6303 libbpf_strerror_r(err, msg, sizeof(msg)));
6307 pb->events[j].events = EPOLLIN;
6308 pb->events[j].data.ptr = cpu_buf;
6309 if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
6310 &pb->events[j]) < 0) {
6312 pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
6314 libbpf_strerror_r(err, msg, sizeof(msg)));
6327 perf_buffer__free(pb);
6328 return ERR_PTR(err);
6331 struct perf_sample_raw {
6332 struct perf_event_header header;
6337 struct perf_sample_lost {
6338 struct perf_event_header header;
6344 static enum bpf_perf_event_ret
6345 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
6347 struct perf_cpu_buf *cpu_buf = ctx;
6348 struct perf_buffer *pb = cpu_buf->pb;
6351 /* user wants full control over parsing perf event */
6353 return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
6356 case PERF_RECORD_SAMPLE: {
6357 struct perf_sample_raw *s = data;
6360 pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
6363 case PERF_RECORD_LOST: {
6364 struct perf_sample_lost *s = data;
6367 pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
6371 pr_warn("unknown perf sample type %d\n", e->type);
6372 return LIBBPF_PERF_EVENT_ERROR;
6374 return LIBBPF_PERF_EVENT_CONT;
6377 static int perf_buffer__process_records(struct perf_buffer *pb,
6378 struct perf_cpu_buf *cpu_buf)
6380 enum bpf_perf_event_ret ret;
6382 ret = bpf_perf_event_read_simple(cpu_buf->base, pb->mmap_size,
6383 pb->page_size, &cpu_buf->buf,
6385 perf_buffer__process_record, cpu_buf);
6386 if (ret != LIBBPF_PERF_EVENT_CONT)
6391 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
6395 cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
6396 for (i = 0; i < cnt; i++) {
6397 struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
6399 err = perf_buffer__process_records(pb, cpu_buf);
6401 pr_warn("error while processing records: %d\n", err);
6405 return cnt < 0 ? -errno : cnt;
6408 struct bpf_prog_info_array_desc {
6409 int array_offset; /* e.g. offset of jited_prog_insns */
6410 int count_offset; /* e.g. offset of jited_prog_len */
6411 int size_offset; /* > 0: offset of rec size,
6412 * < 0: fix size of -size_offset
6416 static struct bpf_prog_info_array_desc bpf_prog_info_array_desc[] = {
6417 [BPF_PROG_INFO_JITED_INSNS] = {
6418 offsetof(struct bpf_prog_info, jited_prog_insns),
6419 offsetof(struct bpf_prog_info, jited_prog_len),
6422 [BPF_PROG_INFO_XLATED_INSNS] = {
6423 offsetof(struct bpf_prog_info, xlated_prog_insns),
6424 offsetof(struct bpf_prog_info, xlated_prog_len),
6427 [BPF_PROG_INFO_MAP_IDS] = {
6428 offsetof(struct bpf_prog_info, map_ids),
6429 offsetof(struct bpf_prog_info, nr_map_ids),
6430 -(int)sizeof(__u32),
6432 [BPF_PROG_INFO_JITED_KSYMS] = {
6433 offsetof(struct bpf_prog_info, jited_ksyms),
6434 offsetof(struct bpf_prog_info, nr_jited_ksyms),
6435 -(int)sizeof(__u64),
6437 [BPF_PROG_INFO_JITED_FUNC_LENS] = {
6438 offsetof(struct bpf_prog_info, jited_func_lens),
6439 offsetof(struct bpf_prog_info, nr_jited_func_lens),
6440 -(int)sizeof(__u32),
6442 [BPF_PROG_INFO_FUNC_INFO] = {
6443 offsetof(struct bpf_prog_info, func_info),
6444 offsetof(struct bpf_prog_info, nr_func_info),
6445 offsetof(struct bpf_prog_info, func_info_rec_size),
6447 [BPF_PROG_INFO_LINE_INFO] = {
6448 offsetof(struct bpf_prog_info, line_info),
6449 offsetof(struct bpf_prog_info, nr_line_info),
6450 offsetof(struct bpf_prog_info, line_info_rec_size),
6452 [BPF_PROG_INFO_JITED_LINE_INFO] = {
6453 offsetof(struct bpf_prog_info, jited_line_info),
6454 offsetof(struct bpf_prog_info, nr_jited_line_info),
6455 offsetof(struct bpf_prog_info, jited_line_info_rec_size),
6457 [BPF_PROG_INFO_PROG_TAGS] = {
6458 offsetof(struct bpf_prog_info, prog_tags),
6459 offsetof(struct bpf_prog_info, nr_prog_tags),
6460 -(int)sizeof(__u8) * BPF_TAG_SIZE,
6465 static __u32 bpf_prog_info_read_offset_u32(struct bpf_prog_info *info,
6468 __u32 *array = (__u32 *)info;
6471 return array[offset / sizeof(__u32)];
6472 return -(int)offset;
6475 static __u64 bpf_prog_info_read_offset_u64(struct bpf_prog_info *info,
6478 __u64 *array = (__u64 *)info;
6481 return array[offset / sizeof(__u64)];
6482 return -(int)offset;
6485 static void bpf_prog_info_set_offset_u32(struct bpf_prog_info *info, int offset,
6488 __u32 *array = (__u32 *)info;
6491 array[offset / sizeof(__u32)] = val;
6494 static void bpf_prog_info_set_offset_u64(struct bpf_prog_info *info, int offset,
6497 __u64 *array = (__u64 *)info;
6500 array[offset / sizeof(__u64)] = val;
6503 struct bpf_prog_info_linear *
6504 bpf_program__get_prog_info_linear(int fd, __u64 arrays)
6506 struct bpf_prog_info_linear *info_linear;
6507 struct bpf_prog_info info = {};
6508 __u32 info_len = sizeof(info);
6513 if (arrays >> BPF_PROG_INFO_LAST_ARRAY)
6514 return ERR_PTR(-EINVAL);
6516 /* step 1: get array dimensions */
6517 err = bpf_obj_get_info_by_fd(fd, &info, &info_len);
6519 pr_debug("can't get prog info: %s", strerror(errno));
6520 return ERR_PTR(-EFAULT);
6523 /* step 2: calculate total size of all arrays */
6524 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
6525 bool include_array = (arrays & (1UL << i)) > 0;
6526 struct bpf_prog_info_array_desc *desc;
6529 desc = bpf_prog_info_array_desc + i;
6531 /* kernel is too old to support this field */
6532 if (info_len < desc->array_offset + sizeof(__u32) ||
6533 info_len < desc->count_offset + sizeof(__u32) ||
6534 (desc->size_offset > 0 && info_len < desc->size_offset))
6535 include_array = false;
6537 if (!include_array) {
6538 arrays &= ~(1UL << i); /* clear the bit */
6542 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
6543 size = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
6545 data_len += count * size;
6548 /* step 3: allocate continuous memory */
6549 data_len = roundup(data_len, sizeof(__u64));
6550 info_linear = malloc(sizeof(struct bpf_prog_info_linear) + data_len);
6552 return ERR_PTR(-ENOMEM);
6554 /* step 4: fill data to info_linear->info */
6555 info_linear->arrays = arrays;
6556 memset(&info_linear->info, 0, sizeof(info));
6557 ptr = info_linear->data;
6559 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
6560 struct bpf_prog_info_array_desc *desc;
6563 if ((arrays & (1UL << i)) == 0)
6566 desc = bpf_prog_info_array_desc + i;
6567 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
6568 size = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
6569 bpf_prog_info_set_offset_u32(&info_linear->info,
6570 desc->count_offset, count);
6571 bpf_prog_info_set_offset_u32(&info_linear->info,
6572 desc->size_offset, size);
6573 bpf_prog_info_set_offset_u64(&info_linear->info,
6576 ptr += count * size;
6579 /* step 5: call syscall again to get required arrays */
6580 err = bpf_obj_get_info_by_fd(fd, &info_linear->info, &info_len);
6582 pr_debug("can't get prog info: %s", strerror(errno));
6584 return ERR_PTR(-EFAULT);
6587 /* step 6: verify the data */
6588 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
6589 struct bpf_prog_info_array_desc *desc;
6592 if ((arrays & (1UL << i)) == 0)
6595 desc = bpf_prog_info_array_desc + i;
6596 v1 = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
6597 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
6598 desc->count_offset);
6600 pr_warn("%s: mismatch in element count\n", __func__);
6602 v1 = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
6603 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
6606 pr_warn("%s: mismatch in rec size\n", __func__);
6609 /* step 7: update info_len and data_len */
6610 info_linear->info_len = sizeof(struct bpf_prog_info);
6611 info_linear->data_len = data_len;
6616 void bpf_program__bpil_addr_to_offs(struct bpf_prog_info_linear *info_linear)
6620 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
6621 struct bpf_prog_info_array_desc *desc;
6624 if ((info_linear->arrays & (1UL << i)) == 0)
6627 desc = bpf_prog_info_array_desc + i;
6628 addr = bpf_prog_info_read_offset_u64(&info_linear->info,
6629 desc->array_offset);
6630 offs = addr - ptr_to_u64(info_linear->data);
6631 bpf_prog_info_set_offset_u64(&info_linear->info,
6632 desc->array_offset, offs);
6636 void bpf_program__bpil_offs_to_addr(struct bpf_prog_info_linear *info_linear)
6640 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
6641 struct bpf_prog_info_array_desc *desc;
6644 if ((info_linear->arrays & (1UL << i)) == 0)
6647 desc = bpf_prog_info_array_desc + i;
6648 offs = bpf_prog_info_read_offset_u64(&info_linear->info,
6649 desc->array_offset);
6650 addr = offs + ptr_to_u64(info_linear->data);
6651 bpf_prog_info_set_offset_u64(&info_linear->info,
6652 desc->array_offset, addr);
6656 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
6658 int err = 0, n, len, start, end = -1;
6664 /* Each sub string separated by ',' has format \d+-\d+ or \d+ */
6666 if (*s == ',' || *s == '\n') {
6670 n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
6671 if (n <= 0 || n > 2) {
6672 pr_warn("Failed to get CPU range %s: %d\n", s, n);
6675 } else if (n == 1) {
6678 if (start < 0 || start > end) {
6679 pr_warn("Invalid CPU range [%d,%d] in %s\n",
6684 tmp = realloc(*mask, end + 1);
6690 memset(tmp + *mask_sz, 0, start - *mask_sz);
6691 memset(tmp + start, 1, end - start + 1);
6696 pr_warn("Empty CPU range\n");
6706 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
6708 int fd, err = 0, len;
6711 fd = open(fcpu, O_RDONLY);
6714 pr_warn("Failed to open cpu mask file %s: %d\n", fcpu, err);
6717 len = read(fd, buf, sizeof(buf));
6720 err = len ? -errno : -EINVAL;
6721 pr_warn("Failed to read cpu mask from %s: %d\n", fcpu, err);
6724 if (len >= sizeof(buf)) {
6725 pr_warn("CPU mask is too big in file %s\n", fcpu);
6730 return parse_cpu_mask_str(buf, mask, mask_sz);
6733 int libbpf_num_possible_cpus(void)
6735 static const char *fcpu = "/sys/devices/system/cpu/possible";
6737 int err, n, i, tmp_cpus;
6740 tmp_cpus = READ_ONCE(cpus);
6744 err = parse_cpu_mask_file(fcpu, &mask, &n);
6749 for (i = 0; i < n; i++) {
6755 WRITE_ONCE(cpus, tmp_cpus);