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.
25 #include <asm/unistd.h>
26 #include <linux/err.h>
27 #include <linux/kernel.h>
28 #include <linux/bpf.h>
29 #include <linux/btf.h>
30 #include <linux/filter.h>
31 #include <linux/list.h>
32 #include <linux/limits.h>
33 #include <linux/perf_event.h>
34 #include <linux/ring_buffer.h>
35 #include <sys/epoll.h>
36 #include <sys/ioctl.h>
39 #include <sys/types.h>
41 #include <sys/utsname.h>
42 #include <tools/libc_compat.h>
49 #include "str_error.h"
50 #include "libbpf_internal.h"
58 #define BPF_FS_MAGIC 0xcafe4a11
61 /* vsprintf() in __base_pr() uses nonliteral format string. It may break
62 * compilation if user enables corresponding warning. Disable it explicitly.
64 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
66 #define __printf(a, b) __attribute__((format(printf, a, b)))
68 static int __base_pr(enum libbpf_print_level level, const char *format,
71 if (level == LIBBPF_DEBUG)
74 return vfprintf(stderr, format, args);
77 static libbpf_print_fn_t __libbpf_pr = __base_pr;
79 libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn)
81 libbpf_print_fn_t old_print_fn = __libbpf_pr;
88 void libbpf_print(enum libbpf_print_level level, const char *format, ...)
95 va_start(args, format);
96 __libbpf_pr(level, format, args);
100 #define STRERR_BUFSIZE 128
102 #define CHECK_ERR(action, err, out) do { \
109 /* Copied from tools/perf/util/util.h */
111 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
115 # define zclose(fd) ({ \
118 ___err = close((fd)); \
123 #ifdef HAVE_LIBELF_MMAP_SUPPORT
124 # define LIBBPF_ELF_C_READ_MMAP ELF_C_READ_MMAP
126 # define LIBBPF_ELF_C_READ_MMAP ELF_C_READ
129 static inline __u64 ptr_to_u64(const void *ptr)
131 return (__u64) (unsigned long) ptr;
134 struct bpf_capabilities {
135 /* v4.14: kernel support for program & map names. */
137 /* v5.2: kernel support for global data sections. */
139 /* BTF_KIND_FUNC and BTF_KIND_FUNC_PROTO support */
141 /* BTF_KIND_VAR and BTF_KIND_DATASEC support */
146 * bpf_prog should be a better name but it has been used in
150 /* Index in elf obj file, for relocation use. */
155 /* section_name with / replaced by _; makes recursive pinning
156 * in bpf_object__pin_programs easier
159 struct bpf_insn *insns;
160 size_t insns_cnt, main_prog_cnt;
161 enum bpf_prog_type type;
182 bpf_program_prep_t preprocessor;
184 struct bpf_object *obj;
186 bpf_program_clear_priv_t clear_priv;
188 enum bpf_attach_type expected_attach_type;
191 __u32 func_info_rec_size;
194 struct bpf_capabilities *caps;
197 __u32 line_info_rec_size;
202 enum libbpf_map_type {
209 static const char * const libbpf_type_to_btf_name[] = {
210 [LIBBPF_MAP_DATA] = ".data",
211 [LIBBPF_MAP_BSS] = ".bss",
212 [LIBBPF_MAP_RODATA] = ".rodata",
222 struct bpf_map_def def;
223 __u32 btf_key_type_id;
224 __u32 btf_value_type_id;
226 bpf_map_clear_priv_t clear_priv;
227 enum libbpf_map_type libbpf_type;
235 static LIST_HEAD(bpf_objects_list);
238 char name[BPF_OBJ_NAME_LEN];
242 struct bpf_program *programs;
244 struct bpf_map *maps;
247 struct bpf_secdata sections;
250 bool has_pseudo_calls;
253 * Information when doing elf related work. Only valid if fd
280 * All loaded bpf_object is linked in a list, which is
281 * hidden to caller. bpf_objects__<func> handlers deal with
284 struct list_head list;
287 struct btf_ext *btf_ext;
290 bpf_object_clear_priv_t clear_priv;
292 struct bpf_capabilities caps;
296 #define obj_elf_valid(o) ((o)->efile.elf)
298 void bpf_program__unload(struct bpf_program *prog)
306 * If the object is opened but the program was never loaded,
307 * it is possible that prog->instances.nr == -1.
309 if (prog->instances.nr > 0) {
310 for (i = 0; i < prog->instances.nr; i++)
311 zclose(prog->instances.fds[i]);
312 } else if (prog->instances.nr != -1) {
313 pr_warning("Internal error: instances.nr is %d\n",
317 prog->instances.nr = -1;
318 zfree(&prog->instances.fds);
320 zclose(prog->btf_fd);
321 zfree(&prog->func_info);
322 zfree(&prog->line_info);
325 static void bpf_program__exit(struct bpf_program *prog)
330 if (prog->clear_priv)
331 prog->clear_priv(prog, prog->priv);
334 prog->clear_priv = NULL;
336 bpf_program__unload(prog);
338 zfree(&prog->section_name);
339 zfree(&prog->pin_name);
341 zfree(&prog->reloc_desc);
348 static char *__bpf_program__pin_name(struct bpf_program *prog)
352 name = p = strdup(prog->section_name);
353 while ((p = strchr(p, '/')))
360 bpf_program__init(void *data, size_t size, char *section_name, int idx,
361 struct bpf_program *prog)
363 const size_t bpf_insn_sz = sizeof(struct bpf_insn);
365 if (size == 0 || size % bpf_insn_sz) {
366 pr_warning("corrupted section '%s', size: %zu\n",
371 memset(prog, 0, sizeof(*prog));
373 prog->section_name = strdup(section_name);
374 if (!prog->section_name) {
375 pr_warning("failed to alloc name for prog under section(%d) %s\n",
380 prog->pin_name = __bpf_program__pin_name(prog);
381 if (!prog->pin_name) {
382 pr_warning("failed to alloc pin name for prog under section(%d) %s\n",
387 prog->insns = malloc(size);
389 pr_warning("failed to alloc insns for prog under section %s\n",
393 prog->insns_cnt = size / bpf_insn_sz;
394 memcpy(prog->insns, data, size);
396 prog->instances.fds = NULL;
397 prog->instances.nr = -1;
398 prog->type = BPF_PROG_TYPE_UNSPEC;
403 bpf_program__exit(prog);
408 bpf_object__add_program(struct bpf_object *obj, void *data, size_t size,
409 char *section_name, int idx)
411 struct bpf_program prog, *progs;
414 err = bpf_program__init(data, size, section_name, idx, &prog);
418 prog.caps = &obj->caps;
419 progs = obj->programs;
420 nr_progs = obj->nr_programs;
422 progs = reallocarray(progs, nr_progs + 1, sizeof(progs[0]));
425 * In this case the original obj->programs
426 * is still valid, so don't need special treat for
427 * bpf_close_object().
429 pr_warning("failed to alloc a new program under section '%s'\n",
431 bpf_program__exit(&prog);
435 pr_debug("found program %s\n", prog.section_name);
436 obj->programs = progs;
437 obj->nr_programs = nr_progs + 1;
439 progs[nr_progs] = prog;
444 bpf_object__init_prog_names(struct bpf_object *obj)
446 Elf_Data *symbols = obj->efile.symbols;
447 struct bpf_program *prog;
450 for (pi = 0; pi < obj->nr_programs; pi++) {
451 const char *name = NULL;
453 prog = &obj->programs[pi];
455 for (si = 0; si < symbols->d_size / sizeof(GElf_Sym) && !name;
459 if (!gelf_getsym(symbols, si, &sym))
461 if (sym.st_shndx != prog->idx)
463 if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL)
466 name = elf_strptr(obj->efile.elf,
467 obj->efile.strtabidx,
470 pr_warning("failed to get sym name string for prog %s\n",
472 return -LIBBPF_ERRNO__LIBELF;
476 if (!name && prog->idx == obj->efile.text_shndx)
480 pr_warning("failed to find sym for prog %s\n",
485 prog->name = strdup(name);
487 pr_warning("failed to allocate memory for prog sym %s\n",
496 static struct bpf_object *bpf_object__new(const char *path,
500 struct bpf_object *obj;
503 obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
505 pr_warning("alloc memory failed for %s\n", path);
506 return ERR_PTR(-ENOMEM);
509 strcpy(obj->path, path);
510 /* Using basename() GNU version which doesn't modify arg. */
511 strncpy(obj->name, basename((void *)path), sizeof(obj->name) - 1);
512 end = strchr(obj->name, '.');
518 * Caller of this function should also call
519 * bpf_object__elf_finish() after data collection to return
520 * obj_buf to user. If not, we should duplicate the buffer to
521 * avoid user freeing them before elf finish.
523 obj->efile.obj_buf = obj_buf;
524 obj->efile.obj_buf_sz = obj_buf_sz;
525 obj->efile.maps_shndx = -1;
526 obj->efile.btf_maps_shndx = -1;
527 obj->efile.data_shndx = -1;
528 obj->efile.rodata_shndx = -1;
529 obj->efile.bss_shndx = -1;
533 INIT_LIST_HEAD(&obj->list);
534 list_add(&obj->list, &bpf_objects_list);
538 static void bpf_object__elf_finish(struct bpf_object *obj)
540 if (!obj_elf_valid(obj))
543 if (obj->efile.elf) {
544 elf_end(obj->efile.elf);
545 obj->efile.elf = NULL;
547 obj->efile.symbols = NULL;
548 obj->efile.data = NULL;
549 obj->efile.rodata = NULL;
550 obj->efile.bss = NULL;
552 zfree(&obj->efile.reloc);
553 obj->efile.nr_reloc = 0;
554 zclose(obj->efile.fd);
555 obj->efile.obj_buf = NULL;
556 obj->efile.obj_buf_sz = 0;
559 static int bpf_object__elf_init(struct bpf_object *obj)
564 if (obj_elf_valid(obj)) {
565 pr_warning("elf init: internal error\n");
566 return -LIBBPF_ERRNO__LIBELF;
569 if (obj->efile.obj_buf_sz > 0) {
571 * obj_buf should have been validated by
572 * bpf_object__open_buffer().
574 obj->efile.elf = elf_memory(obj->efile.obj_buf,
575 obj->efile.obj_buf_sz);
577 obj->efile.fd = open(obj->path, O_RDONLY);
578 if (obj->efile.fd < 0) {
579 char errmsg[STRERR_BUFSIZE], *cp;
582 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
583 pr_warning("failed to open %s: %s\n", obj->path, cp);
587 obj->efile.elf = elf_begin(obj->efile.fd,
588 LIBBPF_ELF_C_READ_MMAP, NULL);
591 if (!obj->efile.elf) {
592 pr_warning("failed to open %s as ELF file\n", obj->path);
593 err = -LIBBPF_ERRNO__LIBELF;
597 if (!gelf_getehdr(obj->efile.elf, &obj->efile.ehdr)) {
598 pr_warning("failed to get EHDR from %s\n", obj->path);
599 err = -LIBBPF_ERRNO__FORMAT;
602 ep = &obj->efile.ehdr;
604 /* Old LLVM set e_machine to EM_NONE */
605 if (ep->e_type != ET_REL ||
606 (ep->e_machine && ep->e_machine != EM_BPF)) {
607 pr_warning("%s is not an eBPF object file\n", obj->path);
608 err = -LIBBPF_ERRNO__FORMAT;
614 bpf_object__elf_finish(obj);
618 static int bpf_object__check_endianness(struct bpf_object *obj)
620 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
621 if (obj->efile.ehdr.e_ident[EI_DATA] == ELFDATA2LSB)
623 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
624 if (obj->efile.ehdr.e_ident[EI_DATA] == ELFDATA2MSB)
627 # error "Unrecognized __BYTE_ORDER__"
629 pr_warning("endianness mismatch.\n");
630 return -LIBBPF_ERRNO__ENDIAN;
634 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
636 memcpy(obj->license, data, min(size, sizeof(obj->license) - 1));
637 pr_debug("license of %s is %s\n", obj->path, obj->license);
642 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
646 if (size != sizeof(kver)) {
647 pr_warning("invalid kver section in %s\n", obj->path);
648 return -LIBBPF_ERRNO__FORMAT;
650 memcpy(&kver, data, sizeof(kver));
651 obj->kern_version = kver;
652 pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
656 static int compare_bpf_map(const void *_a, const void *_b)
658 const struct bpf_map *a = _a;
659 const struct bpf_map *b = _b;
661 if (a->sec_idx != b->sec_idx)
662 return a->sec_idx - b->sec_idx;
663 return a->sec_offset - b->sec_offset;
666 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
668 if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
669 type == BPF_MAP_TYPE_HASH_OF_MAPS)
674 static int bpf_object_search_section_size(const struct bpf_object *obj,
675 const char *name, size_t *d_size)
677 const GElf_Ehdr *ep = &obj->efile.ehdr;
678 Elf *elf = obj->efile.elf;
682 while ((scn = elf_nextscn(elf, scn)) != NULL) {
683 const char *sec_name;
688 if (gelf_getshdr(scn, &sh) != &sh) {
689 pr_warning("failed to get section(%d) header from %s\n",
694 sec_name = elf_strptr(elf, ep->e_shstrndx, sh.sh_name);
696 pr_warning("failed to get section(%d) name from %s\n",
701 if (strcmp(name, sec_name))
704 data = elf_getdata(scn, 0);
706 pr_warning("failed to get section(%d) data from %s(%s)\n",
707 idx, name, obj->path);
711 *d_size = data->d_size;
718 int bpf_object__section_size(const struct bpf_object *obj, const char *name,
727 } else if (!strcmp(name, ".data")) {
729 *size = obj->efile.data->d_size;
730 } else if (!strcmp(name, ".bss")) {
732 *size = obj->efile.bss->d_size;
733 } else if (!strcmp(name, ".rodata")) {
734 if (obj->efile.rodata)
735 *size = obj->efile.rodata->d_size;
737 ret = bpf_object_search_section_size(obj, name, &d_size);
742 return *size ? 0 : ret;
745 int bpf_object__variable_offset(const struct bpf_object *obj, const char *name,
748 Elf_Data *symbols = obj->efile.symbols;
755 for (si = 0; si < symbols->d_size / sizeof(GElf_Sym); si++) {
758 if (!gelf_getsym(symbols, si, &sym))
760 if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL ||
761 GELF_ST_TYPE(sym.st_info) != STT_OBJECT)
764 sname = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
767 pr_warning("failed to get sym name string for var %s\n",
771 if (strcmp(name, sname) == 0) {
780 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
782 struct bpf_map *new_maps;
786 if (obj->nr_maps < obj->maps_cap)
787 return &obj->maps[obj->nr_maps++];
789 new_cap = max((size_t)4, obj->maps_cap * 3 / 2);
790 new_maps = realloc(obj->maps, new_cap * sizeof(*obj->maps));
792 pr_warning("alloc maps for object failed\n");
793 return ERR_PTR(-ENOMEM);
796 obj->maps_cap = new_cap;
797 obj->maps = new_maps;
799 /* zero out new maps */
800 memset(obj->maps + obj->nr_maps, 0,
801 (obj->maps_cap - obj->nr_maps) * sizeof(*obj->maps));
803 * fill all fd with -1 so won't close incorrect fd (fd=0 is stdin)
804 * when failure (zclose won't close negative fd)).
806 for (i = obj->nr_maps; i < obj->maps_cap; i++) {
807 obj->maps[i].fd = -1;
808 obj->maps[i].inner_map_fd = -1;
811 return &obj->maps[obj->nr_maps++];
815 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
816 int sec_idx, Elf_Data *data, void **data_buff)
818 char map_name[BPF_OBJ_NAME_LEN];
819 struct bpf_map_def *def;
822 map = bpf_object__add_map(obj);
826 map->libbpf_type = type;
827 map->sec_idx = sec_idx;
829 snprintf(map_name, sizeof(map_name), "%.8s%.7s", obj->name,
830 libbpf_type_to_btf_name[type]);
831 map->name = strdup(map_name);
833 pr_warning("failed to alloc map name\n");
836 pr_debug("map '%s' (global data): at sec_idx %d, offset %zu.\n",
837 map_name, map->sec_idx, map->sec_offset);
840 def->type = BPF_MAP_TYPE_ARRAY;
841 def->key_size = sizeof(int);
842 def->value_size = data->d_size;
843 def->max_entries = 1;
844 def->map_flags = type == LIBBPF_MAP_RODATA ? BPF_F_RDONLY_PROG : 0;
846 *data_buff = malloc(data->d_size);
849 pr_warning("failed to alloc map content buffer\n");
852 memcpy(*data_buff, data->d_buf, data->d_size);
855 pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
859 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
863 if (!obj->caps.global_data)
866 * Populate obj->maps with libbpf internal maps.
868 if (obj->efile.data_shndx >= 0) {
869 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
870 obj->efile.data_shndx,
872 &obj->sections.data);
876 if (obj->efile.rodata_shndx >= 0) {
877 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
878 obj->efile.rodata_shndx,
880 &obj->sections.rodata);
884 if (obj->efile.bss_shndx >= 0) {
885 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
886 obj->efile.bss_shndx,
887 obj->efile.bss, NULL);
894 static int bpf_object__init_user_maps(struct bpf_object *obj, bool strict)
896 Elf_Data *symbols = obj->efile.symbols;
897 int i, map_def_sz = 0, nr_maps = 0, nr_syms;
898 Elf_Data *data = NULL;
901 if (obj->efile.maps_shndx < 0)
907 scn = elf_getscn(obj->efile.elf, obj->efile.maps_shndx);
909 data = elf_getdata(scn, NULL);
911 pr_warning("failed to get Elf_Data from map section %d\n",
912 obj->efile.maps_shndx);
917 * Count number of maps. Each map has a name.
918 * Array of maps is not supported: only the first element is
921 * TODO: Detect array of map and report error.
923 nr_syms = symbols->d_size / sizeof(GElf_Sym);
924 for (i = 0; i < nr_syms; i++) {
927 if (!gelf_getsym(symbols, i, &sym))
929 if (sym.st_shndx != obj->efile.maps_shndx)
933 /* Assume equally sized map definitions */
934 pr_debug("maps in %s: %d maps in %zd bytes\n",
935 obj->path, nr_maps, data->d_size);
937 map_def_sz = data->d_size / nr_maps;
938 if (!data->d_size || (data->d_size % nr_maps) != 0) {
939 pr_warning("unable to determine map definition size "
940 "section %s, %d maps in %zd bytes\n",
941 obj->path, nr_maps, data->d_size);
945 /* Fill obj->maps using data in "maps" section. */
946 for (i = 0; i < nr_syms; i++) {
948 const char *map_name;
949 struct bpf_map_def *def;
952 if (!gelf_getsym(symbols, i, &sym))
954 if (sym.st_shndx != obj->efile.maps_shndx)
957 map = bpf_object__add_map(obj);
961 map_name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
964 pr_warning("failed to get map #%d name sym string for obj %s\n",
966 return -LIBBPF_ERRNO__FORMAT;
969 map->libbpf_type = LIBBPF_MAP_UNSPEC;
970 map->sec_idx = sym.st_shndx;
971 map->sec_offset = sym.st_value;
972 pr_debug("map '%s' (legacy): at sec_idx %d, offset %zu.\n",
973 map_name, map->sec_idx, map->sec_offset);
974 if (sym.st_value + map_def_sz > data->d_size) {
975 pr_warning("corrupted maps section in %s: last map \"%s\" too small\n",
976 obj->path, map_name);
980 map->name = strdup(map_name);
982 pr_warning("failed to alloc map name\n");
985 pr_debug("map %d is \"%s\"\n", i, map->name);
986 def = (struct bpf_map_def *)(data->d_buf + sym.st_value);
988 * If the definition of the map in the object file fits in
989 * bpf_map_def, copy it. Any extra fields in our version
990 * of bpf_map_def will default to zero as a result of the
993 if (map_def_sz <= sizeof(struct bpf_map_def)) {
994 memcpy(&map->def, def, map_def_sz);
997 * Here the map structure being read is bigger than what
998 * we expect, truncate if the excess bits are all zero.
999 * If they are not zero, reject this map as
1003 for (b = ((char *)def) + sizeof(struct bpf_map_def);
1004 b < ((char *)def) + map_def_sz; b++) {
1006 pr_warning("maps section in %s: \"%s\" "
1007 "has unrecognized, non-zero "
1009 obj->path, map_name);
1014 memcpy(&map->def, def, sizeof(struct bpf_map_def));
1020 static const struct btf_type *
1021 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
1023 const struct btf_type *t = btf__type_by_id(btf, id);
1028 while (btf_is_mod(t) || btf_is_typedef(t)) {
1031 t = btf__type_by_id(btf, t->type);
1038 * Fetch integer attribute of BTF map definition. Such attributes are
1039 * represented using a pointer to an array, in which dimensionality of array
1040 * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
1041 * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
1042 * type definition, while using only sizeof(void *) space in ELF data section.
1044 static bool get_map_field_int(const char *map_name, const struct btf *btf,
1045 const struct btf_type *def,
1046 const struct btf_member *m, __u32 *res) {
1047 const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
1048 const char *name = btf__name_by_offset(btf, m->name_off);
1049 const struct btf_array *arr_info;
1050 const struct btf_type *arr_t;
1052 if (!btf_is_ptr(t)) {
1053 pr_warning("map '%s': attr '%s': expected PTR, got %u.\n",
1054 map_name, name, btf_kind(t));
1058 arr_t = btf__type_by_id(btf, t->type);
1060 pr_warning("map '%s': attr '%s': type [%u] not found.\n",
1061 map_name, name, t->type);
1064 if (!btf_is_array(arr_t)) {
1065 pr_warning("map '%s': attr '%s': expected ARRAY, got %u.\n",
1066 map_name, name, btf_kind(arr_t));
1069 arr_info = btf_array(arr_t);
1070 *res = arr_info->nelems;
1074 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
1075 const struct btf_type *sec,
1076 int var_idx, int sec_idx,
1077 const Elf_Data *data, bool strict)
1079 const struct btf_type *var, *def, *t;
1080 const struct btf_var_secinfo *vi;
1081 const struct btf_var *var_extra;
1082 const struct btf_member *m;
1083 const char *map_name;
1084 struct bpf_map *map;
1087 vi = btf_var_secinfos(sec) + var_idx;
1088 var = btf__type_by_id(obj->btf, vi->type);
1089 var_extra = btf_var(var);
1090 map_name = btf__name_by_offset(obj->btf, var->name_off);
1091 vlen = btf_vlen(var);
1093 if (map_name == NULL || map_name[0] == '\0') {
1094 pr_warning("map #%d: empty name.\n", var_idx);
1097 if ((__u64)vi->offset + vi->size > data->d_size) {
1098 pr_warning("map '%s' BTF data is corrupted.\n", map_name);
1101 if (!btf_is_var(var)) {
1102 pr_warning("map '%s': unexpected var kind %u.\n",
1103 map_name, btf_kind(var));
1106 if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED &&
1107 var_extra->linkage != BTF_VAR_STATIC) {
1108 pr_warning("map '%s': unsupported var linkage %u.\n",
1109 map_name, var_extra->linkage);
1113 def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
1114 if (!btf_is_struct(def)) {
1115 pr_warning("map '%s': unexpected def kind %u.\n",
1116 map_name, btf_kind(var));
1119 if (def->size > vi->size) {
1120 pr_warning("map '%s': invalid def size.\n", map_name);
1124 map = bpf_object__add_map(obj);
1126 return PTR_ERR(map);
1127 map->name = strdup(map_name);
1129 pr_warning("map '%s': failed to alloc map name.\n", map_name);
1132 map->libbpf_type = LIBBPF_MAP_UNSPEC;
1133 map->def.type = BPF_MAP_TYPE_UNSPEC;
1134 map->sec_idx = sec_idx;
1135 map->sec_offset = vi->offset;
1136 pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
1137 map_name, map->sec_idx, map->sec_offset);
1139 vlen = btf_vlen(def);
1140 m = btf_members(def);
1141 for (i = 0; i < vlen; i++, m++) {
1142 const char *name = btf__name_by_offset(obj->btf, m->name_off);
1145 pr_warning("map '%s': invalid field #%d.\n",
1149 if (strcmp(name, "type") == 0) {
1150 if (!get_map_field_int(map_name, obj->btf, def, m,
1153 pr_debug("map '%s': found type = %u.\n",
1154 map_name, map->def.type);
1155 } else if (strcmp(name, "max_entries") == 0) {
1156 if (!get_map_field_int(map_name, obj->btf, def, m,
1157 &map->def.max_entries))
1159 pr_debug("map '%s': found max_entries = %u.\n",
1160 map_name, map->def.max_entries);
1161 } else if (strcmp(name, "map_flags") == 0) {
1162 if (!get_map_field_int(map_name, obj->btf, def, m,
1163 &map->def.map_flags))
1165 pr_debug("map '%s': found map_flags = %u.\n",
1166 map_name, map->def.map_flags);
1167 } else if (strcmp(name, "key_size") == 0) {
1170 if (!get_map_field_int(map_name, obj->btf, def, m,
1173 pr_debug("map '%s': found key_size = %u.\n",
1175 if (map->def.key_size && map->def.key_size != sz) {
1176 pr_warning("map '%s': conflicting key size %u != %u.\n",
1177 map_name, map->def.key_size, sz);
1180 map->def.key_size = sz;
1181 } else if (strcmp(name, "key") == 0) {
1184 t = btf__type_by_id(obj->btf, m->type);
1186 pr_warning("map '%s': key type [%d] not found.\n",
1190 if (!btf_is_ptr(t)) {
1191 pr_warning("map '%s': key spec is not PTR: %u.\n",
1192 map_name, btf_kind(t));
1195 sz = btf__resolve_size(obj->btf, t->type);
1197 pr_warning("map '%s': can't determine key size for type [%u]: %lld.\n",
1198 map_name, t->type, sz);
1201 pr_debug("map '%s': found key [%u], sz = %lld.\n",
1202 map_name, t->type, sz);
1203 if (map->def.key_size && map->def.key_size != sz) {
1204 pr_warning("map '%s': conflicting key size %u != %lld.\n",
1205 map_name, map->def.key_size, sz);
1208 map->def.key_size = sz;
1209 map->btf_key_type_id = t->type;
1210 } else if (strcmp(name, "value_size") == 0) {
1213 if (!get_map_field_int(map_name, obj->btf, def, m,
1216 pr_debug("map '%s': found value_size = %u.\n",
1218 if (map->def.value_size && map->def.value_size != sz) {
1219 pr_warning("map '%s': conflicting value size %u != %u.\n",
1220 map_name, map->def.value_size, sz);
1223 map->def.value_size = sz;
1224 } else if (strcmp(name, "value") == 0) {
1227 t = btf__type_by_id(obj->btf, m->type);
1229 pr_warning("map '%s': value type [%d] not found.\n",
1233 if (!btf_is_ptr(t)) {
1234 pr_warning("map '%s': value spec is not PTR: %u.\n",
1235 map_name, btf_kind(t));
1238 sz = btf__resolve_size(obj->btf, t->type);
1240 pr_warning("map '%s': can't determine value size for type [%u]: %lld.\n",
1241 map_name, t->type, sz);
1244 pr_debug("map '%s': found value [%u], sz = %lld.\n",
1245 map_name, t->type, sz);
1246 if (map->def.value_size && map->def.value_size != sz) {
1247 pr_warning("map '%s': conflicting value size %u != %lld.\n",
1248 map_name, map->def.value_size, sz);
1251 map->def.value_size = sz;
1252 map->btf_value_type_id = t->type;
1255 pr_warning("map '%s': unknown field '%s'.\n",
1259 pr_debug("map '%s': ignoring unknown field '%s'.\n",
1264 if (map->def.type == BPF_MAP_TYPE_UNSPEC) {
1265 pr_warning("map '%s': map type isn't specified.\n", map_name);
1272 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict)
1274 const struct btf_type *sec = NULL;
1275 int nr_types, i, vlen, err;
1276 const struct btf_type *t;
1281 if (obj->efile.btf_maps_shndx < 0)
1284 scn = elf_getscn(obj->efile.elf, obj->efile.btf_maps_shndx);
1286 data = elf_getdata(scn, NULL);
1287 if (!scn || !data) {
1288 pr_warning("failed to get Elf_Data from map section %d (%s)\n",
1289 obj->efile.maps_shndx, MAPS_ELF_SEC);
1293 nr_types = btf__get_nr_types(obj->btf);
1294 for (i = 1; i <= nr_types; i++) {
1295 t = btf__type_by_id(obj->btf, i);
1296 if (!btf_is_datasec(t))
1298 name = btf__name_by_offset(obj->btf, t->name_off);
1299 if (strcmp(name, MAPS_ELF_SEC) == 0) {
1306 pr_warning("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
1310 vlen = btf_vlen(sec);
1311 for (i = 0; i < vlen; i++) {
1312 err = bpf_object__init_user_btf_map(obj, sec, i,
1313 obj->efile.btf_maps_shndx,
1322 static int bpf_object__init_maps(struct bpf_object *obj, int flags)
1324 bool strict = !(flags & MAPS_RELAX_COMPAT);
1327 err = bpf_object__init_user_maps(obj, strict);
1331 err = bpf_object__init_user_btf_maps(obj, strict);
1335 err = bpf_object__init_global_data_maps(obj);
1340 qsort(obj->maps, obj->nr_maps, sizeof(obj->maps[0]),
1346 static bool section_have_execinstr(struct bpf_object *obj, int idx)
1351 scn = elf_getscn(obj->efile.elf, idx);
1355 if (gelf_getshdr(scn, &sh) != &sh)
1358 if (sh.sh_flags & SHF_EXECINSTR)
1364 static void bpf_object__sanitize_btf(struct bpf_object *obj)
1366 bool has_datasec = obj->caps.btf_datasec;
1367 bool has_func = obj->caps.btf_func;
1368 struct btf *btf = obj->btf;
1372 if (!obj->btf || (has_func && has_datasec))
1375 for (i = 1; i <= btf__get_nr_types(btf); i++) {
1376 t = (struct btf_type *)btf__type_by_id(btf, i);
1378 if (!has_datasec && btf_is_var(t)) {
1379 /* replace VAR with INT */
1380 t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
1381 t->size = sizeof(int);
1382 *(int *)(t + 1) = BTF_INT_ENC(0, 0, 32);
1383 } else if (!has_datasec && btf_is_datasec(t)) {
1384 /* replace DATASEC with STRUCT */
1385 const struct btf_var_secinfo *v = btf_var_secinfos(t);
1386 struct btf_member *m = btf_members(t);
1387 struct btf_type *vt;
1390 name = (char *)btf__name_by_offset(btf, t->name_off);
1398 t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
1399 for (j = 0; j < vlen; j++, v++, m++) {
1400 /* order of field assignments is important */
1401 m->offset = v->offset * 8;
1403 /* preserve variable name as member name */
1404 vt = (void *)btf__type_by_id(btf, v->type);
1405 m->name_off = vt->name_off;
1407 } else if (!has_func && btf_is_func_proto(t)) {
1408 /* replace FUNC_PROTO with ENUM */
1410 t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
1411 t->size = sizeof(__u32); /* kernel enforced */
1412 } else if (!has_func && btf_is_func(t)) {
1413 /* replace FUNC with TYPEDEF */
1414 t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
1419 static void bpf_object__sanitize_btf_ext(struct bpf_object *obj)
1424 if (!obj->caps.btf_func) {
1425 btf_ext__free(obj->btf_ext);
1426 obj->btf_ext = NULL;
1430 static bool bpf_object__is_btf_mandatory(const struct bpf_object *obj)
1432 return obj->efile.btf_maps_shndx >= 0;
1435 static int bpf_object__init_btf(struct bpf_object *obj,
1437 Elf_Data *btf_ext_data)
1439 bool btf_required = bpf_object__is_btf_mandatory(obj);
1443 obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
1444 if (IS_ERR(obj->btf)) {
1445 pr_warning("Error loading ELF section %s: %d.\n",
1449 err = btf__finalize_data(obj, obj->btf);
1451 pr_warning("Error finalizing %s: %d.\n",
1458 pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
1459 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
1462 obj->btf_ext = btf_ext__new(btf_ext_data->d_buf,
1463 btf_ext_data->d_size);
1464 if (IS_ERR(obj->btf_ext)) {
1465 pr_warning("Error loading ELF section %s: %ld. Ignored and continue.\n",
1466 BTF_EXT_ELF_SEC, PTR_ERR(obj->btf_ext));
1467 obj->btf_ext = NULL;
1472 if (err || IS_ERR(obj->btf)) {
1474 err = err ? : PTR_ERR(obj->btf);
1477 if (!IS_ERR_OR_NULL(obj->btf))
1478 btf__free(obj->btf);
1481 if (btf_required && !obj->btf) {
1482 pr_warning("BTF is required, but is missing or corrupted.\n");
1483 return err == 0 ? -ENOENT : err;
1488 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
1495 bpf_object__sanitize_btf(obj);
1496 bpf_object__sanitize_btf_ext(obj);
1498 err = btf__load(obj->btf);
1500 pr_warning("Error loading %s into kernel: %d.\n",
1502 btf__free(obj->btf);
1504 if (bpf_object__is_btf_mandatory(obj))
1510 static int bpf_object__elf_collect(struct bpf_object *obj, int flags)
1512 Elf *elf = obj->efile.elf;
1513 GElf_Ehdr *ep = &obj->efile.ehdr;
1514 Elf_Data *btf_ext_data = NULL;
1515 Elf_Data *btf_data = NULL;
1516 Elf_Scn *scn = NULL;
1517 int idx = 0, err = 0;
1519 /* Elf is corrupted/truncated, avoid calling elf_strptr. */
1520 if (!elf_rawdata(elf_getscn(elf, ep->e_shstrndx), NULL)) {
1521 pr_warning("failed to get e_shstrndx from %s\n", obj->path);
1522 return -LIBBPF_ERRNO__FORMAT;
1525 while ((scn = elf_nextscn(elf, scn)) != NULL) {
1531 if (gelf_getshdr(scn, &sh) != &sh) {
1532 pr_warning("failed to get section(%d) header from %s\n",
1534 return -LIBBPF_ERRNO__FORMAT;
1537 name = elf_strptr(elf, ep->e_shstrndx, sh.sh_name);
1539 pr_warning("failed to get section(%d) name from %s\n",
1541 return -LIBBPF_ERRNO__FORMAT;
1544 data = elf_getdata(scn, 0);
1546 pr_warning("failed to get section(%d) data from %s(%s)\n",
1547 idx, name, obj->path);
1548 return -LIBBPF_ERRNO__FORMAT;
1550 pr_debug("section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
1551 idx, name, (unsigned long)data->d_size,
1552 (int)sh.sh_link, (unsigned long)sh.sh_flags,
1555 if (strcmp(name, "license") == 0) {
1556 err = bpf_object__init_license(obj,
1561 } else if (strcmp(name, "version") == 0) {
1562 err = bpf_object__init_kversion(obj,
1567 } else if (strcmp(name, "maps") == 0) {
1568 obj->efile.maps_shndx = idx;
1569 } else if (strcmp(name, MAPS_ELF_SEC) == 0) {
1570 obj->efile.btf_maps_shndx = idx;
1571 } else if (strcmp(name, BTF_ELF_SEC) == 0) {
1573 } else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
1574 btf_ext_data = data;
1575 } else if (sh.sh_type == SHT_SYMTAB) {
1576 if (obj->efile.symbols) {
1577 pr_warning("bpf: multiple SYMTAB in %s\n",
1579 return -LIBBPF_ERRNO__FORMAT;
1581 obj->efile.symbols = data;
1582 obj->efile.strtabidx = sh.sh_link;
1583 } else if (sh.sh_type == SHT_PROGBITS && data->d_size > 0) {
1584 if (sh.sh_flags & SHF_EXECINSTR) {
1585 if (strcmp(name, ".text") == 0)
1586 obj->efile.text_shndx = idx;
1587 err = bpf_object__add_program(obj, data->d_buf,
1588 data->d_size, name, idx);
1590 char errmsg[STRERR_BUFSIZE];
1591 char *cp = libbpf_strerror_r(-err, errmsg,
1594 pr_warning("failed to alloc program %s (%s): %s",
1595 name, obj->path, cp);
1598 } else if (strcmp(name, ".data") == 0) {
1599 obj->efile.data = data;
1600 obj->efile.data_shndx = idx;
1601 } else if (strcmp(name, ".rodata") == 0) {
1602 obj->efile.rodata = data;
1603 obj->efile.rodata_shndx = idx;
1605 pr_debug("skip section(%d) %s\n", idx, name);
1607 } else if (sh.sh_type == SHT_REL) {
1608 int nr_reloc = obj->efile.nr_reloc;
1609 void *reloc = obj->efile.reloc;
1610 int sec = sh.sh_info; /* points to other section */
1612 /* Only do relo for section with exec instructions */
1613 if (!section_have_execinstr(obj, sec)) {
1614 pr_debug("skip relo %s(%d) for section(%d)\n",
1619 reloc = reallocarray(reloc, nr_reloc + 1,
1620 sizeof(*obj->efile.reloc));
1622 pr_warning("realloc failed\n");
1626 obj->efile.reloc = reloc;
1627 obj->efile.nr_reloc++;
1629 obj->efile.reloc[nr_reloc].shdr = sh;
1630 obj->efile.reloc[nr_reloc].data = data;
1631 } else if (sh.sh_type == SHT_NOBITS && strcmp(name, ".bss") == 0) {
1632 obj->efile.bss = data;
1633 obj->efile.bss_shndx = idx;
1635 pr_debug("skip section(%d) %s\n", idx, name);
1639 if (!obj->efile.strtabidx || obj->efile.strtabidx >= idx) {
1640 pr_warning("Corrupted ELF file: index of strtab invalid\n");
1641 return -LIBBPF_ERRNO__FORMAT;
1643 err = bpf_object__init_btf(obj, btf_data, btf_ext_data);
1645 err = bpf_object__init_maps(obj, flags);
1647 err = bpf_object__sanitize_and_load_btf(obj);
1649 err = bpf_object__init_prog_names(obj);
1653 static struct bpf_program *
1654 bpf_object__find_prog_by_idx(struct bpf_object *obj, int idx)
1656 struct bpf_program *prog;
1659 for (i = 0; i < obj->nr_programs; i++) {
1660 prog = &obj->programs[i];
1661 if (prog->idx == idx)
1667 struct bpf_program *
1668 bpf_object__find_program_by_title(const struct bpf_object *obj,
1671 struct bpf_program *pos;
1673 bpf_object__for_each_program(pos, obj) {
1674 if (pos->section_name && !strcmp(pos->section_name, title))
1680 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
1683 return shndx == obj->efile.data_shndx ||
1684 shndx == obj->efile.bss_shndx ||
1685 shndx == obj->efile.rodata_shndx;
1688 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
1691 return shndx == obj->efile.maps_shndx ||
1692 shndx == obj->efile.btf_maps_shndx;
1695 static bool bpf_object__relo_in_known_section(const struct bpf_object *obj,
1698 return shndx == obj->efile.text_shndx ||
1699 bpf_object__shndx_is_maps(obj, shndx) ||
1700 bpf_object__shndx_is_data(obj, shndx);
1703 static enum libbpf_map_type
1704 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
1706 if (shndx == obj->efile.data_shndx)
1707 return LIBBPF_MAP_DATA;
1708 else if (shndx == obj->efile.bss_shndx)
1709 return LIBBPF_MAP_BSS;
1710 else if (shndx == obj->efile.rodata_shndx)
1711 return LIBBPF_MAP_RODATA;
1713 return LIBBPF_MAP_UNSPEC;
1717 bpf_program__collect_reloc(struct bpf_program *prog, GElf_Shdr *shdr,
1718 Elf_Data *data, struct bpf_object *obj)
1720 Elf_Data *symbols = obj->efile.symbols;
1721 struct bpf_map *maps = obj->maps;
1722 size_t nr_maps = obj->nr_maps;
1725 pr_debug("collecting relocating info for: '%s'\n", prog->section_name);
1726 nrels = shdr->sh_size / shdr->sh_entsize;
1728 prog->reloc_desc = malloc(sizeof(*prog->reloc_desc) * nrels);
1729 if (!prog->reloc_desc) {
1730 pr_warning("failed to alloc memory in relocation\n");
1733 prog->nr_reloc = nrels;
1735 for (i = 0; i < nrels; i++) {
1736 struct bpf_insn *insns = prog->insns;
1737 enum libbpf_map_type type;
1738 unsigned int insn_idx;
1739 unsigned int shdr_idx;
1745 if (!gelf_getrel(data, i, &rel)) {
1746 pr_warning("relocation: failed to get %d reloc\n", i);
1747 return -LIBBPF_ERRNO__FORMAT;
1750 if (!gelf_getsym(symbols, GELF_R_SYM(rel.r_info), &sym)) {
1751 pr_warning("relocation: symbol %"PRIx64" not found\n",
1752 GELF_R_SYM(rel.r_info));
1753 return -LIBBPF_ERRNO__FORMAT;
1756 name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
1757 sym.st_name) ? : "<?>";
1759 pr_debug("relo for %lld value %lld name %d (\'%s\')\n",
1760 (long long) (rel.r_info >> 32),
1761 (long long) sym.st_value, sym.st_name, name);
1763 shdr_idx = sym.st_shndx;
1764 insn_idx = rel.r_offset / sizeof(struct bpf_insn);
1765 pr_debug("relocation: insn_idx=%u, shdr_idx=%u\n",
1766 insn_idx, shdr_idx);
1768 if (shdr_idx >= SHN_LORESERVE) {
1769 pr_warning("relocation: not yet supported relo for non-static global \'%s\' variable in special section (0x%x) found in insns[%d].code 0x%x\n",
1770 name, shdr_idx, insn_idx,
1771 insns[insn_idx].code);
1772 return -LIBBPF_ERRNO__RELOC;
1774 if (!bpf_object__relo_in_known_section(obj, shdr_idx)) {
1775 pr_warning("Program '%s' contains unrecognized relo data pointing to section %u\n",
1776 prog->section_name, shdr_idx);
1777 return -LIBBPF_ERRNO__RELOC;
1780 if (insns[insn_idx].code == (BPF_JMP | BPF_CALL)) {
1781 if (insns[insn_idx].src_reg != BPF_PSEUDO_CALL) {
1782 pr_warning("incorrect bpf_call opcode\n");
1783 return -LIBBPF_ERRNO__RELOC;
1785 prog->reloc_desc[i].type = RELO_CALL;
1786 prog->reloc_desc[i].insn_idx = insn_idx;
1787 prog->reloc_desc[i].text_off = sym.st_value;
1788 obj->has_pseudo_calls = true;
1792 if (insns[insn_idx].code != (BPF_LD | BPF_IMM | BPF_DW)) {
1793 pr_warning("bpf: relocation: invalid relo for insns[%d].code 0x%x\n",
1794 insn_idx, insns[insn_idx].code);
1795 return -LIBBPF_ERRNO__RELOC;
1798 if (bpf_object__shndx_is_maps(obj, shdr_idx) ||
1799 bpf_object__shndx_is_data(obj, shdr_idx)) {
1800 type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
1801 if (type != LIBBPF_MAP_UNSPEC) {
1802 if (GELF_ST_BIND(sym.st_info) == STB_GLOBAL) {
1803 pr_warning("bpf: relocation: not yet supported relo for non-static global \'%s\' variable found in insns[%d].code 0x%x\n",
1804 name, insn_idx, insns[insn_idx].code);
1805 return -LIBBPF_ERRNO__RELOC;
1807 if (!obj->caps.global_data) {
1808 pr_warning("bpf: relocation: kernel does not support global \'%s\' variable access in insns[%d]\n",
1810 return -LIBBPF_ERRNO__RELOC;
1814 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
1815 if (maps[map_idx].libbpf_type != type)
1817 if (type != LIBBPF_MAP_UNSPEC ||
1818 (maps[map_idx].sec_idx == sym.st_shndx &&
1819 maps[map_idx].sec_offset == sym.st_value)) {
1820 pr_debug("relocation: found map %zd (%s, sec_idx %d, offset %zu) for insn %u\n",
1821 map_idx, maps[map_idx].name,
1822 maps[map_idx].sec_idx,
1823 maps[map_idx].sec_offset,
1829 if (map_idx >= nr_maps) {
1830 pr_warning("bpf relocation: map_idx %d larger than %d\n",
1831 (int)map_idx, (int)nr_maps - 1);
1832 return -LIBBPF_ERRNO__RELOC;
1835 prog->reloc_desc[i].type = type != LIBBPF_MAP_UNSPEC ?
1836 RELO_DATA : RELO_LD64;
1837 prog->reloc_desc[i].insn_idx = insn_idx;
1838 prog->reloc_desc[i].map_idx = map_idx;
1844 static int bpf_map_find_btf_info(struct bpf_object *obj, struct bpf_map *map)
1846 struct bpf_map_def *def = &map->def;
1847 __u32 key_type_id = 0, value_type_id = 0;
1850 /* if it's BTF-defined map, we don't need to search for type IDs */
1851 if (map->sec_idx == obj->efile.btf_maps_shndx)
1854 if (!bpf_map__is_internal(map)) {
1855 ret = btf__get_map_kv_tids(obj->btf, map->name, def->key_size,
1856 def->value_size, &key_type_id,
1860 * LLVM annotates global data differently in BTF, that is,
1861 * only as '.data', '.bss' or '.rodata'.
1863 ret = btf__find_by_name(obj->btf,
1864 libbpf_type_to_btf_name[map->libbpf_type]);
1869 map->btf_key_type_id = key_type_id;
1870 map->btf_value_type_id = bpf_map__is_internal(map) ?
1871 ret : value_type_id;
1875 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
1877 struct bpf_map_info info = {};
1878 __u32 len = sizeof(info);
1882 err = bpf_obj_get_info_by_fd(fd, &info, &len);
1886 new_name = strdup(info.name);
1890 new_fd = open("/", O_RDONLY | O_CLOEXEC);
1892 goto err_free_new_name;
1894 new_fd = dup3(fd, new_fd, O_CLOEXEC);
1896 goto err_close_new_fd;
1898 err = zclose(map->fd);
1900 goto err_close_new_fd;
1904 map->name = new_name;
1905 map->def.type = info.type;
1906 map->def.key_size = info.key_size;
1907 map->def.value_size = info.value_size;
1908 map->def.max_entries = info.max_entries;
1909 map->def.map_flags = info.map_flags;
1910 map->btf_key_type_id = info.btf_key_type_id;
1911 map->btf_value_type_id = info.btf_value_type_id;
1922 int bpf_map__resize(struct bpf_map *map, __u32 max_entries)
1924 if (!map || !max_entries)
1927 /* If map already created, its attributes can't be changed. */
1931 map->def.max_entries = max_entries;
1937 bpf_object__probe_name(struct bpf_object *obj)
1939 struct bpf_load_program_attr attr;
1940 char *cp, errmsg[STRERR_BUFSIZE];
1941 struct bpf_insn insns[] = {
1942 BPF_MOV64_IMM(BPF_REG_0, 0),
1947 /* make sure basic loading works */
1949 memset(&attr, 0, sizeof(attr));
1950 attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
1952 attr.insns_cnt = ARRAY_SIZE(insns);
1953 attr.license = "GPL";
1955 ret = bpf_load_program_xattr(&attr, NULL, 0);
1957 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
1958 pr_warning("Error in %s():%s(%d). Couldn't load basic 'r0 = 0' BPF program.\n",
1959 __func__, cp, errno);
1964 /* now try the same program, but with the name */
1967 ret = bpf_load_program_xattr(&attr, NULL, 0);
1977 bpf_object__probe_global_data(struct bpf_object *obj)
1979 struct bpf_load_program_attr prg_attr;
1980 struct bpf_create_map_attr map_attr;
1981 char *cp, errmsg[STRERR_BUFSIZE];
1982 struct bpf_insn insns[] = {
1983 BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16),
1984 BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42),
1985 BPF_MOV64_IMM(BPF_REG_0, 0),
1990 memset(&map_attr, 0, sizeof(map_attr));
1991 map_attr.map_type = BPF_MAP_TYPE_ARRAY;
1992 map_attr.key_size = sizeof(int);
1993 map_attr.value_size = 32;
1994 map_attr.max_entries = 1;
1996 map = bpf_create_map_xattr(&map_attr);
1998 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
1999 pr_warning("Error in %s():%s(%d). Couldn't create simple array map.\n",
2000 __func__, cp, errno);
2006 memset(&prg_attr, 0, sizeof(prg_attr));
2007 prg_attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
2008 prg_attr.insns = insns;
2009 prg_attr.insns_cnt = ARRAY_SIZE(insns);
2010 prg_attr.license = "GPL";
2012 ret = bpf_load_program_xattr(&prg_attr, NULL, 0);
2014 obj->caps.global_data = 1;
2022 static int bpf_object__probe_btf_func(struct bpf_object *obj)
2024 const char strs[] = "\0int\0x\0a";
2025 /* void x(int a) {} */
2028 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
2029 /* FUNC_PROTO */ /* [2] */
2030 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
2031 BTF_PARAM_ENC(7, 1),
2032 /* FUNC x */ /* [3] */
2033 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0), 2),
2037 btf_fd = libbpf__load_raw_btf((char *)types, sizeof(types),
2038 strs, sizeof(strs));
2040 obj->caps.btf_func = 1;
2048 static int bpf_object__probe_btf_datasec(struct bpf_object *obj)
2050 const char strs[] = "\0x\0.data";
2054 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
2055 /* VAR x */ /* [2] */
2056 BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
2058 /* DATASEC val */ /* [3] */
2059 BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC, 0, 1), 4),
2060 BTF_VAR_SECINFO_ENC(2, 0, 4),
2064 btf_fd = libbpf__load_raw_btf((char *)types, sizeof(types),
2065 strs, sizeof(strs));
2067 obj->caps.btf_datasec = 1;
2076 bpf_object__probe_caps(struct bpf_object *obj)
2078 int (*probe_fn[])(struct bpf_object *obj) = {
2079 bpf_object__probe_name,
2080 bpf_object__probe_global_data,
2081 bpf_object__probe_btf_func,
2082 bpf_object__probe_btf_datasec,
2086 for (i = 0; i < ARRAY_SIZE(probe_fn); i++) {
2087 ret = probe_fn[i](obj);
2089 pr_debug("Probe #%d failed with %d.\n", i, ret);
2096 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
2098 char *cp, errmsg[STRERR_BUFSIZE];
2102 /* Nothing to do here since kernel already zero-initializes .bss map. */
2103 if (map->libbpf_type == LIBBPF_MAP_BSS)
2106 data = map->libbpf_type == LIBBPF_MAP_DATA ?
2107 obj->sections.data : obj->sections.rodata;
2109 err = bpf_map_update_elem(map->fd, &zero, data, 0);
2110 /* Freeze .rodata map as read-only from syscall side. */
2111 if (!err && map->libbpf_type == LIBBPF_MAP_RODATA) {
2112 err = bpf_map_freeze(map->fd);
2114 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
2115 pr_warning("Error freezing map(%s) as read-only: %s\n",
2124 bpf_object__create_maps(struct bpf_object *obj)
2126 struct bpf_create_map_attr create_attr = {};
2131 for (i = 0; i < obj->nr_maps; i++) {
2132 struct bpf_map *map = &obj->maps[i];
2133 struct bpf_map_def *def = &map->def;
2134 char *cp, errmsg[STRERR_BUFSIZE];
2135 int *pfd = &map->fd;
2138 pr_debug("skip map create (preset) %s: fd=%d\n",
2139 map->name, map->fd);
2144 create_attr.name = map->name;
2145 create_attr.map_ifindex = map->map_ifindex;
2146 create_attr.map_type = def->type;
2147 create_attr.map_flags = def->map_flags;
2148 create_attr.key_size = def->key_size;
2149 create_attr.value_size = def->value_size;
2150 if (def->type == BPF_MAP_TYPE_PERF_EVENT_ARRAY &&
2151 !def->max_entries) {
2153 nr_cpus = libbpf_num_possible_cpus();
2155 pr_warning("failed to determine number of system CPUs: %d\n",
2160 pr_debug("map '%s': setting size to %d\n",
2161 map->name, nr_cpus);
2162 create_attr.max_entries = nr_cpus;
2164 create_attr.max_entries = def->max_entries;
2166 create_attr.btf_fd = 0;
2167 create_attr.btf_key_type_id = 0;
2168 create_attr.btf_value_type_id = 0;
2169 if (bpf_map_type__is_map_in_map(def->type) &&
2170 map->inner_map_fd >= 0)
2171 create_attr.inner_map_fd = map->inner_map_fd;
2173 if (obj->btf && !bpf_map_find_btf_info(obj, map)) {
2174 create_attr.btf_fd = btf__fd(obj->btf);
2175 create_attr.btf_key_type_id = map->btf_key_type_id;
2176 create_attr.btf_value_type_id = map->btf_value_type_id;
2179 *pfd = bpf_create_map_xattr(&create_attr);
2180 if (*pfd < 0 && (create_attr.btf_key_type_id ||
2181 create_attr.btf_value_type_id)) {
2183 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
2184 pr_warning("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
2185 map->name, cp, err);
2186 create_attr.btf_fd = 0;
2187 create_attr.btf_key_type_id = 0;
2188 create_attr.btf_value_type_id = 0;
2189 map->btf_key_type_id = 0;
2190 map->btf_value_type_id = 0;
2191 *pfd = bpf_create_map_xattr(&create_attr);
2199 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
2200 pr_warning("failed to create map (name: '%s'): %s(%d)\n",
2201 map->name, cp, err);
2202 for (j = 0; j < i; j++)
2203 zclose(obj->maps[j].fd);
2207 if (bpf_map__is_internal(map)) {
2208 err = bpf_object__populate_internal_map(obj, map);
2215 pr_debug("created map %s: fd=%d\n", map->name, *pfd);
2222 check_btf_ext_reloc_err(struct bpf_program *prog, int err,
2223 void *btf_prog_info, const char *info_name)
2225 if (err != -ENOENT) {
2226 pr_warning("Error in loading %s for sec %s.\n",
2227 info_name, prog->section_name);
2231 /* err == -ENOENT (i.e. prog->section_name not found in btf_ext) */
2233 if (btf_prog_info) {
2235 * Some info has already been found but has problem
2236 * in the last btf_ext reloc. Must have to error out.
2238 pr_warning("Error in relocating %s for sec %s.\n",
2239 info_name, prog->section_name);
2243 /* Have problem loading the very first info. Ignore the rest. */
2244 pr_warning("Cannot find %s for main program sec %s. Ignore all %s.\n",
2245 info_name, prog->section_name, info_name);
2250 bpf_program_reloc_btf_ext(struct bpf_program *prog, struct bpf_object *obj,
2251 const char *section_name, __u32 insn_offset)
2255 if (!insn_offset || prog->func_info) {
2257 * !insn_offset => main program
2259 * For sub prog, the main program's func_info has to
2260 * be loaded first (i.e. prog->func_info != NULL)
2262 err = btf_ext__reloc_func_info(obj->btf, obj->btf_ext,
2263 section_name, insn_offset,
2265 &prog->func_info_cnt);
2267 return check_btf_ext_reloc_err(prog, err,
2271 prog->func_info_rec_size = btf_ext__func_info_rec_size(obj->btf_ext);
2274 if (!insn_offset || prog->line_info) {
2275 err = btf_ext__reloc_line_info(obj->btf, obj->btf_ext,
2276 section_name, insn_offset,
2278 &prog->line_info_cnt);
2280 return check_btf_ext_reloc_err(prog, err,
2284 prog->line_info_rec_size = btf_ext__line_info_rec_size(obj->btf_ext);
2288 prog->btf_fd = btf__fd(obj->btf);
2293 #define BPF_CORE_SPEC_MAX_LEN 64
2295 /* represents BPF CO-RE field or array element accessor */
2296 struct bpf_core_accessor {
2297 __u32 type_id; /* struct/union type or array element type */
2298 __u32 idx; /* field index or array index */
2299 const char *name; /* field name or NULL for array accessor */
2302 struct bpf_core_spec {
2303 const struct btf *btf;
2304 /* high-level spec: named fields and array indices only */
2305 struct bpf_core_accessor spec[BPF_CORE_SPEC_MAX_LEN];
2306 /* high-level spec length */
2308 /* raw, low-level spec: 1-to-1 with accessor spec string */
2309 int raw_spec[BPF_CORE_SPEC_MAX_LEN];
2310 /* raw spec length */
2312 /* field byte offset represented by spec */
2316 static bool str_is_empty(const char *s)
2322 * Turn bpf_offset_reloc into a low- and high-level spec representation,
2323 * validating correctness along the way, as well as calculating resulting
2324 * field offset (in bytes), specified by accessor string. Low-level spec
2325 * captures every single level of nestedness, including traversing anonymous
2326 * struct/union members. High-level one only captures semantically meaningful
2327 * "turning points": named fields and array indicies.
2328 * E.g., for this case:
2331 * int __unimportant;
2339 * struct sample *s = ...;
2341 * int x = &s->a[3]; // access string = '0:1:2:3'
2343 * Low-level spec has 1:1 mapping with each element of access string (it's
2344 * just a parsed access string representation): [0, 1, 2, 3].
2346 * High-level spec will capture only 3 points:
2347 * - intial zero-index access by pointer (&s->... is the same as &s[0]...);
2348 * - field 'a' access (corresponds to '2' in low-level spec);
2349 * - array element #3 access (corresponds to '3' in low-level spec).
2352 static int bpf_core_spec_parse(const struct btf *btf,
2354 const char *spec_str,
2355 struct bpf_core_spec *spec)
2357 int access_idx, parsed_len, i;
2358 const struct btf_type *t;
2363 if (str_is_empty(spec_str) || *spec_str == ':')
2366 memset(spec, 0, sizeof(*spec));
2369 /* parse spec_str="0:1:2:3:4" into array raw_spec=[0, 1, 2, 3, 4] */
2371 if (*spec_str == ':')
2373 if (sscanf(spec_str, "%d%n", &access_idx, &parsed_len) != 1)
2375 if (spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
2377 spec_str += parsed_len;
2378 spec->raw_spec[spec->raw_len++] = access_idx;
2381 if (spec->raw_len == 0)
2384 /* first spec value is always reloc type array index */
2385 t = skip_mods_and_typedefs(btf, type_id, &id);
2389 access_idx = spec->raw_spec[0];
2390 spec->spec[0].type_id = id;
2391 spec->spec[0].idx = access_idx;
2394 sz = btf__resolve_size(btf, id);
2397 spec->offset = access_idx * sz;
2399 for (i = 1; i < spec->raw_len; i++) {
2400 t = skip_mods_and_typedefs(btf, id, &id);
2404 access_idx = spec->raw_spec[i];
2406 if (btf_is_composite(t)) {
2407 const struct btf_member *m;
2410 if (access_idx >= btf_vlen(t))
2412 if (btf_member_bitfield_size(t, access_idx))
2415 offset = btf_member_bit_offset(t, access_idx);
2418 spec->offset += offset / 8;
2420 m = btf_members(t) + access_idx;
2422 name = btf__name_by_offset(btf, m->name_off);
2423 if (str_is_empty(name))
2426 spec->spec[spec->len].type_id = id;
2427 spec->spec[spec->len].idx = access_idx;
2428 spec->spec[spec->len].name = name;
2433 } else if (btf_is_array(t)) {
2434 const struct btf_array *a = btf_array(t);
2436 t = skip_mods_and_typedefs(btf, a->type, &id);
2437 if (!t || access_idx >= a->nelems)
2440 spec->spec[spec->len].type_id = id;
2441 spec->spec[spec->len].idx = access_idx;
2444 sz = btf__resolve_size(btf, id);
2447 spec->offset += access_idx * sz;
2449 pr_warning("relo for [%u] %s (at idx %d) captures type [%d] of unexpected kind %d\n",
2450 type_id, spec_str, i, id, btf_kind(t));
2458 static bool bpf_core_is_flavor_sep(const char *s)
2460 /* check X___Y name pattern, where X and Y are not underscores */
2461 return s[0] != '_' && /* X */
2462 s[1] == '_' && s[2] == '_' && s[3] == '_' && /* ___ */
2463 s[4] != '_'; /* Y */
2466 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
2467 * before last triple underscore. Struct name part after last triple
2468 * underscore is ignored by BPF CO-RE relocation during relocation matching.
2470 static size_t bpf_core_essential_name_len(const char *name)
2472 size_t n = strlen(name);
2475 for (i = n - 5; i >= 0; i--) {
2476 if (bpf_core_is_flavor_sep(name + i))
2482 /* dynamically sized list of type IDs */
2488 static void bpf_core_free_cands(struct ids_vec *cand_ids)
2490 free(cand_ids->data);
2494 static struct ids_vec *bpf_core_find_cands(const struct btf *local_btf,
2495 __u32 local_type_id,
2496 const struct btf *targ_btf)
2498 size_t local_essent_len, targ_essent_len;
2499 const char *local_name, *targ_name;
2500 const struct btf_type *t;
2501 struct ids_vec *cand_ids;
2505 t = btf__type_by_id(local_btf, local_type_id);
2507 return ERR_PTR(-EINVAL);
2509 local_name = btf__name_by_offset(local_btf, t->name_off);
2510 if (str_is_empty(local_name))
2511 return ERR_PTR(-EINVAL);
2512 local_essent_len = bpf_core_essential_name_len(local_name);
2514 cand_ids = calloc(1, sizeof(*cand_ids));
2516 return ERR_PTR(-ENOMEM);
2518 n = btf__get_nr_types(targ_btf);
2519 for (i = 1; i <= n; i++) {
2520 t = btf__type_by_id(targ_btf, i);
2521 targ_name = btf__name_by_offset(targ_btf, t->name_off);
2522 if (str_is_empty(targ_name))
2525 targ_essent_len = bpf_core_essential_name_len(targ_name);
2526 if (targ_essent_len != local_essent_len)
2529 if (strncmp(local_name, targ_name, local_essent_len) == 0) {
2530 pr_debug("[%d] %s: found candidate [%d] %s\n",
2531 local_type_id, local_name, i, targ_name);
2532 new_ids = realloc(cand_ids->data, cand_ids->len + 1);
2537 cand_ids->data = new_ids;
2538 cand_ids->data[cand_ids->len++] = i;
2543 bpf_core_free_cands(cand_ids);
2544 return ERR_PTR(err);
2547 /* Check two types for compatibility, skipping const/volatile/restrict and
2548 * typedefs, to ensure we are relocating offset to the compatible entities:
2549 * - any two STRUCTs/UNIONs are compatible and can be mixed;
2550 * - any two FWDs are compatible;
2551 * - any two PTRs are always compatible;
2552 * - for ENUMs, check sizes, names are ignored;
2553 * - for INT, size and bitness should match, signedness is ignored;
2554 * - for ARRAY, dimensionality is ignored, element types are checked for
2555 * compatibility recursively;
2556 * - everything else shouldn't be ever a target of relocation.
2557 * These rules are not set in stone and probably will be adjusted as we get
2558 * more experience with using BPF CO-RE relocations.
2560 static int bpf_core_fields_are_compat(const struct btf *local_btf,
2562 const struct btf *targ_btf,
2565 const struct btf_type *local_type, *targ_type;
2568 local_type = skip_mods_and_typedefs(local_btf, local_id, &local_id);
2569 targ_type = skip_mods_and_typedefs(targ_btf, targ_id, &targ_id);
2570 if (!local_type || !targ_type)
2573 if (btf_is_composite(local_type) && btf_is_composite(targ_type))
2575 if (btf_kind(local_type) != btf_kind(targ_type))
2578 switch (btf_kind(local_type)) {
2583 return local_type->size == targ_type->size;
2585 return btf_int_offset(local_type) == 0 &&
2586 btf_int_offset(targ_type) == 0 &&
2587 local_type->size == targ_type->size &&
2588 btf_int_bits(local_type) == btf_int_bits(targ_type);
2589 case BTF_KIND_ARRAY:
2590 local_id = btf_array(local_type)->type;
2591 targ_id = btf_array(targ_type)->type;
2594 pr_warning("unexpected kind %d relocated, local [%d], target [%d]\n",
2595 btf_kind(local_type), local_id, targ_id);
2601 * Given single high-level named field accessor in local type, find
2602 * corresponding high-level accessor for a target type. Along the way,
2603 * maintain low-level spec for target as well. Also keep updating target
2606 * Searching is performed through recursive exhaustive enumeration of all
2607 * fields of a struct/union. If there are any anonymous (embedded)
2608 * structs/unions, they are recursively searched as well. If field with
2609 * desired name is found, check compatibility between local and target types,
2610 * before returning result.
2612 * 1 is returned, if field is found.
2613 * 0 is returned if no compatible field is found.
2614 * <0 is returned on error.
2616 static int bpf_core_match_member(const struct btf *local_btf,
2617 const struct bpf_core_accessor *local_acc,
2618 const struct btf *targ_btf,
2620 struct bpf_core_spec *spec,
2621 __u32 *next_targ_id)
2623 const struct btf_type *local_type, *targ_type;
2624 const struct btf_member *local_member, *m;
2625 const char *local_name, *targ_name;
2629 targ_type = skip_mods_and_typedefs(targ_btf, targ_id, &targ_id);
2632 if (!btf_is_composite(targ_type))
2635 local_id = local_acc->type_id;
2636 local_type = btf__type_by_id(local_btf, local_id);
2637 local_member = btf_members(local_type) + local_acc->idx;
2638 local_name = btf__name_by_offset(local_btf, local_member->name_off);
2640 n = btf_vlen(targ_type);
2641 m = btf_members(targ_type);
2642 for (i = 0; i < n; i++, m++) {
2645 /* bitfield relocations not supported */
2646 if (btf_member_bitfield_size(targ_type, i))
2648 offset = btf_member_bit_offset(targ_type, i);
2652 /* too deep struct/union/array nesting */
2653 if (spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
2656 /* speculate this member will be the good one */
2657 spec->offset += offset / 8;
2658 spec->raw_spec[spec->raw_len++] = i;
2660 targ_name = btf__name_by_offset(targ_btf, m->name_off);
2661 if (str_is_empty(targ_name)) {
2662 /* embedded struct/union, we need to go deeper */
2663 found = bpf_core_match_member(local_btf, local_acc,
2665 spec, next_targ_id);
2666 if (found) /* either found or error */
2668 } else if (strcmp(local_name, targ_name) == 0) {
2669 /* matching named field */
2670 struct bpf_core_accessor *targ_acc;
2672 targ_acc = &spec->spec[spec->len++];
2673 targ_acc->type_id = targ_id;
2675 targ_acc->name = targ_name;
2677 *next_targ_id = m->type;
2678 found = bpf_core_fields_are_compat(local_btf,
2682 spec->len--; /* pop accessor */
2685 /* member turned out not to be what we looked for */
2686 spec->offset -= offset / 8;
2694 * Try to match local spec to a target type and, if successful, produce full
2695 * target spec (high-level, low-level + offset).
2697 static int bpf_core_spec_match(struct bpf_core_spec *local_spec,
2698 const struct btf *targ_btf, __u32 targ_id,
2699 struct bpf_core_spec *targ_spec)
2701 const struct btf_type *targ_type;
2702 const struct bpf_core_accessor *local_acc;
2703 struct bpf_core_accessor *targ_acc;
2706 memset(targ_spec, 0, sizeof(*targ_spec));
2707 targ_spec->btf = targ_btf;
2709 local_acc = &local_spec->spec[0];
2710 targ_acc = &targ_spec->spec[0];
2712 for (i = 0; i < local_spec->len; i++, local_acc++, targ_acc++) {
2713 targ_type = skip_mods_and_typedefs(targ_spec->btf, targ_id,
2718 if (local_acc->name) {
2719 matched = bpf_core_match_member(local_spec->btf,
2722 targ_spec, &targ_id);
2726 /* for i=0, targ_id is already treated as array element
2727 * type (because it's the original struct), for others
2728 * we should find array element type first
2731 const struct btf_array *a;
2733 if (!btf_is_array(targ_type))
2736 a = btf_array(targ_type);
2737 if (local_acc->idx >= a->nelems)
2739 if (!skip_mods_and_typedefs(targ_btf, a->type,
2744 /* too deep struct/union/array nesting */
2745 if (targ_spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
2748 targ_acc->type_id = targ_id;
2749 targ_acc->idx = local_acc->idx;
2750 targ_acc->name = NULL;
2752 targ_spec->raw_spec[targ_spec->raw_len] = targ_acc->idx;
2753 targ_spec->raw_len++;
2755 sz = btf__resolve_size(targ_btf, targ_id);
2758 targ_spec->offset += local_acc->idx * sz;
2766 * Patch relocatable BPF instruction.
2767 * Expected insn->imm value is provided for validation, as well as the new
2770 * Currently three kinds of BPF instructions are supported:
2771 * 1. rX = <imm> (assignment with immediate operand);
2772 * 2. rX += <imm> (arithmetic operations with immediate operand);
2773 * 3. *(rX) = <imm> (indirect memory assignment with immediate operand).
2775 * If actual insn->imm value is wrong, bail out.
2777 static int bpf_core_reloc_insn(struct bpf_program *prog, int insn_off,
2778 __u32 orig_off, __u32 new_off)
2780 struct bpf_insn *insn;
2784 if (insn_off % sizeof(struct bpf_insn))
2786 insn_idx = insn_off / sizeof(struct bpf_insn);
2788 insn = &prog->insns[insn_idx];
2789 class = BPF_CLASS(insn->code);
2791 if (class == BPF_ALU || class == BPF_ALU64) {
2792 if (BPF_SRC(insn->code) != BPF_K)
2794 if (insn->imm != orig_off)
2796 insn->imm = new_off;
2797 pr_debug("prog '%s': patched insn #%d (ALU/ALU64) imm %d -> %d\n",
2798 bpf_program__title(prog, false),
2799 insn_idx, orig_off, new_off);
2801 pr_warning("prog '%s': trying to relocate unrecognized insn #%d, code:%x, src:%x, dst:%x, off:%x, imm:%x\n",
2802 bpf_program__title(prog, false),
2803 insn_idx, insn->code, insn->src_reg, insn->dst_reg,
2804 insn->off, insn->imm);
2811 * Probe few well-known locations for vmlinux kernel image and try to load BTF
2812 * data out of it to use for target BTF.
2814 static struct btf *bpf_core_find_kernel_btf(void)
2816 const char *locations[] = {
2817 "/lib/modules/%1$s/vmlinux-%1$s",
2818 "/usr/lib/modules/%1$s/kernel/vmlinux",
2820 char path[PATH_MAX + 1];
2827 for (i = 0; i < ARRAY_SIZE(locations); i++) {
2828 snprintf(path, PATH_MAX, locations[i], buf.release);
2830 if (access(path, R_OK))
2833 btf = btf__parse_elf(path, NULL);
2834 pr_debug("kernel BTF load from '%s': %ld\n",
2835 path, PTR_ERR(btf));
2842 pr_warning("failed to find valid kernel BTF\n");
2843 return ERR_PTR(-ESRCH);
2846 /* Output spec definition in the format:
2847 * [<type-id>] (<type-name>) + <raw-spec> => <offset>@<spec>,
2848 * where <spec> is a C-syntax view of recorded field access, e.g.: x.a[3].b
2850 static void bpf_core_dump_spec(int level, const struct bpf_core_spec *spec)
2852 const struct btf_type *t;
2857 type_id = spec->spec[0].type_id;
2858 t = btf__type_by_id(spec->btf, type_id);
2859 s = btf__name_by_offset(spec->btf, t->name_off);
2860 libbpf_print(level, "[%u] %s + ", type_id, s);
2862 for (i = 0; i < spec->raw_len; i++)
2863 libbpf_print(level, "%d%s", spec->raw_spec[i],
2864 i == spec->raw_len - 1 ? " => " : ":");
2866 libbpf_print(level, "%u @ &x", spec->offset);
2868 for (i = 0; i < spec->len; i++) {
2869 if (spec->spec[i].name)
2870 libbpf_print(level, ".%s", spec->spec[i].name);
2872 libbpf_print(level, "[%u]", spec->spec[i].idx);
2877 static size_t bpf_core_hash_fn(const void *key, void *ctx)
2882 static bool bpf_core_equal_fn(const void *k1, const void *k2, void *ctx)
2887 static void *u32_as_hash_key(__u32 x)
2889 return (void *)(uintptr_t)x;
2893 * CO-RE relocate single instruction.
2895 * The outline and important points of the algorithm:
2896 * 1. For given local type, find corresponding candidate target types.
2897 * Candidate type is a type with the same "essential" name, ignoring
2898 * everything after last triple underscore (___). E.g., `sample`,
2899 * `sample___flavor_one`, `sample___flavor_another_one`, are all candidates
2900 * for each other. Names with triple underscore are referred to as
2901 * "flavors" and are useful, among other things, to allow to
2902 * specify/support incompatible variations of the same kernel struct, which
2903 * might differ between different kernel versions and/or build
2906 * N.B. Struct "flavors" could be generated by bpftool's BTF-to-C
2907 * converter, when deduplicated BTF of a kernel still contains more than
2908 * one different types with the same name. In that case, ___2, ___3, etc
2909 * are appended starting from second name conflict. But start flavors are
2910 * also useful to be defined "locally", in BPF program, to extract same
2911 * data from incompatible changes between different kernel
2912 * versions/configurations. For instance, to handle field renames between
2913 * kernel versions, one can use two flavors of the struct name with the
2914 * same common name and use conditional relocations to extract that field,
2915 * depending on target kernel version.
2916 * 2. For each candidate type, try to match local specification to this
2917 * candidate target type. Matching involves finding corresponding
2918 * high-level spec accessors, meaning that all named fields should match,
2919 * as well as all array accesses should be within the actual bounds. Also,
2920 * types should be compatible (see bpf_core_fields_are_compat for details).
2921 * 3. It is supported and expected that there might be multiple flavors
2922 * matching the spec. As long as all the specs resolve to the same set of
2923 * offsets across all candidates, there is not error. If there is any
2924 * ambiguity, CO-RE relocation will fail. This is necessary to accomodate
2925 * imprefection of BTF deduplication, which can cause slight duplication of
2926 * the same BTF type, if some directly or indirectly referenced (by
2927 * pointer) type gets resolved to different actual types in different
2928 * object files. If such situation occurs, deduplicated BTF will end up
2929 * with two (or more) structurally identical types, which differ only in
2930 * types they refer to through pointer. This should be OK in most cases and
2932 * 4. Candidate types search is performed by linearly scanning through all
2933 * types in target BTF. It is anticipated that this is overall more
2934 * efficient memory-wise and not significantly worse (if not better)
2935 * CPU-wise compared to prebuilding a map from all local type names to
2936 * a list of candidate type names. It's also sped up by caching resolved
2937 * list of matching candidates per each local "root" type ID, that has at
2938 * least one bpf_offset_reloc associated with it. This list is shared
2939 * between multiple relocations for the same type ID and is updated as some
2940 * of the candidates are pruned due to structural incompatibility.
2942 static int bpf_core_reloc_offset(struct bpf_program *prog,
2943 const struct bpf_offset_reloc *relo,
2945 const struct btf *local_btf,
2946 const struct btf *targ_btf,
2947 struct hashmap *cand_cache)
2949 const char *prog_name = bpf_program__title(prog, false);
2950 struct bpf_core_spec local_spec, cand_spec, targ_spec;
2951 const void *type_key = u32_as_hash_key(relo->type_id);
2952 const struct btf_type *local_type, *cand_type;
2953 const char *local_name, *cand_name;
2954 struct ids_vec *cand_ids;
2955 __u32 local_id, cand_id;
2956 const char *spec_str;
2959 local_id = relo->type_id;
2960 local_type = btf__type_by_id(local_btf, local_id);
2964 local_name = btf__name_by_offset(local_btf, local_type->name_off);
2965 if (str_is_empty(local_name))
2968 spec_str = btf__name_by_offset(local_btf, relo->access_str_off);
2969 if (str_is_empty(spec_str))
2972 err = bpf_core_spec_parse(local_btf, local_id, spec_str, &local_spec);
2974 pr_warning("prog '%s': relo #%d: parsing [%d] %s + %s failed: %d\n",
2975 prog_name, relo_idx, local_id, local_name, spec_str,
2980 pr_debug("prog '%s': relo #%d: spec is ", prog_name, relo_idx);
2981 bpf_core_dump_spec(LIBBPF_DEBUG, &local_spec);
2982 libbpf_print(LIBBPF_DEBUG, "\n");
2984 if (!hashmap__find(cand_cache, type_key, (void **)&cand_ids)) {
2985 cand_ids = bpf_core_find_cands(local_btf, local_id, targ_btf);
2986 if (IS_ERR(cand_ids)) {
2987 pr_warning("prog '%s': relo #%d: target candidate search failed for [%d] %s: %ld",
2988 prog_name, relo_idx, local_id, local_name,
2990 return PTR_ERR(cand_ids);
2992 err = hashmap__set(cand_cache, type_key, cand_ids, NULL, NULL);
2994 bpf_core_free_cands(cand_ids);
2999 for (i = 0, j = 0; i < cand_ids->len; i++) {
3000 cand_id = cand_ids->data[i];
3001 cand_type = btf__type_by_id(targ_btf, cand_id);
3002 cand_name = btf__name_by_offset(targ_btf, cand_type->name_off);
3004 err = bpf_core_spec_match(&local_spec, targ_btf,
3005 cand_id, &cand_spec);
3006 pr_debug("prog '%s': relo #%d: matching candidate #%d %s against spec ",
3007 prog_name, relo_idx, i, cand_name);
3008 bpf_core_dump_spec(LIBBPF_DEBUG, &cand_spec);
3009 libbpf_print(LIBBPF_DEBUG, ": %d\n", err);
3011 pr_warning("prog '%s': relo #%d: matching error: %d\n",
3012 prog_name, relo_idx, err);
3019 targ_spec = cand_spec;
3020 } else if (cand_spec.offset != targ_spec.offset) {
3021 /* if there are many candidates, they should all
3022 * resolve to the same offset
3024 pr_warning("prog '%s': relo #%d: offset ambiguity: %u != %u\n",
3025 prog_name, relo_idx, cand_spec.offset,
3030 cand_ids->data[j++] = cand_spec.spec[0].type_id;
3034 if (cand_ids->len == 0) {
3035 pr_warning("prog '%s': relo #%d: no matching targets found for [%d] %s + %s\n",
3036 prog_name, relo_idx, local_id, local_name, spec_str);
3040 err = bpf_core_reloc_insn(prog, relo->insn_off,
3041 local_spec.offset, targ_spec.offset);
3043 pr_warning("prog '%s': relo #%d: failed to patch insn at offset %d: %d\n",
3044 prog_name, relo_idx, relo->insn_off, err);
3052 bpf_core_reloc_offsets(struct bpf_object *obj, const char *targ_btf_path)
3054 const struct btf_ext_info_sec *sec;
3055 const struct bpf_offset_reloc *rec;
3056 const struct btf_ext_info *seg;
3057 struct hashmap_entry *entry;
3058 struct hashmap *cand_cache = NULL;
3059 struct bpf_program *prog;
3060 struct btf *targ_btf;
3061 const char *sec_name;
3065 targ_btf = btf__parse_elf(targ_btf_path, NULL);
3067 targ_btf = bpf_core_find_kernel_btf();
3068 if (IS_ERR(targ_btf)) {
3069 pr_warning("failed to get target BTF: %ld\n",
3071 return PTR_ERR(targ_btf);
3074 cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
3075 if (IS_ERR(cand_cache)) {
3076 err = PTR_ERR(cand_cache);
3080 seg = &obj->btf_ext->offset_reloc_info;
3081 for_each_btf_ext_sec(seg, sec) {
3082 sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
3083 if (str_is_empty(sec_name)) {
3087 prog = bpf_object__find_program_by_title(obj, sec_name);
3089 pr_warning("failed to find program '%s' for CO-RE offset relocation\n",
3095 pr_debug("prog '%s': performing %d CO-RE offset relocs\n",
3096 sec_name, sec->num_info);
3098 for_each_btf_ext_rec(seg, sec, i, rec) {
3099 err = bpf_core_reloc_offset(prog, rec, i, obj->btf,
3100 targ_btf, cand_cache);
3102 pr_warning("prog '%s': relo #%d: failed to relocate: %d\n",
3110 btf__free(targ_btf);
3111 if (!IS_ERR_OR_NULL(cand_cache)) {
3112 hashmap__for_each_entry(cand_cache, entry, i) {
3113 bpf_core_free_cands(entry->value);
3115 hashmap__free(cand_cache);
3121 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
3125 if (obj->btf_ext->offset_reloc_info.len)
3126 err = bpf_core_reloc_offsets(obj, targ_btf_path);
3132 bpf_program__reloc_text(struct bpf_program *prog, struct bpf_object *obj,
3133 struct reloc_desc *relo)
3135 struct bpf_insn *insn, *new_insn;
3136 struct bpf_program *text;
3140 if (relo->type != RELO_CALL)
3141 return -LIBBPF_ERRNO__RELOC;
3143 if (prog->idx == obj->efile.text_shndx) {
3144 pr_warning("relo in .text insn %d into off %d\n",
3145 relo->insn_idx, relo->text_off);
3146 return -LIBBPF_ERRNO__RELOC;
3149 if (prog->main_prog_cnt == 0) {
3150 text = bpf_object__find_prog_by_idx(obj, obj->efile.text_shndx);
3152 pr_warning("no .text section found yet relo into text exist\n");
3153 return -LIBBPF_ERRNO__RELOC;
3155 new_cnt = prog->insns_cnt + text->insns_cnt;
3156 new_insn = reallocarray(prog->insns, new_cnt, sizeof(*insn));
3158 pr_warning("oom in prog realloc\n");
3163 err = bpf_program_reloc_btf_ext(prog, obj,
3170 memcpy(new_insn + prog->insns_cnt, text->insns,
3171 text->insns_cnt * sizeof(*insn));
3172 prog->insns = new_insn;
3173 prog->main_prog_cnt = prog->insns_cnt;
3174 prog->insns_cnt = new_cnt;
3175 pr_debug("added %zd insn from %s to prog %s\n",
3176 text->insns_cnt, text->section_name,
3177 prog->section_name);
3179 insn = &prog->insns[relo->insn_idx];
3180 insn->imm += prog->main_prog_cnt - relo->insn_idx;
3185 bpf_program__relocate(struct bpf_program *prog, struct bpf_object *obj)
3193 err = bpf_program_reloc_btf_ext(prog, obj,
3194 prog->section_name, 0);
3199 if (!prog->reloc_desc)
3202 for (i = 0; i < prog->nr_reloc; i++) {
3203 if (prog->reloc_desc[i].type == RELO_LD64 ||
3204 prog->reloc_desc[i].type == RELO_DATA) {
3205 bool relo_data = prog->reloc_desc[i].type == RELO_DATA;
3206 struct bpf_insn *insns = prog->insns;
3207 int insn_idx, map_idx;
3209 insn_idx = prog->reloc_desc[i].insn_idx;
3210 map_idx = prog->reloc_desc[i].map_idx;
3212 if (insn_idx + 1 >= (int)prog->insns_cnt) {
3213 pr_warning("relocation out of range: '%s'\n",
3214 prog->section_name);
3215 return -LIBBPF_ERRNO__RELOC;
3219 insns[insn_idx].src_reg = BPF_PSEUDO_MAP_FD;
3221 insns[insn_idx].src_reg = BPF_PSEUDO_MAP_VALUE;
3222 insns[insn_idx + 1].imm = insns[insn_idx].imm;
3224 insns[insn_idx].imm = obj->maps[map_idx].fd;
3225 } else if (prog->reloc_desc[i].type == RELO_CALL) {
3226 err = bpf_program__reloc_text(prog, obj,
3227 &prog->reloc_desc[i]);
3233 zfree(&prog->reloc_desc);
3239 bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
3241 struct bpf_program *prog;
3246 err = bpf_object__relocate_core(obj, targ_btf_path);
3248 pr_warning("failed to perform CO-RE relocations: %d\n",
3253 for (i = 0; i < obj->nr_programs; i++) {
3254 prog = &obj->programs[i];
3256 err = bpf_program__relocate(prog, obj);
3258 pr_warning("failed to relocate '%s'\n",
3259 prog->section_name);
3266 static int bpf_object__collect_reloc(struct bpf_object *obj)
3270 if (!obj_elf_valid(obj)) {
3271 pr_warning("Internal error: elf object is closed\n");
3272 return -LIBBPF_ERRNO__INTERNAL;
3275 for (i = 0; i < obj->efile.nr_reloc; i++) {
3276 GElf_Shdr *shdr = &obj->efile.reloc[i].shdr;
3277 Elf_Data *data = obj->efile.reloc[i].data;
3278 int idx = shdr->sh_info;
3279 struct bpf_program *prog;
3281 if (shdr->sh_type != SHT_REL) {
3282 pr_warning("internal error at %d\n", __LINE__);
3283 return -LIBBPF_ERRNO__INTERNAL;
3286 prog = bpf_object__find_prog_by_idx(obj, idx);
3288 pr_warning("relocation failed: no section(%d)\n", idx);
3289 return -LIBBPF_ERRNO__RELOC;
3292 err = bpf_program__collect_reloc(prog, shdr, data, obj);
3300 load_program(struct bpf_program *prog, struct bpf_insn *insns, int insns_cnt,
3301 char *license, __u32 kern_version, int *pfd)
3303 struct bpf_load_program_attr load_attr;
3304 char *cp, errmsg[STRERR_BUFSIZE];
3305 int log_buf_size = BPF_LOG_BUF_SIZE;
3309 if (!insns || !insns_cnt)
3312 memset(&load_attr, 0, sizeof(struct bpf_load_program_attr));
3313 load_attr.prog_type = prog->type;
3314 load_attr.expected_attach_type = prog->expected_attach_type;
3315 if (prog->caps->name)
3316 load_attr.name = prog->name;
3317 load_attr.insns = insns;
3318 load_attr.insns_cnt = insns_cnt;
3319 load_attr.license = license;
3320 load_attr.kern_version = kern_version;
3321 load_attr.prog_ifindex = prog->prog_ifindex;
3322 load_attr.prog_btf_fd = prog->btf_fd >= 0 ? prog->btf_fd : 0;
3323 load_attr.func_info = prog->func_info;
3324 load_attr.func_info_rec_size = prog->func_info_rec_size;
3325 load_attr.func_info_cnt = prog->func_info_cnt;
3326 load_attr.line_info = prog->line_info;
3327 load_attr.line_info_rec_size = prog->line_info_rec_size;
3328 load_attr.line_info_cnt = prog->line_info_cnt;
3329 load_attr.log_level = prog->log_level;
3330 load_attr.prog_flags = prog->prog_flags;
3333 log_buf = malloc(log_buf_size);
3335 pr_warning("Alloc log buffer for bpf loader error, continue without log\n");
3337 ret = bpf_load_program_xattr(&load_attr, log_buf, log_buf_size);
3340 if (load_attr.log_level)
3341 pr_debug("verifier log:\n%s", log_buf);
3347 if (errno == ENOSPC) {
3352 ret = -LIBBPF_ERRNO__LOAD;
3353 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
3354 pr_warning("load bpf program failed: %s\n", cp);
3356 if (log_buf && log_buf[0] != '\0') {
3357 ret = -LIBBPF_ERRNO__VERIFY;
3358 pr_warning("-- BEGIN DUMP LOG ---\n");
3359 pr_warning("\n%s\n", log_buf);
3360 pr_warning("-- END LOG --\n");
3361 } else if (load_attr.insns_cnt >= BPF_MAXINSNS) {
3362 pr_warning("Program too large (%zu insns), at most %d insns\n",
3363 load_attr.insns_cnt, BPF_MAXINSNS);
3364 ret = -LIBBPF_ERRNO__PROG2BIG;
3366 /* Wrong program type? */
3367 if (load_attr.prog_type != BPF_PROG_TYPE_KPROBE) {
3370 load_attr.prog_type = BPF_PROG_TYPE_KPROBE;
3371 load_attr.expected_attach_type = 0;
3372 fd = bpf_load_program_xattr(&load_attr, NULL, 0);
3375 ret = -LIBBPF_ERRNO__PROGTYPE;
3381 ret = -LIBBPF_ERRNO__KVER;
3390 bpf_program__load(struct bpf_program *prog,
3391 char *license, __u32 kern_version)
3395 if (prog->instances.nr < 0 || !prog->instances.fds) {
3396 if (prog->preprocessor) {
3397 pr_warning("Internal error: can't load program '%s'\n",
3398 prog->section_name);
3399 return -LIBBPF_ERRNO__INTERNAL;
3402 prog->instances.fds = malloc(sizeof(int));
3403 if (!prog->instances.fds) {
3404 pr_warning("Not enough memory for BPF fds\n");
3407 prog->instances.nr = 1;
3408 prog->instances.fds[0] = -1;
3411 if (!prog->preprocessor) {
3412 if (prog->instances.nr != 1) {
3413 pr_warning("Program '%s' is inconsistent: nr(%d) != 1\n",
3414 prog->section_name, prog->instances.nr);
3416 err = load_program(prog, prog->insns, prog->insns_cnt,
3417 license, kern_version, &fd);
3419 prog->instances.fds[0] = fd;
3423 for (i = 0; i < prog->instances.nr; i++) {
3424 struct bpf_prog_prep_result result;
3425 bpf_program_prep_t preprocessor = prog->preprocessor;
3427 memset(&result, 0, sizeof(result));
3428 err = preprocessor(prog, i, prog->insns,
3429 prog->insns_cnt, &result);
3431 pr_warning("Preprocessing the %dth instance of program '%s' failed\n",
3432 i, prog->section_name);
3436 if (!result.new_insn_ptr || !result.new_insn_cnt) {
3437 pr_debug("Skip loading the %dth instance of program '%s'\n",
3438 i, prog->section_name);
3439 prog->instances.fds[i] = -1;
3445 err = load_program(prog, result.new_insn_ptr,
3446 result.new_insn_cnt,
3447 license, kern_version, &fd);
3450 pr_warning("Loading the %dth instance of program '%s' failed\n",
3451 i, prog->section_name);
3457 prog->instances.fds[i] = fd;
3461 pr_warning("failed to load program '%s'\n",
3462 prog->section_name);
3463 zfree(&prog->insns);
3464 prog->insns_cnt = 0;
3468 static bool bpf_program__is_function_storage(const struct bpf_program *prog,
3469 const struct bpf_object *obj)
3471 return prog->idx == obj->efile.text_shndx && obj->has_pseudo_calls;
3475 bpf_object__load_progs(struct bpf_object *obj, int log_level)
3480 for (i = 0; i < obj->nr_programs; i++) {
3481 if (bpf_program__is_function_storage(&obj->programs[i], obj))
3483 obj->programs[i].log_level |= log_level;
3484 err = bpf_program__load(&obj->programs[i],
3493 static bool bpf_prog_type__needs_kver(enum bpf_prog_type type)
3496 case BPF_PROG_TYPE_SOCKET_FILTER:
3497 case BPF_PROG_TYPE_SCHED_CLS:
3498 case BPF_PROG_TYPE_SCHED_ACT:
3499 case BPF_PROG_TYPE_XDP:
3500 case BPF_PROG_TYPE_CGROUP_SKB:
3501 case BPF_PROG_TYPE_CGROUP_SOCK:
3502 case BPF_PROG_TYPE_LWT_IN:
3503 case BPF_PROG_TYPE_LWT_OUT:
3504 case BPF_PROG_TYPE_LWT_XMIT:
3505 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
3506 case BPF_PROG_TYPE_SOCK_OPS:
3507 case BPF_PROG_TYPE_SK_SKB:
3508 case BPF_PROG_TYPE_CGROUP_DEVICE:
3509 case BPF_PROG_TYPE_SK_MSG:
3510 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
3511 case BPF_PROG_TYPE_LIRC_MODE2:
3512 case BPF_PROG_TYPE_SK_REUSEPORT:
3513 case BPF_PROG_TYPE_FLOW_DISSECTOR:
3514 case BPF_PROG_TYPE_UNSPEC:
3515 case BPF_PROG_TYPE_TRACEPOINT:
3516 case BPF_PROG_TYPE_RAW_TRACEPOINT:
3517 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
3518 case BPF_PROG_TYPE_PERF_EVENT:
3519 case BPF_PROG_TYPE_CGROUP_SYSCTL:
3520 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3522 case BPF_PROG_TYPE_KPROBE:
3528 static int bpf_object__validate(struct bpf_object *obj, bool needs_kver)
3530 if (needs_kver && obj->kern_version == 0) {
3531 pr_warning("%s doesn't provide kernel version\n",
3533 return -LIBBPF_ERRNO__KVERSION;
3538 static struct bpf_object *
3539 __bpf_object__open(const char *path, void *obj_buf, size_t obj_buf_sz,
3540 bool needs_kver, int flags)
3542 struct bpf_object *obj;
3545 if (elf_version(EV_CURRENT) == EV_NONE) {
3546 pr_warning("failed to init libelf for %s\n", path);
3547 return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
3550 obj = bpf_object__new(path, obj_buf, obj_buf_sz);
3554 CHECK_ERR(bpf_object__elf_init(obj), err, out);
3555 CHECK_ERR(bpf_object__check_endianness(obj), err, out);
3556 CHECK_ERR(bpf_object__probe_caps(obj), err, out);
3557 CHECK_ERR(bpf_object__elf_collect(obj, flags), err, out);
3558 CHECK_ERR(bpf_object__collect_reloc(obj), err, out);
3559 CHECK_ERR(bpf_object__validate(obj, needs_kver), err, out);
3561 bpf_object__elf_finish(obj);
3564 bpf_object__close(obj);
3565 return ERR_PTR(err);
3568 struct bpf_object *__bpf_object__open_xattr(struct bpf_object_open_attr *attr,
3571 /* param validation */
3575 pr_debug("loading %s\n", attr->file);
3577 return __bpf_object__open(attr->file, NULL, 0,
3578 bpf_prog_type__needs_kver(attr->prog_type),
3582 struct bpf_object *bpf_object__open_xattr(struct bpf_object_open_attr *attr)
3584 return __bpf_object__open_xattr(attr, 0);
3587 struct bpf_object *bpf_object__open(const char *path)
3589 struct bpf_object_open_attr attr = {
3591 .prog_type = BPF_PROG_TYPE_UNSPEC,
3594 return bpf_object__open_xattr(&attr);
3597 struct bpf_object *bpf_object__open_buffer(void *obj_buf,
3603 /* param validation */
3604 if (!obj_buf || obj_buf_sz <= 0)
3608 snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
3609 (unsigned long)obj_buf,
3610 (unsigned long)obj_buf_sz);
3613 pr_debug("loading object '%s' from buffer\n", name);
3615 return __bpf_object__open(name, obj_buf, obj_buf_sz, true, true);
3618 int bpf_object__unload(struct bpf_object *obj)
3625 for (i = 0; i < obj->nr_maps; i++)
3626 zclose(obj->maps[i].fd);
3628 for (i = 0; i < obj->nr_programs; i++)
3629 bpf_program__unload(&obj->programs[i]);
3634 int bpf_object__load_xattr(struct bpf_object_load_attr *attr)
3636 struct bpf_object *obj;
3646 pr_warning("object should not be loaded twice\n");
3652 CHECK_ERR(bpf_object__create_maps(obj), err, out);
3653 CHECK_ERR(bpf_object__relocate(obj, attr->target_btf_path), err, out);
3654 CHECK_ERR(bpf_object__load_progs(obj, attr->log_level), err, out);
3658 bpf_object__unload(obj);
3659 pr_warning("failed to load object '%s'\n", obj->path);
3663 int bpf_object__load(struct bpf_object *obj)
3665 struct bpf_object_load_attr attr = {
3669 return bpf_object__load_xattr(&attr);
3672 static int check_path(const char *path)
3674 char *cp, errmsg[STRERR_BUFSIZE];
3675 struct statfs st_fs;
3682 dname = strdup(path);
3686 dir = dirname(dname);
3687 if (statfs(dir, &st_fs)) {
3688 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
3689 pr_warning("failed to statfs %s: %s\n", dir, cp);
3694 if (!err && st_fs.f_type != BPF_FS_MAGIC) {
3695 pr_warning("specified path %s is not on BPF FS\n", path);
3702 int bpf_program__pin_instance(struct bpf_program *prog, const char *path,
3705 char *cp, errmsg[STRERR_BUFSIZE];
3708 err = check_path(path);
3713 pr_warning("invalid program pointer\n");
3717 if (instance < 0 || instance >= prog->instances.nr) {
3718 pr_warning("invalid prog instance %d of prog %s (max %d)\n",
3719 instance, prog->section_name, prog->instances.nr);
3723 if (bpf_obj_pin(prog->instances.fds[instance], path)) {
3724 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
3725 pr_warning("failed to pin program: %s\n", cp);
3728 pr_debug("pinned program '%s'\n", path);
3733 int bpf_program__unpin_instance(struct bpf_program *prog, const char *path,
3738 err = check_path(path);
3743 pr_warning("invalid program pointer\n");
3747 if (instance < 0 || instance >= prog->instances.nr) {
3748 pr_warning("invalid prog instance %d of prog %s (max %d)\n",
3749 instance, prog->section_name, prog->instances.nr);
3756 pr_debug("unpinned program '%s'\n", path);
3761 static int make_dir(const char *path)
3763 char *cp, errmsg[STRERR_BUFSIZE];
3766 if (mkdir(path, 0700) && errno != EEXIST)
3770 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
3771 pr_warning("failed to mkdir %s: %s\n", path, cp);
3776 int bpf_program__pin(struct bpf_program *prog, const char *path)
3780 err = check_path(path);
3785 pr_warning("invalid program pointer\n");
3789 if (prog->instances.nr <= 0) {
3790 pr_warning("no instances of prog %s to pin\n",
3791 prog->section_name);
3795 if (prog->instances.nr == 1) {
3796 /* don't create subdirs when pinning single instance */
3797 return bpf_program__pin_instance(prog, path, 0);
3800 err = make_dir(path);
3804 for (i = 0; i < prog->instances.nr; i++) {
3808 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
3812 } else if (len >= PATH_MAX) {
3813 err = -ENAMETOOLONG;
3817 err = bpf_program__pin_instance(prog, buf, i);
3825 for (i = i - 1; i >= 0; i--) {
3829 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
3832 else if (len >= PATH_MAX)
3835 bpf_program__unpin_instance(prog, buf, i);
3843 int bpf_program__unpin(struct bpf_program *prog, const char *path)
3847 err = check_path(path);
3852 pr_warning("invalid program pointer\n");
3856 if (prog->instances.nr <= 0) {
3857 pr_warning("no instances of prog %s to pin\n",
3858 prog->section_name);
3862 if (prog->instances.nr == 1) {
3863 /* don't create subdirs when pinning single instance */
3864 return bpf_program__unpin_instance(prog, path, 0);
3867 for (i = 0; i < prog->instances.nr; i++) {
3871 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
3874 else if (len >= PATH_MAX)
3875 return -ENAMETOOLONG;
3877 err = bpf_program__unpin_instance(prog, buf, i);
3889 int bpf_map__pin(struct bpf_map *map, const char *path)
3891 char *cp, errmsg[STRERR_BUFSIZE];
3894 err = check_path(path);
3899 pr_warning("invalid map pointer\n");
3903 if (bpf_obj_pin(map->fd, path)) {
3904 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
3905 pr_warning("failed to pin map: %s\n", cp);
3909 pr_debug("pinned map '%s'\n", path);
3914 int bpf_map__unpin(struct bpf_map *map, const char *path)
3918 err = check_path(path);
3923 pr_warning("invalid map pointer\n");
3930 pr_debug("unpinned map '%s'\n", path);
3935 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
3937 struct bpf_map *map;
3944 pr_warning("object not yet loaded; load it first\n");
3948 err = make_dir(path);
3952 bpf_object__for_each_map(map, obj) {
3956 len = snprintf(buf, PATH_MAX, "%s/%s", path,
3957 bpf_map__name(map));
3960 goto err_unpin_maps;
3961 } else if (len >= PATH_MAX) {
3962 err = -ENAMETOOLONG;
3963 goto err_unpin_maps;
3966 err = bpf_map__pin(map, buf);
3968 goto err_unpin_maps;
3974 while ((map = bpf_map__prev(map, obj))) {
3978 len = snprintf(buf, PATH_MAX, "%s/%s", path,
3979 bpf_map__name(map));
3982 else if (len >= PATH_MAX)
3985 bpf_map__unpin(map, buf);
3991 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
3993 struct bpf_map *map;
3999 bpf_object__for_each_map(map, obj) {
4003 len = snprintf(buf, PATH_MAX, "%s/%s", path,
4004 bpf_map__name(map));
4007 else if (len >= PATH_MAX)
4008 return -ENAMETOOLONG;
4010 err = bpf_map__unpin(map, buf);
4018 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
4020 struct bpf_program *prog;
4027 pr_warning("object not yet loaded; load it first\n");
4031 err = make_dir(path);
4035 bpf_object__for_each_program(prog, obj) {
4039 len = snprintf(buf, PATH_MAX, "%s/%s", path,
4043 goto err_unpin_programs;
4044 } else if (len >= PATH_MAX) {
4045 err = -ENAMETOOLONG;
4046 goto err_unpin_programs;
4049 err = bpf_program__pin(prog, buf);
4051 goto err_unpin_programs;
4057 while ((prog = bpf_program__prev(prog, obj))) {
4061 len = snprintf(buf, PATH_MAX, "%s/%s", path,
4065 else if (len >= PATH_MAX)
4068 bpf_program__unpin(prog, buf);
4074 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
4076 struct bpf_program *prog;
4082 bpf_object__for_each_program(prog, obj) {
4086 len = snprintf(buf, PATH_MAX, "%s/%s", path,
4090 else if (len >= PATH_MAX)
4091 return -ENAMETOOLONG;
4093 err = bpf_program__unpin(prog, buf);
4101 int bpf_object__pin(struct bpf_object *obj, const char *path)
4105 err = bpf_object__pin_maps(obj, path);
4109 err = bpf_object__pin_programs(obj, path);
4111 bpf_object__unpin_maps(obj, path);
4118 void bpf_object__close(struct bpf_object *obj)
4125 if (obj->clear_priv)
4126 obj->clear_priv(obj, obj->priv);
4128 bpf_object__elf_finish(obj);
4129 bpf_object__unload(obj);
4130 btf__free(obj->btf);
4131 btf_ext__free(obj->btf_ext);
4133 for (i = 0; i < obj->nr_maps; i++) {
4134 zfree(&obj->maps[i].name);
4135 if (obj->maps[i].clear_priv)
4136 obj->maps[i].clear_priv(&obj->maps[i],
4138 obj->maps[i].priv = NULL;
4139 obj->maps[i].clear_priv = NULL;
4142 zfree(&obj->sections.rodata);
4143 zfree(&obj->sections.data);
4147 if (obj->programs && obj->nr_programs) {
4148 for (i = 0; i < obj->nr_programs; i++)
4149 bpf_program__exit(&obj->programs[i]);
4151 zfree(&obj->programs);
4153 list_del(&obj->list);
4158 bpf_object__next(struct bpf_object *prev)
4160 struct bpf_object *next;
4163 next = list_first_entry(&bpf_objects_list,
4167 next = list_next_entry(prev, list);
4169 /* Empty list is noticed here so don't need checking on entry. */
4170 if (&next->list == &bpf_objects_list)
4176 const char *bpf_object__name(const struct bpf_object *obj)
4178 return obj ? obj->path : ERR_PTR(-EINVAL);
4181 unsigned int bpf_object__kversion(const struct bpf_object *obj)
4183 return obj ? obj->kern_version : 0;
4186 struct btf *bpf_object__btf(const struct bpf_object *obj)
4188 return obj ? obj->btf : NULL;
4191 int bpf_object__btf_fd(const struct bpf_object *obj)
4193 return obj->btf ? btf__fd(obj->btf) : -1;
4196 int bpf_object__set_priv(struct bpf_object *obj, void *priv,
4197 bpf_object_clear_priv_t clear_priv)
4199 if (obj->priv && obj->clear_priv)
4200 obj->clear_priv(obj, obj->priv);
4203 obj->clear_priv = clear_priv;
4207 void *bpf_object__priv(const struct bpf_object *obj)
4209 return obj ? obj->priv : ERR_PTR(-EINVAL);
4212 static struct bpf_program *
4213 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
4216 size_t nr_programs = obj->nr_programs;
4223 /* Iter from the beginning */
4224 return forward ? &obj->programs[0] :
4225 &obj->programs[nr_programs - 1];
4227 if (p->obj != obj) {
4228 pr_warning("error: program handler doesn't match object\n");
4232 idx = (p - obj->programs) + (forward ? 1 : -1);
4233 if (idx >= obj->nr_programs || idx < 0)
4235 return &obj->programs[idx];
4238 struct bpf_program *
4239 bpf_program__next(struct bpf_program *prev, const struct bpf_object *obj)
4241 struct bpf_program *prog = prev;
4244 prog = __bpf_program__iter(prog, obj, true);
4245 } while (prog && bpf_program__is_function_storage(prog, obj));
4250 struct bpf_program *
4251 bpf_program__prev(struct bpf_program *next, const struct bpf_object *obj)
4253 struct bpf_program *prog = next;
4256 prog = __bpf_program__iter(prog, obj, false);
4257 } while (prog && bpf_program__is_function_storage(prog, obj));
4262 int bpf_program__set_priv(struct bpf_program *prog, void *priv,
4263 bpf_program_clear_priv_t clear_priv)
4265 if (prog->priv && prog->clear_priv)
4266 prog->clear_priv(prog, prog->priv);
4269 prog->clear_priv = clear_priv;
4273 void *bpf_program__priv(const struct bpf_program *prog)
4275 return prog ? prog->priv : ERR_PTR(-EINVAL);
4278 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
4280 prog->prog_ifindex = ifindex;
4283 const char *bpf_program__title(const struct bpf_program *prog, bool needs_copy)
4287 title = prog->section_name;
4289 title = strdup(title);
4291 pr_warning("failed to strdup program title\n");
4292 return ERR_PTR(-ENOMEM);
4299 int bpf_program__fd(const struct bpf_program *prog)
4301 return bpf_program__nth_fd(prog, 0);
4304 int bpf_program__set_prep(struct bpf_program *prog, int nr_instances,
4305 bpf_program_prep_t prep)
4309 if (nr_instances <= 0 || !prep)
4312 if (prog->instances.nr > 0 || prog->instances.fds) {
4313 pr_warning("Can't set pre-processor after loading\n");
4317 instances_fds = malloc(sizeof(int) * nr_instances);
4318 if (!instances_fds) {
4319 pr_warning("alloc memory failed for fds\n");
4323 /* fill all fd with -1 */
4324 memset(instances_fds, -1, sizeof(int) * nr_instances);
4326 prog->instances.nr = nr_instances;
4327 prog->instances.fds = instances_fds;
4328 prog->preprocessor = prep;
4332 int bpf_program__nth_fd(const struct bpf_program *prog, int n)
4339 if (n >= prog->instances.nr || n < 0) {
4340 pr_warning("Can't get the %dth fd from program %s: only %d instances\n",
4341 n, prog->section_name, prog->instances.nr);
4345 fd = prog->instances.fds[n];
4347 pr_warning("%dth instance of program '%s' is invalid\n",
4348 n, prog->section_name);
4355 void bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
4360 static bool bpf_program__is_type(const struct bpf_program *prog,
4361 enum bpf_prog_type type)
4363 return prog ? (prog->type == type) : false;
4366 #define BPF_PROG_TYPE_FNS(NAME, TYPE) \
4367 int bpf_program__set_##NAME(struct bpf_program *prog) \
4371 bpf_program__set_type(prog, TYPE); \
4375 bool bpf_program__is_##NAME(const struct bpf_program *prog) \
4377 return bpf_program__is_type(prog, TYPE); \
4380 BPF_PROG_TYPE_FNS(socket_filter, BPF_PROG_TYPE_SOCKET_FILTER);
4381 BPF_PROG_TYPE_FNS(kprobe, BPF_PROG_TYPE_KPROBE);
4382 BPF_PROG_TYPE_FNS(sched_cls, BPF_PROG_TYPE_SCHED_CLS);
4383 BPF_PROG_TYPE_FNS(sched_act, BPF_PROG_TYPE_SCHED_ACT);
4384 BPF_PROG_TYPE_FNS(tracepoint, BPF_PROG_TYPE_TRACEPOINT);
4385 BPF_PROG_TYPE_FNS(raw_tracepoint, BPF_PROG_TYPE_RAW_TRACEPOINT);
4386 BPF_PROG_TYPE_FNS(xdp, BPF_PROG_TYPE_XDP);
4387 BPF_PROG_TYPE_FNS(perf_event, BPF_PROG_TYPE_PERF_EVENT);
4389 void bpf_program__set_expected_attach_type(struct bpf_program *prog,
4390 enum bpf_attach_type type)
4392 prog->expected_attach_type = type;
4395 #define BPF_PROG_SEC_IMPL(string, ptype, eatype, is_attachable, atype) \
4396 { string, sizeof(string) - 1, ptype, eatype, is_attachable, atype }
4398 /* Programs that can NOT be attached. */
4399 #define BPF_PROG_SEC(string, ptype) BPF_PROG_SEC_IMPL(string, ptype, 0, 0, 0)
4401 /* Programs that can be attached. */
4402 #define BPF_APROG_SEC(string, ptype, atype) \
4403 BPF_PROG_SEC_IMPL(string, ptype, 0, 1, atype)
4405 /* Programs that must specify expected attach type at load time. */
4406 #define BPF_EAPROG_SEC(string, ptype, eatype) \
4407 BPF_PROG_SEC_IMPL(string, ptype, eatype, 1, eatype)
4409 /* Programs that can be attached but attach type can't be identified by section
4410 * name. Kept for backward compatibility.
4412 #define BPF_APROG_COMPAT(string, ptype) BPF_PROG_SEC(string, ptype)
4414 static const struct {
4417 enum bpf_prog_type prog_type;
4418 enum bpf_attach_type expected_attach_type;
4420 enum bpf_attach_type attach_type;
4421 } section_names[] = {
4422 BPF_PROG_SEC("socket", BPF_PROG_TYPE_SOCKET_FILTER),
4423 BPF_PROG_SEC("kprobe/", BPF_PROG_TYPE_KPROBE),
4424 BPF_PROG_SEC("kretprobe/", BPF_PROG_TYPE_KPROBE),
4425 BPF_PROG_SEC("classifier", BPF_PROG_TYPE_SCHED_CLS),
4426 BPF_PROG_SEC("action", BPF_PROG_TYPE_SCHED_ACT),
4427 BPF_PROG_SEC("tracepoint/", BPF_PROG_TYPE_TRACEPOINT),
4428 BPF_PROG_SEC("raw_tracepoint/", BPF_PROG_TYPE_RAW_TRACEPOINT),
4429 BPF_PROG_SEC("xdp", BPF_PROG_TYPE_XDP),
4430 BPF_PROG_SEC("perf_event", BPF_PROG_TYPE_PERF_EVENT),
4431 BPF_PROG_SEC("lwt_in", BPF_PROG_TYPE_LWT_IN),
4432 BPF_PROG_SEC("lwt_out", BPF_PROG_TYPE_LWT_OUT),
4433 BPF_PROG_SEC("lwt_xmit", BPF_PROG_TYPE_LWT_XMIT),
4434 BPF_PROG_SEC("lwt_seg6local", BPF_PROG_TYPE_LWT_SEG6LOCAL),
4435 BPF_APROG_SEC("cgroup_skb/ingress", BPF_PROG_TYPE_CGROUP_SKB,
4436 BPF_CGROUP_INET_INGRESS),
4437 BPF_APROG_SEC("cgroup_skb/egress", BPF_PROG_TYPE_CGROUP_SKB,
4438 BPF_CGROUP_INET_EGRESS),
4439 BPF_APROG_COMPAT("cgroup/skb", BPF_PROG_TYPE_CGROUP_SKB),
4440 BPF_APROG_SEC("cgroup/sock", BPF_PROG_TYPE_CGROUP_SOCK,
4441 BPF_CGROUP_INET_SOCK_CREATE),
4442 BPF_EAPROG_SEC("cgroup/post_bind4", BPF_PROG_TYPE_CGROUP_SOCK,
4443 BPF_CGROUP_INET4_POST_BIND),
4444 BPF_EAPROG_SEC("cgroup/post_bind6", BPF_PROG_TYPE_CGROUP_SOCK,
4445 BPF_CGROUP_INET6_POST_BIND),
4446 BPF_APROG_SEC("cgroup/dev", BPF_PROG_TYPE_CGROUP_DEVICE,
4448 BPF_APROG_SEC("sockops", BPF_PROG_TYPE_SOCK_OPS,
4449 BPF_CGROUP_SOCK_OPS),
4450 BPF_APROG_SEC("sk_skb/stream_parser", BPF_PROG_TYPE_SK_SKB,
4451 BPF_SK_SKB_STREAM_PARSER),
4452 BPF_APROG_SEC("sk_skb/stream_verdict", BPF_PROG_TYPE_SK_SKB,
4453 BPF_SK_SKB_STREAM_VERDICT),
4454 BPF_APROG_COMPAT("sk_skb", BPF_PROG_TYPE_SK_SKB),
4455 BPF_APROG_SEC("sk_msg", BPF_PROG_TYPE_SK_MSG,
4456 BPF_SK_MSG_VERDICT),
4457 BPF_APROG_SEC("lirc_mode2", BPF_PROG_TYPE_LIRC_MODE2,
4459 BPF_APROG_SEC("flow_dissector", BPF_PROG_TYPE_FLOW_DISSECTOR,
4460 BPF_FLOW_DISSECTOR),
4461 BPF_EAPROG_SEC("cgroup/bind4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
4462 BPF_CGROUP_INET4_BIND),
4463 BPF_EAPROG_SEC("cgroup/bind6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
4464 BPF_CGROUP_INET6_BIND),
4465 BPF_EAPROG_SEC("cgroup/connect4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
4466 BPF_CGROUP_INET4_CONNECT),
4467 BPF_EAPROG_SEC("cgroup/connect6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
4468 BPF_CGROUP_INET6_CONNECT),
4469 BPF_EAPROG_SEC("cgroup/sendmsg4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
4470 BPF_CGROUP_UDP4_SENDMSG),
4471 BPF_EAPROG_SEC("cgroup/sendmsg6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
4472 BPF_CGROUP_UDP6_SENDMSG),
4473 BPF_EAPROG_SEC("cgroup/recvmsg4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
4474 BPF_CGROUP_UDP4_RECVMSG),
4475 BPF_EAPROG_SEC("cgroup/recvmsg6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
4476 BPF_CGROUP_UDP6_RECVMSG),
4477 BPF_EAPROG_SEC("cgroup/sysctl", BPF_PROG_TYPE_CGROUP_SYSCTL,
4479 BPF_EAPROG_SEC("cgroup/getsockopt", BPF_PROG_TYPE_CGROUP_SOCKOPT,
4480 BPF_CGROUP_GETSOCKOPT),
4481 BPF_EAPROG_SEC("cgroup/setsockopt", BPF_PROG_TYPE_CGROUP_SOCKOPT,
4482 BPF_CGROUP_SETSOCKOPT),
4485 #undef BPF_PROG_SEC_IMPL
4487 #undef BPF_APROG_SEC
4488 #undef BPF_EAPROG_SEC
4489 #undef BPF_APROG_COMPAT
4491 #define MAX_TYPE_NAME_SIZE 32
4493 static char *libbpf_get_type_names(bool attach_type)
4495 int i, len = ARRAY_SIZE(section_names) * MAX_TYPE_NAME_SIZE;
4503 /* Forge string buf with all available names */
4504 for (i = 0; i < ARRAY_SIZE(section_names); i++) {
4505 if (attach_type && !section_names[i].is_attachable)
4508 if (strlen(buf) + strlen(section_names[i].sec) + 2 > len) {
4513 strcat(buf, section_names[i].sec);
4519 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
4520 enum bpf_attach_type *expected_attach_type)
4528 for (i = 0; i < ARRAY_SIZE(section_names); i++) {
4529 if (strncmp(name, section_names[i].sec, section_names[i].len))
4531 *prog_type = section_names[i].prog_type;
4532 *expected_attach_type = section_names[i].expected_attach_type;
4535 pr_warning("failed to guess program type based on ELF section name '%s'\n", name);
4536 type_names = libbpf_get_type_names(false);
4537 if (type_names != NULL) {
4538 pr_info("supported section(type) names are:%s\n", type_names);
4545 int libbpf_attach_type_by_name(const char *name,
4546 enum bpf_attach_type *attach_type)
4554 for (i = 0; i < ARRAY_SIZE(section_names); i++) {
4555 if (strncmp(name, section_names[i].sec, section_names[i].len))
4557 if (!section_names[i].is_attachable)
4559 *attach_type = section_names[i].attach_type;
4562 pr_warning("failed to guess attach type based on ELF section name '%s'\n", name);
4563 type_names = libbpf_get_type_names(true);
4564 if (type_names != NULL) {
4565 pr_info("attachable section(type) names are:%s\n", type_names);
4573 bpf_program__identify_section(struct bpf_program *prog,
4574 enum bpf_prog_type *prog_type,
4575 enum bpf_attach_type *expected_attach_type)
4577 return libbpf_prog_type_by_name(prog->section_name, prog_type,
4578 expected_attach_type);
4581 int bpf_map__fd(const struct bpf_map *map)
4583 return map ? map->fd : -EINVAL;
4586 const struct bpf_map_def *bpf_map__def(const struct bpf_map *map)
4588 return map ? &map->def : ERR_PTR(-EINVAL);
4591 const char *bpf_map__name(const struct bpf_map *map)
4593 return map ? map->name : NULL;
4596 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
4598 return map ? map->btf_key_type_id : 0;
4601 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
4603 return map ? map->btf_value_type_id : 0;
4606 int bpf_map__set_priv(struct bpf_map *map, void *priv,
4607 bpf_map_clear_priv_t clear_priv)
4613 if (map->clear_priv)
4614 map->clear_priv(map, map->priv);
4618 map->clear_priv = clear_priv;
4622 void *bpf_map__priv(const struct bpf_map *map)
4624 return map ? map->priv : ERR_PTR(-EINVAL);
4627 bool bpf_map__is_offload_neutral(const struct bpf_map *map)
4629 return map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY;
4632 bool bpf_map__is_internal(const struct bpf_map *map)
4634 return map->libbpf_type != LIBBPF_MAP_UNSPEC;
4637 void bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
4639 map->map_ifindex = ifindex;
4642 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
4644 if (!bpf_map_type__is_map_in_map(map->def.type)) {
4645 pr_warning("error: unsupported map type\n");
4648 if (map->inner_map_fd != -1) {
4649 pr_warning("error: inner_map_fd already specified\n");
4652 map->inner_map_fd = fd;
4656 static struct bpf_map *
4657 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
4660 struct bpf_map *s, *e;
4662 if (!obj || !obj->maps)
4666 e = obj->maps + obj->nr_maps;
4668 if ((m < s) || (m >= e)) {
4669 pr_warning("error in %s: map handler doesn't belong to object\n",
4674 idx = (m - obj->maps) + i;
4675 if (idx >= obj->nr_maps || idx < 0)
4677 return &obj->maps[idx];
4681 bpf_map__next(const struct bpf_map *prev, const struct bpf_object *obj)
4686 return __bpf_map__iter(prev, obj, 1);
4690 bpf_map__prev(const struct bpf_map *next, const struct bpf_object *obj)
4695 return obj->maps + obj->nr_maps - 1;
4698 return __bpf_map__iter(next, obj, -1);
4702 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
4704 struct bpf_map *pos;
4706 bpf_object__for_each_map(pos, obj) {
4707 if (pos->name && !strcmp(pos->name, name))
4714 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
4716 return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
4720 bpf_object__find_map_by_offset(struct bpf_object *obj, size_t offset)
4722 return ERR_PTR(-ENOTSUP);
4725 long libbpf_get_error(const void *ptr)
4727 return PTR_ERR_OR_ZERO(ptr);
4730 int bpf_prog_load(const char *file, enum bpf_prog_type type,
4731 struct bpf_object **pobj, int *prog_fd)
4733 struct bpf_prog_load_attr attr;
4735 memset(&attr, 0, sizeof(struct bpf_prog_load_attr));
4737 attr.prog_type = type;
4738 attr.expected_attach_type = 0;
4740 return bpf_prog_load_xattr(&attr, pobj, prog_fd);
4743 int bpf_prog_load_xattr(const struct bpf_prog_load_attr *attr,
4744 struct bpf_object **pobj, int *prog_fd)
4746 struct bpf_object_open_attr open_attr = {};
4747 struct bpf_program *prog, *first_prog = NULL;
4748 enum bpf_attach_type expected_attach_type;
4749 enum bpf_prog_type prog_type;
4750 struct bpf_object *obj;
4751 struct bpf_map *map;
4759 open_attr.file = attr->file;
4760 open_attr.prog_type = attr->prog_type;
4762 obj = bpf_object__open_xattr(&open_attr);
4763 if (IS_ERR_OR_NULL(obj))
4766 bpf_object__for_each_program(prog, obj) {
4768 * If type is not specified, try to guess it based on
4771 prog_type = attr->prog_type;
4772 prog->prog_ifindex = attr->ifindex;
4773 expected_attach_type = attr->expected_attach_type;
4774 if (prog_type == BPF_PROG_TYPE_UNSPEC) {
4775 err = bpf_program__identify_section(prog, &prog_type,
4776 &expected_attach_type);
4778 bpf_object__close(obj);
4783 bpf_program__set_type(prog, prog_type);
4784 bpf_program__set_expected_attach_type(prog,
4785 expected_attach_type);
4787 prog->log_level = attr->log_level;
4788 prog->prog_flags = attr->prog_flags;
4793 bpf_object__for_each_map(map, obj) {
4794 if (!bpf_map__is_offload_neutral(map))
4795 map->map_ifindex = attr->ifindex;
4799 pr_warning("object file doesn't contain bpf program\n");
4800 bpf_object__close(obj);
4804 err = bpf_object__load(obj);
4806 bpf_object__close(obj);
4811 *prog_fd = bpf_program__fd(first_prog);
4816 int (*destroy)(struct bpf_link *link);
4819 int bpf_link__destroy(struct bpf_link *link)
4826 err = link->destroy(link);
4832 struct bpf_link_fd {
4833 struct bpf_link link; /* has to be at the top of struct */
4834 int fd; /* hook FD */
4837 static int bpf_link__destroy_perf_event(struct bpf_link *link)
4839 struct bpf_link_fd *l = (void *)link;
4842 err = ioctl(l->fd, PERF_EVENT_IOC_DISABLE, 0);
4850 struct bpf_link *bpf_program__attach_perf_event(struct bpf_program *prog,
4853 char errmsg[STRERR_BUFSIZE];
4854 struct bpf_link_fd *link;
4858 pr_warning("program '%s': invalid perf event FD %d\n",
4859 bpf_program__title(prog, false), pfd);
4860 return ERR_PTR(-EINVAL);
4862 prog_fd = bpf_program__fd(prog);
4864 pr_warning("program '%s': can't attach BPF program w/o FD (did you load it?)\n",
4865 bpf_program__title(prog, false));
4866 return ERR_PTR(-EINVAL);
4869 link = malloc(sizeof(*link));
4871 return ERR_PTR(-ENOMEM);
4872 link->link.destroy = &bpf_link__destroy_perf_event;
4875 if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
4878 pr_warning("program '%s': failed to attach to pfd %d: %s\n",
4879 bpf_program__title(prog, false), pfd,
4880 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
4881 return ERR_PTR(err);
4883 if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
4886 pr_warning("program '%s': failed to enable pfd %d: %s\n",
4887 bpf_program__title(prog, false), pfd,
4888 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
4889 return ERR_PTR(err);
4891 return (struct bpf_link *)link;
4895 * this function is expected to parse integer in the range of [0, 2^31-1] from
4896 * given file using scanf format string fmt. If actual parsed value is
4897 * negative, the result might be indistinguishable from error
4899 static int parse_uint_from_file(const char *file, const char *fmt)
4901 char buf[STRERR_BUFSIZE];
4905 f = fopen(file, "r");
4908 pr_debug("failed to open '%s': %s\n", file,
4909 libbpf_strerror_r(err, buf, sizeof(buf)));
4912 err = fscanf(f, fmt, &ret);
4914 err = err == EOF ? -EIO : -errno;
4915 pr_debug("failed to parse '%s': %s\n", file,
4916 libbpf_strerror_r(err, buf, sizeof(buf)));
4924 static int determine_kprobe_perf_type(void)
4926 const char *file = "/sys/bus/event_source/devices/kprobe/type";
4928 return parse_uint_from_file(file, "%d\n");
4931 static int determine_uprobe_perf_type(void)
4933 const char *file = "/sys/bus/event_source/devices/uprobe/type";
4935 return parse_uint_from_file(file, "%d\n");
4938 static int determine_kprobe_retprobe_bit(void)
4940 const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
4942 return parse_uint_from_file(file, "config:%d\n");
4945 static int determine_uprobe_retprobe_bit(void)
4947 const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
4949 return parse_uint_from_file(file, "config:%d\n");
4952 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
4953 uint64_t offset, int pid)
4955 struct perf_event_attr attr = {};
4956 char errmsg[STRERR_BUFSIZE];
4959 type = uprobe ? determine_uprobe_perf_type()
4960 : determine_kprobe_perf_type();
4962 pr_warning("failed to determine %s perf type: %s\n",
4963 uprobe ? "uprobe" : "kprobe",
4964 libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
4968 int bit = uprobe ? determine_uprobe_retprobe_bit()
4969 : determine_kprobe_retprobe_bit();
4972 pr_warning("failed to determine %s retprobe bit: %s\n",
4973 uprobe ? "uprobe" : "kprobe",
4974 libbpf_strerror_r(bit, errmsg,
4978 attr.config |= 1 << bit;
4980 attr.size = sizeof(attr);
4982 attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
4983 attr.config2 = offset; /* kprobe_addr or probe_offset */
4985 /* pid filter is meaningful only for uprobes */
4986 pfd = syscall(__NR_perf_event_open, &attr,
4987 pid < 0 ? -1 : pid /* pid */,
4988 pid == -1 ? 0 : -1 /* cpu */,
4989 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
4992 pr_warning("%s perf_event_open() failed: %s\n",
4993 uprobe ? "uprobe" : "kprobe",
4994 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
5000 struct bpf_link *bpf_program__attach_kprobe(struct bpf_program *prog,
5002 const char *func_name)
5004 char errmsg[STRERR_BUFSIZE];
5005 struct bpf_link *link;
5008 pfd = perf_event_open_probe(false /* uprobe */, retprobe, func_name,
5009 0 /* offset */, -1 /* pid */);
5011 pr_warning("program '%s': failed to create %s '%s' perf event: %s\n",
5012 bpf_program__title(prog, false),
5013 retprobe ? "kretprobe" : "kprobe", func_name,
5014 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
5015 return ERR_PTR(pfd);
5017 link = bpf_program__attach_perf_event(prog, pfd);
5020 err = PTR_ERR(link);
5021 pr_warning("program '%s': failed to attach to %s '%s': %s\n",
5022 bpf_program__title(prog, false),
5023 retprobe ? "kretprobe" : "kprobe", func_name,
5024 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
5030 struct bpf_link *bpf_program__attach_uprobe(struct bpf_program *prog,
5031 bool retprobe, pid_t pid,
5032 const char *binary_path,
5035 char errmsg[STRERR_BUFSIZE];
5036 struct bpf_link *link;
5039 pfd = perf_event_open_probe(true /* uprobe */, retprobe,
5040 binary_path, func_offset, pid);
5042 pr_warning("program '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
5043 bpf_program__title(prog, false),
5044 retprobe ? "uretprobe" : "uprobe",
5045 binary_path, func_offset,
5046 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
5047 return ERR_PTR(pfd);
5049 link = bpf_program__attach_perf_event(prog, pfd);
5052 err = PTR_ERR(link);
5053 pr_warning("program '%s': failed to attach to %s '%s:0x%zx': %s\n",
5054 bpf_program__title(prog, false),
5055 retprobe ? "uretprobe" : "uprobe",
5056 binary_path, func_offset,
5057 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
5063 static int determine_tracepoint_id(const char *tp_category,
5064 const char *tp_name)
5066 char file[PATH_MAX];
5069 ret = snprintf(file, sizeof(file),
5070 "/sys/kernel/debug/tracing/events/%s/%s/id",
5071 tp_category, tp_name);
5074 if (ret >= sizeof(file)) {
5075 pr_debug("tracepoint %s/%s path is too long\n",
5076 tp_category, tp_name);
5079 return parse_uint_from_file(file, "%d\n");
5082 static int perf_event_open_tracepoint(const char *tp_category,
5083 const char *tp_name)
5085 struct perf_event_attr attr = {};
5086 char errmsg[STRERR_BUFSIZE];
5087 int tp_id, pfd, err;
5089 tp_id = determine_tracepoint_id(tp_category, tp_name);
5091 pr_warning("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
5092 tp_category, tp_name,
5093 libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
5097 attr.type = PERF_TYPE_TRACEPOINT;
5098 attr.size = sizeof(attr);
5099 attr.config = tp_id;
5101 pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
5102 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
5105 pr_warning("tracepoint '%s/%s' perf_event_open() failed: %s\n",
5106 tp_category, tp_name,
5107 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
5113 struct bpf_link *bpf_program__attach_tracepoint(struct bpf_program *prog,
5114 const char *tp_category,
5115 const char *tp_name)
5117 char errmsg[STRERR_BUFSIZE];
5118 struct bpf_link *link;
5121 pfd = perf_event_open_tracepoint(tp_category, tp_name);
5123 pr_warning("program '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
5124 bpf_program__title(prog, false),
5125 tp_category, tp_name,
5126 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
5127 return ERR_PTR(pfd);
5129 link = bpf_program__attach_perf_event(prog, pfd);
5132 err = PTR_ERR(link);
5133 pr_warning("program '%s': failed to attach to tracepoint '%s/%s': %s\n",
5134 bpf_program__title(prog, false),
5135 tp_category, tp_name,
5136 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
5142 static int bpf_link__destroy_fd(struct bpf_link *link)
5144 struct bpf_link_fd *l = (void *)link;
5146 return close(l->fd);
5149 struct bpf_link *bpf_program__attach_raw_tracepoint(struct bpf_program *prog,
5150 const char *tp_name)
5152 char errmsg[STRERR_BUFSIZE];
5153 struct bpf_link_fd *link;
5156 prog_fd = bpf_program__fd(prog);
5158 pr_warning("program '%s': can't attach before loaded\n",
5159 bpf_program__title(prog, false));
5160 return ERR_PTR(-EINVAL);
5163 link = malloc(sizeof(*link));
5165 return ERR_PTR(-ENOMEM);
5166 link->link.destroy = &bpf_link__destroy_fd;
5168 pfd = bpf_raw_tracepoint_open(tp_name, prog_fd);
5172 pr_warning("program '%s': failed to attach to raw tracepoint '%s': %s\n",
5173 bpf_program__title(prog, false), tp_name,
5174 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
5175 return ERR_PTR(pfd);
5178 return (struct bpf_link *)link;
5181 enum bpf_perf_event_ret
5182 bpf_perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
5183 void **copy_mem, size_t *copy_size,
5184 bpf_perf_event_print_t fn, void *private_data)
5186 struct perf_event_mmap_page *header = mmap_mem;
5187 __u64 data_head = ring_buffer_read_head(header);
5188 __u64 data_tail = header->data_tail;
5189 void *base = ((__u8 *)header) + page_size;
5190 int ret = LIBBPF_PERF_EVENT_CONT;
5191 struct perf_event_header *ehdr;
5194 while (data_head != data_tail) {
5195 ehdr = base + (data_tail & (mmap_size - 1));
5196 ehdr_size = ehdr->size;
5198 if (((void *)ehdr) + ehdr_size > base + mmap_size) {
5199 void *copy_start = ehdr;
5200 size_t len_first = base + mmap_size - copy_start;
5201 size_t len_secnd = ehdr_size - len_first;
5203 if (*copy_size < ehdr_size) {
5205 *copy_mem = malloc(ehdr_size);
5208 ret = LIBBPF_PERF_EVENT_ERROR;
5211 *copy_size = ehdr_size;
5214 memcpy(*copy_mem, copy_start, len_first);
5215 memcpy(*copy_mem + len_first, base, len_secnd);
5219 ret = fn(ehdr, private_data);
5220 data_tail += ehdr_size;
5221 if (ret != LIBBPF_PERF_EVENT_CONT)
5225 ring_buffer_write_tail(header, data_tail);
5231 struct perf_buffer_params {
5232 struct perf_event_attr *attr;
5233 /* if event_cb is specified, it takes precendence */
5234 perf_buffer_event_fn event_cb;
5235 /* sample_cb and lost_cb are higher-level common-case callbacks */
5236 perf_buffer_sample_fn sample_cb;
5237 perf_buffer_lost_fn lost_cb;
5244 struct perf_cpu_buf {
5245 struct perf_buffer *pb;
5246 void *base; /* mmap()'ed memory */
5247 void *buf; /* for reconstructing segmented data */
5254 struct perf_buffer {
5255 perf_buffer_event_fn event_cb;
5256 perf_buffer_sample_fn sample_cb;
5257 perf_buffer_lost_fn lost_cb;
5258 void *ctx; /* passed into callbacks */
5262 struct perf_cpu_buf **cpu_bufs;
5263 struct epoll_event *events;
5265 int epoll_fd; /* perf event FD */
5266 int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
5269 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
5270 struct perf_cpu_buf *cpu_buf)
5274 if (cpu_buf->base &&
5275 munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
5276 pr_warning("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
5277 if (cpu_buf->fd >= 0) {
5278 ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
5285 void perf_buffer__free(struct perf_buffer *pb)
5292 for (i = 0; i < pb->cpu_cnt && pb->cpu_bufs[i]; i++) {
5293 struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
5295 bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
5296 perf_buffer__free_cpu_buf(pb, cpu_buf);
5300 if (pb->epoll_fd >= 0)
5301 close(pb->epoll_fd);
5306 static struct perf_cpu_buf *
5307 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
5308 int cpu, int map_key)
5310 struct perf_cpu_buf *cpu_buf;
5311 char msg[STRERR_BUFSIZE];
5314 cpu_buf = calloc(1, sizeof(*cpu_buf));
5316 return ERR_PTR(-ENOMEM);
5320 cpu_buf->map_key = map_key;
5322 cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
5323 -1, PERF_FLAG_FD_CLOEXEC);
5324 if (cpu_buf->fd < 0) {
5326 pr_warning("failed to open perf buffer event on cpu #%d: %s\n",
5327 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
5331 cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
5332 PROT_READ | PROT_WRITE, MAP_SHARED,
5334 if (cpu_buf->base == MAP_FAILED) {
5335 cpu_buf->base = NULL;
5337 pr_warning("failed to mmap perf buffer on cpu #%d: %s\n",
5338 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
5342 if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
5344 pr_warning("failed to enable perf buffer event on cpu #%d: %s\n",
5345 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
5352 perf_buffer__free_cpu_buf(pb, cpu_buf);
5353 return (struct perf_cpu_buf *)ERR_PTR(err);
5356 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
5357 struct perf_buffer_params *p);
5359 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
5360 const struct perf_buffer_opts *opts)
5362 struct perf_buffer_params p = {};
5363 struct perf_event_attr attr = {
5364 .config = PERF_COUNT_SW_BPF_OUTPUT,
5365 .type = PERF_TYPE_SOFTWARE,
5366 .sample_type = PERF_SAMPLE_RAW,
5372 p.sample_cb = opts ? opts->sample_cb : NULL;
5373 p.lost_cb = opts ? opts->lost_cb : NULL;
5374 p.ctx = opts ? opts->ctx : NULL;
5376 return __perf_buffer__new(map_fd, page_cnt, &p);
5379 struct perf_buffer *
5380 perf_buffer__new_raw(int map_fd, size_t page_cnt,
5381 const struct perf_buffer_raw_opts *opts)
5383 struct perf_buffer_params p = {};
5385 p.attr = opts->attr;
5386 p.event_cb = opts->event_cb;
5388 p.cpu_cnt = opts->cpu_cnt;
5389 p.cpus = opts->cpus;
5390 p.map_keys = opts->map_keys;
5392 return __perf_buffer__new(map_fd, page_cnt, &p);
5395 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
5396 struct perf_buffer_params *p)
5398 struct bpf_map_info map = {};
5399 char msg[STRERR_BUFSIZE];
5400 struct perf_buffer *pb;
5404 if (page_cnt & (page_cnt - 1)) {
5405 pr_warning("page count should be power of two, but is %zu\n",
5407 return ERR_PTR(-EINVAL);
5410 map_info_len = sizeof(map);
5411 err = bpf_obj_get_info_by_fd(map_fd, &map, &map_info_len);
5414 pr_warning("failed to get map info for map FD %d: %s\n",
5415 map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
5416 return ERR_PTR(err);
5419 if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
5420 pr_warning("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
5422 return ERR_PTR(-EINVAL);
5425 pb = calloc(1, sizeof(*pb));
5427 return ERR_PTR(-ENOMEM);
5429 pb->event_cb = p->event_cb;
5430 pb->sample_cb = p->sample_cb;
5431 pb->lost_cb = p->lost_cb;
5434 pb->page_size = getpagesize();
5435 pb->mmap_size = pb->page_size * page_cnt;
5436 pb->map_fd = map_fd;
5438 pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
5439 if (pb->epoll_fd < 0) {
5441 pr_warning("failed to create epoll instance: %s\n",
5442 libbpf_strerror_r(err, msg, sizeof(msg)));
5446 if (p->cpu_cnt > 0) {
5447 pb->cpu_cnt = p->cpu_cnt;
5449 pb->cpu_cnt = libbpf_num_possible_cpus();
5450 if (pb->cpu_cnt < 0) {
5454 if (map.max_entries < pb->cpu_cnt)
5455 pb->cpu_cnt = map.max_entries;
5458 pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
5461 pr_warning("failed to allocate events: out of memory\n");
5464 pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
5465 if (!pb->cpu_bufs) {
5467 pr_warning("failed to allocate buffers: out of memory\n");
5471 for (i = 0; i < pb->cpu_cnt; i++) {
5472 struct perf_cpu_buf *cpu_buf;
5475 cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
5476 map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
5478 cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
5479 if (IS_ERR(cpu_buf)) {
5480 err = PTR_ERR(cpu_buf);
5484 pb->cpu_bufs[i] = cpu_buf;
5486 err = bpf_map_update_elem(pb->map_fd, &map_key,
5490 pr_warning("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
5491 cpu, map_key, cpu_buf->fd,
5492 libbpf_strerror_r(err, msg, sizeof(msg)));
5496 pb->events[i].events = EPOLLIN;
5497 pb->events[i].data.ptr = cpu_buf;
5498 if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
5499 &pb->events[i]) < 0) {
5501 pr_warning("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
5503 libbpf_strerror_r(err, msg, sizeof(msg)));
5512 perf_buffer__free(pb);
5513 return ERR_PTR(err);
5516 struct perf_sample_raw {
5517 struct perf_event_header header;
5522 struct perf_sample_lost {
5523 struct perf_event_header header;
5529 static enum bpf_perf_event_ret
5530 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
5532 struct perf_cpu_buf *cpu_buf = ctx;
5533 struct perf_buffer *pb = cpu_buf->pb;
5536 /* user wants full control over parsing perf event */
5538 return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
5541 case PERF_RECORD_SAMPLE: {
5542 struct perf_sample_raw *s = data;
5545 pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
5548 case PERF_RECORD_LOST: {
5549 struct perf_sample_lost *s = data;
5552 pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
5556 pr_warning("unknown perf sample type %d\n", e->type);
5557 return LIBBPF_PERF_EVENT_ERROR;
5559 return LIBBPF_PERF_EVENT_CONT;
5562 static int perf_buffer__process_records(struct perf_buffer *pb,
5563 struct perf_cpu_buf *cpu_buf)
5565 enum bpf_perf_event_ret ret;
5567 ret = bpf_perf_event_read_simple(cpu_buf->base, pb->mmap_size,
5568 pb->page_size, &cpu_buf->buf,
5570 perf_buffer__process_record, cpu_buf);
5571 if (ret != LIBBPF_PERF_EVENT_CONT)
5576 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
5580 cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
5581 for (i = 0; i < cnt; i++) {
5582 struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
5584 err = perf_buffer__process_records(pb, cpu_buf);
5586 pr_warning("error while processing records: %d\n", err);
5590 return cnt < 0 ? -errno : cnt;
5593 struct bpf_prog_info_array_desc {
5594 int array_offset; /* e.g. offset of jited_prog_insns */
5595 int count_offset; /* e.g. offset of jited_prog_len */
5596 int size_offset; /* > 0: offset of rec size,
5597 * < 0: fix size of -size_offset
5601 static struct bpf_prog_info_array_desc bpf_prog_info_array_desc[] = {
5602 [BPF_PROG_INFO_JITED_INSNS] = {
5603 offsetof(struct bpf_prog_info, jited_prog_insns),
5604 offsetof(struct bpf_prog_info, jited_prog_len),
5607 [BPF_PROG_INFO_XLATED_INSNS] = {
5608 offsetof(struct bpf_prog_info, xlated_prog_insns),
5609 offsetof(struct bpf_prog_info, xlated_prog_len),
5612 [BPF_PROG_INFO_MAP_IDS] = {
5613 offsetof(struct bpf_prog_info, map_ids),
5614 offsetof(struct bpf_prog_info, nr_map_ids),
5615 -(int)sizeof(__u32),
5617 [BPF_PROG_INFO_JITED_KSYMS] = {
5618 offsetof(struct bpf_prog_info, jited_ksyms),
5619 offsetof(struct bpf_prog_info, nr_jited_ksyms),
5620 -(int)sizeof(__u64),
5622 [BPF_PROG_INFO_JITED_FUNC_LENS] = {
5623 offsetof(struct bpf_prog_info, jited_func_lens),
5624 offsetof(struct bpf_prog_info, nr_jited_func_lens),
5625 -(int)sizeof(__u32),
5627 [BPF_PROG_INFO_FUNC_INFO] = {
5628 offsetof(struct bpf_prog_info, func_info),
5629 offsetof(struct bpf_prog_info, nr_func_info),
5630 offsetof(struct bpf_prog_info, func_info_rec_size),
5632 [BPF_PROG_INFO_LINE_INFO] = {
5633 offsetof(struct bpf_prog_info, line_info),
5634 offsetof(struct bpf_prog_info, nr_line_info),
5635 offsetof(struct bpf_prog_info, line_info_rec_size),
5637 [BPF_PROG_INFO_JITED_LINE_INFO] = {
5638 offsetof(struct bpf_prog_info, jited_line_info),
5639 offsetof(struct bpf_prog_info, nr_jited_line_info),
5640 offsetof(struct bpf_prog_info, jited_line_info_rec_size),
5642 [BPF_PROG_INFO_PROG_TAGS] = {
5643 offsetof(struct bpf_prog_info, prog_tags),
5644 offsetof(struct bpf_prog_info, nr_prog_tags),
5645 -(int)sizeof(__u8) * BPF_TAG_SIZE,
5650 static __u32 bpf_prog_info_read_offset_u32(struct bpf_prog_info *info, int offset)
5652 __u32 *array = (__u32 *)info;
5655 return array[offset / sizeof(__u32)];
5656 return -(int)offset;
5659 static __u64 bpf_prog_info_read_offset_u64(struct bpf_prog_info *info, int offset)
5661 __u64 *array = (__u64 *)info;
5664 return array[offset / sizeof(__u64)];
5665 return -(int)offset;
5668 static void bpf_prog_info_set_offset_u32(struct bpf_prog_info *info, int offset,
5671 __u32 *array = (__u32 *)info;
5674 array[offset / sizeof(__u32)] = val;
5677 static void bpf_prog_info_set_offset_u64(struct bpf_prog_info *info, int offset,
5680 __u64 *array = (__u64 *)info;
5683 array[offset / sizeof(__u64)] = val;
5686 struct bpf_prog_info_linear *
5687 bpf_program__get_prog_info_linear(int fd, __u64 arrays)
5689 struct bpf_prog_info_linear *info_linear;
5690 struct bpf_prog_info info = {};
5691 __u32 info_len = sizeof(info);
5696 if (arrays >> BPF_PROG_INFO_LAST_ARRAY)
5697 return ERR_PTR(-EINVAL);
5699 /* step 1: get array dimensions */
5700 err = bpf_obj_get_info_by_fd(fd, &info, &info_len);
5702 pr_debug("can't get prog info: %s", strerror(errno));
5703 return ERR_PTR(-EFAULT);
5706 /* step 2: calculate total size of all arrays */
5707 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
5708 bool include_array = (arrays & (1UL << i)) > 0;
5709 struct bpf_prog_info_array_desc *desc;
5712 desc = bpf_prog_info_array_desc + i;
5714 /* kernel is too old to support this field */
5715 if (info_len < desc->array_offset + sizeof(__u32) ||
5716 info_len < desc->count_offset + sizeof(__u32) ||
5717 (desc->size_offset > 0 && info_len < desc->size_offset))
5718 include_array = false;
5720 if (!include_array) {
5721 arrays &= ~(1UL << i); /* clear the bit */
5725 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
5726 size = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
5728 data_len += count * size;
5731 /* step 3: allocate continuous memory */
5732 data_len = roundup(data_len, sizeof(__u64));
5733 info_linear = malloc(sizeof(struct bpf_prog_info_linear) + data_len);
5735 return ERR_PTR(-ENOMEM);
5737 /* step 4: fill data to info_linear->info */
5738 info_linear->arrays = arrays;
5739 memset(&info_linear->info, 0, sizeof(info));
5740 ptr = info_linear->data;
5742 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
5743 struct bpf_prog_info_array_desc *desc;
5746 if ((arrays & (1UL << i)) == 0)
5749 desc = bpf_prog_info_array_desc + i;
5750 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
5751 size = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
5752 bpf_prog_info_set_offset_u32(&info_linear->info,
5753 desc->count_offset, count);
5754 bpf_prog_info_set_offset_u32(&info_linear->info,
5755 desc->size_offset, size);
5756 bpf_prog_info_set_offset_u64(&info_linear->info,
5759 ptr += count * size;
5762 /* step 5: call syscall again to get required arrays */
5763 err = bpf_obj_get_info_by_fd(fd, &info_linear->info, &info_len);
5765 pr_debug("can't get prog info: %s", strerror(errno));
5767 return ERR_PTR(-EFAULT);
5770 /* step 6: verify the data */
5771 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
5772 struct bpf_prog_info_array_desc *desc;
5775 if ((arrays & (1UL << i)) == 0)
5778 desc = bpf_prog_info_array_desc + i;
5779 v1 = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
5780 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
5781 desc->count_offset);
5783 pr_warning("%s: mismatch in element count\n", __func__);
5785 v1 = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
5786 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
5789 pr_warning("%s: mismatch in rec size\n", __func__);
5792 /* step 7: update info_len and data_len */
5793 info_linear->info_len = sizeof(struct bpf_prog_info);
5794 info_linear->data_len = data_len;
5799 void bpf_program__bpil_addr_to_offs(struct bpf_prog_info_linear *info_linear)
5803 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
5804 struct bpf_prog_info_array_desc *desc;
5807 if ((info_linear->arrays & (1UL << i)) == 0)
5810 desc = bpf_prog_info_array_desc + i;
5811 addr = bpf_prog_info_read_offset_u64(&info_linear->info,
5812 desc->array_offset);
5813 offs = addr - ptr_to_u64(info_linear->data);
5814 bpf_prog_info_set_offset_u64(&info_linear->info,
5815 desc->array_offset, offs);
5819 void bpf_program__bpil_offs_to_addr(struct bpf_prog_info_linear *info_linear)
5823 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
5824 struct bpf_prog_info_array_desc *desc;
5827 if ((info_linear->arrays & (1UL << i)) == 0)
5830 desc = bpf_prog_info_array_desc + i;
5831 offs = bpf_prog_info_read_offset_u64(&info_linear->info,
5832 desc->array_offset);
5833 addr = offs + ptr_to_u64(info_linear->data);
5834 bpf_prog_info_set_offset_u64(&info_linear->info,
5835 desc->array_offset, addr);
5839 int libbpf_num_possible_cpus(void)
5841 static const char *fcpu = "/sys/devices/system/cpu/possible";
5842 int len = 0, n = 0, il = 0, ir = 0;
5843 unsigned int start = 0, end = 0;
5852 fd = open(fcpu, O_RDONLY);
5855 pr_warning("Failed to open file %s: %s\n",
5856 fcpu, strerror(error));
5859 len = read(fd, buf, sizeof(buf));
5862 error = len ? errno : EINVAL;
5863 pr_warning("Failed to read # of possible cpus from %s: %s\n",
5864 fcpu, strerror(error));
5867 if (len == sizeof(buf)) {
5868 pr_warning("File %s size overflow\n", fcpu);
5873 for (ir = 0, cpus = 0; ir <= len; ir++) {
5874 /* Each sub string separated by ',' has format \d+-\d+ or \d+ */
5875 if (buf[ir] == ',' || buf[ir] == '\0') {
5877 n = sscanf(&buf[il], "%u-%u", &start, &end);
5879 pr_warning("Failed to get # CPUs from %s\n",
5882 } else if (n == 1) {
5885 cpus += end - start + 1;
5890 pr_warning("Invalid #CPUs %d from %s\n", cpus, fcpu);