1 // SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
4 * Common eBPF ELF object loading operations.
6 * Copyright (C) 2013-2015 Alexei Starovoitov <ast@kernel.org>
7 * Copyright (C) 2015 Wang Nan <wangnan0@huawei.com>
8 * Copyright (C) 2015 Huawei Inc.
9 * Copyright (C) 2017 Nicira, Inc.
10 * Copyright (C) 2019 Isovalent, Inc.
26 #include <asm/unistd.h>
27 #include <linux/err.h>
28 #include <linux/kernel.h>
29 #include <linux/bpf.h>
30 #include <linux/btf.h>
31 #include <linux/filter.h>
32 #include <linux/list.h>
33 #include <linux/limits.h>
34 #include <linux/perf_event.h>
35 #include <linux/ring_buffer.h>
36 #include <linux/version.h>
37 #include <sys/epoll.h>
38 #include <sys/ioctl.h>
41 #include <sys/types.h>
43 #include <sys/utsname.h>
44 #include <tools/libc_compat.h>
51 #include "str_error.h"
52 #include "libbpf_internal.h"
60 #define BPF_FS_MAGIC 0xcafe4a11
63 /* vsprintf() in __base_pr() uses nonliteral format string. It may break
64 * compilation if user enables corresponding warning. Disable it explicitly.
66 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
68 #define __printf(a, b) __attribute__((format(printf, a, b)))
70 static int __base_pr(enum libbpf_print_level level, const char *format,
73 if (level == LIBBPF_DEBUG)
76 return vfprintf(stderr, format, args);
79 static libbpf_print_fn_t __libbpf_pr = __base_pr;
81 libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn)
83 libbpf_print_fn_t old_print_fn = __libbpf_pr;
90 void libbpf_print(enum libbpf_print_level level, const char *format, ...)
97 va_start(args, format);
98 __libbpf_pr(level, format, args);
102 #define STRERR_BUFSIZE 128
104 #define CHECK_ERR(action, err, out) do { \
111 /* Copied from tools/perf/util/util.h */
113 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
117 # define zclose(fd) ({ \
120 ___err = close((fd)); \
125 #ifdef HAVE_LIBELF_MMAP_SUPPORT
126 # define LIBBPF_ELF_C_READ_MMAP ELF_C_READ_MMAP
128 # define LIBBPF_ELF_C_READ_MMAP ELF_C_READ
131 static inline __u64 ptr_to_u64(const void *ptr)
133 return (__u64) (unsigned long) ptr;
136 struct bpf_capabilities {
137 /* v4.14: kernel support for program & map names. */
139 /* v5.2: kernel support for global data sections. */
141 /* BTF_KIND_FUNC and BTF_KIND_FUNC_PROTO support */
143 /* BTF_KIND_VAR and BTF_KIND_DATASEC support */
148 * bpf_prog should be a better name but it has been used in
152 /* Index in elf obj file, for relocation use. */
157 /* section_name with / replaced by _; makes recursive pinning
158 * in bpf_object__pin_programs easier
161 struct bpf_insn *insns;
162 size_t insns_cnt, main_prog_cnt;
163 enum bpf_prog_type type;
184 bpf_program_prep_t preprocessor;
186 struct bpf_object *obj;
188 bpf_program_clear_priv_t clear_priv;
190 enum bpf_attach_type expected_attach_type;
193 __u32 func_info_rec_size;
196 struct bpf_capabilities *caps;
199 __u32 line_info_rec_size;
204 enum libbpf_map_type {
211 static const char * const libbpf_type_to_btf_name[] = {
212 [LIBBPF_MAP_DATA] = ".data",
213 [LIBBPF_MAP_BSS] = ".bss",
214 [LIBBPF_MAP_RODATA] = ".rodata",
224 struct bpf_map_def def;
225 __u32 btf_key_type_id;
226 __u32 btf_value_type_id;
228 bpf_map_clear_priv_t clear_priv;
229 enum libbpf_map_type libbpf_type;
239 static LIST_HEAD(bpf_objects_list);
242 char name[BPF_OBJ_NAME_LEN];
246 struct bpf_program *programs;
248 struct bpf_map *maps;
251 struct bpf_secdata sections;
254 bool has_pseudo_calls;
255 bool relaxed_core_relocs;
258 * Information when doing elf related work. Only valid if fd
285 * All loaded bpf_object is linked in a list, which is
286 * hidden to caller. bpf_objects__<func> handlers deal with
289 struct list_head list;
292 struct btf_ext *btf_ext;
295 bpf_object_clear_priv_t clear_priv;
297 struct bpf_capabilities caps;
301 #define obj_elf_valid(o) ((o)->efile.elf)
303 void bpf_program__unload(struct bpf_program *prog)
311 * If the object is opened but the program was never loaded,
312 * it is possible that prog->instances.nr == -1.
314 if (prog->instances.nr > 0) {
315 for (i = 0; i < prog->instances.nr; i++)
316 zclose(prog->instances.fds[i]);
317 } else if (prog->instances.nr != -1) {
318 pr_warn("Internal error: instances.nr is %d\n",
322 prog->instances.nr = -1;
323 zfree(&prog->instances.fds);
325 zfree(&prog->func_info);
326 zfree(&prog->line_info);
329 static void bpf_program__exit(struct bpf_program *prog)
334 if (prog->clear_priv)
335 prog->clear_priv(prog, prog->priv);
338 prog->clear_priv = NULL;
340 bpf_program__unload(prog);
342 zfree(&prog->section_name);
343 zfree(&prog->pin_name);
345 zfree(&prog->reloc_desc);
352 static char *__bpf_program__pin_name(struct bpf_program *prog)
356 name = p = strdup(prog->section_name);
357 while ((p = strchr(p, '/')))
364 bpf_program__init(void *data, size_t size, char *section_name, int idx,
365 struct bpf_program *prog)
367 const size_t bpf_insn_sz = sizeof(struct bpf_insn);
369 if (size == 0 || size % bpf_insn_sz) {
370 pr_warn("corrupted section '%s', size: %zu\n",
375 memset(prog, 0, sizeof(*prog));
377 prog->section_name = strdup(section_name);
378 if (!prog->section_name) {
379 pr_warn("failed to alloc name for prog under section(%d) %s\n",
384 prog->pin_name = __bpf_program__pin_name(prog);
385 if (!prog->pin_name) {
386 pr_warn("failed to alloc pin name for prog under section(%d) %s\n",
391 prog->insns = malloc(size);
393 pr_warn("failed to alloc insns for prog under section %s\n",
397 prog->insns_cnt = size / bpf_insn_sz;
398 memcpy(prog->insns, data, size);
400 prog->instances.fds = NULL;
401 prog->instances.nr = -1;
402 prog->type = BPF_PROG_TYPE_UNSPEC;
406 bpf_program__exit(prog);
411 bpf_object__add_program(struct bpf_object *obj, void *data, size_t size,
412 char *section_name, int idx)
414 struct bpf_program prog, *progs;
417 err = bpf_program__init(data, size, section_name, idx, &prog);
421 prog.caps = &obj->caps;
422 progs = obj->programs;
423 nr_progs = obj->nr_programs;
425 progs = reallocarray(progs, nr_progs + 1, sizeof(progs[0]));
428 * In this case the original obj->programs
429 * is still valid, so don't need special treat for
430 * bpf_close_object().
432 pr_warn("failed to alloc a new program under section '%s'\n",
434 bpf_program__exit(&prog);
438 pr_debug("found program %s\n", prog.section_name);
439 obj->programs = progs;
440 obj->nr_programs = nr_progs + 1;
442 progs[nr_progs] = prog;
447 bpf_object__init_prog_names(struct bpf_object *obj)
449 Elf_Data *symbols = obj->efile.symbols;
450 struct bpf_program *prog;
453 for (pi = 0; pi < obj->nr_programs; pi++) {
454 const char *name = NULL;
456 prog = &obj->programs[pi];
458 for (si = 0; si < symbols->d_size / sizeof(GElf_Sym) && !name;
462 if (!gelf_getsym(symbols, si, &sym))
464 if (sym.st_shndx != prog->idx)
466 if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL)
469 name = elf_strptr(obj->efile.elf,
470 obj->efile.strtabidx,
473 pr_warn("failed to get sym name string for prog %s\n",
475 return -LIBBPF_ERRNO__LIBELF;
479 if (!name && prog->idx == obj->efile.text_shndx)
483 pr_warn("failed to find sym for prog %s\n",
488 prog->name = strdup(name);
490 pr_warn("failed to allocate memory for prog sym %s\n",
499 static __u32 get_kernel_version(void)
501 __u32 major, minor, patch;
505 if (sscanf(info.release, "%u.%u.%u", &major, &minor, &patch) != 3)
507 return KERNEL_VERSION(major, minor, patch);
510 static struct bpf_object *bpf_object__new(const char *path,
513 const char *obj_name)
515 struct bpf_object *obj;
518 obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
520 pr_warn("alloc memory failed for %s\n", path);
521 return ERR_PTR(-ENOMEM);
524 strcpy(obj->path, path);
526 strncpy(obj->name, obj_name, sizeof(obj->name) - 1);
527 obj->name[sizeof(obj->name) - 1] = 0;
529 /* Using basename() GNU version which doesn't modify arg. */
530 strncpy(obj->name, basename((void *)path),
531 sizeof(obj->name) - 1);
532 end = strchr(obj->name, '.');
539 * Caller of this function should also call
540 * bpf_object__elf_finish() after data collection to return
541 * obj_buf to user. If not, we should duplicate the buffer to
542 * avoid user freeing them before elf finish.
544 obj->efile.obj_buf = obj_buf;
545 obj->efile.obj_buf_sz = obj_buf_sz;
546 obj->efile.maps_shndx = -1;
547 obj->efile.btf_maps_shndx = -1;
548 obj->efile.data_shndx = -1;
549 obj->efile.rodata_shndx = -1;
550 obj->efile.bss_shndx = -1;
552 obj->kern_version = get_kernel_version();
555 INIT_LIST_HEAD(&obj->list);
556 list_add(&obj->list, &bpf_objects_list);
560 static void bpf_object__elf_finish(struct bpf_object *obj)
562 if (!obj_elf_valid(obj))
565 if (obj->efile.elf) {
566 elf_end(obj->efile.elf);
567 obj->efile.elf = NULL;
569 obj->efile.symbols = NULL;
570 obj->efile.data = NULL;
571 obj->efile.rodata = NULL;
572 obj->efile.bss = NULL;
574 zfree(&obj->efile.reloc);
575 obj->efile.nr_reloc = 0;
576 zclose(obj->efile.fd);
577 obj->efile.obj_buf = NULL;
578 obj->efile.obj_buf_sz = 0;
581 static int bpf_object__elf_init(struct bpf_object *obj)
586 if (obj_elf_valid(obj)) {
587 pr_warn("elf init: internal error\n");
588 return -LIBBPF_ERRNO__LIBELF;
591 if (obj->efile.obj_buf_sz > 0) {
593 * obj_buf should have been validated by
594 * bpf_object__open_buffer().
596 obj->efile.elf = elf_memory((char *)obj->efile.obj_buf,
597 obj->efile.obj_buf_sz);
599 obj->efile.fd = open(obj->path, O_RDONLY);
600 if (obj->efile.fd < 0) {
601 char errmsg[STRERR_BUFSIZE], *cp;
604 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
605 pr_warn("failed to open %s: %s\n", obj->path, cp);
609 obj->efile.elf = elf_begin(obj->efile.fd,
610 LIBBPF_ELF_C_READ_MMAP, NULL);
613 if (!obj->efile.elf) {
614 pr_warn("failed to open %s as ELF file\n", obj->path);
615 err = -LIBBPF_ERRNO__LIBELF;
619 if (!gelf_getehdr(obj->efile.elf, &obj->efile.ehdr)) {
620 pr_warn("failed to get EHDR from %s\n", obj->path);
621 err = -LIBBPF_ERRNO__FORMAT;
624 ep = &obj->efile.ehdr;
626 /* Old LLVM set e_machine to EM_NONE */
627 if (ep->e_type != ET_REL ||
628 (ep->e_machine && ep->e_machine != EM_BPF)) {
629 pr_warn("%s is not an eBPF object file\n", obj->path);
630 err = -LIBBPF_ERRNO__FORMAT;
636 bpf_object__elf_finish(obj);
640 static int bpf_object__check_endianness(struct bpf_object *obj)
642 #if __BYTE_ORDER == __LITTLE_ENDIAN
643 if (obj->efile.ehdr.e_ident[EI_DATA] == ELFDATA2LSB)
645 #elif __BYTE_ORDER == __BIG_ENDIAN
646 if (obj->efile.ehdr.e_ident[EI_DATA] == ELFDATA2MSB)
649 # error "Unrecognized __BYTE_ORDER__"
651 pr_warn("endianness mismatch.\n");
652 return -LIBBPF_ERRNO__ENDIAN;
656 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
658 memcpy(obj->license, data, min(size, sizeof(obj->license) - 1));
659 pr_debug("license of %s is %s\n", obj->path, obj->license);
664 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
668 if (size != sizeof(kver)) {
669 pr_warn("invalid kver section in %s\n", obj->path);
670 return -LIBBPF_ERRNO__FORMAT;
672 memcpy(&kver, data, sizeof(kver));
673 obj->kern_version = kver;
674 pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
678 static int compare_bpf_map(const void *_a, const void *_b)
680 const struct bpf_map *a = _a;
681 const struct bpf_map *b = _b;
683 if (a->sec_idx != b->sec_idx)
684 return a->sec_idx - b->sec_idx;
685 return a->sec_offset - b->sec_offset;
688 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
690 if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
691 type == BPF_MAP_TYPE_HASH_OF_MAPS)
696 static int bpf_object_search_section_size(const struct bpf_object *obj,
697 const char *name, size_t *d_size)
699 const GElf_Ehdr *ep = &obj->efile.ehdr;
700 Elf *elf = obj->efile.elf;
704 while ((scn = elf_nextscn(elf, scn)) != NULL) {
705 const char *sec_name;
710 if (gelf_getshdr(scn, &sh) != &sh) {
711 pr_warn("failed to get section(%d) header from %s\n",
716 sec_name = elf_strptr(elf, ep->e_shstrndx, sh.sh_name);
718 pr_warn("failed to get section(%d) name from %s\n",
723 if (strcmp(name, sec_name))
726 data = elf_getdata(scn, 0);
728 pr_warn("failed to get section(%d) data from %s(%s)\n",
729 idx, name, obj->path);
733 *d_size = data->d_size;
740 int bpf_object__section_size(const struct bpf_object *obj, const char *name,
749 } else if (!strcmp(name, ".data")) {
751 *size = obj->efile.data->d_size;
752 } else if (!strcmp(name, ".bss")) {
754 *size = obj->efile.bss->d_size;
755 } else if (!strcmp(name, ".rodata")) {
756 if (obj->efile.rodata)
757 *size = obj->efile.rodata->d_size;
759 ret = bpf_object_search_section_size(obj, name, &d_size);
764 return *size ? 0 : ret;
767 int bpf_object__variable_offset(const struct bpf_object *obj, const char *name,
770 Elf_Data *symbols = obj->efile.symbols;
777 for (si = 0; si < symbols->d_size / sizeof(GElf_Sym); si++) {
780 if (!gelf_getsym(symbols, si, &sym))
782 if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL ||
783 GELF_ST_TYPE(sym.st_info) != STT_OBJECT)
786 sname = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
789 pr_warn("failed to get sym name string for var %s\n",
793 if (strcmp(name, sname) == 0) {
802 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
804 struct bpf_map *new_maps;
808 if (obj->nr_maps < obj->maps_cap)
809 return &obj->maps[obj->nr_maps++];
811 new_cap = max((size_t)4, obj->maps_cap * 3 / 2);
812 new_maps = realloc(obj->maps, new_cap * sizeof(*obj->maps));
814 pr_warn("alloc maps for object failed\n");
815 return ERR_PTR(-ENOMEM);
818 obj->maps_cap = new_cap;
819 obj->maps = new_maps;
821 /* zero out new maps */
822 memset(obj->maps + obj->nr_maps, 0,
823 (obj->maps_cap - obj->nr_maps) * sizeof(*obj->maps));
825 * fill all fd with -1 so won't close incorrect fd (fd=0 is stdin)
826 * when failure (zclose won't close negative fd)).
828 for (i = obj->nr_maps; i < obj->maps_cap; i++) {
829 obj->maps[i].fd = -1;
830 obj->maps[i].inner_map_fd = -1;
833 return &obj->maps[obj->nr_maps++];
837 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
838 int sec_idx, Elf_Data *data, void **data_buff)
840 char map_name[BPF_OBJ_NAME_LEN];
841 struct bpf_map_def *def;
844 map = bpf_object__add_map(obj);
848 map->libbpf_type = type;
849 map->sec_idx = sec_idx;
851 snprintf(map_name, sizeof(map_name), "%.8s%.7s", obj->name,
852 libbpf_type_to_btf_name[type]);
853 map->name = strdup(map_name);
855 pr_warn("failed to alloc map name\n");
858 pr_debug("map '%s' (global data): at sec_idx %d, offset %zu.\n",
859 map_name, map->sec_idx, map->sec_offset);
862 def->type = BPF_MAP_TYPE_ARRAY;
863 def->key_size = sizeof(int);
864 def->value_size = data->d_size;
865 def->max_entries = 1;
866 def->map_flags = type == LIBBPF_MAP_RODATA ? BPF_F_RDONLY_PROG : 0;
868 *data_buff = malloc(data->d_size);
871 pr_warn("failed to alloc map content buffer\n");
874 memcpy(*data_buff, data->d_buf, data->d_size);
877 pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
881 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
885 if (!obj->caps.global_data)
888 * Populate obj->maps with libbpf internal maps.
890 if (obj->efile.data_shndx >= 0) {
891 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
892 obj->efile.data_shndx,
894 &obj->sections.data);
898 if (obj->efile.rodata_shndx >= 0) {
899 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
900 obj->efile.rodata_shndx,
902 &obj->sections.rodata);
906 if (obj->efile.bss_shndx >= 0) {
907 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
908 obj->efile.bss_shndx,
909 obj->efile.bss, NULL);
916 static int bpf_object__init_user_maps(struct bpf_object *obj, bool strict)
918 Elf_Data *symbols = obj->efile.symbols;
919 int i, map_def_sz = 0, nr_maps = 0, nr_syms;
920 Elf_Data *data = NULL;
923 if (obj->efile.maps_shndx < 0)
929 scn = elf_getscn(obj->efile.elf, obj->efile.maps_shndx);
931 data = elf_getdata(scn, NULL);
933 pr_warn("failed to get Elf_Data from map section %d\n",
934 obj->efile.maps_shndx);
939 * Count number of maps. Each map has a name.
940 * Array of maps is not supported: only the first element is
943 * TODO: Detect array of map and report error.
945 nr_syms = symbols->d_size / sizeof(GElf_Sym);
946 for (i = 0; i < nr_syms; i++) {
949 if (!gelf_getsym(symbols, i, &sym))
951 if (sym.st_shndx != obj->efile.maps_shndx)
955 /* Assume equally sized map definitions */
956 pr_debug("maps in %s: %d maps in %zd bytes\n",
957 obj->path, nr_maps, data->d_size);
959 map_def_sz = data->d_size / nr_maps;
960 if (!data->d_size || (data->d_size % nr_maps) != 0) {
961 pr_warn("unable to determine map definition size "
962 "section %s, %d maps in %zd bytes\n",
963 obj->path, nr_maps, data->d_size);
967 /* Fill obj->maps using data in "maps" section. */
968 for (i = 0; i < nr_syms; i++) {
970 const char *map_name;
971 struct bpf_map_def *def;
974 if (!gelf_getsym(symbols, i, &sym))
976 if (sym.st_shndx != obj->efile.maps_shndx)
979 map = bpf_object__add_map(obj);
983 map_name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
986 pr_warn("failed to get map #%d name sym string for obj %s\n",
988 return -LIBBPF_ERRNO__FORMAT;
991 map->libbpf_type = LIBBPF_MAP_UNSPEC;
992 map->sec_idx = sym.st_shndx;
993 map->sec_offset = sym.st_value;
994 pr_debug("map '%s' (legacy): at sec_idx %d, offset %zu.\n",
995 map_name, map->sec_idx, map->sec_offset);
996 if (sym.st_value + map_def_sz > data->d_size) {
997 pr_warn("corrupted maps section in %s: last map \"%s\" too small\n",
998 obj->path, map_name);
1002 map->name = strdup(map_name);
1004 pr_warn("failed to alloc map name\n");
1007 pr_debug("map %d is \"%s\"\n", i, map->name);
1008 def = (struct bpf_map_def *)(data->d_buf + sym.st_value);
1010 * If the definition of the map in the object file fits in
1011 * bpf_map_def, copy it. Any extra fields in our version
1012 * of bpf_map_def will default to zero as a result of the
1015 if (map_def_sz <= sizeof(struct bpf_map_def)) {
1016 memcpy(&map->def, def, map_def_sz);
1019 * Here the map structure being read is bigger than what
1020 * we expect, truncate if the excess bits are all zero.
1021 * If they are not zero, reject this map as
1025 for (b = ((char *)def) + sizeof(struct bpf_map_def);
1026 b < ((char *)def) + map_def_sz; b++) {
1028 pr_warn("maps section in %s: \"%s\" "
1029 "has unrecognized, non-zero "
1031 obj->path, map_name);
1036 memcpy(&map->def, def, sizeof(struct bpf_map_def));
1042 static const struct btf_type *
1043 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
1045 const struct btf_type *t = btf__type_by_id(btf, id);
1050 while (btf_is_mod(t) || btf_is_typedef(t)) {
1053 t = btf__type_by_id(btf, t->type);
1060 * Fetch integer attribute of BTF map definition. Such attributes are
1061 * represented using a pointer to an array, in which dimensionality of array
1062 * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
1063 * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
1064 * type definition, while using only sizeof(void *) space in ELF data section.
1066 static bool get_map_field_int(const char *map_name, const struct btf *btf,
1067 const struct btf_type *def,
1068 const struct btf_member *m, __u32 *res) {
1069 const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
1070 const char *name = btf__name_by_offset(btf, m->name_off);
1071 const struct btf_array *arr_info;
1072 const struct btf_type *arr_t;
1074 if (!btf_is_ptr(t)) {
1075 pr_warn("map '%s': attr '%s': expected PTR, got %u.\n",
1076 map_name, name, btf_kind(t));
1080 arr_t = btf__type_by_id(btf, t->type);
1082 pr_warn("map '%s': attr '%s': type [%u] not found.\n",
1083 map_name, name, t->type);
1086 if (!btf_is_array(arr_t)) {
1087 pr_warn("map '%s': attr '%s': expected ARRAY, got %u.\n",
1088 map_name, name, btf_kind(arr_t));
1091 arr_info = btf_array(arr_t);
1092 *res = arr_info->nelems;
1096 static int build_map_pin_path(struct bpf_map *map, const char *path)
1102 path = "/sys/fs/bpf";
1104 len = snprintf(buf, PATH_MAX, "%s/%s", path, bpf_map__name(map));
1107 else if (len >= PATH_MAX)
1108 return -ENAMETOOLONG;
1110 err = bpf_map__set_pin_path(map, buf);
1117 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
1118 const struct btf_type *sec,
1119 int var_idx, int sec_idx,
1120 const Elf_Data *data, bool strict,
1121 const char *pin_root_path)
1123 const struct btf_type *var, *def, *t;
1124 const struct btf_var_secinfo *vi;
1125 const struct btf_var *var_extra;
1126 const struct btf_member *m;
1127 const char *map_name;
1128 struct bpf_map *map;
1131 vi = btf_var_secinfos(sec) + var_idx;
1132 var = btf__type_by_id(obj->btf, vi->type);
1133 var_extra = btf_var(var);
1134 map_name = btf__name_by_offset(obj->btf, var->name_off);
1135 vlen = btf_vlen(var);
1137 if (map_name == NULL || map_name[0] == '\0') {
1138 pr_warn("map #%d: empty name.\n", var_idx);
1141 if ((__u64)vi->offset + vi->size > data->d_size) {
1142 pr_warn("map '%s' BTF data is corrupted.\n", map_name);
1145 if (!btf_is_var(var)) {
1146 pr_warn("map '%s': unexpected var kind %u.\n",
1147 map_name, btf_kind(var));
1150 if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED &&
1151 var_extra->linkage != BTF_VAR_STATIC) {
1152 pr_warn("map '%s': unsupported var linkage %u.\n",
1153 map_name, var_extra->linkage);
1157 def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
1158 if (!btf_is_struct(def)) {
1159 pr_warn("map '%s': unexpected def kind %u.\n",
1160 map_name, btf_kind(var));
1163 if (def->size > vi->size) {
1164 pr_warn("map '%s': invalid def size.\n", map_name);
1168 map = bpf_object__add_map(obj);
1170 return PTR_ERR(map);
1171 map->name = strdup(map_name);
1173 pr_warn("map '%s': failed to alloc map name.\n", map_name);
1176 map->libbpf_type = LIBBPF_MAP_UNSPEC;
1177 map->def.type = BPF_MAP_TYPE_UNSPEC;
1178 map->sec_idx = sec_idx;
1179 map->sec_offset = vi->offset;
1180 pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
1181 map_name, map->sec_idx, map->sec_offset);
1183 vlen = btf_vlen(def);
1184 m = btf_members(def);
1185 for (i = 0; i < vlen; i++, m++) {
1186 const char *name = btf__name_by_offset(obj->btf, m->name_off);
1189 pr_warn("map '%s': invalid field #%d.\n", map_name, i);
1192 if (strcmp(name, "type") == 0) {
1193 if (!get_map_field_int(map_name, obj->btf, def, m,
1196 pr_debug("map '%s': found type = %u.\n",
1197 map_name, map->def.type);
1198 } else if (strcmp(name, "max_entries") == 0) {
1199 if (!get_map_field_int(map_name, obj->btf, def, m,
1200 &map->def.max_entries))
1202 pr_debug("map '%s': found max_entries = %u.\n",
1203 map_name, map->def.max_entries);
1204 } else if (strcmp(name, "map_flags") == 0) {
1205 if (!get_map_field_int(map_name, obj->btf, def, m,
1206 &map->def.map_flags))
1208 pr_debug("map '%s': found map_flags = %u.\n",
1209 map_name, map->def.map_flags);
1210 } else if (strcmp(name, "key_size") == 0) {
1213 if (!get_map_field_int(map_name, obj->btf, def, m,
1216 pr_debug("map '%s': found key_size = %u.\n",
1218 if (map->def.key_size && map->def.key_size != sz) {
1219 pr_warn("map '%s': conflicting key size %u != %u.\n",
1220 map_name, map->def.key_size, sz);
1223 map->def.key_size = sz;
1224 } else if (strcmp(name, "key") == 0) {
1227 t = btf__type_by_id(obj->btf, m->type);
1229 pr_warn("map '%s': key type [%d] not found.\n",
1233 if (!btf_is_ptr(t)) {
1234 pr_warn("map '%s': key spec is not PTR: %u.\n",
1235 map_name, btf_kind(t));
1238 sz = btf__resolve_size(obj->btf, t->type);
1240 pr_warn("map '%s': can't determine key size for type [%u]: %lld.\n",
1241 map_name, t->type, sz);
1244 pr_debug("map '%s': found key [%u], sz = %lld.\n",
1245 map_name, t->type, sz);
1246 if (map->def.key_size && map->def.key_size != sz) {
1247 pr_warn("map '%s': conflicting key size %u != %lld.\n",
1248 map_name, map->def.key_size, sz);
1251 map->def.key_size = sz;
1252 map->btf_key_type_id = t->type;
1253 } else if (strcmp(name, "value_size") == 0) {
1256 if (!get_map_field_int(map_name, obj->btf, def, m,
1259 pr_debug("map '%s': found value_size = %u.\n",
1261 if (map->def.value_size && map->def.value_size != sz) {
1262 pr_warn("map '%s': conflicting value size %u != %u.\n",
1263 map_name, map->def.value_size, sz);
1266 map->def.value_size = sz;
1267 } else if (strcmp(name, "value") == 0) {
1270 t = btf__type_by_id(obj->btf, m->type);
1272 pr_warn("map '%s': value type [%d] not found.\n",
1276 if (!btf_is_ptr(t)) {
1277 pr_warn("map '%s': value spec is not PTR: %u.\n",
1278 map_name, btf_kind(t));
1281 sz = btf__resolve_size(obj->btf, t->type);
1283 pr_warn("map '%s': can't determine value size for type [%u]: %lld.\n",
1284 map_name, t->type, sz);
1287 pr_debug("map '%s': found value [%u], sz = %lld.\n",
1288 map_name, t->type, sz);
1289 if (map->def.value_size && map->def.value_size != sz) {
1290 pr_warn("map '%s': conflicting value size %u != %lld.\n",
1291 map_name, map->def.value_size, sz);
1294 map->def.value_size = sz;
1295 map->btf_value_type_id = t->type;
1296 } else if (strcmp(name, "pinning") == 0) {
1300 if (!get_map_field_int(map_name, obj->btf, def, m,
1303 pr_debug("map '%s': found pinning = %u.\n",
1306 if (val != LIBBPF_PIN_NONE &&
1307 val != LIBBPF_PIN_BY_NAME) {
1308 pr_warn("map '%s': invalid pinning value %u.\n",
1312 if (val == LIBBPF_PIN_BY_NAME) {
1313 err = build_map_pin_path(map, pin_root_path);
1315 pr_warn("map '%s': couldn't build pin path.\n",
1322 pr_warn("map '%s': unknown field '%s'.\n",
1326 pr_debug("map '%s': ignoring unknown field '%s'.\n",
1331 if (map->def.type == BPF_MAP_TYPE_UNSPEC) {
1332 pr_warn("map '%s': map type isn't specified.\n", map_name);
1339 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
1340 const char *pin_root_path)
1342 const struct btf_type *sec = NULL;
1343 int nr_types, i, vlen, err;
1344 const struct btf_type *t;
1349 if (obj->efile.btf_maps_shndx < 0)
1352 scn = elf_getscn(obj->efile.elf, obj->efile.btf_maps_shndx);
1354 data = elf_getdata(scn, NULL);
1355 if (!scn || !data) {
1356 pr_warn("failed to get Elf_Data from map section %d (%s)\n",
1357 obj->efile.maps_shndx, MAPS_ELF_SEC);
1361 nr_types = btf__get_nr_types(obj->btf);
1362 for (i = 1; i <= nr_types; i++) {
1363 t = btf__type_by_id(obj->btf, i);
1364 if (!btf_is_datasec(t))
1366 name = btf__name_by_offset(obj->btf, t->name_off);
1367 if (strcmp(name, MAPS_ELF_SEC) == 0) {
1374 pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
1378 vlen = btf_vlen(sec);
1379 for (i = 0; i < vlen; i++) {
1380 err = bpf_object__init_user_btf_map(obj, sec, i,
1381 obj->efile.btf_maps_shndx,
1382 data, strict, pin_root_path);
1390 static int bpf_object__init_maps(struct bpf_object *obj, bool relaxed_maps,
1391 const char *pin_root_path)
1393 bool strict = !relaxed_maps;
1396 err = bpf_object__init_user_maps(obj, strict);
1400 err = bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
1404 err = bpf_object__init_global_data_maps(obj);
1409 qsort(obj->maps, obj->nr_maps, sizeof(obj->maps[0]),
1415 static bool section_have_execinstr(struct bpf_object *obj, int idx)
1420 scn = elf_getscn(obj->efile.elf, idx);
1424 if (gelf_getshdr(scn, &sh) != &sh)
1427 if (sh.sh_flags & SHF_EXECINSTR)
1433 static void bpf_object__sanitize_btf(struct bpf_object *obj)
1435 bool has_datasec = obj->caps.btf_datasec;
1436 bool has_func = obj->caps.btf_func;
1437 struct btf *btf = obj->btf;
1441 if (!obj->btf || (has_func && has_datasec))
1444 for (i = 1; i <= btf__get_nr_types(btf); i++) {
1445 t = (struct btf_type *)btf__type_by_id(btf, i);
1447 if (!has_datasec && btf_is_var(t)) {
1448 /* replace VAR with INT */
1449 t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
1451 * using size = 1 is the safest choice, 4 will be too
1452 * big and cause kernel BTF validation failure if
1453 * original variable took less than 4 bytes
1456 *(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
1457 } else if (!has_datasec && btf_is_datasec(t)) {
1458 /* replace DATASEC with STRUCT */
1459 const struct btf_var_secinfo *v = btf_var_secinfos(t);
1460 struct btf_member *m = btf_members(t);
1461 struct btf_type *vt;
1464 name = (char *)btf__name_by_offset(btf, t->name_off);
1472 t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
1473 for (j = 0; j < vlen; j++, v++, m++) {
1474 /* order of field assignments is important */
1475 m->offset = v->offset * 8;
1477 /* preserve variable name as member name */
1478 vt = (void *)btf__type_by_id(btf, v->type);
1479 m->name_off = vt->name_off;
1481 } else if (!has_func && btf_is_func_proto(t)) {
1482 /* replace FUNC_PROTO with ENUM */
1484 t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
1485 t->size = sizeof(__u32); /* kernel enforced */
1486 } else if (!has_func && btf_is_func(t)) {
1487 /* replace FUNC with TYPEDEF */
1488 t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
1493 static void bpf_object__sanitize_btf_ext(struct bpf_object *obj)
1498 if (!obj->caps.btf_func) {
1499 btf_ext__free(obj->btf_ext);
1500 obj->btf_ext = NULL;
1504 static bool bpf_object__is_btf_mandatory(const struct bpf_object *obj)
1506 return obj->efile.btf_maps_shndx >= 0;
1509 static int bpf_object__init_btf(struct bpf_object *obj,
1511 Elf_Data *btf_ext_data)
1513 bool btf_required = bpf_object__is_btf_mandatory(obj);
1517 obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
1518 if (IS_ERR(obj->btf)) {
1519 pr_warn("Error loading ELF section %s: %d.\n",
1523 err = btf__finalize_data(obj, obj->btf);
1525 pr_warn("Error finalizing %s: %d.\n", BTF_ELF_SEC, err);
1531 pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
1532 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
1535 obj->btf_ext = btf_ext__new(btf_ext_data->d_buf,
1536 btf_ext_data->d_size);
1537 if (IS_ERR(obj->btf_ext)) {
1538 pr_warn("Error loading ELF section %s: %ld. Ignored and continue.\n",
1539 BTF_EXT_ELF_SEC, PTR_ERR(obj->btf_ext));
1540 obj->btf_ext = NULL;
1545 if (err || IS_ERR(obj->btf)) {
1547 err = err ? : PTR_ERR(obj->btf);
1550 if (!IS_ERR_OR_NULL(obj->btf))
1551 btf__free(obj->btf);
1554 if (btf_required && !obj->btf) {
1555 pr_warn("BTF is required, but is missing or corrupted.\n");
1556 return err == 0 ? -ENOENT : err;
1561 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
1568 bpf_object__sanitize_btf(obj);
1569 bpf_object__sanitize_btf_ext(obj);
1571 err = btf__load(obj->btf);
1573 pr_warn("Error loading %s into kernel: %d.\n",
1575 btf__free(obj->btf);
1577 /* btf_ext can't exist without btf, so free it as well */
1579 btf_ext__free(obj->btf_ext);
1580 obj->btf_ext = NULL;
1583 if (bpf_object__is_btf_mandatory(obj))
1589 static int bpf_object__elf_collect(struct bpf_object *obj, bool relaxed_maps,
1590 const char *pin_root_path)
1592 Elf *elf = obj->efile.elf;
1593 GElf_Ehdr *ep = &obj->efile.ehdr;
1594 Elf_Data *btf_ext_data = NULL;
1595 Elf_Data *btf_data = NULL;
1596 Elf_Scn *scn = NULL;
1597 int idx = 0, err = 0;
1599 /* Elf is corrupted/truncated, avoid calling elf_strptr. */
1600 if (!elf_rawdata(elf_getscn(elf, ep->e_shstrndx), NULL)) {
1601 pr_warn("failed to get e_shstrndx from %s\n", obj->path);
1602 return -LIBBPF_ERRNO__FORMAT;
1605 while ((scn = elf_nextscn(elf, scn)) != NULL) {
1611 if (gelf_getshdr(scn, &sh) != &sh) {
1612 pr_warn("failed to get section(%d) header from %s\n",
1614 return -LIBBPF_ERRNO__FORMAT;
1617 name = elf_strptr(elf, ep->e_shstrndx, sh.sh_name);
1619 pr_warn("failed to get section(%d) name from %s\n",
1621 return -LIBBPF_ERRNO__FORMAT;
1624 data = elf_getdata(scn, 0);
1626 pr_warn("failed to get section(%d) data from %s(%s)\n",
1627 idx, name, obj->path);
1628 return -LIBBPF_ERRNO__FORMAT;
1630 pr_debug("section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
1631 idx, name, (unsigned long)data->d_size,
1632 (int)sh.sh_link, (unsigned long)sh.sh_flags,
1635 if (strcmp(name, "license") == 0) {
1636 err = bpf_object__init_license(obj,
1641 } else if (strcmp(name, "version") == 0) {
1642 err = bpf_object__init_kversion(obj,
1647 } else if (strcmp(name, "maps") == 0) {
1648 obj->efile.maps_shndx = idx;
1649 } else if (strcmp(name, MAPS_ELF_SEC) == 0) {
1650 obj->efile.btf_maps_shndx = idx;
1651 } else if (strcmp(name, BTF_ELF_SEC) == 0) {
1653 } else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
1654 btf_ext_data = data;
1655 } else if (sh.sh_type == SHT_SYMTAB) {
1656 if (obj->efile.symbols) {
1657 pr_warn("bpf: multiple SYMTAB in %s\n",
1659 return -LIBBPF_ERRNO__FORMAT;
1661 obj->efile.symbols = data;
1662 obj->efile.strtabidx = sh.sh_link;
1663 } else if (sh.sh_type == SHT_PROGBITS && data->d_size > 0) {
1664 if (sh.sh_flags & SHF_EXECINSTR) {
1665 if (strcmp(name, ".text") == 0)
1666 obj->efile.text_shndx = idx;
1667 err = bpf_object__add_program(obj, data->d_buf,
1668 data->d_size, name, idx);
1670 char errmsg[STRERR_BUFSIZE];
1671 char *cp = libbpf_strerror_r(-err, errmsg,
1674 pr_warn("failed to alloc program %s (%s): %s",
1675 name, obj->path, cp);
1678 } else if (strcmp(name, ".data") == 0) {
1679 obj->efile.data = data;
1680 obj->efile.data_shndx = idx;
1681 } else if (strcmp(name, ".rodata") == 0) {
1682 obj->efile.rodata = data;
1683 obj->efile.rodata_shndx = idx;
1685 pr_debug("skip section(%d) %s\n", idx, name);
1687 } else if (sh.sh_type == SHT_REL) {
1688 int nr_reloc = obj->efile.nr_reloc;
1689 void *reloc = obj->efile.reloc;
1690 int sec = sh.sh_info; /* points to other section */
1692 /* Only do relo for section with exec instructions */
1693 if (!section_have_execinstr(obj, sec)) {
1694 pr_debug("skip relo %s(%d) for section(%d)\n",
1699 reloc = reallocarray(reloc, nr_reloc + 1,
1700 sizeof(*obj->efile.reloc));
1702 pr_warn("realloc failed\n");
1706 obj->efile.reloc = reloc;
1707 obj->efile.nr_reloc++;
1709 obj->efile.reloc[nr_reloc].shdr = sh;
1710 obj->efile.reloc[nr_reloc].data = data;
1711 } else if (sh.sh_type == SHT_NOBITS && strcmp(name, ".bss") == 0) {
1712 obj->efile.bss = data;
1713 obj->efile.bss_shndx = idx;
1715 pr_debug("skip section(%d) %s\n", idx, name);
1719 if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
1720 pr_warn("Corrupted ELF file: index of strtab invalid\n");
1721 return -LIBBPF_ERRNO__FORMAT;
1723 err = bpf_object__init_btf(obj, btf_data, btf_ext_data);
1725 err = bpf_object__init_maps(obj, relaxed_maps, pin_root_path);
1727 err = bpf_object__sanitize_and_load_btf(obj);
1729 err = bpf_object__init_prog_names(obj);
1733 static struct bpf_program *
1734 bpf_object__find_prog_by_idx(struct bpf_object *obj, int idx)
1736 struct bpf_program *prog;
1739 for (i = 0; i < obj->nr_programs; i++) {
1740 prog = &obj->programs[i];
1741 if (prog->idx == idx)
1747 struct bpf_program *
1748 bpf_object__find_program_by_title(const struct bpf_object *obj,
1751 struct bpf_program *pos;
1753 bpf_object__for_each_program(pos, obj) {
1754 if (pos->section_name && !strcmp(pos->section_name, title))
1760 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
1763 return shndx == obj->efile.data_shndx ||
1764 shndx == obj->efile.bss_shndx ||
1765 shndx == obj->efile.rodata_shndx;
1768 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
1771 return shndx == obj->efile.maps_shndx ||
1772 shndx == obj->efile.btf_maps_shndx;
1775 static bool bpf_object__relo_in_known_section(const struct bpf_object *obj,
1778 return shndx == obj->efile.text_shndx ||
1779 bpf_object__shndx_is_maps(obj, shndx) ||
1780 bpf_object__shndx_is_data(obj, shndx);
1783 static enum libbpf_map_type
1784 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
1786 if (shndx == obj->efile.data_shndx)
1787 return LIBBPF_MAP_DATA;
1788 else if (shndx == obj->efile.bss_shndx)
1789 return LIBBPF_MAP_BSS;
1790 else if (shndx == obj->efile.rodata_shndx)
1791 return LIBBPF_MAP_RODATA;
1793 return LIBBPF_MAP_UNSPEC;
1797 bpf_program__collect_reloc(struct bpf_program *prog, GElf_Shdr *shdr,
1798 Elf_Data *data, struct bpf_object *obj)
1800 Elf_Data *symbols = obj->efile.symbols;
1801 struct bpf_map *maps = obj->maps;
1802 size_t nr_maps = obj->nr_maps;
1805 pr_debug("collecting relocating info for: '%s'\n", prog->section_name);
1806 nrels = shdr->sh_size / shdr->sh_entsize;
1808 prog->reloc_desc = malloc(sizeof(*prog->reloc_desc) * nrels);
1809 if (!prog->reloc_desc) {
1810 pr_warn("failed to alloc memory in relocation\n");
1813 prog->nr_reloc = nrels;
1815 for (i = 0; i < nrels; i++) {
1816 struct bpf_insn *insns = prog->insns;
1817 enum libbpf_map_type type;
1818 unsigned int insn_idx;
1819 unsigned int shdr_idx;
1825 if (!gelf_getrel(data, i, &rel)) {
1826 pr_warn("relocation: failed to get %d reloc\n", i);
1827 return -LIBBPF_ERRNO__FORMAT;
1830 if (!gelf_getsym(symbols, GELF_R_SYM(rel.r_info), &sym)) {
1831 pr_warn("relocation: symbol %"PRIx64" not found\n",
1832 GELF_R_SYM(rel.r_info));
1833 return -LIBBPF_ERRNO__FORMAT;
1836 name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
1837 sym.st_name) ? : "<?>";
1839 pr_debug("relo for %lld value %lld name %d (\'%s\')\n",
1840 (long long) (rel.r_info >> 32),
1841 (long long) sym.st_value, sym.st_name, name);
1843 shdr_idx = sym.st_shndx;
1844 insn_idx = rel.r_offset / sizeof(struct bpf_insn);
1845 pr_debug("relocation: insn_idx=%u, shdr_idx=%u\n",
1846 insn_idx, shdr_idx);
1848 if (shdr_idx >= SHN_LORESERVE) {
1849 pr_warn("relocation: not yet supported relo for non-static global \'%s\' variable in special section (0x%x) found in insns[%d].code 0x%x\n",
1850 name, shdr_idx, insn_idx,
1851 insns[insn_idx].code);
1852 return -LIBBPF_ERRNO__RELOC;
1854 if (!bpf_object__relo_in_known_section(obj, shdr_idx)) {
1855 pr_warn("Program '%s' contains unrecognized relo data pointing to section %u\n",
1856 prog->section_name, shdr_idx);
1857 return -LIBBPF_ERRNO__RELOC;
1860 if (insns[insn_idx].code == (BPF_JMP | BPF_CALL)) {
1861 if (insns[insn_idx].src_reg != BPF_PSEUDO_CALL) {
1862 pr_warn("incorrect bpf_call opcode\n");
1863 return -LIBBPF_ERRNO__RELOC;
1865 prog->reloc_desc[i].type = RELO_CALL;
1866 prog->reloc_desc[i].insn_idx = insn_idx;
1867 prog->reloc_desc[i].text_off = sym.st_value;
1868 obj->has_pseudo_calls = true;
1872 if (insns[insn_idx].code != (BPF_LD | BPF_IMM | BPF_DW)) {
1873 pr_warn("bpf: relocation: invalid relo for insns[%d].code 0x%x\n",
1874 insn_idx, insns[insn_idx].code);
1875 return -LIBBPF_ERRNO__RELOC;
1878 if (bpf_object__shndx_is_maps(obj, shdr_idx) ||
1879 bpf_object__shndx_is_data(obj, shdr_idx)) {
1880 type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
1881 if (type != LIBBPF_MAP_UNSPEC) {
1882 if (GELF_ST_BIND(sym.st_info) == STB_GLOBAL) {
1883 pr_warn("bpf: relocation: not yet supported relo for non-static global \'%s\' variable found in insns[%d].code 0x%x\n",
1884 name, insn_idx, insns[insn_idx].code);
1885 return -LIBBPF_ERRNO__RELOC;
1887 if (!obj->caps.global_data) {
1888 pr_warn("bpf: relocation: kernel does not support global \'%s\' variable access in insns[%d]\n",
1890 return -LIBBPF_ERRNO__RELOC;
1894 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
1895 if (maps[map_idx].libbpf_type != type)
1897 if (type != LIBBPF_MAP_UNSPEC ||
1898 (maps[map_idx].sec_idx == sym.st_shndx &&
1899 maps[map_idx].sec_offset == sym.st_value)) {
1900 pr_debug("relocation: found map %zd (%s, sec_idx %d, offset %zu) for insn %u\n",
1901 map_idx, maps[map_idx].name,
1902 maps[map_idx].sec_idx,
1903 maps[map_idx].sec_offset,
1909 if (map_idx >= nr_maps) {
1910 pr_warn("bpf relocation: map_idx %d larger than %d\n",
1911 (int)map_idx, (int)nr_maps - 1);
1912 return -LIBBPF_ERRNO__RELOC;
1915 prog->reloc_desc[i].type = type != LIBBPF_MAP_UNSPEC ?
1916 RELO_DATA : RELO_LD64;
1917 prog->reloc_desc[i].insn_idx = insn_idx;
1918 prog->reloc_desc[i].map_idx = map_idx;
1924 static int bpf_map_find_btf_info(struct bpf_object *obj, struct bpf_map *map)
1926 struct bpf_map_def *def = &map->def;
1927 __u32 key_type_id = 0, value_type_id = 0;
1930 /* if it's BTF-defined map, we don't need to search for type IDs */
1931 if (map->sec_idx == obj->efile.btf_maps_shndx)
1934 if (!bpf_map__is_internal(map)) {
1935 ret = btf__get_map_kv_tids(obj->btf, map->name, def->key_size,
1936 def->value_size, &key_type_id,
1940 * LLVM annotates global data differently in BTF, that is,
1941 * only as '.data', '.bss' or '.rodata'.
1943 ret = btf__find_by_name(obj->btf,
1944 libbpf_type_to_btf_name[map->libbpf_type]);
1949 map->btf_key_type_id = key_type_id;
1950 map->btf_value_type_id = bpf_map__is_internal(map) ?
1951 ret : value_type_id;
1955 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
1957 struct bpf_map_info info = {};
1958 __u32 len = sizeof(info);
1962 err = bpf_obj_get_info_by_fd(fd, &info, &len);
1966 new_name = strdup(info.name);
1970 new_fd = open("/", O_RDONLY | O_CLOEXEC);
1973 goto err_free_new_name;
1976 new_fd = dup3(fd, new_fd, O_CLOEXEC);
1979 goto err_close_new_fd;
1982 err = zclose(map->fd);
1985 goto err_close_new_fd;
1990 map->name = new_name;
1991 map->def.type = info.type;
1992 map->def.key_size = info.key_size;
1993 map->def.value_size = info.value_size;
1994 map->def.max_entries = info.max_entries;
1995 map->def.map_flags = info.map_flags;
1996 map->btf_key_type_id = info.btf_key_type_id;
1997 map->btf_value_type_id = info.btf_value_type_id;
2008 int bpf_map__resize(struct bpf_map *map, __u32 max_entries)
2010 if (!map || !max_entries)
2013 /* If map already created, its attributes can't be changed. */
2017 map->def.max_entries = max_entries;
2023 bpf_object__probe_name(struct bpf_object *obj)
2025 struct bpf_load_program_attr attr;
2026 char *cp, errmsg[STRERR_BUFSIZE];
2027 struct bpf_insn insns[] = {
2028 BPF_MOV64_IMM(BPF_REG_0, 0),
2033 /* make sure basic loading works */
2035 memset(&attr, 0, sizeof(attr));
2036 attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
2038 attr.insns_cnt = ARRAY_SIZE(insns);
2039 attr.license = "GPL";
2041 ret = bpf_load_program_xattr(&attr, NULL, 0);
2043 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
2044 pr_warn("Error in %s():%s(%d). Couldn't load basic 'r0 = 0' BPF program.\n",
2045 __func__, cp, errno);
2050 /* now try the same program, but with the name */
2053 ret = bpf_load_program_xattr(&attr, NULL, 0);
2063 bpf_object__probe_global_data(struct bpf_object *obj)
2065 struct bpf_load_program_attr prg_attr;
2066 struct bpf_create_map_attr map_attr;
2067 char *cp, errmsg[STRERR_BUFSIZE];
2068 struct bpf_insn insns[] = {
2069 BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16),
2070 BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42),
2071 BPF_MOV64_IMM(BPF_REG_0, 0),
2076 memset(&map_attr, 0, sizeof(map_attr));
2077 map_attr.map_type = BPF_MAP_TYPE_ARRAY;
2078 map_attr.key_size = sizeof(int);
2079 map_attr.value_size = 32;
2080 map_attr.max_entries = 1;
2082 map = bpf_create_map_xattr(&map_attr);
2084 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
2085 pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
2086 __func__, cp, errno);
2092 memset(&prg_attr, 0, sizeof(prg_attr));
2093 prg_attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
2094 prg_attr.insns = insns;
2095 prg_attr.insns_cnt = ARRAY_SIZE(insns);
2096 prg_attr.license = "GPL";
2098 ret = bpf_load_program_xattr(&prg_attr, NULL, 0);
2100 obj->caps.global_data = 1;
2108 static int bpf_object__probe_btf_func(struct bpf_object *obj)
2110 const char strs[] = "\0int\0x\0a";
2111 /* void x(int a) {} */
2114 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
2115 /* FUNC_PROTO */ /* [2] */
2116 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
2117 BTF_PARAM_ENC(7, 1),
2118 /* FUNC x */ /* [3] */
2119 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0), 2),
2123 btf_fd = libbpf__load_raw_btf((char *)types, sizeof(types),
2124 strs, sizeof(strs));
2126 obj->caps.btf_func = 1;
2134 static int bpf_object__probe_btf_datasec(struct bpf_object *obj)
2136 const char strs[] = "\0x\0.data";
2140 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
2141 /* VAR x */ /* [2] */
2142 BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
2144 /* DATASEC val */ /* [3] */
2145 BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC, 0, 1), 4),
2146 BTF_VAR_SECINFO_ENC(2, 0, 4),
2150 btf_fd = libbpf__load_raw_btf((char *)types, sizeof(types),
2151 strs, sizeof(strs));
2153 obj->caps.btf_datasec = 1;
2162 bpf_object__probe_caps(struct bpf_object *obj)
2164 int (*probe_fn[])(struct bpf_object *obj) = {
2165 bpf_object__probe_name,
2166 bpf_object__probe_global_data,
2167 bpf_object__probe_btf_func,
2168 bpf_object__probe_btf_datasec,
2172 for (i = 0; i < ARRAY_SIZE(probe_fn); i++) {
2173 ret = probe_fn[i](obj);
2175 pr_debug("Probe #%d failed with %d.\n", i, ret);
2181 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
2183 struct bpf_map_info map_info = {};
2184 char msg[STRERR_BUFSIZE];
2187 map_info_len = sizeof(map_info);
2189 if (bpf_obj_get_info_by_fd(map_fd, &map_info, &map_info_len)) {
2190 pr_warn("failed to get map info for map FD %d: %s\n",
2191 map_fd, libbpf_strerror_r(errno, msg, sizeof(msg)));
2195 return (map_info.type == map->def.type &&
2196 map_info.key_size == map->def.key_size &&
2197 map_info.value_size == map->def.value_size &&
2198 map_info.max_entries == map->def.max_entries &&
2199 map_info.map_flags == map->def.map_flags);
2203 bpf_object__reuse_map(struct bpf_map *map)
2205 char *cp, errmsg[STRERR_BUFSIZE];
2208 pin_fd = bpf_obj_get(map->pin_path);
2211 if (err == -ENOENT) {
2212 pr_debug("found no pinned map to reuse at '%s'\n",
2217 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
2218 pr_warn("couldn't retrieve pinned map '%s': %s\n",
2223 if (!map_is_reuse_compat(map, pin_fd)) {
2224 pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
2230 err = bpf_map__reuse_fd(map, pin_fd);
2236 pr_debug("reused pinned map at '%s'\n", map->pin_path);
2242 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
2244 char *cp, errmsg[STRERR_BUFSIZE];
2248 /* Nothing to do here since kernel already zero-initializes .bss map. */
2249 if (map->libbpf_type == LIBBPF_MAP_BSS)
2252 data = map->libbpf_type == LIBBPF_MAP_DATA ?
2253 obj->sections.data : obj->sections.rodata;
2255 err = bpf_map_update_elem(map->fd, &zero, data, 0);
2256 /* Freeze .rodata map as read-only from syscall side. */
2257 if (!err && map->libbpf_type == LIBBPF_MAP_RODATA) {
2258 err = bpf_map_freeze(map->fd);
2260 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
2261 pr_warn("Error freezing map(%s) as read-only: %s\n",
2270 bpf_object__create_maps(struct bpf_object *obj)
2272 struct bpf_create_map_attr create_attr = {};
2277 for (i = 0; i < obj->nr_maps; i++) {
2278 struct bpf_map *map = &obj->maps[i];
2279 struct bpf_map_def *def = &map->def;
2280 char *cp, errmsg[STRERR_BUFSIZE];
2281 int *pfd = &map->fd;
2283 if (map->pin_path) {
2284 err = bpf_object__reuse_map(map);
2286 pr_warn("error reusing pinned map %s\n",
2293 pr_debug("skip map create (preset) %s: fd=%d\n",
2294 map->name, map->fd);
2299 create_attr.name = map->name;
2300 create_attr.map_ifindex = map->map_ifindex;
2301 create_attr.map_type = def->type;
2302 create_attr.map_flags = def->map_flags;
2303 create_attr.key_size = def->key_size;
2304 create_attr.value_size = def->value_size;
2305 if (def->type == BPF_MAP_TYPE_PERF_EVENT_ARRAY &&
2306 !def->max_entries) {
2308 nr_cpus = libbpf_num_possible_cpus();
2310 pr_warn("failed to determine number of system CPUs: %d\n",
2315 pr_debug("map '%s': setting size to %d\n",
2316 map->name, nr_cpus);
2317 create_attr.max_entries = nr_cpus;
2319 create_attr.max_entries = def->max_entries;
2321 create_attr.btf_fd = 0;
2322 create_attr.btf_key_type_id = 0;
2323 create_attr.btf_value_type_id = 0;
2324 if (bpf_map_type__is_map_in_map(def->type) &&
2325 map->inner_map_fd >= 0)
2326 create_attr.inner_map_fd = map->inner_map_fd;
2328 if (obj->btf && !bpf_map_find_btf_info(obj, map)) {
2329 create_attr.btf_fd = btf__fd(obj->btf);
2330 create_attr.btf_key_type_id = map->btf_key_type_id;
2331 create_attr.btf_value_type_id = map->btf_value_type_id;
2334 *pfd = bpf_create_map_xattr(&create_attr);
2335 if (*pfd < 0 && (create_attr.btf_key_type_id ||
2336 create_attr.btf_value_type_id)) {
2338 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
2339 pr_warn("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
2340 map->name, cp, err);
2341 create_attr.btf_fd = 0;
2342 create_attr.btf_key_type_id = 0;
2343 create_attr.btf_value_type_id = 0;
2344 map->btf_key_type_id = 0;
2345 map->btf_value_type_id = 0;
2346 *pfd = bpf_create_map_xattr(&create_attr);
2354 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
2355 pr_warn("failed to create map (name: '%s'): %s(%d)\n",
2356 map->name, cp, err);
2357 for (j = 0; j < i; j++)
2358 zclose(obj->maps[j].fd);
2362 if (bpf_map__is_internal(map)) {
2363 err = bpf_object__populate_internal_map(obj, map);
2370 if (map->pin_path && !map->pinned) {
2371 err = bpf_map__pin(map, NULL);
2373 pr_warn("failed to auto-pin map name '%s' at '%s'\n",
2374 map->name, map->pin_path);
2379 pr_debug("created map %s: fd=%d\n", map->name, *pfd);
2386 check_btf_ext_reloc_err(struct bpf_program *prog, int err,
2387 void *btf_prog_info, const char *info_name)
2389 if (err != -ENOENT) {
2390 pr_warn("Error in loading %s for sec %s.\n",
2391 info_name, prog->section_name);
2395 /* err == -ENOENT (i.e. prog->section_name not found in btf_ext) */
2397 if (btf_prog_info) {
2399 * Some info has already been found but has problem
2400 * in the last btf_ext reloc. Must have to error out.
2402 pr_warn("Error in relocating %s for sec %s.\n",
2403 info_name, prog->section_name);
2407 /* Have problem loading the very first info. Ignore the rest. */
2408 pr_warn("Cannot find %s for main program sec %s. Ignore all %s.\n",
2409 info_name, prog->section_name, info_name);
2414 bpf_program_reloc_btf_ext(struct bpf_program *prog, struct bpf_object *obj,
2415 const char *section_name, __u32 insn_offset)
2419 if (!insn_offset || prog->func_info) {
2421 * !insn_offset => main program
2423 * For sub prog, the main program's func_info has to
2424 * be loaded first (i.e. prog->func_info != NULL)
2426 err = btf_ext__reloc_func_info(obj->btf, obj->btf_ext,
2427 section_name, insn_offset,
2429 &prog->func_info_cnt);
2431 return check_btf_ext_reloc_err(prog, err,
2435 prog->func_info_rec_size = btf_ext__func_info_rec_size(obj->btf_ext);
2438 if (!insn_offset || prog->line_info) {
2439 err = btf_ext__reloc_line_info(obj->btf, obj->btf_ext,
2440 section_name, insn_offset,
2442 &prog->line_info_cnt);
2444 return check_btf_ext_reloc_err(prog, err,
2448 prog->line_info_rec_size = btf_ext__line_info_rec_size(obj->btf_ext);
2454 #define BPF_CORE_SPEC_MAX_LEN 64
2456 /* represents BPF CO-RE field or array element accessor */
2457 struct bpf_core_accessor {
2458 __u32 type_id; /* struct/union type or array element type */
2459 __u32 idx; /* field index or array index */
2460 const char *name; /* field name or NULL for array accessor */
2463 struct bpf_core_spec {
2464 const struct btf *btf;
2465 /* high-level spec: named fields and array indices only */
2466 struct bpf_core_accessor spec[BPF_CORE_SPEC_MAX_LEN];
2467 /* high-level spec length */
2469 /* raw, low-level spec: 1-to-1 with accessor spec string */
2470 int raw_spec[BPF_CORE_SPEC_MAX_LEN];
2471 /* raw spec length */
2473 /* field bit offset represented by spec */
2477 static bool str_is_empty(const char *s)
2483 * Turn bpf_field_reloc into a low- and high-level spec representation,
2484 * validating correctness along the way, as well as calculating resulting
2485 * field bit offset, specified by accessor string. Low-level spec captures
2486 * every single level of nestedness, including traversing anonymous
2487 * struct/union members. High-level one only captures semantically meaningful
2488 * "turning points": named fields and array indicies.
2489 * E.g., for this case:
2492 * int __unimportant;
2500 * struct sample *s = ...;
2502 * int x = &s->a[3]; // access string = '0:1:2:3'
2504 * Low-level spec has 1:1 mapping with each element of access string (it's
2505 * just a parsed access string representation): [0, 1, 2, 3].
2507 * High-level spec will capture only 3 points:
2508 * - intial zero-index access by pointer (&s->... is the same as &s[0]...);
2509 * - field 'a' access (corresponds to '2' in low-level spec);
2510 * - array element #3 access (corresponds to '3' in low-level spec).
2513 static int bpf_core_spec_parse(const struct btf *btf,
2515 const char *spec_str,
2516 struct bpf_core_spec *spec)
2518 int access_idx, parsed_len, i;
2519 const struct btf_type *t;
2524 if (str_is_empty(spec_str) || *spec_str == ':')
2527 memset(spec, 0, sizeof(*spec));
2530 /* parse spec_str="0:1:2:3:4" into array raw_spec=[0, 1, 2, 3, 4] */
2532 if (*spec_str == ':')
2534 if (sscanf(spec_str, "%d%n", &access_idx, &parsed_len) != 1)
2536 if (spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
2538 spec_str += parsed_len;
2539 spec->raw_spec[spec->raw_len++] = access_idx;
2542 if (spec->raw_len == 0)
2545 /* first spec value is always reloc type array index */
2546 t = skip_mods_and_typedefs(btf, type_id, &id);
2550 access_idx = spec->raw_spec[0];
2551 spec->spec[0].type_id = id;
2552 spec->spec[0].idx = access_idx;
2555 sz = btf__resolve_size(btf, id);
2558 spec->bit_offset = access_idx * sz * 8;
2560 for (i = 1; i < spec->raw_len; i++) {
2561 t = skip_mods_and_typedefs(btf, id, &id);
2565 access_idx = spec->raw_spec[i];
2567 if (btf_is_composite(t)) {
2568 const struct btf_member *m;
2571 if (access_idx >= btf_vlen(t))
2574 bit_offset = btf_member_bit_offset(t, access_idx);
2575 spec->bit_offset += bit_offset;
2577 m = btf_members(t) + access_idx;
2579 name = btf__name_by_offset(btf, m->name_off);
2580 if (str_is_empty(name))
2583 spec->spec[spec->len].type_id = id;
2584 spec->spec[spec->len].idx = access_idx;
2585 spec->spec[spec->len].name = name;
2590 } else if (btf_is_array(t)) {
2591 const struct btf_array *a = btf_array(t);
2593 t = skip_mods_and_typedefs(btf, a->type, &id);
2594 if (!t || access_idx >= a->nelems)
2597 spec->spec[spec->len].type_id = id;
2598 spec->spec[spec->len].idx = access_idx;
2601 sz = btf__resolve_size(btf, id);
2604 spec->bit_offset += access_idx * sz * 8;
2606 pr_warn("relo for [%u] %s (at idx %d) captures type [%d] of unexpected kind %d\n",
2607 type_id, spec_str, i, id, btf_kind(t));
2615 static bool bpf_core_is_flavor_sep(const char *s)
2617 /* check X___Y name pattern, where X and Y are not underscores */
2618 return s[0] != '_' && /* X */
2619 s[1] == '_' && s[2] == '_' && s[3] == '_' && /* ___ */
2620 s[4] != '_'; /* Y */
2623 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
2624 * before last triple underscore. Struct name part after last triple
2625 * underscore is ignored by BPF CO-RE relocation during relocation matching.
2627 static size_t bpf_core_essential_name_len(const char *name)
2629 size_t n = strlen(name);
2632 for (i = n - 5; i >= 0; i--) {
2633 if (bpf_core_is_flavor_sep(name + i))
2639 /* dynamically sized list of type IDs */
2645 static void bpf_core_free_cands(struct ids_vec *cand_ids)
2647 free(cand_ids->data);
2651 static struct ids_vec *bpf_core_find_cands(const struct btf *local_btf,
2652 __u32 local_type_id,
2653 const struct btf *targ_btf)
2655 size_t local_essent_len, targ_essent_len;
2656 const char *local_name, *targ_name;
2657 const struct btf_type *t;
2658 struct ids_vec *cand_ids;
2662 t = btf__type_by_id(local_btf, local_type_id);
2664 return ERR_PTR(-EINVAL);
2666 local_name = btf__name_by_offset(local_btf, t->name_off);
2667 if (str_is_empty(local_name))
2668 return ERR_PTR(-EINVAL);
2669 local_essent_len = bpf_core_essential_name_len(local_name);
2671 cand_ids = calloc(1, sizeof(*cand_ids));
2673 return ERR_PTR(-ENOMEM);
2675 n = btf__get_nr_types(targ_btf);
2676 for (i = 1; i <= n; i++) {
2677 t = btf__type_by_id(targ_btf, i);
2678 targ_name = btf__name_by_offset(targ_btf, t->name_off);
2679 if (str_is_empty(targ_name))
2682 targ_essent_len = bpf_core_essential_name_len(targ_name);
2683 if (targ_essent_len != local_essent_len)
2686 if (strncmp(local_name, targ_name, local_essent_len) == 0) {
2687 pr_debug("[%d] %s: found candidate [%d] %s\n",
2688 local_type_id, local_name, i, targ_name);
2689 new_ids = realloc(cand_ids->data, cand_ids->len + 1);
2694 cand_ids->data = new_ids;
2695 cand_ids->data[cand_ids->len++] = i;
2700 bpf_core_free_cands(cand_ids);
2701 return ERR_PTR(err);
2704 /* Check two types for compatibility, skipping const/volatile/restrict and
2705 * typedefs, to ensure we are relocating compatible entities:
2706 * - any two STRUCTs/UNIONs are compatible and can be mixed;
2707 * - any two FWDs are compatible;
2708 * - any two PTRs are always compatible;
2709 * - for ENUMs, check sizes, names are ignored;
2710 * - for INT, size and signedness are ignored;
2711 * - for ARRAY, dimensionality is ignored, element types are checked for
2712 * compatibility recursively;
2713 * - everything else shouldn't be ever a target of relocation.
2714 * These rules are not set in stone and probably will be adjusted as we get
2715 * more experience with using BPF CO-RE relocations.
2717 static int bpf_core_fields_are_compat(const struct btf *local_btf,
2719 const struct btf *targ_btf,
2722 const struct btf_type *local_type, *targ_type;
2725 local_type = skip_mods_and_typedefs(local_btf, local_id, &local_id);
2726 targ_type = skip_mods_and_typedefs(targ_btf, targ_id, &targ_id);
2727 if (!local_type || !targ_type)
2730 if (btf_is_composite(local_type) && btf_is_composite(targ_type))
2732 if (btf_kind(local_type) != btf_kind(targ_type))
2735 switch (btf_kind(local_type)) {
2740 return local_type->size == targ_type->size;
2742 /* just reject deprecated bitfield-like integers; all other
2743 * integers are by default compatible between each other
2745 return btf_int_offset(local_type) == 0 &&
2746 btf_int_offset(targ_type) == 0;
2747 case BTF_KIND_ARRAY:
2748 local_id = btf_array(local_type)->type;
2749 targ_id = btf_array(targ_type)->type;
2752 pr_warn("unexpected kind %d relocated, local [%d], target [%d]\n",
2753 btf_kind(local_type), local_id, targ_id);
2759 * Given single high-level named field accessor in local type, find
2760 * corresponding high-level accessor for a target type. Along the way,
2761 * maintain low-level spec for target as well. Also keep updating target
2764 * Searching is performed through recursive exhaustive enumeration of all
2765 * fields of a struct/union. If there are any anonymous (embedded)
2766 * structs/unions, they are recursively searched as well. If field with
2767 * desired name is found, check compatibility between local and target types,
2768 * before returning result.
2770 * 1 is returned, if field is found.
2771 * 0 is returned if no compatible field is found.
2772 * <0 is returned on error.
2774 static int bpf_core_match_member(const struct btf *local_btf,
2775 const struct bpf_core_accessor *local_acc,
2776 const struct btf *targ_btf,
2778 struct bpf_core_spec *spec,
2779 __u32 *next_targ_id)
2781 const struct btf_type *local_type, *targ_type;
2782 const struct btf_member *local_member, *m;
2783 const char *local_name, *targ_name;
2787 targ_type = skip_mods_and_typedefs(targ_btf, targ_id, &targ_id);
2790 if (!btf_is_composite(targ_type))
2793 local_id = local_acc->type_id;
2794 local_type = btf__type_by_id(local_btf, local_id);
2795 local_member = btf_members(local_type) + local_acc->idx;
2796 local_name = btf__name_by_offset(local_btf, local_member->name_off);
2798 n = btf_vlen(targ_type);
2799 m = btf_members(targ_type);
2800 for (i = 0; i < n; i++, m++) {
2803 bit_offset = btf_member_bit_offset(targ_type, i);
2805 /* too deep struct/union/array nesting */
2806 if (spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
2809 /* speculate this member will be the good one */
2810 spec->bit_offset += bit_offset;
2811 spec->raw_spec[spec->raw_len++] = i;
2813 targ_name = btf__name_by_offset(targ_btf, m->name_off);
2814 if (str_is_empty(targ_name)) {
2815 /* embedded struct/union, we need to go deeper */
2816 found = bpf_core_match_member(local_btf, local_acc,
2818 spec, next_targ_id);
2819 if (found) /* either found or error */
2821 } else if (strcmp(local_name, targ_name) == 0) {
2822 /* matching named field */
2823 struct bpf_core_accessor *targ_acc;
2825 targ_acc = &spec->spec[spec->len++];
2826 targ_acc->type_id = targ_id;
2828 targ_acc->name = targ_name;
2830 *next_targ_id = m->type;
2831 found = bpf_core_fields_are_compat(local_btf,
2835 spec->len--; /* pop accessor */
2838 /* member turned out not to be what we looked for */
2839 spec->bit_offset -= bit_offset;
2847 * Try to match local spec to a target type and, if successful, produce full
2848 * target spec (high-level, low-level + bit offset).
2850 static int bpf_core_spec_match(struct bpf_core_spec *local_spec,
2851 const struct btf *targ_btf, __u32 targ_id,
2852 struct bpf_core_spec *targ_spec)
2854 const struct btf_type *targ_type;
2855 const struct bpf_core_accessor *local_acc;
2856 struct bpf_core_accessor *targ_acc;
2859 memset(targ_spec, 0, sizeof(*targ_spec));
2860 targ_spec->btf = targ_btf;
2862 local_acc = &local_spec->spec[0];
2863 targ_acc = &targ_spec->spec[0];
2865 for (i = 0; i < local_spec->len; i++, local_acc++, targ_acc++) {
2866 targ_type = skip_mods_and_typedefs(targ_spec->btf, targ_id,
2871 if (local_acc->name) {
2872 matched = bpf_core_match_member(local_spec->btf,
2875 targ_spec, &targ_id);
2879 /* for i=0, targ_id is already treated as array element
2880 * type (because it's the original struct), for others
2881 * we should find array element type first
2884 const struct btf_array *a;
2886 if (!btf_is_array(targ_type))
2889 a = btf_array(targ_type);
2890 if (local_acc->idx >= a->nelems)
2892 if (!skip_mods_and_typedefs(targ_btf, a->type,
2897 /* too deep struct/union/array nesting */
2898 if (targ_spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
2901 targ_acc->type_id = targ_id;
2902 targ_acc->idx = local_acc->idx;
2903 targ_acc->name = NULL;
2905 targ_spec->raw_spec[targ_spec->raw_len] = targ_acc->idx;
2906 targ_spec->raw_len++;
2908 sz = btf__resolve_size(targ_btf, targ_id);
2911 targ_spec->bit_offset += local_acc->idx * sz * 8;
2918 static int bpf_core_calc_field_relo(const struct bpf_program *prog,
2919 const struct bpf_field_reloc *relo,
2920 const struct bpf_core_spec *spec,
2921 __u32 *val, bool *validate)
2923 const struct bpf_core_accessor *acc = &spec->spec[spec->len - 1];
2924 const struct btf_type *t = btf__type_by_id(spec->btf, acc->type_id);
2925 __u32 byte_off, byte_sz, bit_off, bit_sz;
2926 const struct btf_member *m;
2927 const struct btf_type *mt;
2930 /* a[n] accessor needs special handling */
2932 if (relo->kind != BPF_FIELD_BYTE_OFFSET) {
2933 pr_warn("prog '%s': relo %d at insn #%d can't be applied to array access'\n",
2934 bpf_program__title(prog, false),
2935 relo->kind, relo->insn_off / 8);
2938 *val = spec->bit_offset / 8;
2944 m = btf_members(t) + acc->idx;
2945 mt = skip_mods_and_typedefs(spec->btf, m->type, NULL);
2946 bit_off = spec->bit_offset;
2947 bit_sz = btf_member_bitfield_size(t, acc->idx);
2949 bitfield = bit_sz > 0;
2952 byte_off = bit_off / 8 / byte_sz * byte_sz;
2953 /* figure out smallest int size necessary for bitfield load */
2954 while (bit_off + bit_sz - byte_off * 8 > byte_sz * 8) {
2956 /* bitfield can't be read with 64-bit read */
2957 pr_warn("prog '%s': relo %d at insn #%d can't be satisfied for bitfield\n",
2958 bpf_program__title(prog, false),
2959 relo->kind, relo->insn_off / 8);
2963 byte_off = bit_off / 8 / byte_sz * byte_sz;
2967 byte_off = spec->bit_offset / 8;
2968 bit_sz = byte_sz * 8;
2971 /* for bitfields, all the relocatable aspects are ambiguous and we
2972 * might disagree with compiler, so turn off validation of expected
2973 * value, except for signedness
2976 *validate = !bitfield;
2978 switch (relo->kind) {
2979 case BPF_FIELD_BYTE_OFFSET:
2982 case BPF_FIELD_BYTE_SIZE:
2985 case BPF_FIELD_SIGNED:
2986 /* enums will be assumed unsigned */
2987 *val = btf_is_enum(mt) ||
2988 (btf_int_encoding(mt) & BTF_INT_SIGNED);
2990 *validate = true; /* signedness is never ambiguous */
2992 case BPF_FIELD_LSHIFT_U64:
2993 #if __BYTE_ORDER == __LITTLE_ENDIAN
2994 *val = 64 - (bit_off + bit_sz - byte_off * 8);
2996 *val = (8 - byte_sz) * 8 + (bit_off - byte_off * 8);
2999 case BPF_FIELD_RSHIFT_U64:
3002 *validate = true; /* right shift is never ambiguous */
3004 case BPF_FIELD_EXISTS:
3006 pr_warn("prog '%s': unknown relo %d at insn #%d\n",
3007 bpf_program__title(prog, false),
3008 relo->kind, relo->insn_off / 8);
3016 * Patch relocatable BPF instruction.
3018 * Patched value is determined by relocation kind and target specification.
3019 * For field existence relocation target spec will be NULL if field is not
3021 * Expected insn->imm value is determined using relocation kind and local
3022 * spec, and is checked before patching instruction. If actual insn->imm value
3023 * is wrong, bail out with error.
3025 * Currently three kinds of BPF instructions are supported:
3026 * 1. rX = <imm> (assignment with immediate operand);
3027 * 2. rX += <imm> (arithmetic operations with immediate operand);
3029 static int bpf_core_reloc_insn(struct bpf_program *prog,
3030 const struct bpf_field_reloc *relo,
3031 const struct bpf_core_spec *local_spec,
3032 const struct bpf_core_spec *targ_spec)
3034 bool failed = false, validate = true;
3035 __u32 orig_val, new_val;
3036 struct bpf_insn *insn;
3040 if (relo->insn_off % sizeof(struct bpf_insn))
3042 insn_idx = relo->insn_off / sizeof(struct bpf_insn);
3044 if (relo->kind == BPF_FIELD_EXISTS) {
3045 orig_val = 1; /* can't generate EXISTS relo w/o local field */
3046 new_val = targ_spec ? 1 : 0;
3047 } else if (!targ_spec) {
3049 new_val = (__u32)-1;
3051 err = bpf_core_calc_field_relo(prog, relo, local_spec,
3052 &orig_val, &validate);
3055 err = bpf_core_calc_field_relo(prog, relo, targ_spec,
3061 insn = &prog->insns[insn_idx];
3062 class = BPF_CLASS(insn->code);
3064 if (class == BPF_ALU || class == BPF_ALU64) {
3065 if (BPF_SRC(insn->code) != BPF_K)
3067 if (!failed && validate && insn->imm != orig_val) {
3068 pr_warn("prog '%s': unexpected insn #%d value: got %u, exp %u -> %u\n",
3069 bpf_program__title(prog, false), insn_idx,
3070 insn->imm, orig_val, new_val);
3073 orig_val = insn->imm;
3074 insn->imm = new_val;
3075 pr_debug("prog '%s': patched insn #%d (ALU/ALU64)%s imm %u -> %u\n",
3076 bpf_program__title(prog, false), insn_idx,
3077 failed ? " w/ failed reloc" : "", orig_val, new_val);
3079 pr_warn("prog '%s': trying to relocate unrecognized insn #%d, code:%x, src:%x, dst:%x, off:%x, imm:%x\n",
3080 bpf_program__title(prog, false),
3081 insn_idx, insn->code, insn->src_reg, insn->dst_reg,
3082 insn->off, insn->imm);
3089 static struct btf *btf_load_raw(const char *path)
3097 if (stat(path, &st))
3098 return ERR_PTR(-errno);
3100 data = malloc(st.st_size);
3102 return ERR_PTR(-ENOMEM);
3104 f = fopen(path, "rb");
3106 btf = ERR_PTR(-errno);
3110 read_cnt = fread(data, 1, st.st_size, f);
3112 if (read_cnt < st.st_size) {
3113 btf = ERR_PTR(-EBADF);
3117 btf = btf__new(data, read_cnt);
3125 * Probe few well-known locations for vmlinux kernel image and try to load BTF
3126 * data out of it to use for target BTF.
3128 static struct btf *bpf_core_find_kernel_btf(void)
3131 const char *path_fmt;
3134 /* try canonical vmlinux BTF through sysfs first */
3135 { "/sys/kernel/btf/vmlinux", true /* raw BTF */ },
3136 /* fall back to trying to find vmlinux ELF on disk otherwise */
3137 { "/boot/vmlinux-%1$s" },
3138 { "/lib/modules/%1$s/vmlinux-%1$s" },
3139 { "/lib/modules/%1$s/build/vmlinux" },
3140 { "/usr/lib/modules/%1$s/kernel/vmlinux" },
3141 { "/usr/lib/debug/boot/vmlinux-%1$s" },
3142 { "/usr/lib/debug/boot/vmlinux-%1$s.debug" },
3143 { "/usr/lib/debug/lib/modules/%1$s/vmlinux" },
3145 char path[PATH_MAX + 1];
3152 for (i = 0; i < ARRAY_SIZE(locations); i++) {
3153 snprintf(path, PATH_MAX, locations[i].path_fmt, buf.release);
3155 if (access(path, R_OK))
3158 if (locations[i].raw_btf)
3159 btf = btf_load_raw(path);
3161 btf = btf__parse_elf(path, NULL);
3163 pr_debug("loading kernel BTF '%s': %ld\n",
3164 path, IS_ERR(btf) ? PTR_ERR(btf) : 0);
3171 pr_warn("failed to find valid kernel BTF\n");
3172 return ERR_PTR(-ESRCH);
3175 /* Output spec definition in the format:
3176 * [<type-id>] (<type-name>) + <raw-spec> => <offset>@<spec>,
3177 * where <spec> is a C-syntax view of recorded field access, e.g.: x.a[3].b
3179 static void bpf_core_dump_spec(int level, const struct bpf_core_spec *spec)
3181 const struct btf_type *t;
3186 type_id = spec->spec[0].type_id;
3187 t = btf__type_by_id(spec->btf, type_id);
3188 s = btf__name_by_offset(spec->btf, t->name_off);
3189 libbpf_print(level, "[%u] %s + ", type_id, s);
3191 for (i = 0; i < spec->raw_len; i++)
3192 libbpf_print(level, "%d%s", spec->raw_spec[i],
3193 i == spec->raw_len - 1 ? " => " : ":");
3195 libbpf_print(level, "%u.%u @ &x",
3196 spec->bit_offset / 8, spec->bit_offset % 8);
3198 for (i = 0; i < spec->len; i++) {
3199 if (spec->spec[i].name)
3200 libbpf_print(level, ".%s", spec->spec[i].name);
3202 libbpf_print(level, "[%u]", spec->spec[i].idx);
3207 static size_t bpf_core_hash_fn(const void *key, void *ctx)
3212 static bool bpf_core_equal_fn(const void *k1, const void *k2, void *ctx)
3217 static void *u32_as_hash_key(__u32 x)
3219 return (void *)(uintptr_t)x;
3223 * CO-RE relocate single instruction.
3225 * The outline and important points of the algorithm:
3226 * 1. For given local type, find corresponding candidate target types.
3227 * Candidate type is a type with the same "essential" name, ignoring
3228 * everything after last triple underscore (___). E.g., `sample`,
3229 * `sample___flavor_one`, `sample___flavor_another_one`, are all candidates
3230 * for each other. Names with triple underscore are referred to as
3231 * "flavors" and are useful, among other things, to allow to
3232 * specify/support incompatible variations of the same kernel struct, which
3233 * might differ between different kernel versions and/or build
3236 * N.B. Struct "flavors" could be generated by bpftool's BTF-to-C
3237 * converter, when deduplicated BTF of a kernel still contains more than
3238 * one different types with the same name. In that case, ___2, ___3, etc
3239 * are appended starting from second name conflict. But start flavors are
3240 * also useful to be defined "locally", in BPF program, to extract same
3241 * data from incompatible changes between different kernel
3242 * versions/configurations. For instance, to handle field renames between
3243 * kernel versions, one can use two flavors of the struct name with the
3244 * same common name and use conditional relocations to extract that field,
3245 * depending on target kernel version.
3246 * 2. For each candidate type, try to match local specification to this
3247 * candidate target type. Matching involves finding corresponding
3248 * high-level spec accessors, meaning that all named fields should match,
3249 * as well as all array accesses should be within the actual bounds. Also,
3250 * types should be compatible (see bpf_core_fields_are_compat for details).
3251 * 3. It is supported and expected that there might be multiple flavors
3252 * matching the spec. As long as all the specs resolve to the same set of
3253 * offsets across all candidates, there is no error. If there is any
3254 * ambiguity, CO-RE relocation will fail. This is necessary to accomodate
3255 * imprefection of BTF deduplication, which can cause slight duplication of
3256 * the same BTF type, if some directly or indirectly referenced (by
3257 * pointer) type gets resolved to different actual types in different
3258 * object files. If such situation occurs, deduplicated BTF will end up
3259 * with two (or more) structurally identical types, which differ only in
3260 * types they refer to through pointer. This should be OK in most cases and
3262 * 4. Candidate types search is performed by linearly scanning through all
3263 * types in target BTF. It is anticipated that this is overall more
3264 * efficient memory-wise and not significantly worse (if not better)
3265 * CPU-wise compared to prebuilding a map from all local type names to
3266 * a list of candidate type names. It's also sped up by caching resolved
3267 * list of matching candidates per each local "root" type ID, that has at
3268 * least one bpf_field_reloc associated with it. This list is shared
3269 * between multiple relocations for the same type ID and is updated as some
3270 * of the candidates are pruned due to structural incompatibility.
3272 static int bpf_core_reloc_field(struct bpf_program *prog,
3273 const struct bpf_field_reloc *relo,
3275 const struct btf *local_btf,
3276 const struct btf *targ_btf,
3277 struct hashmap *cand_cache)
3279 const char *prog_name = bpf_program__title(prog, false);
3280 struct bpf_core_spec local_spec, cand_spec, targ_spec;
3281 const void *type_key = u32_as_hash_key(relo->type_id);
3282 const struct btf_type *local_type, *cand_type;
3283 const char *local_name, *cand_name;
3284 struct ids_vec *cand_ids;
3285 __u32 local_id, cand_id;
3286 const char *spec_str;
3289 local_id = relo->type_id;
3290 local_type = btf__type_by_id(local_btf, local_id);
3294 local_name = btf__name_by_offset(local_btf, local_type->name_off);
3295 if (str_is_empty(local_name))
3298 spec_str = btf__name_by_offset(local_btf, relo->access_str_off);
3299 if (str_is_empty(spec_str))
3302 err = bpf_core_spec_parse(local_btf, local_id, spec_str, &local_spec);
3304 pr_warn("prog '%s': relo #%d: parsing [%d] %s + %s failed: %d\n",
3305 prog_name, relo_idx, local_id, local_name, spec_str,
3310 pr_debug("prog '%s': relo #%d: kind %d, spec is ", prog_name, relo_idx,
3312 bpf_core_dump_spec(LIBBPF_DEBUG, &local_spec);
3313 libbpf_print(LIBBPF_DEBUG, "\n");
3315 if (!hashmap__find(cand_cache, type_key, (void **)&cand_ids)) {
3316 cand_ids = bpf_core_find_cands(local_btf, local_id, targ_btf);
3317 if (IS_ERR(cand_ids)) {
3318 pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s: %ld",
3319 prog_name, relo_idx, local_id, local_name,
3321 return PTR_ERR(cand_ids);
3323 err = hashmap__set(cand_cache, type_key, cand_ids, NULL, NULL);
3325 bpf_core_free_cands(cand_ids);
3330 for (i = 0, j = 0; i < cand_ids->len; i++) {
3331 cand_id = cand_ids->data[i];
3332 cand_type = btf__type_by_id(targ_btf, cand_id);
3333 cand_name = btf__name_by_offset(targ_btf, cand_type->name_off);
3335 err = bpf_core_spec_match(&local_spec, targ_btf,
3336 cand_id, &cand_spec);
3337 pr_debug("prog '%s': relo #%d: matching candidate #%d %s against spec ",
3338 prog_name, relo_idx, i, cand_name);
3339 bpf_core_dump_spec(LIBBPF_DEBUG, &cand_spec);
3340 libbpf_print(LIBBPF_DEBUG, ": %d\n", err);
3342 pr_warn("prog '%s': relo #%d: matching error: %d\n",
3343 prog_name, relo_idx, err);
3350 targ_spec = cand_spec;
3351 } else if (cand_spec.bit_offset != targ_spec.bit_offset) {
3352 /* if there are many candidates, they should all
3353 * resolve to the same bit offset
3355 pr_warn("prog '%s': relo #%d: offset ambiguity: %u != %u\n",
3356 prog_name, relo_idx, cand_spec.bit_offset,
3357 targ_spec.bit_offset);
3361 cand_ids->data[j++] = cand_spec.spec[0].type_id;
3365 * For BPF_FIELD_EXISTS relo or when relaxed CO-RE reloc mode is
3366 * requested, it's expected that we might not find any candidates.
3367 * In this case, if field wasn't found in any candidate, the list of
3368 * candidates shouldn't change at all, we'll just handle relocating
3369 * appropriately, depending on relo's kind.
3374 if (j == 0 && !prog->obj->relaxed_core_relocs &&
3375 relo->kind != BPF_FIELD_EXISTS) {
3376 pr_warn("prog '%s': relo #%d: no matching targets found for [%d] %s + %s\n",
3377 prog_name, relo_idx, local_id, local_name, spec_str);
3381 /* bpf_core_reloc_insn should know how to handle missing targ_spec */
3382 err = bpf_core_reloc_insn(prog, relo, &local_spec,
3383 j ? &targ_spec : NULL);
3385 pr_warn("prog '%s': relo #%d: failed to patch insn at offset %d: %d\n",
3386 prog_name, relo_idx, relo->insn_off, err);
3394 bpf_core_reloc_fields(struct bpf_object *obj, const char *targ_btf_path)
3396 const struct btf_ext_info_sec *sec;
3397 const struct bpf_field_reloc *rec;
3398 const struct btf_ext_info *seg;
3399 struct hashmap_entry *entry;
3400 struct hashmap *cand_cache = NULL;
3401 struct bpf_program *prog;
3402 struct btf *targ_btf;
3403 const char *sec_name;
3407 targ_btf = btf__parse_elf(targ_btf_path, NULL);
3409 targ_btf = bpf_core_find_kernel_btf();
3410 if (IS_ERR(targ_btf)) {
3411 pr_warn("failed to get target BTF: %ld\n", PTR_ERR(targ_btf));
3412 return PTR_ERR(targ_btf);
3415 cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
3416 if (IS_ERR(cand_cache)) {
3417 err = PTR_ERR(cand_cache);
3421 seg = &obj->btf_ext->field_reloc_info;
3422 for_each_btf_ext_sec(seg, sec) {
3423 sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
3424 if (str_is_empty(sec_name)) {
3428 prog = bpf_object__find_program_by_title(obj, sec_name);
3430 pr_warn("failed to find program '%s' for CO-RE offset relocation\n",
3436 pr_debug("prog '%s': performing %d CO-RE offset relocs\n",
3437 sec_name, sec->num_info);
3439 for_each_btf_ext_rec(seg, sec, i, rec) {
3440 err = bpf_core_reloc_field(prog, rec, i, obj->btf,
3441 targ_btf, cand_cache);
3443 pr_warn("prog '%s': relo #%d: failed to relocate: %d\n",
3451 btf__free(targ_btf);
3452 if (!IS_ERR_OR_NULL(cand_cache)) {
3453 hashmap__for_each_entry(cand_cache, entry, i) {
3454 bpf_core_free_cands(entry->value);
3456 hashmap__free(cand_cache);
3462 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
3466 if (obj->btf_ext->field_reloc_info.len)
3467 err = bpf_core_reloc_fields(obj, targ_btf_path);
3473 bpf_program__reloc_text(struct bpf_program *prog, struct bpf_object *obj,
3474 struct reloc_desc *relo)
3476 struct bpf_insn *insn, *new_insn;
3477 struct bpf_program *text;
3481 if (relo->type != RELO_CALL)
3482 return -LIBBPF_ERRNO__RELOC;
3484 if (prog->idx == obj->efile.text_shndx) {
3485 pr_warn("relo in .text insn %d into off %d\n",
3486 relo->insn_idx, relo->text_off);
3487 return -LIBBPF_ERRNO__RELOC;
3490 if (prog->main_prog_cnt == 0) {
3491 text = bpf_object__find_prog_by_idx(obj, obj->efile.text_shndx);
3493 pr_warn("no .text section found yet relo into text exist\n");
3494 return -LIBBPF_ERRNO__RELOC;
3496 new_cnt = prog->insns_cnt + text->insns_cnt;
3497 new_insn = reallocarray(prog->insns, new_cnt, sizeof(*insn));
3499 pr_warn("oom in prog realloc\n");
3504 err = bpf_program_reloc_btf_ext(prog, obj,
3511 memcpy(new_insn + prog->insns_cnt, text->insns,
3512 text->insns_cnt * sizeof(*insn));
3513 prog->insns = new_insn;
3514 prog->main_prog_cnt = prog->insns_cnt;
3515 prog->insns_cnt = new_cnt;
3516 pr_debug("added %zd insn from %s to prog %s\n",
3517 text->insns_cnt, text->section_name,
3518 prog->section_name);
3520 insn = &prog->insns[relo->insn_idx];
3521 insn->imm += prog->main_prog_cnt - relo->insn_idx;
3526 bpf_program__relocate(struct bpf_program *prog, struct bpf_object *obj)
3534 err = bpf_program_reloc_btf_ext(prog, obj,
3535 prog->section_name, 0);
3540 if (!prog->reloc_desc)
3543 for (i = 0; i < prog->nr_reloc; i++) {
3544 if (prog->reloc_desc[i].type == RELO_LD64 ||
3545 prog->reloc_desc[i].type == RELO_DATA) {
3546 bool relo_data = prog->reloc_desc[i].type == RELO_DATA;
3547 struct bpf_insn *insns = prog->insns;
3548 int insn_idx, map_idx;
3550 insn_idx = prog->reloc_desc[i].insn_idx;
3551 map_idx = prog->reloc_desc[i].map_idx;
3553 if (insn_idx + 1 >= (int)prog->insns_cnt) {
3554 pr_warn("relocation out of range: '%s'\n",
3555 prog->section_name);
3556 return -LIBBPF_ERRNO__RELOC;
3560 insns[insn_idx].src_reg = BPF_PSEUDO_MAP_FD;
3562 insns[insn_idx].src_reg = BPF_PSEUDO_MAP_VALUE;
3563 insns[insn_idx + 1].imm = insns[insn_idx].imm;
3565 insns[insn_idx].imm = obj->maps[map_idx].fd;
3566 } else if (prog->reloc_desc[i].type == RELO_CALL) {
3567 err = bpf_program__reloc_text(prog, obj,
3568 &prog->reloc_desc[i]);
3574 zfree(&prog->reloc_desc);
3580 bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
3582 struct bpf_program *prog;
3587 err = bpf_object__relocate_core(obj, targ_btf_path);
3589 pr_warn("failed to perform CO-RE relocations: %d\n",
3594 for (i = 0; i < obj->nr_programs; i++) {
3595 prog = &obj->programs[i];
3597 err = bpf_program__relocate(prog, obj);
3599 pr_warn("failed to relocate '%s'\n", prog->section_name);
3606 static int bpf_object__collect_reloc(struct bpf_object *obj)
3610 if (!obj_elf_valid(obj)) {
3611 pr_warn("Internal error: elf object is closed\n");
3612 return -LIBBPF_ERRNO__INTERNAL;
3615 for (i = 0; i < obj->efile.nr_reloc; i++) {
3616 GElf_Shdr *shdr = &obj->efile.reloc[i].shdr;
3617 Elf_Data *data = obj->efile.reloc[i].data;
3618 int idx = shdr->sh_info;
3619 struct bpf_program *prog;
3621 if (shdr->sh_type != SHT_REL) {
3622 pr_warn("internal error at %d\n", __LINE__);
3623 return -LIBBPF_ERRNO__INTERNAL;
3626 prog = bpf_object__find_prog_by_idx(obj, idx);
3628 pr_warn("relocation failed: no section(%d)\n", idx);
3629 return -LIBBPF_ERRNO__RELOC;
3632 err = bpf_program__collect_reloc(prog, shdr, data, obj);
3640 load_program(struct bpf_program *prog, struct bpf_insn *insns, int insns_cnt,
3641 char *license, __u32 kern_version, int *pfd)
3643 struct bpf_load_program_attr load_attr;
3644 char *cp, errmsg[STRERR_BUFSIZE];
3645 int log_buf_size = BPF_LOG_BUF_SIZE;
3649 if (!insns || !insns_cnt)
3652 memset(&load_attr, 0, sizeof(struct bpf_load_program_attr));
3653 load_attr.prog_type = prog->type;
3654 load_attr.expected_attach_type = prog->expected_attach_type;
3655 if (prog->caps->name)
3656 load_attr.name = prog->name;
3657 load_attr.insns = insns;
3658 load_attr.insns_cnt = insns_cnt;
3659 load_attr.license = license;
3660 load_attr.kern_version = kern_version;
3661 load_attr.prog_ifindex = prog->prog_ifindex;
3662 /* if .BTF.ext was loaded, kernel supports associated BTF for prog */
3663 if (prog->obj->btf_ext)
3664 btf_fd = bpf_object__btf_fd(prog->obj);
3667 load_attr.prog_btf_fd = btf_fd >= 0 ? btf_fd : 0;
3668 load_attr.func_info = prog->func_info;
3669 load_attr.func_info_rec_size = prog->func_info_rec_size;
3670 load_attr.func_info_cnt = prog->func_info_cnt;
3671 load_attr.line_info = prog->line_info;
3672 load_attr.line_info_rec_size = prog->line_info_rec_size;
3673 load_attr.line_info_cnt = prog->line_info_cnt;
3674 load_attr.log_level = prog->log_level;
3675 load_attr.prog_flags = prog->prog_flags;
3676 load_attr.attach_btf_id = prog->attach_btf_id;
3679 log_buf = malloc(log_buf_size);
3681 pr_warn("Alloc log buffer for bpf loader error, continue without log\n");
3683 ret = bpf_load_program_xattr(&load_attr, log_buf, log_buf_size);
3686 if (load_attr.log_level)
3687 pr_debug("verifier log:\n%s", log_buf);
3693 if (errno == ENOSPC) {
3698 ret = -LIBBPF_ERRNO__LOAD;
3699 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
3700 pr_warn("load bpf program failed: %s\n", cp);
3702 if (log_buf && log_buf[0] != '\0') {
3703 ret = -LIBBPF_ERRNO__VERIFY;
3704 pr_warn("-- BEGIN DUMP LOG ---\n");
3705 pr_warn("\n%s\n", log_buf);
3706 pr_warn("-- END LOG --\n");
3707 } else if (load_attr.insns_cnt >= BPF_MAXINSNS) {
3708 pr_warn("Program too large (%zu insns), at most %d insns\n",
3709 load_attr.insns_cnt, BPF_MAXINSNS);
3710 ret = -LIBBPF_ERRNO__PROG2BIG;
3712 /* Wrong program type? */
3713 if (load_attr.prog_type != BPF_PROG_TYPE_KPROBE) {
3716 load_attr.prog_type = BPF_PROG_TYPE_KPROBE;
3717 load_attr.expected_attach_type = 0;
3718 fd = bpf_load_program_xattr(&load_attr, NULL, 0);
3721 ret = -LIBBPF_ERRNO__PROGTYPE;
3727 ret = -LIBBPF_ERRNO__KVER;
3736 bpf_program__load(struct bpf_program *prog,
3737 char *license, __u32 kern_version)
3741 if (prog->instances.nr < 0 || !prog->instances.fds) {
3742 if (prog->preprocessor) {
3743 pr_warn("Internal error: can't load program '%s'\n",
3744 prog->section_name);
3745 return -LIBBPF_ERRNO__INTERNAL;
3748 prog->instances.fds = malloc(sizeof(int));
3749 if (!prog->instances.fds) {
3750 pr_warn("Not enough memory for BPF fds\n");
3753 prog->instances.nr = 1;
3754 prog->instances.fds[0] = -1;
3757 if (!prog->preprocessor) {
3758 if (prog->instances.nr != 1) {
3759 pr_warn("Program '%s' is inconsistent: nr(%d) != 1\n",
3760 prog->section_name, prog->instances.nr);
3762 err = load_program(prog, prog->insns, prog->insns_cnt,
3763 license, kern_version, &fd);
3765 prog->instances.fds[0] = fd;
3769 for (i = 0; i < prog->instances.nr; i++) {
3770 struct bpf_prog_prep_result result;
3771 bpf_program_prep_t preprocessor = prog->preprocessor;
3773 memset(&result, 0, sizeof(result));
3774 err = preprocessor(prog, i, prog->insns,
3775 prog->insns_cnt, &result);
3777 pr_warn("Preprocessing the %dth instance of program '%s' failed\n",
3778 i, prog->section_name);
3782 if (!result.new_insn_ptr || !result.new_insn_cnt) {
3783 pr_debug("Skip loading the %dth instance of program '%s'\n",
3784 i, prog->section_name);
3785 prog->instances.fds[i] = -1;
3791 err = load_program(prog, result.new_insn_ptr,
3792 result.new_insn_cnt,
3793 license, kern_version, &fd);
3796 pr_warn("Loading the %dth instance of program '%s' failed\n",
3797 i, prog->section_name);
3803 prog->instances.fds[i] = fd;
3807 pr_warn("failed to load program '%s'\n", prog->section_name);
3808 zfree(&prog->insns);
3809 prog->insns_cnt = 0;
3813 static bool bpf_program__is_function_storage(const struct bpf_program *prog,
3814 const struct bpf_object *obj)
3816 return prog->idx == obj->efile.text_shndx && obj->has_pseudo_calls;
3820 bpf_object__load_progs(struct bpf_object *obj, int log_level)
3825 for (i = 0; i < obj->nr_programs; i++) {
3826 if (bpf_program__is_function_storage(&obj->programs[i], obj))
3828 obj->programs[i].log_level |= log_level;
3829 err = bpf_program__load(&obj->programs[i],
3838 static int libbpf_attach_btf_id_by_name(const char *name, __u32 *btf_id);
3840 static struct bpf_object *
3841 __bpf_object__open(const char *path, const void *obj_buf, size_t obj_buf_sz,
3842 struct bpf_object_open_opts *opts)
3844 const char *pin_root_path;
3845 struct bpf_program *prog;
3846 struct bpf_object *obj;
3847 const char *obj_name;
3852 if (elf_version(EV_CURRENT) == EV_NONE) {
3853 pr_warn("failed to init libelf for %s\n",
3854 path ? : "(mem buf)");
3855 return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
3858 if (!OPTS_VALID(opts, bpf_object_open_opts))
3859 return ERR_PTR(-EINVAL);
3861 obj_name = OPTS_GET(opts, object_name, path);
3864 snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
3865 (unsigned long)obj_buf,
3866 (unsigned long)obj_buf_sz);
3867 obj_name = tmp_name;
3870 pr_debug("loading object '%s' from buffer\n", obj_name);
3873 obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
3877 obj->relaxed_core_relocs = OPTS_GET(opts, relaxed_core_relocs, false);
3878 relaxed_maps = OPTS_GET(opts, relaxed_maps, false);
3879 pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
3881 CHECK_ERR(bpf_object__elf_init(obj), err, out);
3882 CHECK_ERR(bpf_object__check_endianness(obj), err, out);
3883 CHECK_ERR(bpf_object__probe_caps(obj), err, out);
3884 CHECK_ERR(bpf_object__elf_collect(obj, relaxed_maps, pin_root_path),
3886 CHECK_ERR(bpf_object__collect_reloc(obj), err, out);
3887 bpf_object__elf_finish(obj);
3889 bpf_object__for_each_program(prog, obj) {
3890 enum bpf_prog_type prog_type;
3891 enum bpf_attach_type attach_type;
3894 err = libbpf_prog_type_by_name(prog->section_name, &prog_type,
3897 /* couldn't guess, but user might manually specify */
3902 bpf_program__set_type(prog, prog_type);
3903 bpf_program__set_expected_attach_type(prog, attach_type);
3904 if (prog_type == BPF_PROG_TYPE_TRACING) {
3905 err = libbpf_attach_btf_id_by_name(prog->section_name, &btf_id);
3908 prog->attach_btf_id = btf_id;
3914 bpf_object__close(obj);
3915 return ERR_PTR(err);
3918 static struct bpf_object *
3919 __bpf_object__open_xattr(struct bpf_object_open_attr *attr, int flags)
3921 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts,
3922 .relaxed_maps = flags & MAPS_RELAX_COMPAT,
3925 /* param validation */
3929 pr_debug("loading %s\n", attr->file);
3930 return __bpf_object__open(attr->file, NULL, 0, &opts);
3933 struct bpf_object *bpf_object__open_xattr(struct bpf_object_open_attr *attr)
3935 return __bpf_object__open_xattr(attr, 0);
3938 struct bpf_object *bpf_object__open(const char *path)
3940 struct bpf_object_open_attr attr = {
3942 .prog_type = BPF_PROG_TYPE_UNSPEC,
3945 return bpf_object__open_xattr(&attr);
3949 bpf_object__open_file(const char *path, struct bpf_object_open_opts *opts)
3952 return ERR_PTR(-EINVAL);
3954 pr_debug("loading %s\n", path);
3956 return __bpf_object__open(path, NULL, 0, opts);
3960 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
3961 struct bpf_object_open_opts *opts)
3963 if (!obj_buf || obj_buf_sz == 0)
3964 return ERR_PTR(-EINVAL);
3966 return __bpf_object__open(NULL, obj_buf, obj_buf_sz, opts);
3970 bpf_object__open_buffer(const void *obj_buf, size_t obj_buf_sz,
3973 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts,
3974 .object_name = name,
3975 /* wrong default, but backwards-compatible */
3976 .relaxed_maps = true,
3979 /* returning NULL is wrong, but backwards-compatible */
3980 if (!obj_buf || obj_buf_sz == 0)
3983 return bpf_object__open_mem(obj_buf, obj_buf_sz, &opts);
3986 int bpf_object__unload(struct bpf_object *obj)
3993 for (i = 0; i < obj->nr_maps; i++)
3994 zclose(obj->maps[i].fd);
3996 for (i = 0; i < obj->nr_programs; i++)
3997 bpf_program__unload(&obj->programs[i]);
4002 int bpf_object__load_xattr(struct bpf_object_load_attr *attr)
4004 struct bpf_object *obj;
4014 pr_warn("object should not be loaded twice\n");
4020 CHECK_ERR(bpf_object__create_maps(obj), err, out);
4021 CHECK_ERR(bpf_object__relocate(obj, attr->target_btf_path), err, out);
4022 CHECK_ERR(bpf_object__load_progs(obj, attr->log_level), err, out);
4026 bpf_object__unload(obj);
4027 pr_warn("failed to load object '%s'\n", obj->path);
4031 int bpf_object__load(struct bpf_object *obj)
4033 struct bpf_object_load_attr attr = {
4037 return bpf_object__load_xattr(&attr);
4040 static int make_parent_dir(const char *path)
4042 char *cp, errmsg[STRERR_BUFSIZE];
4046 dname = strdup(path);
4050 dir = dirname(dname);
4051 if (mkdir(dir, 0700) && errno != EEXIST)
4056 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
4057 pr_warn("failed to mkdir %s: %s\n", path, cp);
4062 static int check_path(const char *path)
4064 char *cp, errmsg[STRERR_BUFSIZE];
4065 struct statfs st_fs;
4072 dname = strdup(path);
4076 dir = dirname(dname);
4077 if (statfs(dir, &st_fs)) {
4078 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
4079 pr_warn("failed to statfs %s: %s\n", dir, cp);
4084 if (!err && st_fs.f_type != BPF_FS_MAGIC) {
4085 pr_warn("specified path %s is not on BPF FS\n", path);
4092 int bpf_program__pin_instance(struct bpf_program *prog, const char *path,
4095 char *cp, errmsg[STRERR_BUFSIZE];
4098 err = make_parent_dir(path);
4102 err = check_path(path);
4107 pr_warn("invalid program pointer\n");
4111 if (instance < 0 || instance >= prog->instances.nr) {
4112 pr_warn("invalid prog instance %d of prog %s (max %d)\n",
4113 instance, prog->section_name, prog->instances.nr);
4117 if (bpf_obj_pin(prog->instances.fds[instance], path)) {
4118 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
4119 pr_warn("failed to pin program: %s\n", cp);
4122 pr_debug("pinned program '%s'\n", path);
4127 int bpf_program__unpin_instance(struct bpf_program *prog, const char *path,
4132 err = check_path(path);
4137 pr_warn("invalid program pointer\n");
4141 if (instance < 0 || instance >= prog->instances.nr) {
4142 pr_warn("invalid prog instance %d of prog %s (max %d)\n",
4143 instance, prog->section_name, prog->instances.nr);
4150 pr_debug("unpinned program '%s'\n", path);
4155 int bpf_program__pin(struct bpf_program *prog, const char *path)
4159 err = make_parent_dir(path);
4163 err = check_path(path);
4168 pr_warn("invalid program pointer\n");
4172 if (prog->instances.nr <= 0) {
4173 pr_warn("no instances of prog %s to pin\n",
4174 prog->section_name);
4178 if (prog->instances.nr == 1) {
4179 /* don't create subdirs when pinning single instance */
4180 return bpf_program__pin_instance(prog, path, 0);
4183 for (i = 0; i < prog->instances.nr; i++) {
4187 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
4191 } else if (len >= PATH_MAX) {
4192 err = -ENAMETOOLONG;
4196 err = bpf_program__pin_instance(prog, buf, i);
4204 for (i = i - 1; i >= 0; i--) {
4208 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
4211 else if (len >= PATH_MAX)
4214 bpf_program__unpin_instance(prog, buf, i);
4222 int bpf_program__unpin(struct bpf_program *prog, const char *path)
4226 err = check_path(path);
4231 pr_warn("invalid program pointer\n");
4235 if (prog->instances.nr <= 0) {
4236 pr_warn("no instances of prog %s to pin\n",
4237 prog->section_name);
4241 if (prog->instances.nr == 1) {
4242 /* don't create subdirs when pinning single instance */
4243 return bpf_program__unpin_instance(prog, path, 0);
4246 for (i = 0; i < prog->instances.nr; i++) {
4250 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
4253 else if (len >= PATH_MAX)
4254 return -ENAMETOOLONG;
4256 err = bpf_program__unpin_instance(prog, buf, i);
4268 int bpf_map__pin(struct bpf_map *map, const char *path)
4270 char *cp, errmsg[STRERR_BUFSIZE];
4274 pr_warn("invalid map pointer\n");
4278 if (map->pin_path) {
4279 if (path && strcmp(path, map->pin_path)) {
4280 pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
4281 bpf_map__name(map), map->pin_path, path);
4283 } else if (map->pinned) {
4284 pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
4285 bpf_map__name(map), map->pin_path);
4290 pr_warn("missing a path to pin map '%s' at\n",
4291 bpf_map__name(map));
4293 } else if (map->pinned) {
4294 pr_warn("map '%s' already pinned\n", bpf_map__name(map));
4298 map->pin_path = strdup(path);
4299 if (!map->pin_path) {
4305 err = make_parent_dir(map->pin_path);
4309 err = check_path(map->pin_path);
4313 if (bpf_obj_pin(map->fd, map->pin_path)) {
4319 pr_debug("pinned map '%s'\n", map->pin_path);
4324 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
4325 pr_warn("failed to pin map: %s\n", cp);
4329 int bpf_map__unpin(struct bpf_map *map, const char *path)
4334 pr_warn("invalid map pointer\n");
4338 if (map->pin_path) {
4339 if (path && strcmp(path, map->pin_path)) {
4340 pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
4341 bpf_map__name(map), map->pin_path, path);
4344 path = map->pin_path;
4346 pr_warn("no path to unpin map '%s' from\n",
4347 bpf_map__name(map));
4351 err = check_path(path);
4359 map->pinned = false;
4360 pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
4365 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
4375 free(map->pin_path);
4376 map->pin_path = new;
4380 const char *bpf_map__get_pin_path(const struct bpf_map *map)
4382 return map->pin_path;
4385 bool bpf_map__is_pinned(const struct bpf_map *map)
4390 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
4392 struct bpf_map *map;
4399 pr_warn("object not yet loaded; load it first\n");
4403 bpf_object__for_each_map(map, obj) {
4404 char *pin_path = NULL;
4410 len = snprintf(buf, PATH_MAX, "%s/%s", path,
4411 bpf_map__name(map));
4414 goto err_unpin_maps;
4415 } else if (len >= PATH_MAX) {
4416 err = -ENAMETOOLONG;
4417 goto err_unpin_maps;
4420 } else if (!map->pin_path) {
4424 err = bpf_map__pin(map, pin_path);
4426 goto err_unpin_maps;
4432 while ((map = bpf_map__prev(map, obj))) {
4436 bpf_map__unpin(map, NULL);
4442 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
4444 struct bpf_map *map;
4450 bpf_object__for_each_map(map, obj) {
4451 char *pin_path = NULL;
4457 len = snprintf(buf, PATH_MAX, "%s/%s", path,
4458 bpf_map__name(map));
4461 else if (len >= PATH_MAX)
4462 return -ENAMETOOLONG;
4464 } else if (!map->pin_path) {
4468 err = bpf_map__unpin(map, pin_path);
4476 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
4478 struct bpf_program *prog;
4485 pr_warn("object not yet loaded; load it first\n");
4489 bpf_object__for_each_program(prog, obj) {
4493 len = snprintf(buf, PATH_MAX, "%s/%s", path,
4497 goto err_unpin_programs;
4498 } else if (len >= PATH_MAX) {
4499 err = -ENAMETOOLONG;
4500 goto err_unpin_programs;
4503 err = bpf_program__pin(prog, buf);
4505 goto err_unpin_programs;
4511 while ((prog = bpf_program__prev(prog, obj))) {
4515 len = snprintf(buf, PATH_MAX, "%s/%s", path,
4519 else if (len >= PATH_MAX)
4522 bpf_program__unpin(prog, buf);
4528 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
4530 struct bpf_program *prog;
4536 bpf_object__for_each_program(prog, obj) {
4540 len = snprintf(buf, PATH_MAX, "%s/%s", path,
4544 else if (len >= PATH_MAX)
4545 return -ENAMETOOLONG;
4547 err = bpf_program__unpin(prog, buf);
4555 int bpf_object__pin(struct bpf_object *obj, const char *path)
4559 err = bpf_object__pin_maps(obj, path);
4563 err = bpf_object__pin_programs(obj, path);
4565 bpf_object__unpin_maps(obj, path);
4572 void bpf_object__close(struct bpf_object *obj)
4579 if (obj->clear_priv)
4580 obj->clear_priv(obj, obj->priv);
4582 bpf_object__elf_finish(obj);
4583 bpf_object__unload(obj);
4584 btf__free(obj->btf);
4585 btf_ext__free(obj->btf_ext);
4587 for (i = 0; i < obj->nr_maps; i++) {
4588 zfree(&obj->maps[i].name);
4589 zfree(&obj->maps[i].pin_path);
4590 if (obj->maps[i].clear_priv)
4591 obj->maps[i].clear_priv(&obj->maps[i],
4593 obj->maps[i].priv = NULL;
4594 obj->maps[i].clear_priv = NULL;
4597 zfree(&obj->sections.rodata);
4598 zfree(&obj->sections.data);
4602 if (obj->programs && obj->nr_programs) {
4603 for (i = 0; i < obj->nr_programs; i++)
4604 bpf_program__exit(&obj->programs[i]);
4606 zfree(&obj->programs);
4608 list_del(&obj->list);
4613 bpf_object__next(struct bpf_object *prev)
4615 struct bpf_object *next;
4618 next = list_first_entry(&bpf_objects_list,
4622 next = list_next_entry(prev, list);
4624 /* Empty list is noticed here so don't need checking on entry. */
4625 if (&next->list == &bpf_objects_list)
4631 const char *bpf_object__name(const struct bpf_object *obj)
4633 return obj ? obj->name : ERR_PTR(-EINVAL);
4636 unsigned int bpf_object__kversion(const struct bpf_object *obj)
4638 return obj ? obj->kern_version : 0;
4641 struct btf *bpf_object__btf(const struct bpf_object *obj)
4643 return obj ? obj->btf : NULL;
4646 int bpf_object__btf_fd(const struct bpf_object *obj)
4648 return obj->btf ? btf__fd(obj->btf) : -1;
4651 int bpf_object__set_priv(struct bpf_object *obj, void *priv,
4652 bpf_object_clear_priv_t clear_priv)
4654 if (obj->priv && obj->clear_priv)
4655 obj->clear_priv(obj, obj->priv);
4658 obj->clear_priv = clear_priv;
4662 void *bpf_object__priv(const struct bpf_object *obj)
4664 return obj ? obj->priv : ERR_PTR(-EINVAL);
4667 static struct bpf_program *
4668 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
4671 size_t nr_programs = obj->nr_programs;
4678 /* Iter from the beginning */
4679 return forward ? &obj->programs[0] :
4680 &obj->programs[nr_programs - 1];
4682 if (p->obj != obj) {
4683 pr_warn("error: program handler doesn't match object\n");
4687 idx = (p - obj->programs) + (forward ? 1 : -1);
4688 if (idx >= obj->nr_programs || idx < 0)
4690 return &obj->programs[idx];
4693 struct bpf_program *
4694 bpf_program__next(struct bpf_program *prev, const struct bpf_object *obj)
4696 struct bpf_program *prog = prev;
4699 prog = __bpf_program__iter(prog, obj, true);
4700 } while (prog && bpf_program__is_function_storage(prog, obj));
4705 struct bpf_program *
4706 bpf_program__prev(struct bpf_program *next, const struct bpf_object *obj)
4708 struct bpf_program *prog = next;
4711 prog = __bpf_program__iter(prog, obj, false);
4712 } while (prog && bpf_program__is_function_storage(prog, obj));
4717 int bpf_program__set_priv(struct bpf_program *prog, void *priv,
4718 bpf_program_clear_priv_t clear_priv)
4720 if (prog->priv && prog->clear_priv)
4721 prog->clear_priv(prog, prog->priv);
4724 prog->clear_priv = clear_priv;
4728 void *bpf_program__priv(const struct bpf_program *prog)
4730 return prog ? prog->priv : ERR_PTR(-EINVAL);
4733 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
4735 prog->prog_ifindex = ifindex;
4738 const char *bpf_program__title(const struct bpf_program *prog, bool needs_copy)
4742 title = prog->section_name;
4744 title = strdup(title);
4746 pr_warn("failed to strdup program title\n");
4747 return ERR_PTR(-ENOMEM);
4754 int bpf_program__fd(const struct bpf_program *prog)
4756 return bpf_program__nth_fd(prog, 0);
4759 int bpf_program__set_prep(struct bpf_program *prog, int nr_instances,
4760 bpf_program_prep_t prep)
4764 if (nr_instances <= 0 || !prep)
4767 if (prog->instances.nr > 0 || prog->instances.fds) {
4768 pr_warn("Can't set pre-processor after loading\n");
4772 instances_fds = malloc(sizeof(int) * nr_instances);
4773 if (!instances_fds) {
4774 pr_warn("alloc memory failed for fds\n");
4778 /* fill all fd with -1 */
4779 memset(instances_fds, -1, sizeof(int) * nr_instances);
4781 prog->instances.nr = nr_instances;
4782 prog->instances.fds = instances_fds;
4783 prog->preprocessor = prep;
4787 int bpf_program__nth_fd(const struct bpf_program *prog, int n)
4794 if (n >= prog->instances.nr || n < 0) {
4795 pr_warn("Can't get the %dth fd from program %s: only %d instances\n",
4796 n, prog->section_name, prog->instances.nr);
4800 fd = prog->instances.fds[n];
4802 pr_warn("%dth instance of program '%s' is invalid\n",
4803 n, prog->section_name);
4810 enum bpf_prog_type bpf_program__get_type(struct bpf_program *prog)
4815 void bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
4820 static bool bpf_program__is_type(const struct bpf_program *prog,
4821 enum bpf_prog_type type)
4823 return prog ? (prog->type == type) : false;
4826 #define BPF_PROG_TYPE_FNS(NAME, TYPE) \
4827 int bpf_program__set_##NAME(struct bpf_program *prog) \
4831 bpf_program__set_type(prog, TYPE); \
4835 bool bpf_program__is_##NAME(const struct bpf_program *prog) \
4837 return bpf_program__is_type(prog, TYPE); \
4840 BPF_PROG_TYPE_FNS(socket_filter, BPF_PROG_TYPE_SOCKET_FILTER);
4841 BPF_PROG_TYPE_FNS(kprobe, BPF_PROG_TYPE_KPROBE);
4842 BPF_PROG_TYPE_FNS(sched_cls, BPF_PROG_TYPE_SCHED_CLS);
4843 BPF_PROG_TYPE_FNS(sched_act, BPF_PROG_TYPE_SCHED_ACT);
4844 BPF_PROG_TYPE_FNS(tracepoint, BPF_PROG_TYPE_TRACEPOINT);
4845 BPF_PROG_TYPE_FNS(raw_tracepoint, BPF_PROG_TYPE_RAW_TRACEPOINT);
4846 BPF_PROG_TYPE_FNS(xdp, BPF_PROG_TYPE_XDP);
4847 BPF_PROG_TYPE_FNS(perf_event, BPF_PROG_TYPE_PERF_EVENT);
4848 BPF_PROG_TYPE_FNS(tracing, BPF_PROG_TYPE_TRACING);
4850 enum bpf_attach_type
4851 bpf_program__get_expected_attach_type(struct bpf_program *prog)
4853 return prog->expected_attach_type;
4856 void bpf_program__set_expected_attach_type(struct bpf_program *prog,
4857 enum bpf_attach_type type)
4859 prog->expected_attach_type = type;
4862 #define BPF_PROG_SEC_IMPL(string, ptype, eatype, is_attachable, btf, atype) \
4863 { string, sizeof(string) - 1, ptype, eatype, is_attachable, btf, atype }
4865 /* Programs that can NOT be attached. */
4866 #define BPF_PROG_SEC(string, ptype) BPF_PROG_SEC_IMPL(string, ptype, 0, 0, 0, 0)
4868 /* Programs that can be attached. */
4869 #define BPF_APROG_SEC(string, ptype, atype) \
4870 BPF_PROG_SEC_IMPL(string, ptype, 0, 1, 0, atype)
4872 /* Programs that must specify expected attach type at load time. */
4873 #define BPF_EAPROG_SEC(string, ptype, eatype) \
4874 BPF_PROG_SEC_IMPL(string, ptype, eatype, 1, 0, eatype)
4876 /* Programs that use BTF to identify attach point */
4877 #define BPF_PROG_BTF(string, ptype, eatype) \
4878 BPF_PROG_SEC_IMPL(string, ptype, eatype, 0, 1, 0)
4880 /* Programs that can be attached but attach type can't be identified by section
4881 * name. Kept for backward compatibility.
4883 #define BPF_APROG_COMPAT(string, ptype) BPF_PROG_SEC(string, ptype)
4885 static const struct {
4888 enum bpf_prog_type prog_type;
4889 enum bpf_attach_type expected_attach_type;
4892 enum bpf_attach_type attach_type;
4893 } section_names[] = {
4894 BPF_PROG_SEC("socket", BPF_PROG_TYPE_SOCKET_FILTER),
4895 BPF_PROG_SEC("kprobe/", BPF_PROG_TYPE_KPROBE),
4896 BPF_PROG_SEC("uprobe/", BPF_PROG_TYPE_KPROBE),
4897 BPF_PROG_SEC("kretprobe/", BPF_PROG_TYPE_KPROBE),
4898 BPF_PROG_SEC("uretprobe/", BPF_PROG_TYPE_KPROBE),
4899 BPF_PROG_SEC("classifier", BPF_PROG_TYPE_SCHED_CLS),
4900 BPF_PROG_SEC("action", BPF_PROG_TYPE_SCHED_ACT),
4901 BPF_PROG_SEC("tracepoint/", BPF_PROG_TYPE_TRACEPOINT),
4902 BPF_PROG_SEC("tp/", BPF_PROG_TYPE_TRACEPOINT),
4903 BPF_PROG_SEC("raw_tracepoint/", BPF_PROG_TYPE_RAW_TRACEPOINT),
4904 BPF_PROG_SEC("raw_tp/", BPF_PROG_TYPE_RAW_TRACEPOINT),
4905 BPF_PROG_BTF("tp_btf/", BPF_PROG_TYPE_TRACING,
4907 BPF_PROG_SEC("xdp", BPF_PROG_TYPE_XDP),
4908 BPF_PROG_SEC("perf_event", BPF_PROG_TYPE_PERF_EVENT),
4909 BPF_PROG_SEC("lwt_in", BPF_PROG_TYPE_LWT_IN),
4910 BPF_PROG_SEC("lwt_out", BPF_PROG_TYPE_LWT_OUT),
4911 BPF_PROG_SEC("lwt_xmit", BPF_PROG_TYPE_LWT_XMIT),
4912 BPF_PROG_SEC("lwt_seg6local", BPF_PROG_TYPE_LWT_SEG6LOCAL),
4913 BPF_APROG_SEC("cgroup_skb/ingress", BPF_PROG_TYPE_CGROUP_SKB,
4914 BPF_CGROUP_INET_INGRESS),
4915 BPF_APROG_SEC("cgroup_skb/egress", BPF_PROG_TYPE_CGROUP_SKB,
4916 BPF_CGROUP_INET_EGRESS),
4917 BPF_APROG_COMPAT("cgroup/skb", BPF_PROG_TYPE_CGROUP_SKB),
4918 BPF_APROG_SEC("cgroup/sock", BPF_PROG_TYPE_CGROUP_SOCK,
4919 BPF_CGROUP_INET_SOCK_CREATE),
4920 BPF_EAPROG_SEC("cgroup/post_bind4", BPF_PROG_TYPE_CGROUP_SOCK,
4921 BPF_CGROUP_INET4_POST_BIND),
4922 BPF_EAPROG_SEC("cgroup/post_bind6", BPF_PROG_TYPE_CGROUP_SOCK,
4923 BPF_CGROUP_INET6_POST_BIND),
4924 BPF_APROG_SEC("cgroup/dev", BPF_PROG_TYPE_CGROUP_DEVICE,
4926 BPF_APROG_SEC("sockops", BPF_PROG_TYPE_SOCK_OPS,
4927 BPF_CGROUP_SOCK_OPS),
4928 BPF_APROG_SEC("sk_skb/stream_parser", BPF_PROG_TYPE_SK_SKB,
4929 BPF_SK_SKB_STREAM_PARSER),
4930 BPF_APROG_SEC("sk_skb/stream_verdict", BPF_PROG_TYPE_SK_SKB,
4931 BPF_SK_SKB_STREAM_VERDICT),
4932 BPF_APROG_COMPAT("sk_skb", BPF_PROG_TYPE_SK_SKB),
4933 BPF_APROG_SEC("sk_msg", BPF_PROG_TYPE_SK_MSG,
4934 BPF_SK_MSG_VERDICT),
4935 BPF_APROG_SEC("lirc_mode2", BPF_PROG_TYPE_LIRC_MODE2,
4937 BPF_APROG_SEC("flow_dissector", BPF_PROG_TYPE_FLOW_DISSECTOR,
4938 BPF_FLOW_DISSECTOR),
4939 BPF_EAPROG_SEC("cgroup/bind4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
4940 BPF_CGROUP_INET4_BIND),
4941 BPF_EAPROG_SEC("cgroup/bind6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
4942 BPF_CGROUP_INET6_BIND),
4943 BPF_EAPROG_SEC("cgroup/connect4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
4944 BPF_CGROUP_INET4_CONNECT),
4945 BPF_EAPROG_SEC("cgroup/connect6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
4946 BPF_CGROUP_INET6_CONNECT),
4947 BPF_EAPROG_SEC("cgroup/sendmsg4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
4948 BPF_CGROUP_UDP4_SENDMSG),
4949 BPF_EAPROG_SEC("cgroup/sendmsg6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
4950 BPF_CGROUP_UDP6_SENDMSG),
4951 BPF_EAPROG_SEC("cgroup/recvmsg4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
4952 BPF_CGROUP_UDP4_RECVMSG),
4953 BPF_EAPROG_SEC("cgroup/recvmsg6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
4954 BPF_CGROUP_UDP6_RECVMSG),
4955 BPF_EAPROG_SEC("cgroup/sysctl", BPF_PROG_TYPE_CGROUP_SYSCTL,
4957 BPF_EAPROG_SEC("cgroup/getsockopt", BPF_PROG_TYPE_CGROUP_SOCKOPT,
4958 BPF_CGROUP_GETSOCKOPT),
4959 BPF_EAPROG_SEC("cgroup/setsockopt", BPF_PROG_TYPE_CGROUP_SOCKOPT,
4960 BPF_CGROUP_SETSOCKOPT),
4963 #undef BPF_PROG_SEC_IMPL
4965 #undef BPF_APROG_SEC
4966 #undef BPF_EAPROG_SEC
4967 #undef BPF_APROG_COMPAT
4969 #define MAX_TYPE_NAME_SIZE 32
4971 static char *libbpf_get_type_names(bool attach_type)
4973 int i, len = ARRAY_SIZE(section_names) * MAX_TYPE_NAME_SIZE;
4981 /* Forge string buf with all available names */
4982 for (i = 0; i < ARRAY_SIZE(section_names); i++) {
4983 if (attach_type && !section_names[i].is_attachable)
4986 if (strlen(buf) + strlen(section_names[i].sec) + 2 > len) {
4991 strcat(buf, section_names[i].sec);
4997 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
4998 enum bpf_attach_type *expected_attach_type)
5006 for (i = 0; i < ARRAY_SIZE(section_names); i++) {
5007 if (strncmp(name, section_names[i].sec, section_names[i].len))
5009 *prog_type = section_names[i].prog_type;
5010 *expected_attach_type = section_names[i].expected_attach_type;
5013 pr_warn("failed to guess program type based on ELF section name '%s'\n", name);
5014 type_names = libbpf_get_type_names(false);
5015 if (type_names != NULL) {
5016 pr_info("supported section(type) names are:%s\n", type_names);
5023 #define BTF_PREFIX "btf_trace_"
5024 static int libbpf_attach_btf_id_by_name(const char *name, __u32 *btf_id)
5026 struct btf *btf = bpf_core_find_kernel_btf();
5027 char raw_tp_btf_name[128] = BTF_PREFIX;
5028 char *dst = raw_tp_btf_name + sizeof(BTF_PREFIX) - 1;
5029 int ret, i, err = -EINVAL;
5032 pr_warn("vmlinux BTF is not found\n");
5039 for (i = 0; i < ARRAY_SIZE(section_names); i++) {
5040 if (!section_names[i].is_attach_btf)
5042 if (strncmp(name, section_names[i].sec, section_names[i].len))
5044 /* prepend "btf_trace_" prefix per kernel convention */
5045 strncat(dst, name + section_names[i].len,
5046 sizeof(raw_tp_btf_name) - sizeof(BTF_PREFIX));
5047 ret = btf__find_by_name(btf, raw_tp_btf_name);
5049 pr_warn("%s is not found in vmlinux BTF\n", dst);
5056 pr_warn("failed to identify btf_id based on ELF section name '%s'\n", name);
5063 int libbpf_attach_type_by_name(const char *name,
5064 enum bpf_attach_type *attach_type)
5072 for (i = 0; i < ARRAY_SIZE(section_names); i++) {
5073 if (strncmp(name, section_names[i].sec, section_names[i].len))
5075 if (!section_names[i].is_attachable)
5077 *attach_type = section_names[i].attach_type;
5080 pr_warn("failed to guess attach type based on ELF section name '%s'\n", name);
5081 type_names = libbpf_get_type_names(true);
5082 if (type_names != NULL) {
5083 pr_info("attachable section(type) names are:%s\n", type_names);
5090 int bpf_map__fd(const struct bpf_map *map)
5092 return map ? map->fd : -EINVAL;
5095 const struct bpf_map_def *bpf_map__def(const struct bpf_map *map)
5097 return map ? &map->def : ERR_PTR(-EINVAL);
5100 const char *bpf_map__name(const struct bpf_map *map)
5102 return map ? map->name : NULL;
5105 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
5107 return map ? map->btf_key_type_id : 0;
5110 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
5112 return map ? map->btf_value_type_id : 0;
5115 int bpf_map__set_priv(struct bpf_map *map, void *priv,
5116 bpf_map_clear_priv_t clear_priv)
5122 if (map->clear_priv)
5123 map->clear_priv(map, map->priv);
5127 map->clear_priv = clear_priv;
5131 void *bpf_map__priv(const struct bpf_map *map)
5133 return map ? map->priv : ERR_PTR(-EINVAL);
5136 bool bpf_map__is_offload_neutral(const struct bpf_map *map)
5138 return map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY;
5141 bool bpf_map__is_internal(const struct bpf_map *map)
5143 return map->libbpf_type != LIBBPF_MAP_UNSPEC;
5146 void bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
5148 map->map_ifindex = ifindex;
5151 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
5153 if (!bpf_map_type__is_map_in_map(map->def.type)) {
5154 pr_warn("error: unsupported map type\n");
5157 if (map->inner_map_fd != -1) {
5158 pr_warn("error: inner_map_fd already specified\n");
5161 map->inner_map_fd = fd;
5165 static struct bpf_map *
5166 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
5169 struct bpf_map *s, *e;
5171 if (!obj || !obj->maps)
5175 e = obj->maps + obj->nr_maps;
5177 if ((m < s) || (m >= e)) {
5178 pr_warn("error in %s: map handler doesn't belong to object\n",
5183 idx = (m - obj->maps) + i;
5184 if (idx >= obj->nr_maps || idx < 0)
5186 return &obj->maps[idx];
5190 bpf_map__next(const struct bpf_map *prev, const struct bpf_object *obj)
5195 return __bpf_map__iter(prev, obj, 1);
5199 bpf_map__prev(const struct bpf_map *next, const struct bpf_object *obj)
5204 return obj->maps + obj->nr_maps - 1;
5207 return __bpf_map__iter(next, obj, -1);
5211 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
5213 struct bpf_map *pos;
5215 bpf_object__for_each_map(pos, obj) {
5216 if (pos->name && !strcmp(pos->name, name))
5223 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
5225 return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
5229 bpf_object__find_map_by_offset(struct bpf_object *obj, size_t offset)
5231 return ERR_PTR(-ENOTSUP);
5234 long libbpf_get_error(const void *ptr)
5236 return PTR_ERR_OR_ZERO(ptr);
5239 int bpf_prog_load(const char *file, enum bpf_prog_type type,
5240 struct bpf_object **pobj, int *prog_fd)
5242 struct bpf_prog_load_attr attr;
5244 memset(&attr, 0, sizeof(struct bpf_prog_load_attr));
5246 attr.prog_type = type;
5247 attr.expected_attach_type = 0;
5249 return bpf_prog_load_xattr(&attr, pobj, prog_fd);
5252 int bpf_prog_load_xattr(const struct bpf_prog_load_attr *attr,
5253 struct bpf_object **pobj, int *prog_fd)
5255 struct bpf_object_open_attr open_attr = {};
5256 struct bpf_program *prog, *first_prog = NULL;
5257 struct bpf_object *obj;
5258 struct bpf_map *map;
5266 open_attr.file = attr->file;
5267 open_attr.prog_type = attr->prog_type;
5269 obj = bpf_object__open_xattr(&open_attr);
5270 if (IS_ERR_OR_NULL(obj))
5273 bpf_object__for_each_program(prog, obj) {
5274 enum bpf_attach_type attach_type = attr->expected_attach_type;
5276 * to preserve backwards compatibility, bpf_prog_load treats
5277 * attr->prog_type, if specified, as an override to whatever
5278 * bpf_object__open guessed
5280 if (attr->prog_type != BPF_PROG_TYPE_UNSPEC) {
5281 bpf_program__set_type(prog, attr->prog_type);
5282 bpf_program__set_expected_attach_type(prog,
5285 if (bpf_program__get_type(prog) == BPF_PROG_TYPE_UNSPEC) {
5287 * we haven't guessed from section name and user
5288 * didn't provide a fallback type, too bad...
5290 bpf_object__close(obj);
5294 prog->prog_ifindex = attr->ifindex;
5295 prog->log_level = attr->log_level;
5296 prog->prog_flags = attr->prog_flags;
5301 bpf_object__for_each_map(map, obj) {
5302 if (!bpf_map__is_offload_neutral(map))
5303 map->map_ifindex = attr->ifindex;
5307 pr_warn("object file doesn't contain bpf program\n");
5308 bpf_object__close(obj);
5312 err = bpf_object__load(obj);
5314 bpf_object__close(obj);
5319 *prog_fd = bpf_program__fd(first_prog);
5324 int (*destroy)(struct bpf_link *link);
5327 int bpf_link__destroy(struct bpf_link *link)
5334 err = link->destroy(link);
5340 struct bpf_link_fd {
5341 struct bpf_link link; /* has to be at the top of struct */
5342 int fd; /* hook FD */
5345 static int bpf_link__destroy_perf_event(struct bpf_link *link)
5347 struct bpf_link_fd *l = (void *)link;
5350 err = ioctl(l->fd, PERF_EVENT_IOC_DISABLE, 0);
5358 struct bpf_link *bpf_program__attach_perf_event(struct bpf_program *prog,
5361 char errmsg[STRERR_BUFSIZE];
5362 struct bpf_link_fd *link;
5366 pr_warn("program '%s': invalid perf event FD %d\n",
5367 bpf_program__title(prog, false), pfd);
5368 return ERR_PTR(-EINVAL);
5370 prog_fd = bpf_program__fd(prog);
5372 pr_warn("program '%s': can't attach BPF program w/o FD (did you load it?)\n",
5373 bpf_program__title(prog, false));
5374 return ERR_PTR(-EINVAL);
5377 link = malloc(sizeof(*link));
5379 return ERR_PTR(-ENOMEM);
5380 link->link.destroy = &bpf_link__destroy_perf_event;
5383 if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
5386 pr_warn("program '%s': failed to attach to pfd %d: %s\n",
5387 bpf_program__title(prog, false), pfd,
5388 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
5389 return ERR_PTR(err);
5391 if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
5394 pr_warn("program '%s': failed to enable pfd %d: %s\n",
5395 bpf_program__title(prog, false), pfd,
5396 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
5397 return ERR_PTR(err);
5399 return (struct bpf_link *)link;
5403 * this function is expected to parse integer in the range of [0, 2^31-1] from
5404 * given file using scanf format string fmt. If actual parsed value is
5405 * negative, the result might be indistinguishable from error
5407 static int parse_uint_from_file(const char *file, const char *fmt)
5409 char buf[STRERR_BUFSIZE];
5413 f = fopen(file, "r");
5416 pr_debug("failed to open '%s': %s\n", file,
5417 libbpf_strerror_r(err, buf, sizeof(buf)));
5420 err = fscanf(f, fmt, &ret);
5422 err = err == EOF ? -EIO : -errno;
5423 pr_debug("failed to parse '%s': %s\n", file,
5424 libbpf_strerror_r(err, buf, sizeof(buf)));
5432 static int determine_kprobe_perf_type(void)
5434 const char *file = "/sys/bus/event_source/devices/kprobe/type";
5436 return parse_uint_from_file(file, "%d\n");
5439 static int determine_uprobe_perf_type(void)
5441 const char *file = "/sys/bus/event_source/devices/uprobe/type";
5443 return parse_uint_from_file(file, "%d\n");
5446 static int determine_kprobe_retprobe_bit(void)
5448 const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
5450 return parse_uint_from_file(file, "config:%d\n");
5453 static int determine_uprobe_retprobe_bit(void)
5455 const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
5457 return parse_uint_from_file(file, "config:%d\n");
5460 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
5461 uint64_t offset, int pid)
5463 struct perf_event_attr attr = {};
5464 char errmsg[STRERR_BUFSIZE];
5467 type = uprobe ? determine_uprobe_perf_type()
5468 : determine_kprobe_perf_type();
5470 pr_warn("failed to determine %s perf type: %s\n",
5471 uprobe ? "uprobe" : "kprobe",
5472 libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
5476 int bit = uprobe ? determine_uprobe_retprobe_bit()
5477 : determine_kprobe_retprobe_bit();
5480 pr_warn("failed to determine %s retprobe bit: %s\n",
5481 uprobe ? "uprobe" : "kprobe",
5482 libbpf_strerror_r(bit, errmsg, sizeof(errmsg)));
5485 attr.config |= 1 << bit;
5487 attr.size = sizeof(attr);
5489 attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
5490 attr.config2 = offset; /* kprobe_addr or probe_offset */
5492 /* pid filter is meaningful only for uprobes */
5493 pfd = syscall(__NR_perf_event_open, &attr,
5494 pid < 0 ? -1 : pid /* pid */,
5495 pid == -1 ? 0 : -1 /* cpu */,
5496 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
5499 pr_warn("%s perf_event_open() failed: %s\n",
5500 uprobe ? "uprobe" : "kprobe",
5501 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
5507 struct bpf_link *bpf_program__attach_kprobe(struct bpf_program *prog,
5509 const char *func_name)
5511 char errmsg[STRERR_BUFSIZE];
5512 struct bpf_link *link;
5515 pfd = perf_event_open_probe(false /* uprobe */, retprobe, func_name,
5516 0 /* offset */, -1 /* pid */);
5518 pr_warn("program '%s': failed to create %s '%s' perf event: %s\n",
5519 bpf_program__title(prog, false),
5520 retprobe ? "kretprobe" : "kprobe", func_name,
5521 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
5522 return ERR_PTR(pfd);
5524 link = bpf_program__attach_perf_event(prog, pfd);
5527 err = PTR_ERR(link);
5528 pr_warn("program '%s': failed to attach to %s '%s': %s\n",
5529 bpf_program__title(prog, false),
5530 retprobe ? "kretprobe" : "kprobe", func_name,
5531 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
5537 struct bpf_link *bpf_program__attach_uprobe(struct bpf_program *prog,
5538 bool retprobe, pid_t pid,
5539 const char *binary_path,
5542 char errmsg[STRERR_BUFSIZE];
5543 struct bpf_link *link;
5546 pfd = perf_event_open_probe(true /* uprobe */, retprobe,
5547 binary_path, func_offset, pid);
5549 pr_warn("program '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
5550 bpf_program__title(prog, false),
5551 retprobe ? "uretprobe" : "uprobe",
5552 binary_path, func_offset,
5553 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
5554 return ERR_PTR(pfd);
5556 link = bpf_program__attach_perf_event(prog, pfd);
5559 err = PTR_ERR(link);
5560 pr_warn("program '%s': failed to attach to %s '%s:0x%zx': %s\n",
5561 bpf_program__title(prog, false),
5562 retprobe ? "uretprobe" : "uprobe",
5563 binary_path, func_offset,
5564 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
5570 static int determine_tracepoint_id(const char *tp_category,
5571 const char *tp_name)
5573 char file[PATH_MAX];
5576 ret = snprintf(file, sizeof(file),
5577 "/sys/kernel/debug/tracing/events/%s/%s/id",
5578 tp_category, tp_name);
5581 if (ret >= sizeof(file)) {
5582 pr_debug("tracepoint %s/%s path is too long\n",
5583 tp_category, tp_name);
5586 return parse_uint_from_file(file, "%d\n");
5589 static int perf_event_open_tracepoint(const char *tp_category,
5590 const char *tp_name)
5592 struct perf_event_attr attr = {};
5593 char errmsg[STRERR_BUFSIZE];
5594 int tp_id, pfd, err;
5596 tp_id = determine_tracepoint_id(tp_category, tp_name);
5598 pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
5599 tp_category, tp_name,
5600 libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
5604 attr.type = PERF_TYPE_TRACEPOINT;
5605 attr.size = sizeof(attr);
5606 attr.config = tp_id;
5608 pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
5609 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
5612 pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
5613 tp_category, tp_name,
5614 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
5620 struct bpf_link *bpf_program__attach_tracepoint(struct bpf_program *prog,
5621 const char *tp_category,
5622 const char *tp_name)
5624 char errmsg[STRERR_BUFSIZE];
5625 struct bpf_link *link;
5628 pfd = perf_event_open_tracepoint(tp_category, tp_name);
5630 pr_warn("program '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
5631 bpf_program__title(prog, false),
5632 tp_category, tp_name,
5633 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
5634 return ERR_PTR(pfd);
5636 link = bpf_program__attach_perf_event(prog, pfd);
5639 err = PTR_ERR(link);
5640 pr_warn("program '%s': failed to attach to tracepoint '%s/%s': %s\n",
5641 bpf_program__title(prog, false),
5642 tp_category, tp_name,
5643 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
5649 static int bpf_link__destroy_fd(struct bpf_link *link)
5651 struct bpf_link_fd *l = (void *)link;
5653 return close(l->fd);
5656 struct bpf_link *bpf_program__attach_raw_tracepoint(struct bpf_program *prog,
5657 const char *tp_name)
5659 char errmsg[STRERR_BUFSIZE];
5660 struct bpf_link_fd *link;
5663 prog_fd = bpf_program__fd(prog);
5665 pr_warn("program '%s': can't attach before loaded\n",
5666 bpf_program__title(prog, false));
5667 return ERR_PTR(-EINVAL);
5670 link = malloc(sizeof(*link));
5672 return ERR_PTR(-ENOMEM);
5673 link->link.destroy = &bpf_link__destroy_fd;
5675 pfd = bpf_raw_tracepoint_open(tp_name, prog_fd);
5679 pr_warn("program '%s': failed to attach to raw tracepoint '%s': %s\n",
5680 bpf_program__title(prog, false), tp_name,
5681 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
5682 return ERR_PTR(pfd);
5685 return (struct bpf_link *)link;
5688 enum bpf_perf_event_ret
5689 bpf_perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
5690 void **copy_mem, size_t *copy_size,
5691 bpf_perf_event_print_t fn, void *private_data)
5693 struct perf_event_mmap_page *header = mmap_mem;
5694 __u64 data_head = ring_buffer_read_head(header);
5695 __u64 data_tail = header->data_tail;
5696 void *base = ((__u8 *)header) + page_size;
5697 int ret = LIBBPF_PERF_EVENT_CONT;
5698 struct perf_event_header *ehdr;
5701 while (data_head != data_tail) {
5702 ehdr = base + (data_tail & (mmap_size - 1));
5703 ehdr_size = ehdr->size;
5705 if (((void *)ehdr) + ehdr_size > base + mmap_size) {
5706 void *copy_start = ehdr;
5707 size_t len_first = base + mmap_size - copy_start;
5708 size_t len_secnd = ehdr_size - len_first;
5710 if (*copy_size < ehdr_size) {
5712 *copy_mem = malloc(ehdr_size);
5715 ret = LIBBPF_PERF_EVENT_ERROR;
5718 *copy_size = ehdr_size;
5721 memcpy(*copy_mem, copy_start, len_first);
5722 memcpy(*copy_mem + len_first, base, len_secnd);
5726 ret = fn(ehdr, private_data);
5727 data_tail += ehdr_size;
5728 if (ret != LIBBPF_PERF_EVENT_CONT)
5732 ring_buffer_write_tail(header, data_tail);
5738 struct perf_buffer_params {
5739 struct perf_event_attr *attr;
5740 /* if event_cb is specified, it takes precendence */
5741 perf_buffer_event_fn event_cb;
5742 /* sample_cb and lost_cb are higher-level common-case callbacks */
5743 perf_buffer_sample_fn sample_cb;
5744 perf_buffer_lost_fn lost_cb;
5751 struct perf_cpu_buf {
5752 struct perf_buffer *pb;
5753 void *base; /* mmap()'ed memory */
5754 void *buf; /* for reconstructing segmented data */
5761 struct perf_buffer {
5762 perf_buffer_event_fn event_cb;
5763 perf_buffer_sample_fn sample_cb;
5764 perf_buffer_lost_fn lost_cb;
5765 void *ctx; /* passed into callbacks */
5769 struct perf_cpu_buf **cpu_bufs;
5770 struct epoll_event *events;
5772 int epoll_fd; /* perf event FD */
5773 int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
5776 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
5777 struct perf_cpu_buf *cpu_buf)
5781 if (cpu_buf->base &&
5782 munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
5783 pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
5784 if (cpu_buf->fd >= 0) {
5785 ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
5792 void perf_buffer__free(struct perf_buffer *pb)
5799 for (i = 0; i < pb->cpu_cnt && pb->cpu_bufs[i]; i++) {
5800 struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
5802 bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
5803 perf_buffer__free_cpu_buf(pb, cpu_buf);
5807 if (pb->epoll_fd >= 0)
5808 close(pb->epoll_fd);
5813 static struct perf_cpu_buf *
5814 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
5815 int cpu, int map_key)
5817 struct perf_cpu_buf *cpu_buf;
5818 char msg[STRERR_BUFSIZE];
5821 cpu_buf = calloc(1, sizeof(*cpu_buf));
5823 return ERR_PTR(-ENOMEM);
5827 cpu_buf->map_key = map_key;
5829 cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
5830 -1, PERF_FLAG_FD_CLOEXEC);
5831 if (cpu_buf->fd < 0) {
5833 pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
5834 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
5838 cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
5839 PROT_READ | PROT_WRITE, MAP_SHARED,
5841 if (cpu_buf->base == MAP_FAILED) {
5842 cpu_buf->base = NULL;
5844 pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
5845 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
5849 if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
5851 pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
5852 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
5859 perf_buffer__free_cpu_buf(pb, cpu_buf);
5860 return (struct perf_cpu_buf *)ERR_PTR(err);
5863 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
5864 struct perf_buffer_params *p);
5866 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
5867 const struct perf_buffer_opts *opts)
5869 struct perf_buffer_params p = {};
5870 struct perf_event_attr attr = { 0, };
5872 attr.config = PERF_COUNT_SW_BPF_OUTPUT,
5873 attr.type = PERF_TYPE_SOFTWARE;
5874 attr.sample_type = PERF_SAMPLE_RAW;
5875 attr.sample_period = 1;
5876 attr.wakeup_events = 1;
5879 p.sample_cb = opts ? opts->sample_cb : NULL;
5880 p.lost_cb = opts ? opts->lost_cb : NULL;
5881 p.ctx = opts ? opts->ctx : NULL;
5883 return __perf_buffer__new(map_fd, page_cnt, &p);
5886 struct perf_buffer *
5887 perf_buffer__new_raw(int map_fd, size_t page_cnt,
5888 const struct perf_buffer_raw_opts *opts)
5890 struct perf_buffer_params p = {};
5892 p.attr = opts->attr;
5893 p.event_cb = opts->event_cb;
5895 p.cpu_cnt = opts->cpu_cnt;
5896 p.cpus = opts->cpus;
5897 p.map_keys = opts->map_keys;
5899 return __perf_buffer__new(map_fd, page_cnt, &p);
5902 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
5903 struct perf_buffer_params *p)
5905 struct bpf_map_info map = {};
5906 char msg[STRERR_BUFSIZE];
5907 struct perf_buffer *pb;
5911 if (page_cnt & (page_cnt - 1)) {
5912 pr_warn("page count should be power of two, but is %zu\n",
5914 return ERR_PTR(-EINVAL);
5917 map_info_len = sizeof(map);
5918 err = bpf_obj_get_info_by_fd(map_fd, &map, &map_info_len);
5921 pr_warn("failed to get map info for map FD %d: %s\n",
5922 map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
5923 return ERR_PTR(err);
5926 if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
5927 pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
5929 return ERR_PTR(-EINVAL);
5932 pb = calloc(1, sizeof(*pb));
5934 return ERR_PTR(-ENOMEM);
5936 pb->event_cb = p->event_cb;
5937 pb->sample_cb = p->sample_cb;
5938 pb->lost_cb = p->lost_cb;
5941 pb->page_size = getpagesize();
5942 pb->mmap_size = pb->page_size * page_cnt;
5943 pb->map_fd = map_fd;
5945 pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
5946 if (pb->epoll_fd < 0) {
5948 pr_warn("failed to create epoll instance: %s\n",
5949 libbpf_strerror_r(err, msg, sizeof(msg)));
5953 if (p->cpu_cnt > 0) {
5954 pb->cpu_cnt = p->cpu_cnt;
5956 pb->cpu_cnt = libbpf_num_possible_cpus();
5957 if (pb->cpu_cnt < 0) {
5961 if (map.max_entries < pb->cpu_cnt)
5962 pb->cpu_cnt = map.max_entries;
5965 pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
5968 pr_warn("failed to allocate events: out of memory\n");
5971 pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
5972 if (!pb->cpu_bufs) {
5974 pr_warn("failed to allocate buffers: out of memory\n");
5978 for (i = 0; i < pb->cpu_cnt; i++) {
5979 struct perf_cpu_buf *cpu_buf;
5982 cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
5983 map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
5985 cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
5986 if (IS_ERR(cpu_buf)) {
5987 err = PTR_ERR(cpu_buf);
5991 pb->cpu_bufs[i] = cpu_buf;
5993 err = bpf_map_update_elem(pb->map_fd, &map_key,
5997 pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
5998 cpu, map_key, cpu_buf->fd,
5999 libbpf_strerror_r(err, msg, sizeof(msg)));
6003 pb->events[i].events = EPOLLIN;
6004 pb->events[i].data.ptr = cpu_buf;
6005 if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
6006 &pb->events[i]) < 0) {
6008 pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
6010 libbpf_strerror_r(err, msg, sizeof(msg)));
6019 perf_buffer__free(pb);
6020 return ERR_PTR(err);
6023 struct perf_sample_raw {
6024 struct perf_event_header header;
6029 struct perf_sample_lost {
6030 struct perf_event_header header;
6036 static enum bpf_perf_event_ret
6037 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
6039 struct perf_cpu_buf *cpu_buf = ctx;
6040 struct perf_buffer *pb = cpu_buf->pb;
6043 /* user wants full control over parsing perf event */
6045 return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
6048 case PERF_RECORD_SAMPLE: {
6049 struct perf_sample_raw *s = data;
6052 pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
6055 case PERF_RECORD_LOST: {
6056 struct perf_sample_lost *s = data;
6059 pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
6063 pr_warn("unknown perf sample type %d\n", e->type);
6064 return LIBBPF_PERF_EVENT_ERROR;
6066 return LIBBPF_PERF_EVENT_CONT;
6069 static int perf_buffer__process_records(struct perf_buffer *pb,
6070 struct perf_cpu_buf *cpu_buf)
6072 enum bpf_perf_event_ret ret;
6074 ret = bpf_perf_event_read_simple(cpu_buf->base, pb->mmap_size,
6075 pb->page_size, &cpu_buf->buf,
6077 perf_buffer__process_record, cpu_buf);
6078 if (ret != LIBBPF_PERF_EVENT_CONT)
6083 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
6087 cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
6088 for (i = 0; i < cnt; i++) {
6089 struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
6091 err = perf_buffer__process_records(pb, cpu_buf);
6093 pr_warn("error while processing records: %d\n", err);
6097 return cnt < 0 ? -errno : cnt;
6100 struct bpf_prog_info_array_desc {
6101 int array_offset; /* e.g. offset of jited_prog_insns */
6102 int count_offset; /* e.g. offset of jited_prog_len */
6103 int size_offset; /* > 0: offset of rec size,
6104 * < 0: fix size of -size_offset
6108 static struct bpf_prog_info_array_desc bpf_prog_info_array_desc[] = {
6109 [BPF_PROG_INFO_JITED_INSNS] = {
6110 offsetof(struct bpf_prog_info, jited_prog_insns),
6111 offsetof(struct bpf_prog_info, jited_prog_len),
6114 [BPF_PROG_INFO_XLATED_INSNS] = {
6115 offsetof(struct bpf_prog_info, xlated_prog_insns),
6116 offsetof(struct bpf_prog_info, xlated_prog_len),
6119 [BPF_PROG_INFO_MAP_IDS] = {
6120 offsetof(struct bpf_prog_info, map_ids),
6121 offsetof(struct bpf_prog_info, nr_map_ids),
6122 -(int)sizeof(__u32),
6124 [BPF_PROG_INFO_JITED_KSYMS] = {
6125 offsetof(struct bpf_prog_info, jited_ksyms),
6126 offsetof(struct bpf_prog_info, nr_jited_ksyms),
6127 -(int)sizeof(__u64),
6129 [BPF_PROG_INFO_JITED_FUNC_LENS] = {
6130 offsetof(struct bpf_prog_info, jited_func_lens),
6131 offsetof(struct bpf_prog_info, nr_jited_func_lens),
6132 -(int)sizeof(__u32),
6134 [BPF_PROG_INFO_FUNC_INFO] = {
6135 offsetof(struct bpf_prog_info, func_info),
6136 offsetof(struct bpf_prog_info, nr_func_info),
6137 offsetof(struct bpf_prog_info, func_info_rec_size),
6139 [BPF_PROG_INFO_LINE_INFO] = {
6140 offsetof(struct bpf_prog_info, line_info),
6141 offsetof(struct bpf_prog_info, nr_line_info),
6142 offsetof(struct bpf_prog_info, line_info_rec_size),
6144 [BPF_PROG_INFO_JITED_LINE_INFO] = {
6145 offsetof(struct bpf_prog_info, jited_line_info),
6146 offsetof(struct bpf_prog_info, nr_jited_line_info),
6147 offsetof(struct bpf_prog_info, jited_line_info_rec_size),
6149 [BPF_PROG_INFO_PROG_TAGS] = {
6150 offsetof(struct bpf_prog_info, prog_tags),
6151 offsetof(struct bpf_prog_info, nr_prog_tags),
6152 -(int)sizeof(__u8) * BPF_TAG_SIZE,
6157 static __u32 bpf_prog_info_read_offset_u32(struct bpf_prog_info *info, int offset)
6159 __u32 *array = (__u32 *)info;
6162 return array[offset / sizeof(__u32)];
6163 return -(int)offset;
6166 static __u64 bpf_prog_info_read_offset_u64(struct bpf_prog_info *info, int offset)
6168 __u64 *array = (__u64 *)info;
6171 return array[offset / sizeof(__u64)];
6172 return -(int)offset;
6175 static void bpf_prog_info_set_offset_u32(struct bpf_prog_info *info, int offset,
6178 __u32 *array = (__u32 *)info;
6181 array[offset / sizeof(__u32)] = val;
6184 static void bpf_prog_info_set_offset_u64(struct bpf_prog_info *info, int offset,
6187 __u64 *array = (__u64 *)info;
6190 array[offset / sizeof(__u64)] = val;
6193 struct bpf_prog_info_linear *
6194 bpf_program__get_prog_info_linear(int fd, __u64 arrays)
6196 struct bpf_prog_info_linear *info_linear;
6197 struct bpf_prog_info info = {};
6198 __u32 info_len = sizeof(info);
6203 if (arrays >> BPF_PROG_INFO_LAST_ARRAY)
6204 return ERR_PTR(-EINVAL);
6206 /* step 1: get array dimensions */
6207 err = bpf_obj_get_info_by_fd(fd, &info, &info_len);
6209 pr_debug("can't get prog info: %s", strerror(errno));
6210 return ERR_PTR(-EFAULT);
6213 /* step 2: calculate total size of all arrays */
6214 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
6215 bool include_array = (arrays & (1UL << i)) > 0;
6216 struct bpf_prog_info_array_desc *desc;
6219 desc = bpf_prog_info_array_desc + i;
6221 /* kernel is too old to support this field */
6222 if (info_len < desc->array_offset + sizeof(__u32) ||
6223 info_len < desc->count_offset + sizeof(__u32) ||
6224 (desc->size_offset > 0 && info_len < desc->size_offset))
6225 include_array = false;
6227 if (!include_array) {
6228 arrays &= ~(1UL << i); /* clear the bit */
6232 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
6233 size = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
6235 data_len += count * size;
6238 /* step 3: allocate continuous memory */
6239 data_len = roundup(data_len, sizeof(__u64));
6240 info_linear = malloc(sizeof(struct bpf_prog_info_linear) + data_len);
6242 return ERR_PTR(-ENOMEM);
6244 /* step 4: fill data to info_linear->info */
6245 info_linear->arrays = arrays;
6246 memset(&info_linear->info, 0, sizeof(info));
6247 ptr = info_linear->data;
6249 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
6250 struct bpf_prog_info_array_desc *desc;
6253 if ((arrays & (1UL << i)) == 0)
6256 desc = bpf_prog_info_array_desc + i;
6257 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
6258 size = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
6259 bpf_prog_info_set_offset_u32(&info_linear->info,
6260 desc->count_offset, count);
6261 bpf_prog_info_set_offset_u32(&info_linear->info,
6262 desc->size_offset, size);
6263 bpf_prog_info_set_offset_u64(&info_linear->info,
6266 ptr += count * size;
6269 /* step 5: call syscall again to get required arrays */
6270 err = bpf_obj_get_info_by_fd(fd, &info_linear->info, &info_len);
6272 pr_debug("can't get prog info: %s", strerror(errno));
6274 return ERR_PTR(-EFAULT);
6277 /* step 6: verify the data */
6278 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
6279 struct bpf_prog_info_array_desc *desc;
6282 if ((arrays & (1UL << i)) == 0)
6285 desc = bpf_prog_info_array_desc + i;
6286 v1 = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
6287 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
6288 desc->count_offset);
6290 pr_warn("%s: mismatch in element count\n", __func__);
6292 v1 = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
6293 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
6296 pr_warn("%s: mismatch in rec size\n", __func__);
6299 /* step 7: update info_len and data_len */
6300 info_linear->info_len = sizeof(struct bpf_prog_info);
6301 info_linear->data_len = data_len;
6306 void bpf_program__bpil_addr_to_offs(struct bpf_prog_info_linear *info_linear)
6310 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
6311 struct bpf_prog_info_array_desc *desc;
6314 if ((info_linear->arrays & (1UL << i)) == 0)
6317 desc = bpf_prog_info_array_desc + i;
6318 addr = bpf_prog_info_read_offset_u64(&info_linear->info,
6319 desc->array_offset);
6320 offs = addr - ptr_to_u64(info_linear->data);
6321 bpf_prog_info_set_offset_u64(&info_linear->info,
6322 desc->array_offset, offs);
6326 void bpf_program__bpil_offs_to_addr(struct bpf_prog_info_linear *info_linear)
6330 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
6331 struct bpf_prog_info_array_desc *desc;
6334 if ((info_linear->arrays & (1UL << i)) == 0)
6337 desc = bpf_prog_info_array_desc + i;
6338 offs = bpf_prog_info_read_offset_u64(&info_linear->info,
6339 desc->array_offset);
6340 addr = offs + ptr_to_u64(info_linear->data);
6341 bpf_prog_info_set_offset_u64(&info_linear->info,
6342 desc->array_offset, addr);
6346 int libbpf_num_possible_cpus(void)
6348 static const char *fcpu = "/sys/devices/system/cpu/possible";
6349 int len = 0, n = 0, il = 0, ir = 0;
6350 unsigned int start = 0, end = 0;
6357 tmp_cpus = READ_ONCE(cpus);
6361 fd = open(fcpu, O_RDONLY);
6364 pr_warn("Failed to open file %s: %s\n", fcpu, strerror(error));
6367 len = read(fd, buf, sizeof(buf));
6370 error = len ? errno : EINVAL;
6371 pr_warn("Failed to read # of possible cpus from %s: %s\n",
6372 fcpu, strerror(error));
6375 if (len == sizeof(buf)) {
6376 pr_warn("File %s size overflow\n", fcpu);
6381 for (ir = 0, tmp_cpus = 0; ir <= len; ir++) {
6382 /* Each sub string separated by ',' has format \d+-\d+ or \d+ */
6383 if (buf[ir] == ',' || buf[ir] == '\0') {
6385 n = sscanf(&buf[il], "%u-%u", &start, &end);
6387 pr_warn("Failed to get # CPUs from %s\n",
6390 } else if (n == 1) {
6393 tmp_cpus += end - start + 1;
6397 if (tmp_cpus <= 0) {
6398 pr_warn("Invalid #CPUs %d from %s\n", tmp_cpus, fcpu);
6402 WRITE_ONCE(cpus, tmp_cpus);