1 // SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
4 * Common eBPF ELF object loading operations.
6 * Copyright (C) 2013-2015 Alexei Starovoitov <ast@kernel.org>
7 * Copyright (C) 2015 Wang Nan <wangnan0@huawei.com>
8 * Copyright (C) 2015 Huawei Inc.
9 * Copyright (C) 2017 Nicira, Inc.
10 * Copyright (C) 2019 Isovalent, Inc.
26 #include <asm/unistd.h>
27 #include <linux/err.h>
28 #include <linux/kernel.h>
29 #include <linux/bpf.h>
30 #include <linux/btf.h>
31 #include <linux/filter.h>
32 #include <linux/list.h>
33 #include <linux/limits.h>
34 #include <linux/perf_event.h>
35 #include <linux/ring_buffer.h>
36 #include <sys/epoll.h>
37 #include <sys/ioctl.h>
40 #include <sys/types.h>
42 #include <tools/libc_compat.h>
49 #include "str_error.h"
50 #include "libbpf_internal.h"
57 #define BPF_FS_MAGIC 0xcafe4a11
60 /* vsprintf() in __base_pr() uses nonliteral format string. It may break
61 * compilation if user enables corresponding warning. Disable it explicitly.
63 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
65 #define __printf(a, b) __attribute__((format(printf, a, b)))
67 static int __base_pr(enum libbpf_print_level level, const char *format,
70 if (level == LIBBPF_DEBUG)
73 return vfprintf(stderr, format, args);
76 static libbpf_print_fn_t __libbpf_pr = __base_pr;
78 void libbpf_set_print(libbpf_print_fn_t fn)
84 void libbpf_print(enum libbpf_print_level level, const char *format, ...)
91 va_start(args, format);
92 __libbpf_pr(level, format, args);
96 #define STRERR_BUFSIZE 128
98 #define CHECK_ERR(action, err, out) do { \
105 /* Copied from tools/perf/util/util.h */
107 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
111 # define zclose(fd) ({ \
114 ___err = close((fd)); \
119 #ifdef HAVE_LIBELF_MMAP_SUPPORT
120 # define LIBBPF_ELF_C_READ_MMAP ELF_C_READ_MMAP
122 # define LIBBPF_ELF_C_READ_MMAP ELF_C_READ
125 static inline __u64 ptr_to_u64(const void *ptr)
127 return (__u64) (unsigned long) ptr;
130 struct bpf_capabilities {
131 /* v4.14: kernel support for program & map names. */
133 /* v5.2: kernel support for global data sections. */
135 /* BTF_KIND_FUNC and BTF_KIND_FUNC_PROTO support */
137 /* BTF_KIND_VAR and BTF_KIND_DATASEC support */
142 * bpf_prog should be a better name but it has been used in
146 /* Index in elf obj file, for relocation use. */
151 /* section_name with / replaced by _; makes recursive pinning
152 * in bpf_object__pin_programs easier
155 struct bpf_insn *insns;
156 size_t insns_cnt, main_prog_cnt;
157 enum bpf_prog_type type;
178 bpf_program_prep_t preprocessor;
180 struct bpf_object *obj;
182 bpf_program_clear_priv_t clear_priv;
184 enum bpf_attach_type expected_attach_type;
187 __u32 func_info_rec_size;
190 struct bpf_capabilities *caps;
193 __u32 line_info_rec_size;
198 enum libbpf_map_type {
205 static const char * const libbpf_type_to_btf_name[] = {
206 [LIBBPF_MAP_DATA] = ".data",
207 [LIBBPF_MAP_BSS] = ".bss",
208 [LIBBPF_MAP_RODATA] = ".rodata",
218 struct bpf_map_def def;
219 __u32 btf_key_type_id;
220 __u32 btf_value_type_id;
222 bpf_map_clear_priv_t clear_priv;
223 enum libbpf_map_type libbpf_type;
231 static LIST_HEAD(bpf_objects_list);
234 char name[BPF_OBJ_NAME_LEN];
238 struct bpf_program *programs;
240 struct bpf_map *maps;
243 struct bpf_secdata sections;
246 bool has_pseudo_calls;
249 * Information when doing elf related work. Only valid if fd
276 * All loaded bpf_object is linked in a list, which is
277 * hidden to caller. bpf_objects__<func> handlers deal with
280 struct list_head list;
283 struct btf_ext *btf_ext;
286 bpf_object_clear_priv_t clear_priv;
288 struct bpf_capabilities caps;
292 #define obj_elf_valid(o) ((o)->efile.elf)
294 void bpf_program__unload(struct bpf_program *prog)
302 * If the object is opened but the program was never loaded,
303 * it is possible that prog->instances.nr == -1.
305 if (prog->instances.nr > 0) {
306 for (i = 0; i < prog->instances.nr; i++)
307 zclose(prog->instances.fds[i]);
308 } else if (prog->instances.nr != -1) {
309 pr_warning("Internal error: instances.nr is %d\n",
313 prog->instances.nr = -1;
314 zfree(&prog->instances.fds);
316 zclose(prog->btf_fd);
317 zfree(&prog->func_info);
318 zfree(&prog->line_info);
321 static void bpf_program__exit(struct bpf_program *prog)
326 if (prog->clear_priv)
327 prog->clear_priv(prog, prog->priv);
330 prog->clear_priv = NULL;
332 bpf_program__unload(prog);
334 zfree(&prog->section_name);
335 zfree(&prog->pin_name);
337 zfree(&prog->reloc_desc);
344 static char *__bpf_program__pin_name(struct bpf_program *prog)
348 name = p = strdup(prog->section_name);
349 while ((p = strchr(p, '/')))
356 bpf_program__init(void *data, size_t size, char *section_name, int idx,
357 struct bpf_program *prog)
359 const size_t bpf_insn_sz = sizeof(struct bpf_insn);
361 if (size == 0 || size % bpf_insn_sz) {
362 pr_warning("corrupted section '%s', size: %zu\n",
367 memset(prog, 0, sizeof(*prog));
369 prog->section_name = strdup(section_name);
370 if (!prog->section_name) {
371 pr_warning("failed to alloc name for prog under section(%d) %s\n",
376 prog->pin_name = __bpf_program__pin_name(prog);
377 if (!prog->pin_name) {
378 pr_warning("failed to alloc pin name for prog under section(%d) %s\n",
383 prog->insns = malloc(size);
385 pr_warning("failed to alloc insns for prog under section %s\n",
389 prog->insns_cnt = size / bpf_insn_sz;
390 memcpy(prog->insns, data, size);
392 prog->instances.fds = NULL;
393 prog->instances.nr = -1;
394 prog->type = BPF_PROG_TYPE_UNSPEC;
399 bpf_program__exit(prog);
404 bpf_object__add_program(struct bpf_object *obj, void *data, size_t size,
405 char *section_name, int idx)
407 struct bpf_program prog, *progs;
410 err = bpf_program__init(data, size, section_name, idx, &prog);
414 prog.caps = &obj->caps;
415 progs = obj->programs;
416 nr_progs = obj->nr_programs;
418 progs = reallocarray(progs, nr_progs + 1, sizeof(progs[0]));
421 * In this case the original obj->programs
422 * is still valid, so don't need special treat for
423 * bpf_close_object().
425 pr_warning("failed to alloc a new program under section '%s'\n",
427 bpf_program__exit(&prog);
431 pr_debug("found program %s\n", prog.section_name);
432 obj->programs = progs;
433 obj->nr_programs = nr_progs + 1;
435 progs[nr_progs] = prog;
440 bpf_object__init_prog_names(struct bpf_object *obj)
442 Elf_Data *symbols = obj->efile.symbols;
443 struct bpf_program *prog;
446 for (pi = 0; pi < obj->nr_programs; pi++) {
447 const char *name = NULL;
449 prog = &obj->programs[pi];
451 for (si = 0; si < symbols->d_size / sizeof(GElf_Sym) && !name;
455 if (!gelf_getsym(symbols, si, &sym))
457 if (sym.st_shndx != prog->idx)
459 if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL)
462 name = elf_strptr(obj->efile.elf,
463 obj->efile.strtabidx,
466 pr_warning("failed to get sym name string for prog %s\n",
468 return -LIBBPF_ERRNO__LIBELF;
472 if (!name && prog->idx == obj->efile.text_shndx)
476 pr_warning("failed to find sym for prog %s\n",
481 prog->name = strdup(name);
483 pr_warning("failed to allocate memory for prog sym %s\n",
492 static struct bpf_object *bpf_object__new(const char *path,
496 struct bpf_object *obj;
499 obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
501 pr_warning("alloc memory failed for %s\n", path);
502 return ERR_PTR(-ENOMEM);
505 strcpy(obj->path, path);
506 /* Using basename() GNU version which doesn't modify arg. */
507 strncpy(obj->name, basename((void *)path), sizeof(obj->name) - 1);
508 end = strchr(obj->name, '.');
514 * Caller of this function should also call
515 * bpf_object__elf_finish() after data collection to return
516 * obj_buf to user. If not, we should duplicate the buffer to
517 * avoid user freeing them before elf finish.
519 obj->efile.obj_buf = obj_buf;
520 obj->efile.obj_buf_sz = obj_buf_sz;
521 obj->efile.maps_shndx = -1;
522 obj->efile.btf_maps_shndx = -1;
523 obj->efile.data_shndx = -1;
524 obj->efile.rodata_shndx = -1;
525 obj->efile.bss_shndx = -1;
529 INIT_LIST_HEAD(&obj->list);
530 list_add(&obj->list, &bpf_objects_list);
534 static void bpf_object__elf_finish(struct bpf_object *obj)
536 if (!obj_elf_valid(obj))
539 if (obj->efile.elf) {
540 elf_end(obj->efile.elf);
541 obj->efile.elf = NULL;
543 obj->efile.symbols = NULL;
544 obj->efile.data = NULL;
545 obj->efile.rodata = NULL;
546 obj->efile.bss = NULL;
548 zfree(&obj->efile.reloc);
549 obj->efile.nr_reloc = 0;
550 zclose(obj->efile.fd);
551 obj->efile.obj_buf = NULL;
552 obj->efile.obj_buf_sz = 0;
555 static int bpf_object__elf_init(struct bpf_object *obj)
560 if (obj_elf_valid(obj)) {
561 pr_warning("elf init: internal error\n");
562 return -LIBBPF_ERRNO__LIBELF;
565 if (obj->efile.obj_buf_sz > 0) {
567 * obj_buf should have been validated by
568 * bpf_object__open_buffer().
570 obj->efile.elf = elf_memory(obj->efile.obj_buf,
571 obj->efile.obj_buf_sz);
573 obj->efile.fd = open(obj->path, O_RDONLY);
574 if (obj->efile.fd < 0) {
575 char errmsg[STRERR_BUFSIZE], *cp;
578 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
579 pr_warning("failed to open %s: %s\n", obj->path, cp);
583 obj->efile.elf = elf_begin(obj->efile.fd,
584 LIBBPF_ELF_C_READ_MMAP, NULL);
587 if (!obj->efile.elf) {
588 pr_warning("failed to open %s as ELF file\n", obj->path);
589 err = -LIBBPF_ERRNO__LIBELF;
593 if (!gelf_getehdr(obj->efile.elf, &obj->efile.ehdr)) {
594 pr_warning("failed to get EHDR from %s\n", obj->path);
595 err = -LIBBPF_ERRNO__FORMAT;
598 ep = &obj->efile.ehdr;
600 /* Old LLVM set e_machine to EM_NONE */
601 if (ep->e_type != ET_REL ||
602 (ep->e_machine && ep->e_machine != EM_BPF)) {
603 pr_warning("%s is not an eBPF object file\n", obj->path);
604 err = -LIBBPF_ERRNO__FORMAT;
610 bpf_object__elf_finish(obj);
614 static int bpf_object__check_endianness(struct bpf_object *obj)
616 #if __BYTE_ORDER == __LITTLE_ENDIAN
617 if (obj->efile.ehdr.e_ident[EI_DATA] == ELFDATA2LSB)
619 #elif __BYTE_ORDER == __BIG_ENDIAN
620 if (obj->efile.ehdr.e_ident[EI_DATA] == ELFDATA2MSB)
623 # error "Unrecognized __BYTE_ORDER__"
625 pr_warning("endianness mismatch.\n");
626 return -LIBBPF_ERRNO__ENDIAN;
630 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
632 memcpy(obj->license, data, min(size, sizeof(obj->license) - 1));
633 pr_debug("license of %s is %s\n", obj->path, obj->license);
638 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
642 if (size != sizeof(kver)) {
643 pr_warning("invalid kver section in %s\n", obj->path);
644 return -LIBBPF_ERRNO__FORMAT;
646 memcpy(&kver, data, sizeof(kver));
647 obj->kern_version = kver;
648 pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
652 static int compare_bpf_map(const void *_a, const void *_b)
654 const struct bpf_map *a = _a;
655 const struct bpf_map *b = _b;
657 if (a->sec_idx != b->sec_idx)
658 return a->sec_idx - b->sec_idx;
659 return a->sec_offset - b->sec_offset;
662 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
664 if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
665 type == BPF_MAP_TYPE_HASH_OF_MAPS)
670 static int bpf_object_search_section_size(const struct bpf_object *obj,
671 const char *name, size_t *d_size)
673 const GElf_Ehdr *ep = &obj->efile.ehdr;
674 Elf *elf = obj->efile.elf;
678 while ((scn = elf_nextscn(elf, scn)) != NULL) {
679 const char *sec_name;
684 if (gelf_getshdr(scn, &sh) != &sh) {
685 pr_warning("failed to get section(%d) header from %s\n",
690 sec_name = elf_strptr(elf, ep->e_shstrndx, sh.sh_name);
692 pr_warning("failed to get section(%d) name from %s\n",
697 if (strcmp(name, sec_name))
700 data = elf_getdata(scn, 0);
702 pr_warning("failed to get section(%d) data from %s(%s)\n",
703 idx, name, obj->path);
707 *d_size = data->d_size;
714 int bpf_object__section_size(const struct bpf_object *obj, const char *name,
723 } else if (!strcmp(name, ".data")) {
725 *size = obj->efile.data->d_size;
726 } else if (!strcmp(name, ".bss")) {
728 *size = obj->efile.bss->d_size;
729 } else if (!strcmp(name, ".rodata")) {
730 if (obj->efile.rodata)
731 *size = obj->efile.rodata->d_size;
733 ret = bpf_object_search_section_size(obj, name, &d_size);
738 return *size ? 0 : ret;
741 int bpf_object__variable_offset(const struct bpf_object *obj, const char *name,
744 Elf_Data *symbols = obj->efile.symbols;
751 for (si = 0; si < symbols->d_size / sizeof(GElf_Sym); si++) {
754 if (!gelf_getsym(symbols, si, &sym))
756 if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL ||
757 GELF_ST_TYPE(sym.st_info) != STT_OBJECT)
760 sname = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
763 pr_warning("failed to get sym name string for var %s\n",
767 if (strcmp(name, sname) == 0) {
776 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
778 struct bpf_map *new_maps;
782 if (obj->nr_maps < obj->maps_cap)
783 return &obj->maps[obj->nr_maps++];
785 new_cap = max((size_t)4, obj->maps_cap * 3 / 2);
786 new_maps = realloc(obj->maps, new_cap * sizeof(*obj->maps));
788 pr_warning("alloc maps for object failed\n");
789 return ERR_PTR(-ENOMEM);
792 obj->maps_cap = new_cap;
793 obj->maps = new_maps;
795 /* zero out new maps */
796 memset(obj->maps + obj->nr_maps, 0,
797 (obj->maps_cap - obj->nr_maps) * sizeof(*obj->maps));
799 * fill all fd with -1 so won't close incorrect fd (fd=0 is stdin)
800 * when failure (zclose won't close negative fd)).
802 for (i = obj->nr_maps; i < obj->maps_cap; i++) {
803 obj->maps[i].fd = -1;
804 obj->maps[i].inner_map_fd = -1;
807 return &obj->maps[obj->nr_maps++];
811 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
812 int sec_idx, Elf_Data *data, void **data_buff)
814 char map_name[BPF_OBJ_NAME_LEN];
815 struct bpf_map_def *def;
818 map = bpf_object__add_map(obj);
822 map->libbpf_type = type;
823 map->sec_idx = sec_idx;
825 snprintf(map_name, sizeof(map_name), "%.8s%.7s", obj->name,
826 libbpf_type_to_btf_name[type]);
827 map->name = strdup(map_name);
829 pr_warning("failed to alloc map name\n");
832 pr_debug("map '%s' (global data): at sec_idx %d, offset %zu.\n",
833 map_name, map->sec_idx, map->sec_offset);
836 def->type = BPF_MAP_TYPE_ARRAY;
837 def->key_size = sizeof(int);
838 def->value_size = data->d_size;
839 def->max_entries = 1;
840 def->map_flags = type == LIBBPF_MAP_RODATA ? BPF_F_RDONLY_PROG : 0;
842 *data_buff = malloc(data->d_size);
845 pr_warning("failed to alloc map content buffer\n");
848 memcpy(*data_buff, data->d_buf, data->d_size);
851 pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
855 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
859 if (!obj->caps.global_data)
862 * Populate obj->maps with libbpf internal maps.
864 if (obj->efile.data_shndx >= 0) {
865 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
866 obj->efile.data_shndx,
868 &obj->sections.data);
872 if (obj->efile.rodata_shndx >= 0) {
873 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
874 obj->efile.rodata_shndx,
876 &obj->sections.rodata);
880 if (obj->efile.bss_shndx >= 0) {
881 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
882 obj->efile.bss_shndx,
883 obj->efile.bss, NULL);
890 static int bpf_object__init_user_maps(struct bpf_object *obj, bool strict)
892 Elf_Data *symbols = obj->efile.symbols;
893 int i, map_def_sz = 0, nr_maps = 0, nr_syms;
894 Elf_Data *data = NULL;
897 if (obj->efile.maps_shndx < 0)
903 scn = elf_getscn(obj->efile.elf, obj->efile.maps_shndx);
905 data = elf_getdata(scn, NULL);
907 pr_warning("failed to get Elf_Data from map section %d\n",
908 obj->efile.maps_shndx);
913 * Count number of maps. Each map has a name.
914 * Array of maps is not supported: only the first element is
917 * TODO: Detect array of map and report error.
919 nr_syms = symbols->d_size / sizeof(GElf_Sym);
920 for (i = 0; i < nr_syms; i++) {
923 if (!gelf_getsym(symbols, i, &sym))
925 if (sym.st_shndx != obj->efile.maps_shndx)
929 /* Assume equally sized map definitions */
930 pr_debug("maps in %s: %d maps in %zd bytes\n",
931 obj->path, nr_maps, data->d_size);
933 map_def_sz = data->d_size / nr_maps;
934 if (!data->d_size || (data->d_size % nr_maps) != 0) {
935 pr_warning("unable to determine map definition size "
936 "section %s, %d maps in %zd bytes\n",
937 obj->path, nr_maps, data->d_size);
941 /* Fill obj->maps using data in "maps" section. */
942 for (i = 0; i < nr_syms; i++) {
944 const char *map_name;
945 struct bpf_map_def *def;
948 if (!gelf_getsym(symbols, i, &sym))
950 if (sym.st_shndx != obj->efile.maps_shndx)
953 map = bpf_object__add_map(obj);
957 map_name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
960 pr_warning("failed to get map #%d name sym string for obj %s\n",
962 return -LIBBPF_ERRNO__FORMAT;
965 map->libbpf_type = LIBBPF_MAP_UNSPEC;
966 map->sec_idx = sym.st_shndx;
967 map->sec_offset = sym.st_value;
968 pr_debug("map '%s' (legacy): at sec_idx %d, offset %zu.\n",
969 map_name, map->sec_idx, map->sec_offset);
970 if (sym.st_value + map_def_sz > data->d_size) {
971 pr_warning("corrupted maps section in %s: last map \"%s\" too small\n",
972 obj->path, map_name);
976 map->name = strdup(map_name);
978 pr_warning("failed to alloc map name\n");
981 pr_debug("map %d is \"%s\"\n", i, map->name);
982 def = (struct bpf_map_def *)(data->d_buf + sym.st_value);
984 * If the definition of the map in the object file fits in
985 * bpf_map_def, copy it. Any extra fields in our version
986 * of bpf_map_def will default to zero as a result of the
989 if (map_def_sz <= sizeof(struct bpf_map_def)) {
990 memcpy(&map->def, def, map_def_sz);
993 * Here the map structure being read is bigger than what
994 * we expect, truncate if the excess bits are all zero.
995 * If they are not zero, reject this map as
999 for (b = ((char *)def) + sizeof(struct bpf_map_def);
1000 b < ((char *)def) + map_def_sz; b++) {
1002 pr_warning("maps section in %s: \"%s\" "
1003 "has unrecognized, non-zero "
1005 obj->path, map_name);
1010 memcpy(&map->def, def, sizeof(struct bpf_map_def));
1016 static const struct btf_type *skip_mods_and_typedefs(const struct btf *btf,
1019 const struct btf_type *t = btf__type_by_id(btf, id);
1022 switch (BTF_INFO_KIND(t->info)) {
1023 case BTF_KIND_VOLATILE:
1024 case BTF_KIND_CONST:
1025 case BTF_KIND_RESTRICT:
1026 case BTF_KIND_TYPEDEF:
1027 t = btf__type_by_id(btf, t->type);
1036 * Fetch integer attribute of BTF map definition. Such attributes are
1037 * represented using a pointer to an array, in which dimensionality of array
1038 * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
1039 * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
1040 * type definition, while using only sizeof(void *) space in ELF data section.
1042 static bool get_map_field_int(const char *map_name, const struct btf *btf,
1043 const struct btf_type *def,
1044 const struct btf_member *m, __u32 *res) {
1045 const struct btf_type *t = skip_mods_and_typedefs(btf, m->type);
1046 const char *name = btf__name_by_offset(btf, m->name_off);
1047 const struct btf_array *arr_info;
1048 const struct btf_type *arr_t;
1050 if (BTF_INFO_KIND(t->info) != BTF_KIND_PTR) {
1051 pr_warning("map '%s': attr '%s': expected PTR, got %u.\n",
1052 map_name, name, BTF_INFO_KIND(t->info));
1056 arr_t = btf__type_by_id(btf, t->type);
1058 pr_warning("map '%s': attr '%s': type [%u] not found.\n",
1059 map_name, name, t->type);
1062 if (BTF_INFO_KIND(arr_t->info) != BTF_KIND_ARRAY) {
1063 pr_warning("map '%s': attr '%s': expected ARRAY, got %u.\n",
1064 map_name, name, BTF_INFO_KIND(arr_t->info));
1067 arr_info = (const void *)(arr_t + 1);
1068 *res = arr_info->nelems;
1072 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
1073 const struct btf_type *sec,
1074 int var_idx, int sec_idx,
1075 const Elf_Data *data, bool strict)
1077 const struct btf_type *var, *def, *t;
1078 const struct btf_var_secinfo *vi;
1079 const struct btf_var *var_extra;
1080 const struct btf_member *m;
1081 const char *map_name;
1082 struct bpf_map *map;
1085 vi = (const struct btf_var_secinfo *)(const void *)(sec + 1) + var_idx;
1086 var = btf__type_by_id(obj->btf, vi->type);
1087 var_extra = (const void *)(var + 1);
1088 map_name = btf__name_by_offset(obj->btf, var->name_off);
1089 vlen = BTF_INFO_VLEN(var->info);
1091 if (map_name == NULL || map_name[0] == '\0') {
1092 pr_warning("map #%d: empty name.\n", var_idx);
1095 if ((__u64)vi->offset + vi->size > data->d_size) {
1096 pr_warning("map '%s' BTF data is corrupted.\n", map_name);
1099 if (BTF_INFO_KIND(var->info) != BTF_KIND_VAR) {
1100 pr_warning("map '%s': unexpected var kind %u.\n",
1101 map_name, BTF_INFO_KIND(var->info));
1104 if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED &&
1105 var_extra->linkage != BTF_VAR_STATIC) {
1106 pr_warning("map '%s': unsupported var linkage %u.\n",
1107 map_name, var_extra->linkage);
1111 def = skip_mods_and_typedefs(obj->btf, var->type);
1112 if (BTF_INFO_KIND(def->info) != BTF_KIND_STRUCT) {
1113 pr_warning("map '%s': unexpected def kind %u.\n",
1114 map_name, BTF_INFO_KIND(var->info));
1117 if (def->size > vi->size) {
1118 pr_warning("map '%s': invalid def size.\n", map_name);
1122 map = bpf_object__add_map(obj);
1124 return PTR_ERR(map);
1125 map->name = strdup(map_name);
1127 pr_warning("map '%s': failed to alloc map name.\n", map_name);
1130 map->libbpf_type = LIBBPF_MAP_UNSPEC;
1131 map->def.type = BPF_MAP_TYPE_UNSPEC;
1132 map->sec_idx = sec_idx;
1133 map->sec_offset = vi->offset;
1134 pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
1135 map_name, map->sec_idx, map->sec_offset);
1137 vlen = BTF_INFO_VLEN(def->info);
1138 m = (const void *)(def + 1);
1139 for (i = 0; i < vlen; i++, m++) {
1140 const char *name = btf__name_by_offset(obj->btf, m->name_off);
1143 pr_warning("map '%s': invalid field #%d.\n",
1147 if (strcmp(name, "type") == 0) {
1148 if (!get_map_field_int(map_name, obj->btf, def, m,
1151 pr_debug("map '%s': found type = %u.\n",
1152 map_name, map->def.type);
1153 } else if (strcmp(name, "max_entries") == 0) {
1154 if (!get_map_field_int(map_name, obj->btf, def, m,
1155 &map->def.max_entries))
1157 pr_debug("map '%s': found max_entries = %u.\n",
1158 map_name, map->def.max_entries);
1159 } else if (strcmp(name, "map_flags") == 0) {
1160 if (!get_map_field_int(map_name, obj->btf, def, m,
1161 &map->def.map_flags))
1163 pr_debug("map '%s': found map_flags = %u.\n",
1164 map_name, map->def.map_flags);
1165 } else if (strcmp(name, "key_size") == 0) {
1168 if (!get_map_field_int(map_name, obj->btf, def, m,
1171 pr_debug("map '%s': found key_size = %u.\n",
1173 if (map->def.key_size && map->def.key_size != sz) {
1174 pr_warning("map '%s': conflicting key size %u != %u.\n",
1175 map_name, map->def.key_size, sz);
1178 map->def.key_size = sz;
1179 } else if (strcmp(name, "key") == 0) {
1182 t = btf__type_by_id(obj->btf, m->type);
1184 pr_warning("map '%s': key type [%d] not found.\n",
1188 if (BTF_INFO_KIND(t->info) != BTF_KIND_PTR) {
1189 pr_warning("map '%s': key spec is not PTR: %u.\n",
1190 map_name, BTF_INFO_KIND(t->info));
1193 sz = btf__resolve_size(obj->btf, t->type);
1195 pr_warning("map '%s': can't determine key size for type [%u]: %lld.\n",
1196 map_name, t->type, sz);
1199 pr_debug("map '%s': found key [%u], sz = %lld.\n",
1200 map_name, t->type, sz);
1201 if (map->def.key_size && map->def.key_size != sz) {
1202 pr_warning("map '%s': conflicting key size %u != %lld.\n",
1203 map_name, map->def.key_size, sz);
1206 map->def.key_size = sz;
1207 map->btf_key_type_id = t->type;
1208 } else if (strcmp(name, "value_size") == 0) {
1211 if (!get_map_field_int(map_name, obj->btf, def, m,
1214 pr_debug("map '%s': found value_size = %u.\n",
1216 if (map->def.value_size && map->def.value_size != sz) {
1217 pr_warning("map '%s': conflicting value size %u != %u.\n",
1218 map_name, map->def.value_size, sz);
1221 map->def.value_size = sz;
1222 } else if (strcmp(name, "value") == 0) {
1225 t = btf__type_by_id(obj->btf, m->type);
1227 pr_warning("map '%s': value type [%d] not found.\n",
1231 if (BTF_INFO_KIND(t->info) != BTF_KIND_PTR) {
1232 pr_warning("map '%s': value spec is not PTR: %u.\n",
1233 map_name, BTF_INFO_KIND(t->info));
1236 sz = btf__resolve_size(obj->btf, t->type);
1238 pr_warning("map '%s': can't determine value size for type [%u]: %lld.\n",
1239 map_name, t->type, sz);
1242 pr_debug("map '%s': found value [%u], sz = %lld.\n",
1243 map_name, t->type, sz);
1244 if (map->def.value_size && map->def.value_size != sz) {
1245 pr_warning("map '%s': conflicting value size %u != %lld.\n",
1246 map_name, map->def.value_size, sz);
1249 map->def.value_size = sz;
1250 map->btf_value_type_id = t->type;
1253 pr_warning("map '%s': unknown field '%s'.\n",
1257 pr_debug("map '%s': ignoring unknown field '%s'.\n",
1262 if (map->def.type == BPF_MAP_TYPE_UNSPEC) {
1263 pr_warning("map '%s': map type isn't specified.\n", map_name);
1270 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict)
1272 const struct btf_type *sec = NULL;
1273 int nr_types, i, vlen, err;
1274 const struct btf_type *t;
1279 if (obj->efile.btf_maps_shndx < 0)
1282 scn = elf_getscn(obj->efile.elf, obj->efile.btf_maps_shndx);
1284 data = elf_getdata(scn, NULL);
1285 if (!scn || !data) {
1286 pr_warning("failed to get Elf_Data from map section %d (%s)\n",
1287 obj->efile.maps_shndx, MAPS_ELF_SEC);
1291 nr_types = btf__get_nr_types(obj->btf);
1292 for (i = 1; i <= nr_types; i++) {
1293 t = btf__type_by_id(obj->btf, i);
1294 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
1296 name = btf__name_by_offset(obj->btf, t->name_off);
1297 if (strcmp(name, MAPS_ELF_SEC) == 0) {
1304 pr_warning("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
1308 vlen = BTF_INFO_VLEN(sec->info);
1309 for (i = 0; i < vlen; i++) {
1310 err = bpf_object__init_user_btf_map(obj, sec, i,
1311 obj->efile.btf_maps_shndx,
1320 static int bpf_object__init_maps(struct bpf_object *obj, int flags)
1322 bool strict = !(flags & MAPS_RELAX_COMPAT);
1325 err = bpf_object__init_user_maps(obj, strict);
1329 err = bpf_object__init_user_btf_maps(obj, strict);
1333 err = bpf_object__init_global_data_maps(obj);
1338 qsort(obj->maps, obj->nr_maps, sizeof(obj->maps[0]),
1344 static bool section_have_execinstr(struct bpf_object *obj, int idx)
1349 scn = elf_getscn(obj->efile.elf, idx);
1353 if (gelf_getshdr(scn, &sh) != &sh)
1356 if (sh.sh_flags & SHF_EXECINSTR)
1362 static void bpf_object__sanitize_btf(struct bpf_object *obj)
1364 bool has_datasec = obj->caps.btf_datasec;
1365 bool has_func = obj->caps.btf_func;
1366 struct btf *btf = obj->btf;
1371 if (!obj->btf || (has_func && has_datasec))
1374 for (i = 1; i <= btf__get_nr_types(btf); i++) {
1375 t = (struct btf_type *)btf__type_by_id(btf, i);
1376 kind = BTF_INFO_KIND(t->info);
1378 if (!has_datasec && kind == BTF_KIND_VAR) {
1379 /* replace VAR with INT */
1380 t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
1382 * using size = 1 is the safest choice, 4 will be too
1383 * big and cause kernel BTF validation failure if
1384 * original variable took less than 4 bytes
1387 *(int *)(t+1) = BTF_INT_ENC(0, 0, 8);
1388 } else if (!has_datasec && kind == BTF_KIND_DATASEC) {
1389 /* replace DATASEC with STRUCT */
1390 struct btf_var_secinfo *v = (void *)(t + 1);
1391 struct btf_member *m = (void *)(t + 1);
1392 struct btf_type *vt;
1395 name = (char *)btf__name_by_offset(btf, t->name_off);
1402 vlen = BTF_INFO_VLEN(t->info);
1403 t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
1404 for (j = 0; j < vlen; j++, v++, m++) {
1405 /* order of field assignments is important */
1406 m->offset = v->offset * 8;
1408 /* preserve variable name as member name */
1409 vt = (void *)btf__type_by_id(btf, v->type);
1410 m->name_off = vt->name_off;
1412 } else if (!has_func && kind == BTF_KIND_FUNC_PROTO) {
1413 /* replace FUNC_PROTO with ENUM */
1414 vlen = BTF_INFO_VLEN(t->info);
1415 t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
1416 t->size = sizeof(__u32); /* kernel enforced */
1417 } else if (!has_func && kind == BTF_KIND_FUNC) {
1418 /* replace FUNC with TYPEDEF */
1419 t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
1424 static void bpf_object__sanitize_btf_ext(struct bpf_object *obj)
1429 if (!obj->caps.btf_func) {
1430 btf_ext__free(obj->btf_ext);
1431 obj->btf_ext = NULL;
1435 static bool bpf_object__is_btf_mandatory(const struct bpf_object *obj)
1437 return obj->efile.btf_maps_shndx >= 0;
1440 static int bpf_object__init_btf(struct bpf_object *obj,
1442 Elf_Data *btf_ext_data)
1444 bool btf_required = bpf_object__is_btf_mandatory(obj);
1448 obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
1449 if (IS_ERR(obj->btf)) {
1450 pr_warning("Error loading ELF section %s: %d.\n",
1454 err = btf__finalize_data(obj, obj->btf);
1456 pr_warning("Error finalizing %s: %d.\n",
1463 pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
1464 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
1467 obj->btf_ext = btf_ext__new(btf_ext_data->d_buf,
1468 btf_ext_data->d_size);
1469 if (IS_ERR(obj->btf_ext)) {
1470 pr_warning("Error loading ELF section %s: %ld. Ignored and continue.\n",
1471 BTF_EXT_ELF_SEC, PTR_ERR(obj->btf_ext));
1472 obj->btf_ext = NULL;
1477 if (err || IS_ERR(obj->btf)) {
1479 err = err ? : PTR_ERR(obj->btf);
1482 if (!IS_ERR_OR_NULL(obj->btf))
1483 btf__free(obj->btf);
1486 if (btf_required && !obj->btf) {
1487 pr_warning("BTF is required, but is missing or corrupted.\n");
1488 return err == 0 ? -ENOENT : err;
1493 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
1500 bpf_object__sanitize_btf(obj);
1501 bpf_object__sanitize_btf_ext(obj);
1503 err = btf__load(obj->btf);
1505 pr_warning("Error loading %s into kernel: %d.\n",
1507 btf__free(obj->btf);
1509 /* btf_ext can't exist without btf, so free it as well */
1511 btf_ext__free(obj->btf_ext);
1512 obj->btf_ext = NULL;
1515 if (bpf_object__is_btf_mandatory(obj))
1521 static int bpf_object__elf_collect(struct bpf_object *obj, int flags)
1523 Elf *elf = obj->efile.elf;
1524 GElf_Ehdr *ep = &obj->efile.ehdr;
1525 Elf_Data *btf_ext_data = NULL;
1526 Elf_Data *btf_data = NULL;
1527 Elf_Scn *scn = NULL;
1528 int idx = 0, err = 0;
1530 /* Elf is corrupted/truncated, avoid calling elf_strptr. */
1531 if (!elf_rawdata(elf_getscn(elf, ep->e_shstrndx), NULL)) {
1532 pr_warning("failed to get e_shstrndx from %s\n", obj->path);
1533 return -LIBBPF_ERRNO__FORMAT;
1536 while ((scn = elf_nextscn(elf, scn)) != NULL) {
1542 if (gelf_getshdr(scn, &sh) != &sh) {
1543 pr_warning("failed to get section(%d) header from %s\n",
1545 return -LIBBPF_ERRNO__FORMAT;
1548 name = elf_strptr(elf, ep->e_shstrndx, sh.sh_name);
1550 pr_warning("failed to get section(%d) name from %s\n",
1552 return -LIBBPF_ERRNO__FORMAT;
1555 data = elf_getdata(scn, 0);
1557 pr_warning("failed to get section(%d) data from %s(%s)\n",
1558 idx, name, obj->path);
1559 return -LIBBPF_ERRNO__FORMAT;
1561 pr_debug("section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
1562 idx, name, (unsigned long)data->d_size,
1563 (int)sh.sh_link, (unsigned long)sh.sh_flags,
1566 if (strcmp(name, "license") == 0) {
1567 err = bpf_object__init_license(obj,
1572 } else if (strcmp(name, "version") == 0) {
1573 err = bpf_object__init_kversion(obj,
1578 } else if (strcmp(name, "maps") == 0) {
1579 obj->efile.maps_shndx = idx;
1580 } else if (strcmp(name, MAPS_ELF_SEC) == 0) {
1581 obj->efile.btf_maps_shndx = idx;
1582 } else if (strcmp(name, BTF_ELF_SEC) == 0) {
1584 } else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
1585 btf_ext_data = data;
1586 } else if (sh.sh_type == SHT_SYMTAB) {
1587 if (obj->efile.symbols) {
1588 pr_warning("bpf: multiple SYMTAB in %s\n",
1590 return -LIBBPF_ERRNO__FORMAT;
1592 obj->efile.symbols = data;
1593 obj->efile.strtabidx = sh.sh_link;
1594 } else if (sh.sh_type == SHT_PROGBITS && data->d_size > 0) {
1595 if (sh.sh_flags & SHF_EXECINSTR) {
1596 if (strcmp(name, ".text") == 0)
1597 obj->efile.text_shndx = idx;
1598 err = bpf_object__add_program(obj, data->d_buf,
1599 data->d_size, name, idx);
1601 char errmsg[STRERR_BUFSIZE];
1602 char *cp = libbpf_strerror_r(-err, errmsg,
1605 pr_warning("failed to alloc program %s (%s): %s",
1606 name, obj->path, cp);
1609 } else if (strcmp(name, ".data") == 0) {
1610 obj->efile.data = data;
1611 obj->efile.data_shndx = idx;
1612 } else if (strcmp(name, ".rodata") == 0) {
1613 obj->efile.rodata = data;
1614 obj->efile.rodata_shndx = idx;
1616 pr_debug("skip section(%d) %s\n", idx, name);
1618 } else if (sh.sh_type == SHT_REL) {
1619 int nr_reloc = obj->efile.nr_reloc;
1620 void *reloc = obj->efile.reloc;
1621 int sec = sh.sh_info; /* points to other section */
1623 /* Only do relo for section with exec instructions */
1624 if (!section_have_execinstr(obj, sec)) {
1625 pr_debug("skip relo %s(%d) for section(%d)\n",
1630 reloc = reallocarray(reloc, nr_reloc + 1,
1631 sizeof(*obj->efile.reloc));
1633 pr_warning("realloc failed\n");
1637 obj->efile.reloc = reloc;
1638 obj->efile.nr_reloc++;
1640 obj->efile.reloc[nr_reloc].shdr = sh;
1641 obj->efile.reloc[nr_reloc].data = data;
1642 } else if (sh.sh_type == SHT_NOBITS && strcmp(name, ".bss") == 0) {
1643 obj->efile.bss = data;
1644 obj->efile.bss_shndx = idx;
1646 pr_debug("skip section(%d) %s\n", idx, name);
1650 if (!obj->efile.strtabidx || obj->efile.strtabidx >= idx) {
1651 pr_warning("Corrupted ELF file: index of strtab invalid\n");
1652 return -LIBBPF_ERRNO__FORMAT;
1654 err = bpf_object__init_btf(obj, btf_data, btf_ext_data);
1656 err = bpf_object__init_maps(obj, flags);
1658 err = bpf_object__sanitize_and_load_btf(obj);
1660 err = bpf_object__init_prog_names(obj);
1664 static struct bpf_program *
1665 bpf_object__find_prog_by_idx(struct bpf_object *obj, int idx)
1667 struct bpf_program *prog;
1670 for (i = 0; i < obj->nr_programs; i++) {
1671 prog = &obj->programs[i];
1672 if (prog->idx == idx)
1678 struct bpf_program *
1679 bpf_object__find_program_by_title(const struct bpf_object *obj,
1682 struct bpf_program *pos;
1684 bpf_object__for_each_program(pos, obj) {
1685 if (pos->section_name && !strcmp(pos->section_name, title))
1691 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
1694 return shndx == obj->efile.data_shndx ||
1695 shndx == obj->efile.bss_shndx ||
1696 shndx == obj->efile.rodata_shndx;
1699 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
1702 return shndx == obj->efile.maps_shndx ||
1703 shndx == obj->efile.btf_maps_shndx;
1706 static bool bpf_object__relo_in_known_section(const struct bpf_object *obj,
1709 return shndx == obj->efile.text_shndx ||
1710 bpf_object__shndx_is_maps(obj, shndx) ||
1711 bpf_object__shndx_is_data(obj, shndx);
1714 static enum libbpf_map_type
1715 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
1717 if (shndx == obj->efile.data_shndx)
1718 return LIBBPF_MAP_DATA;
1719 else if (shndx == obj->efile.bss_shndx)
1720 return LIBBPF_MAP_BSS;
1721 else if (shndx == obj->efile.rodata_shndx)
1722 return LIBBPF_MAP_RODATA;
1724 return LIBBPF_MAP_UNSPEC;
1728 bpf_program__collect_reloc(struct bpf_program *prog, GElf_Shdr *shdr,
1729 Elf_Data *data, struct bpf_object *obj)
1731 Elf_Data *symbols = obj->efile.symbols;
1732 struct bpf_map *maps = obj->maps;
1733 size_t nr_maps = obj->nr_maps;
1736 pr_debug("collecting relocating info for: '%s'\n", prog->section_name);
1737 nrels = shdr->sh_size / shdr->sh_entsize;
1739 prog->reloc_desc = malloc(sizeof(*prog->reloc_desc) * nrels);
1740 if (!prog->reloc_desc) {
1741 pr_warning("failed to alloc memory in relocation\n");
1744 prog->nr_reloc = nrels;
1746 for (i = 0; i < nrels; i++) {
1747 struct bpf_insn *insns = prog->insns;
1748 enum libbpf_map_type type;
1749 unsigned int insn_idx;
1750 unsigned int shdr_idx;
1756 if (!gelf_getrel(data, i, &rel)) {
1757 pr_warning("relocation: failed to get %d reloc\n", i);
1758 return -LIBBPF_ERRNO__FORMAT;
1761 if (!gelf_getsym(symbols, GELF_R_SYM(rel.r_info), &sym)) {
1762 pr_warning("relocation: symbol %"PRIx64" not found\n",
1763 GELF_R_SYM(rel.r_info));
1764 return -LIBBPF_ERRNO__FORMAT;
1767 name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
1768 sym.st_name) ? : "<?>";
1770 pr_debug("relo for %lld value %lld name %d (\'%s\')\n",
1771 (long long) (rel.r_info >> 32),
1772 (long long) sym.st_value, sym.st_name, name);
1774 shdr_idx = sym.st_shndx;
1775 if (!bpf_object__relo_in_known_section(obj, shdr_idx)) {
1776 pr_warning("Program '%s' contains unrecognized relo data pointing to section %u\n",
1777 prog->section_name, shdr_idx);
1778 return -LIBBPF_ERRNO__RELOC;
1781 insn_idx = rel.r_offset / sizeof(struct bpf_insn);
1782 pr_debug("relocation: insn_idx=%u\n", insn_idx);
1784 if (insns[insn_idx].code == (BPF_JMP | BPF_CALL)) {
1785 if (insns[insn_idx].src_reg != BPF_PSEUDO_CALL) {
1786 pr_warning("incorrect bpf_call opcode\n");
1787 return -LIBBPF_ERRNO__RELOC;
1789 prog->reloc_desc[i].type = RELO_CALL;
1790 prog->reloc_desc[i].insn_idx = insn_idx;
1791 prog->reloc_desc[i].text_off = sym.st_value;
1792 obj->has_pseudo_calls = true;
1796 if (insns[insn_idx].code != (BPF_LD | BPF_IMM | BPF_DW)) {
1797 pr_warning("bpf: relocation: invalid relo for insns[%d].code 0x%x\n",
1798 insn_idx, insns[insn_idx].code);
1799 return -LIBBPF_ERRNO__RELOC;
1802 if (bpf_object__shndx_is_maps(obj, shdr_idx) ||
1803 bpf_object__shndx_is_data(obj, shdr_idx)) {
1804 type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
1805 if (type != LIBBPF_MAP_UNSPEC) {
1806 if (GELF_ST_BIND(sym.st_info) == STB_GLOBAL) {
1807 pr_warning("bpf: relocation: not yet supported relo for non-static global \'%s\' variable found in insns[%d].code 0x%x\n",
1808 name, insn_idx, insns[insn_idx].code);
1809 return -LIBBPF_ERRNO__RELOC;
1811 if (!obj->caps.global_data) {
1812 pr_warning("bpf: relocation: kernel does not support global \'%s\' variable access in insns[%d]\n",
1814 return -LIBBPF_ERRNO__RELOC;
1818 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
1819 if (maps[map_idx].libbpf_type != type)
1821 if (type != LIBBPF_MAP_UNSPEC ||
1822 (maps[map_idx].sec_idx == sym.st_shndx &&
1823 maps[map_idx].sec_offset == sym.st_value)) {
1824 pr_debug("relocation: found map %zd (%s, sec_idx %d, offset %zu) for insn %u\n",
1825 map_idx, maps[map_idx].name,
1826 maps[map_idx].sec_idx,
1827 maps[map_idx].sec_offset,
1833 if (map_idx >= nr_maps) {
1834 pr_warning("bpf relocation: map_idx %d larger than %d\n",
1835 (int)map_idx, (int)nr_maps - 1);
1836 return -LIBBPF_ERRNO__RELOC;
1839 prog->reloc_desc[i].type = type != LIBBPF_MAP_UNSPEC ?
1840 RELO_DATA : RELO_LD64;
1841 prog->reloc_desc[i].insn_idx = insn_idx;
1842 prog->reloc_desc[i].map_idx = map_idx;
1848 static int bpf_map_find_btf_info(struct bpf_object *obj, struct bpf_map *map)
1850 struct bpf_map_def *def = &map->def;
1851 __u32 key_type_id = 0, value_type_id = 0;
1854 /* if it's BTF-defined map, we don't need to search for type IDs */
1855 if (map->sec_idx == obj->efile.btf_maps_shndx)
1858 if (!bpf_map__is_internal(map)) {
1859 ret = btf__get_map_kv_tids(obj->btf, map->name, def->key_size,
1860 def->value_size, &key_type_id,
1864 * LLVM annotates global data differently in BTF, that is,
1865 * only as '.data', '.bss' or '.rodata'.
1867 ret = btf__find_by_name(obj->btf,
1868 libbpf_type_to_btf_name[map->libbpf_type]);
1873 map->btf_key_type_id = key_type_id;
1874 map->btf_value_type_id = bpf_map__is_internal(map) ?
1875 ret : value_type_id;
1879 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
1881 struct bpf_map_info info = {};
1882 __u32 len = sizeof(info);
1886 err = bpf_obj_get_info_by_fd(fd, &info, &len);
1890 new_name = strdup(info.name);
1894 new_fd = open("/", O_RDONLY | O_CLOEXEC);
1896 goto err_free_new_name;
1898 new_fd = dup3(fd, new_fd, O_CLOEXEC);
1900 goto err_close_new_fd;
1902 err = zclose(map->fd);
1904 goto err_close_new_fd;
1908 map->name = new_name;
1909 map->def.type = info.type;
1910 map->def.key_size = info.key_size;
1911 map->def.value_size = info.value_size;
1912 map->def.max_entries = info.max_entries;
1913 map->def.map_flags = info.map_flags;
1914 map->btf_key_type_id = info.btf_key_type_id;
1915 map->btf_value_type_id = info.btf_value_type_id;
1926 int bpf_map__resize(struct bpf_map *map, __u32 max_entries)
1928 if (!map || !max_entries)
1931 /* If map already created, its attributes can't be changed. */
1935 map->def.max_entries = max_entries;
1941 bpf_object__probe_name(struct bpf_object *obj)
1943 struct bpf_load_program_attr attr;
1944 char *cp, errmsg[STRERR_BUFSIZE];
1945 struct bpf_insn insns[] = {
1946 BPF_MOV64_IMM(BPF_REG_0, 0),
1951 /* make sure basic loading works */
1953 memset(&attr, 0, sizeof(attr));
1954 attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
1956 attr.insns_cnt = ARRAY_SIZE(insns);
1957 attr.license = "GPL";
1959 ret = bpf_load_program_xattr(&attr, NULL, 0);
1961 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
1962 pr_warning("Error in %s():%s(%d). Couldn't load basic 'r0 = 0' BPF program.\n",
1963 __func__, cp, errno);
1968 /* now try the same program, but with the name */
1971 ret = bpf_load_program_xattr(&attr, NULL, 0);
1981 bpf_object__probe_global_data(struct bpf_object *obj)
1983 struct bpf_load_program_attr prg_attr;
1984 struct bpf_create_map_attr map_attr;
1985 char *cp, errmsg[STRERR_BUFSIZE];
1986 struct bpf_insn insns[] = {
1987 BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16),
1988 BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42),
1989 BPF_MOV64_IMM(BPF_REG_0, 0),
1994 memset(&map_attr, 0, sizeof(map_attr));
1995 map_attr.map_type = BPF_MAP_TYPE_ARRAY;
1996 map_attr.key_size = sizeof(int);
1997 map_attr.value_size = 32;
1998 map_attr.max_entries = 1;
2000 map = bpf_create_map_xattr(&map_attr);
2002 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
2003 pr_warning("Error in %s():%s(%d). Couldn't create simple array map.\n",
2004 __func__, cp, errno);
2010 memset(&prg_attr, 0, sizeof(prg_attr));
2011 prg_attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
2012 prg_attr.insns = insns;
2013 prg_attr.insns_cnt = ARRAY_SIZE(insns);
2014 prg_attr.license = "GPL";
2016 ret = bpf_load_program_xattr(&prg_attr, NULL, 0);
2018 obj->caps.global_data = 1;
2026 static int bpf_object__probe_btf_func(struct bpf_object *obj)
2028 const char strs[] = "\0int\0x\0a";
2029 /* void x(int a) {} */
2032 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
2033 /* FUNC_PROTO */ /* [2] */
2034 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
2035 BTF_PARAM_ENC(7, 1),
2036 /* FUNC x */ /* [3] */
2037 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0), 2),
2041 btf_fd = libbpf__load_raw_btf((char *)types, sizeof(types),
2042 strs, sizeof(strs));
2044 obj->caps.btf_func = 1;
2052 static int bpf_object__probe_btf_datasec(struct bpf_object *obj)
2054 const char strs[] = "\0x\0.data";
2058 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
2059 /* VAR x */ /* [2] */
2060 BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
2062 /* DATASEC val */ /* [3] */
2063 BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC, 0, 1), 4),
2064 BTF_VAR_SECINFO_ENC(2, 0, 4),
2068 btf_fd = libbpf__load_raw_btf((char *)types, sizeof(types),
2069 strs, sizeof(strs));
2071 obj->caps.btf_datasec = 1;
2080 bpf_object__probe_caps(struct bpf_object *obj)
2082 int (*probe_fn[])(struct bpf_object *obj) = {
2083 bpf_object__probe_name,
2084 bpf_object__probe_global_data,
2085 bpf_object__probe_btf_func,
2086 bpf_object__probe_btf_datasec,
2090 for (i = 0; i < ARRAY_SIZE(probe_fn); i++) {
2091 ret = probe_fn[i](obj);
2093 pr_debug("Probe #%d failed with %d.\n", i, ret);
2100 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
2102 char *cp, errmsg[STRERR_BUFSIZE];
2106 /* Nothing to do here since kernel already zero-initializes .bss map. */
2107 if (map->libbpf_type == LIBBPF_MAP_BSS)
2110 data = map->libbpf_type == LIBBPF_MAP_DATA ?
2111 obj->sections.data : obj->sections.rodata;
2113 err = bpf_map_update_elem(map->fd, &zero, data, 0);
2114 /* Freeze .rodata map as read-only from syscall side. */
2115 if (!err && map->libbpf_type == LIBBPF_MAP_RODATA) {
2116 err = bpf_map_freeze(map->fd);
2118 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
2119 pr_warning("Error freezing map(%s) as read-only: %s\n",
2128 bpf_object__create_maps(struct bpf_object *obj)
2130 struct bpf_create_map_attr create_attr = {};
2135 for (i = 0; i < obj->nr_maps; i++) {
2136 struct bpf_map *map = &obj->maps[i];
2137 struct bpf_map_def *def = &map->def;
2138 char *cp, errmsg[STRERR_BUFSIZE];
2139 int *pfd = &map->fd;
2142 pr_debug("skip map create (preset) %s: fd=%d\n",
2143 map->name, map->fd);
2148 create_attr.name = map->name;
2149 create_attr.map_ifindex = map->map_ifindex;
2150 create_attr.map_type = def->type;
2151 create_attr.map_flags = def->map_flags;
2152 create_attr.key_size = def->key_size;
2153 create_attr.value_size = def->value_size;
2154 if (def->type == BPF_MAP_TYPE_PERF_EVENT_ARRAY &&
2155 !def->max_entries) {
2157 nr_cpus = libbpf_num_possible_cpus();
2159 pr_warning("failed to determine number of system CPUs: %d\n",
2164 pr_debug("map '%s': setting size to %d\n",
2165 map->name, nr_cpus);
2166 create_attr.max_entries = nr_cpus;
2168 create_attr.max_entries = def->max_entries;
2170 create_attr.btf_fd = 0;
2171 create_attr.btf_key_type_id = 0;
2172 create_attr.btf_value_type_id = 0;
2173 if (bpf_map_type__is_map_in_map(def->type) &&
2174 map->inner_map_fd >= 0)
2175 create_attr.inner_map_fd = map->inner_map_fd;
2177 if (obj->btf && !bpf_map_find_btf_info(obj, map)) {
2178 create_attr.btf_fd = btf__fd(obj->btf);
2179 create_attr.btf_key_type_id = map->btf_key_type_id;
2180 create_attr.btf_value_type_id = map->btf_value_type_id;
2183 *pfd = bpf_create_map_xattr(&create_attr);
2184 if (*pfd < 0 && (create_attr.btf_key_type_id ||
2185 create_attr.btf_value_type_id)) {
2187 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
2188 pr_warning("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
2189 map->name, cp, err);
2190 create_attr.btf_fd = 0;
2191 create_attr.btf_key_type_id = 0;
2192 create_attr.btf_value_type_id = 0;
2193 map->btf_key_type_id = 0;
2194 map->btf_value_type_id = 0;
2195 *pfd = bpf_create_map_xattr(&create_attr);
2203 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
2204 pr_warning("failed to create map (name: '%s'): %s(%d)\n",
2205 map->name, cp, err);
2206 for (j = 0; j < i; j++)
2207 zclose(obj->maps[j].fd);
2211 if (bpf_map__is_internal(map)) {
2212 err = bpf_object__populate_internal_map(obj, map);
2219 pr_debug("created map %s: fd=%d\n", map->name, *pfd);
2226 check_btf_ext_reloc_err(struct bpf_program *prog, int err,
2227 void *btf_prog_info, const char *info_name)
2229 if (err != -ENOENT) {
2230 pr_warning("Error in loading %s for sec %s.\n",
2231 info_name, prog->section_name);
2235 /* err == -ENOENT (i.e. prog->section_name not found in btf_ext) */
2237 if (btf_prog_info) {
2239 * Some info has already been found but has problem
2240 * in the last btf_ext reloc. Must have to error out.
2242 pr_warning("Error in relocating %s for sec %s.\n",
2243 info_name, prog->section_name);
2247 /* Have problem loading the very first info. Ignore the rest. */
2248 pr_warning("Cannot find %s for main program sec %s. Ignore all %s.\n",
2249 info_name, prog->section_name, info_name);
2254 bpf_program_reloc_btf_ext(struct bpf_program *prog, struct bpf_object *obj,
2255 const char *section_name, __u32 insn_offset)
2259 if (!insn_offset || prog->func_info) {
2261 * !insn_offset => main program
2263 * For sub prog, the main program's func_info has to
2264 * be loaded first (i.e. prog->func_info != NULL)
2266 err = btf_ext__reloc_func_info(obj->btf, obj->btf_ext,
2267 section_name, insn_offset,
2269 &prog->func_info_cnt);
2271 return check_btf_ext_reloc_err(prog, err,
2275 prog->func_info_rec_size = btf_ext__func_info_rec_size(obj->btf_ext);
2278 if (!insn_offset || prog->line_info) {
2279 err = btf_ext__reloc_line_info(obj->btf, obj->btf_ext,
2280 section_name, insn_offset,
2282 &prog->line_info_cnt);
2284 return check_btf_ext_reloc_err(prog, err,
2288 prog->line_info_rec_size = btf_ext__line_info_rec_size(obj->btf_ext);
2292 prog->btf_fd = btf__fd(obj->btf);
2298 bpf_program__reloc_text(struct bpf_program *prog, struct bpf_object *obj,
2299 struct reloc_desc *relo)
2301 struct bpf_insn *insn, *new_insn;
2302 struct bpf_program *text;
2306 if (relo->type != RELO_CALL)
2307 return -LIBBPF_ERRNO__RELOC;
2309 if (prog->idx == obj->efile.text_shndx) {
2310 pr_warning("relo in .text insn %d into off %d\n",
2311 relo->insn_idx, relo->text_off);
2312 return -LIBBPF_ERRNO__RELOC;
2315 if (prog->main_prog_cnt == 0) {
2316 text = bpf_object__find_prog_by_idx(obj, obj->efile.text_shndx);
2318 pr_warning("no .text section found yet relo into text exist\n");
2319 return -LIBBPF_ERRNO__RELOC;
2321 new_cnt = prog->insns_cnt + text->insns_cnt;
2322 new_insn = reallocarray(prog->insns, new_cnt, sizeof(*insn));
2324 pr_warning("oom in prog realloc\n");
2329 err = bpf_program_reloc_btf_ext(prog, obj,
2336 memcpy(new_insn + prog->insns_cnt, text->insns,
2337 text->insns_cnt * sizeof(*insn));
2338 prog->insns = new_insn;
2339 prog->main_prog_cnt = prog->insns_cnt;
2340 prog->insns_cnt = new_cnt;
2341 pr_debug("added %zd insn from %s to prog %s\n",
2342 text->insns_cnt, text->section_name,
2343 prog->section_name);
2345 insn = &prog->insns[relo->insn_idx];
2346 insn->imm += prog->main_prog_cnt - relo->insn_idx;
2351 bpf_program__relocate(struct bpf_program *prog, struct bpf_object *obj)
2359 err = bpf_program_reloc_btf_ext(prog, obj,
2360 prog->section_name, 0);
2365 if (!prog->reloc_desc)
2368 for (i = 0; i < prog->nr_reloc; i++) {
2369 if (prog->reloc_desc[i].type == RELO_LD64 ||
2370 prog->reloc_desc[i].type == RELO_DATA) {
2371 bool relo_data = prog->reloc_desc[i].type == RELO_DATA;
2372 struct bpf_insn *insns = prog->insns;
2373 int insn_idx, map_idx;
2375 insn_idx = prog->reloc_desc[i].insn_idx;
2376 map_idx = prog->reloc_desc[i].map_idx;
2378 if (insn_idx + 1 >= (int)prog->insns_cnt) {
2379 pr_warning("relocation out of range: '%s'\n",
2380 prog->section_name);
2381 return -LIBBPF_ERRNO__RELOC;
2385 insns[insn_idx].src_reg = BPF_PSEUDO_MAP_FD;
2387 insns[insn_idx].src_reg = BPF_PSEUDO_MAP_VALUE;
2388 insns[insn_idx + 1].imm = insns[insn_idx].imm;
2390 insns[insn_idx].imm = obj->maps[map_idx].fd;
2391 } else if (prog->reloc_desc[i].type == RELO_CALL) {
2392 err = bpf_program__reloc_text(prog, obj,
2393 &prog->reloc_desc[i]);
2399 zfree(&prog->reloc_desc);
2406 bpf_object__relocate(struct bpf_object *obj)
2408 struct bpf_program *prog;
2412 for (i = 0; i < obj->nr_programs; i++) {
2413 prog = &obj->programs[i];
2415 err = bpf_program__relocate(prog, obj);
2417 pr_warning("failed to relocate '%s'\n",
2418 prog->section_name);
2425 static int bpf_object__collect_reloc(struct bpf_object *obj)
2429 if (!obj_elf_valid(obj)) {
2430 pr_warning("Internal error: elf object is closed\n");
2431 return -LIBBPF_ERRNO__INTERNAL;
2434 for (i = 0; i < obj->efile.nr_reloc; i++) {
2435 GElf_Shdr *shdr = &obj->efile.reloc[i].shdr;
2436 Elf_Data *data = obj->efile.reloc[i].data;
2437 int idx = shdr->sh_info;
2438 struct bpf_program *prog;
2440 if (shdr->sh_type != SHT_REL) {
2441 pr_warning("internal error at %d\n", __LINE__);
2442 return -LIBBPF_ERRNO__INTERNAL;
2445 prog = bpf_object__find_prog_by_idx(obj, idx);
2447 pr_warning("relocation failed: no section(%d)\n", idx);
2448 return -LIBBPF_ERRNO__RELOC;
2451 err = bpf_program__collect_reloc(prog, shdr, data, obj);
2459 load_program(struct bpf_program *prog, struct bpf_insn *insns, int insns_cnt,
2460 char *license, __u32 kern_version, int *pfd)
2462 struct bpf_load_program_attr load_attr;
2463 char *cp, errmsg[STRERR_BUFSIZE];
2464 int log_buf_size = BPF_LOG_BUF_SIZE;
2468 if (!insns || !insns_cnt)
2471 memset(&load_attr, 0, sizeof(struct bpf_load_program_attr));
2472 load_attr.prog_type = prog->type;
2473 load_attr.expected_attach_type = prog->expected_attach_type;
2474 if (prog->caps->name)
2475 load_attr.name = prog->name;
2476 load_attr.insns = insns;
2477 load_attr.insns_cnt = insns_cnt;
2478 load_attr.license = license;
2479 load_attr.kern_version = kern_version;
2480 load_attr.prog_ifindex = prog->prog_ifindex;
2481 load_attr.prog_btf_fd = prog->btf_fd >= 0 ? prog->btf_fd : 0;
2482 load_attr.func_info = prog->func_info;
2483 load_attr.func_info_rec_size = prog->func_info_rec_size;
2484 load_attr.func_info_cnt = prog->func_info_cnt;
2485 load_attr.line_info = prog->line_info;
2486 load_attr.line_info_rec_size = prog->line_info_rec_size;
2487 load_attr.line_info_cnt = prog->line_info_cnt;
2488 load_attr.log_level = prog->log_level;
2489 load_attr.prog_flags = prog->prog_flags;
2492 log_buf = malloc(log_buf_size);
2494 pr_warning("Alloc log buffer for bpf loader error, continue without log\n");
2496 ret = bpf_load_program_xattr(&load_attr, log_buf, log_buf_size);
2499 if (load_attr.log_level)
2500 pr_debug("verifier log:\n%s", log_buf);
2506 if (errno == ENOSPC) {
2511 ret = -LIBBPF_ERRNO__LOAD;
2512 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
2513 pr_warning("load bpf program failed: %s\n", cp);
2515 if (log_buf && log_buf[0] != '\0') {
2516 ret = -LIBBPF_ERRNO__VERIFY;
2517 pr_warning("-- BEGIN DUMP LOG ---\n");
2518 pr_warning("\n%s\n", log_buf);
2519 pr_warning("-- END LOG --\n");
2520 } else if (load_attr.insns_cnt >= BPF_MAXINSNS) {
2521 pr_warning("Program too large (%zu insns), at most %d insns\n",
2522 load_attr.insns_cnt, BPF_MAXINSNS);
2523 ret = -LIBBPF_ERRNO__PROG2BIG;
2525 /* Wrong program type? */
2526 if (load_attr.prog_type != BPF_PROG_TYPE_KPROBE) {
2529 load_attr.prog_type = BPF_PROG_TYPE_KPROBE;
2530 load_attr.expected_attach_type = 0;
2531 fd = bpf_load_program_xattr(&load_attr, NULL, 0);
2534 ret = -LIBBPF_ERRNO__PROGTYPE;
2540 ret = -LIBBPF_ERRNO__KVER;
2549 bpf_program__load(struct bpf_program *prog,
2550 char *license, __u32 kern_version)
2554 if (prog->instances.nr < 0 || !prog->instances.fds) {
2555 if (prog->preprocessor) {
2556 pr_warning("Internal error: can't load program '%s'\n",
2557 prog->section_name);
2558 return -LIBBPF_ERRNO__INTERNAL;
2561 prog->instances.fds = malloc(sizeof(int));
2562 if (!prog->instances.fds) {
2563 pr_warning("Not enough memory for BPF fds\n");
2566 prog->instances.nr = 1;
2567 prog->instances.fds[0] = -1;
2570 if (!prog->preprocessor) {
2571 if (prog->instances.nr != 1) {
2572 pr_warning("Program '%s' is inconsistent: nr(%d) != 1\n",
2573 prog->section_name, prog->instances.nr);
2575 err = load_program(prog, prog->insns, prog->insns_cnt,
2576 license, kern_version, &fd);
2578 prog->instances.fds[0] = fd;
2582 for (i = 0; i < prog->instances.nr; i++) {
2583 struct bpf_prog_prep_result result;
2584 bpf_program_prep_t preprocessor = prog->preprocessor;
2586 memset(&result, 0, sizeof(result));
2587 err = preprocessor(prog, i, prog->insns,
2588 prog->insns_cnt, &result);
2590 pr_warning("Preprocessing the %dth instance of program '%s' failed\n",
2591 i, prog->section_name);
2595 if (!result.new_insn_ptr || !result.new_insn_cnt) {
2596 pr_debug("Skip loading the %dth instance of program '%s'\n",
2597 i, prog->section_name);
2598 prog->instances.fds[i] = -1;
2604 err = load_program(prog, result.new_insn_ptr,
2605 result.new_insn_cnt,
2606 license, kern_version, &fd);
2609 pr_warning("Loading the %dth instance of program '%s' failed\n",
2610 i, prog->section_name);
2616 prog->instances.fds[i] = fd;
2620 pr_warning("failed to load program '%s'\n",
2621 prog->section_name);
2622 zfree(&prog->insns);
2623 prog->insns_cnt = 0;
2627 static bool bpf_program__is_function_storage(const struct bpf_program *prog,
2628 const struct bpf_object *obj)
2630 return prog->idx == obj->efile.text_shndx && obj->has_pseudo_calls;
2634 bpf_object__load_progs(struct bpf_object *obj, int log_level)
2639 for (i = 0; i < obj->nr_programs; i++) {
2640 if (bpf_program__is_function_storage(&obj->programs[i], obj))
2642 obj->programs[i].log_level |= log_level;
2643 err = bpf_program__load(&obj->programs[i],
2652 static bool bpf_prog_type__needs_kver(enum bpf_prog_type type)
2655 case BPF_PROG_TYPE_SOCKET_FILTER:
2656 case BPF_PROG_TYPE_SCHED_CLS:
2657 case BPF_PROG_TYPE_SCHED_ACT:
2658 case BPF_PROG_TYPE_XDP:
2659 case BPF_PROG_TYPE_CGROUP_SKB:
2660 case BPF_PROG_TYPE_CGROUP_SOCK:
2661 case BPF_PROG_TYPE_LWT_IN:
2662 case BPF_PROG_TYPE_LWT_OUT:
2663 case BPF_PROG_TYPE_LWT_XMIT:
2664 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
2665 case BPF_PROG_TYPE_SOCK_OPS:
2666 case BPF_PROG_TYPE_SK_SKB:
2667 case BPF_PROG_TYPE_CGROUP_DEVICE:
2668 case BPF_PROG_TYPE_SK_MSG:
2669 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
2670 case BPF_PROG_TYPE_LIRC_MODE2:
2671 case BPF_PROG_TYPE_SK_REUSEPORT:
2672 case BPF_PROG_TYPE_FLOW_DISSECTOR:
2673 case BPF_PROG_TYPE_UNSPEC:
2674 case BPF_PROG_TYPE_TRACEPOINT:
2675 case BPF_PROG_TYPE_RAW_TRACEPOINT:
2676 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
2677 case BPF_PROG_TYPE_PERF_EVENT:
2678 case BPF_PROG_TYPE_CGROUP_SYSCTL:
2679 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
2681 case BPF_PROG_TYPE_KPROBE:
2687 static int bpf_object__validate(struct bpf_object *obj, bool needs_kver)
2689 if (needs_kver && obj->kern_version == 0) {
2690 pr_warning("%s doesn't provide kernel version\n",
2692 return -LIBBPF_ERRNO__KVERSION;
2697 static struct bpf_object *
2698 __bpf_object__open(const char *path, void *obj_buf, size_t obj_buf_sz,
2699 bool needs_kver, int flags)
2701 struct bpf_object *obj;
2704 if (elf_version(EV_CURRENT) == EV_NONE) {
2705 pr_warning("failed to init libelf for %s\n", path);
2706 return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
2709 obj = bpf_object__new(path, obj_buf, obj_buf_sz);
2713 CHECK_ERR(bpf_object__elf_init(obj), err, out);
2714 CHECK_ERR(bpf_object__check_endianness(obj), err, out);
2715 CHECK_ERR(bpf_object__probe_caps(obj), err, out);
2716 CHECK_ERR(bpf_object__elf_collect(obj, flags), err, out);
2717 CHECK_ERR(bpf_object__collect_reloc(obj), err, out);
2718 CHECK_ERR(bpf_object__validate(obj, needs_kver), err, out);
2720 bpf_object__elf_finish(obj);
2723 bpf_object__close(obj);
2724 return ERR_PTR(err);
2727 struct bpf_object *__bpf_object__open_xattr(struct bpf_object_open_attr *attr,
2730 /* param validation */
2734 pr_debug("loading %s\n", attr->file);
2736 return __bpf_object__open(attr->file, NULL, 0,
2737 bpf_prog_type__needs_kver(attr->prog_type),
2741 struct bpf_object *bpf_object__open_xattr(struct bpf_object_open_attr *attr)
2743 return __bpf_object__open_xattr(attr, 0);
2746 struct bpf_object *bpf_object__open(const char *path)
2748 struct bpf_object_open_attr attr = {
2750 .prog_type = BPF_PROG_TYPE_UNSPEC,
2753 return bpf_object__open_xattr(&attr);
2756 struct bpf_object *bpf_object__open_buffer(void *obj_buf,
2762 /* param validation */
2763 if (!obj_buf || obj_buf_sz <= 0)
2767 snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
2768 (unsigned long)obj_buf,
2769 (unsigned long)obj_buf_sz);
2772 pr_debug("loading object '%s' from buffer\n", name);
2774 return __bpf_object__open(name, obj_buf, obj_buf_sz, true, true);
2777 int bpf_object__unload(struct bpf_object *obj)
2784 for (i = 0; i < obj->nr_maps; i++)
2785 zclose(obj->maps[i].fd);
2787 for (i = 0; i < obj->nr_programs; i++)
2788 bpf_program__unload(&obj->programs[i]);
2793 int bpf_object__load_xattr(struct bpf_object_load_attr *attr)
2795 struct bpf_object *obj;
2805 pr_warning("object should not be loaded twice\n");
2811 CHECK_ERR(bpf_object__create_maps(obj), err, out);
2812 CHECK_ERR(bpf_object__relocate(obj), err, out);
2813 CHECK_ERR(bpf_object__load_progs(obj, attr->log_level), err, out);
2817 bpf_object__unload(obj);
2818 pr_warning("failed to load object '%s'\n", obj->path);
2822 int bpf_object__load(struct bpf_object *obj)
2824 struct bpf_object_load_attr attr = {
2828 return bpf_object__load_xattr(&attr);
2831 static int check_path(const char *path)
2833 char *cp, errmsg[STRERR_BUFSIZE];
2834 struct statfs st_fs;
2841 dname = strdup(path);
2845 dir = dirname(dname);
2846 if (statfs(dir, &st_fs)) {
2847 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
2848 pr_warning("failed to statfs %s: %s\n", dir, cp);
2853 if (!err && st_fs.f_type != BPF_FS_MAGIC) {
2854 pr_warning("specified path %s is not on BPF FS\n", path);
2861 int bpf_program__pin_instance(struct bpf_program *prog, const char *path,
2864 char *cp, errmsg[STRERR_BUFSIZE];
2867 err = check_path(path);
2872 pr_warning("invalid program pointer\n");
2876 if (instance < 0 || instance >= prog->instances.nr) {
2877 pr_warning("invalid prog instance %d of prog %s (max %d)\n",
2878 instance, prog->section_name, prog->instances.nr);
2882 if (bpf_obj_pin(prog->instances.fds[instance], path)) {
2883 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
2884 pr_warning("failed to pin program: %s\n", cp);
2887 pr_debug("pinned program '%s'\n", path);
2892 int bpf_program__unpin_instance(struct bpf_program *prog, const char *path,
2897 err = check_path(path);
2902 pr_warning("invalid program pointer\n");
2906 if (instance < 0 || instance >= prog->instances.nr) {
2907 pr_warning("invalid prog instance %d of prog %s (max %d)\n",
2908 instance, prog->section_name, prog->instances.nr);
2915 pr_debug("unpinned program '%s'\n", path);
2920 static int make_dir(const char *path)
2922 char *cp, errmsg[STRERR_BUFSIZE];
2925 if (mkdir(path, 0700) && errno != EEXIST)
2929 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
2930 pr_warning("failed to mkdir %s: %s\n", path, cp);
2935 int bpf_program__pin(struct bpf_program *prog, const char *path)
2939 err = check_path(path);
2944 pr_warning("invalid program pointer\n");
2948 if (prog->instances.nr <= 0) {
2949 pr_warning("no instances of prog %s to pin\n",
2950 prog->section_name);
2954 if (prog->instances.nr == 1) {
2955 /* don't create subdirs when pinning single instance */
2956 return bpf_program__pin_instance(prog, path, 0);
2959 err = make_dir(path);
2963 for (i = 0; i < prog->instances.nr; i++) {
2967 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
2971 } else if (len >= PATH_MAX) {
2972 err = -ENAMETOOLONG;
2976 err = bpf_program__pin_instance(prog, buf, i);
2984 for (i = i - 1; i >= 0; i--) {
2988 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
2991 else if (len >= PATH_MAX)
2994 bpf_program__unpin_instance(prog, buf, i);
3002 int bpf_program__unpin(struct bpf_program *prog, const char *path)
3006 err = check_path(path);
3011 pr_warning("invalid program pointer\n");
3015 if (prog->instances.nr <= 0) {
3016 pr_warning("no instances of prog %s to pin\n",
3017 prog->section_name);
3021 if (prog->instances.nr == 1) {
3022 /* don't create subdirs when pinning single instance */
3023 return bpf_program__unpin_instance(prog, path, 0);
3026 for (i = 0; i < prog->instances.nr; i++) {
3030 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
3033 else if (len >= PATH_MAX)
3034 return -ENAMETOOLONG;
3036 err = bpf_program__unpin_instance(prog, buf, i);
3048 int bpf_map__pin(struct bpf_map *map, const char *path)
3050 char *cp, errmsg[STRERR_BUFSIZE];
3053 err = check_path(path);
3058 pr_warning("invalid map pointer\n");
3062 if (bpf_obj_pin(map->fd, path)) {
3063 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
3064 pr_warning("failed to pin map: %s\n", cp);
3068 pr_debug("pinned map '%s'\n", path);
3073 int bpf_map__unpin(struct bpf_map *map, const char *path)
3077 err = check_path(path);
3082 pr_warning("invalid map pointer\n");
3089 pr_debug("unpinned map '%s'\n", path);
3094 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
3096 struct bpf_map *map;
3103 pr_warning("object not yet loaded; load it first\n");
3107 err = make_dir(path);
3111 bpf_object__for_each_map(map, obj) {
3115 len = snprintf(buf, PATH_MAX, "%s/%s", path,
3116 bpf_map__name(map));
3119 goto err_unpin_maps;
3120 } else if (len >= PATH_MAX) {
3121 err = -ENAMETOOLONG;
3122 goto err_unpin_maps;
3125 err = bpf_map__pin(map, buf);
3127 goto err_unpin_maps;
3133 while ((map = bpf_map__prev(map, obj))) {
3137 len = snprintf(buf, PATH_MAX, "%s/%s", path,
3138 bpf_map__name(map));
3141 else if (len >= PATH_MAX)
3144 bpf_map__unpin(map, buf);
3150 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
3152 struct bpf_map *map;
3158 bpf_object__for_each_map(map, obj) {
3162 len = snprintf(buf, PATH_MAX, "%s/%s", path,
3163 bpf_map__name(map));
3166 else if (len >= PATH_MAX)
3167 return -ENAMETOOLONG;
3169 err = bpf_map__unpin(map, buf);
3177 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
3179 struct bpf_program *prog;
3186 pr_warning("object not yet loaded; load it first\n");
3190 err = make_dir(path);
3194 bpf_object__for_each_program(prog, obj) {
3198 len = snprintf(buf, PATH_MAX, "%s/%s", path,
3202 goto err_unpin_programs;
3203 } else if (len >= PATH_MAX) {
3204 err = -ENAMETOOLONG;
3205 goto err_unpin_programs;
3208 err = bpf_program__pin(prog, buf);
3210 goto err_unpin_programs;
3216 while ((prog = bpf_program__prev(prog, obj))) {
3220 len = snprintf(buf, PATH_MAX, "%s/%s", path,
3224 else if (len >= PATH_MAX)
3227 bpf_program__unpin(prog, buf);
3233 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
3235 struct bpf_program *prog;
3241 bpf_object__for_each_program(prog, obj) {
3245 len = snprintf(buf, PATH_MAX, "%s/%s", path,
3249 else if (len >= PATH_MAX)
3250 return -ENAMETOOLONG;
3252 err = bpf_program__unpin(prog, buf);
3260 int bpf_object__pin(struct bpf_object *obj, const char *path)
3264 err = bpf_object__pin_maps(obj, path);
3268 err = bpf_object__pin_programs(obj, path);
3270 bpf_object__unpin_maps(obj, path);
3277 void bpf_object__close(struct bpf_object *obj)
3284 if (obj->clear_priv)
3285 obj->clear_priv(obj, obj->priv);
3287 bpf_object__elf_finish(obj);
3288 bpf_object__unload(obj);
3289 btf__free(obj->btf);
3290 btf_ext__free(obj->btf_ext);
3292 for (i = 0; i < obj->nr_maps; i++) {
3293 zfree(&obj->maps[i].name);
3294 if (obj->maps[i].clear_priv)
3295 obj->maps[i].clear_priv(&obj->maps[i],
3297 obj->maps[i].priv = NULL;
3298 obj->maps[i].clear_priv = NULL;
3301 zfree(&obj->sections.rodata);
3302 zfree(&obj->sections.data);
3306 if (obj->programs && obj->nr_programs) {
3307 for (i = 0; i < obj->nr_programs; i++)
3308 bpf_program__exit(&obj->programs[i]);
3310 zfree(&obj->programs);
3312 list_del(&obj->list);
3317 bpf_object__next(struct bpf_object *prev)
3319 struct bpf_object *next;
3322 next = list_first_entry(&bpf_objects_list,
3326 next = list_next_entry(prev, list);
3328 /* Empty list is noticed here so don't need checking on entry. */
3329 if (&next->list == &bpf_objects_list)
3335 const char *bpf_object__name(const struct bpf_object *obj)
3337 return obj ? obj->path : ERR_PTR(-EINVAL);
3340 unsigned int bpf_object__kversion(const struct bpf_object *obj)
3342 return obj ? obj->kern_version : 0;
3345 struct btf *bpf_object__btf(const struct bpf_object *obj)
3347 return obj ? obj->btf : NULL;
3350 int bpf_object__btf_fd(const struct bpf_object *obj)
3352 return obj->btf ? btf__fd(obj->btf) : -1;
3355 int bpf_object__set_priv(struct bpf_object *obj, void *priv,
3356 bpf_object_clear_priv_t clear_priv)
3358 if (obj->priv && obj->clear_priv)
3359 obj->clear_priv(obj, obj->priv);
3362 obj->clear_priv = clear_priv;
3366 void *bpf_object__priv(const struct bpf_object *obj)
3368 return obj ? obj->priv : ERR_PTR(-EINVAL);
3371 static struct bpf_program *
3372 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
3375 size_t nr_programs = obj->nr_programs;
3382 /* Iter from the beginning */
3383 return forward ? &obj->programs[0] :
3384 &obj->programs[nr_programs - 1];
3386 if (p->obj != obj) {
3387 pr_warning("error: program handler doesn't match object\n");
3391 idx = (p - obj->programs) + (forward ? 1 : -1);
3392 if (idx >= obj->nr_programs || idx < 0)
3394 return &obj->programs[idx];
3397 struct bpf_program *
3398 bpf_program__next(struct bpf_program *prev, const struct bpf_object *obj)
3400 struct bpf_program *prog = prev;
3403 prog = __bpf_program__iter(prog, obj, true);
3404 } while (prog && bpf_program__is_function_storage(prog, obj));
3409 struct bpf_program *
3410 bpf_program__prev(struct bpf_program *next, const struct bpf_object *obj)
3412 struct bpf_program *prog = next;
3415 prog = __bpf_program__iter(prog, obj, false);
3416 } while (prog && bpf_program__is_function_storage(prog, obj));
3421 int bpf_program__set_priv(struct bpf_program *prog, void *priv,
3422 bpf_program_clear_priv_t clear_priv)
3424 if (prog->priv && prog->clear_priv)
3425 prog->clear_priv(prog, prog->priv);
3428 prog->clear_priv = clear_priv;
3432 void *bpf_program__priv(const struct bpf_program *prog)
3434 return prog ? prog->priv : ERR_PTR(-EINVAL);
3437 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
3439 prog->prog_ifindex = ifindex;
3442 const char *bpf_program__title(const struct bpf_program *prog, bool needs_copy)
3446 title = prog->section_name;
3448 title = strdup(title);
3450 pr_warning("failed to strdup program title\n");
3451 return ERR_PTR(-ENOMEM);
3458 int bpf_program__fd(const struct bpf_program *prog)
3460 return bpf_program__nth_fd(prog, 0);
3463 int bpf_program__set_prep(struct bpf_program *prog, int nr_instances,
3464 bpf_program_prep_t prep)
3468 if (nr_instances <= 0 || !prep)
3471 if (prog->instances.nr > 0 || prog->instances.fds) {
3472 pr_warning("Can't set pre-processor after loading\n");
3476 instances_fds = malloc(sizeof(int) * nr_instances);
3477 if (!instances_fds) {
3478 pr_warning("alloc memory failed for fds\n");
3482 /* fill all fd with -1 */
3483 memset(instances_fds, -1, sizeof(int) * nr_instances);
3485 prog->instances.nr = nr_instances;
3486 prog->instances.fds = instances_fds;
3487 prog->preprocessor = prep;
3491 int bpf_program__nth_fd(const struct bpf_program *prog, int n)
3498 if (n >= prog->instances.nr || n < 0) {
3499 pr_warning("Can't get the %dth fd from program %s: only %d instances\n",
3500 n, prog->section_name, prog->instances.nr);
3504 fd = prog->instances.fds[n];
3506 pr_warning("%dth instance of program '%s' is invalid\n",
3507 n, prog->section_name);
3514 void bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
3519 static bool bpf_program__is_type(const struct bpf_program *prog,
3520 enum bpf_prog_type type)
3522 return prog ? (prog->type == type) : false;
3525 #define BPF_PROG_TYPE_FNS(NAME, TYPE) \
3526 int bpf_program__set_##NAME(struct bpf_program *prog) \
3530 bpf_program__set_type(prog, TYPE); \
3534 bool bpf_program__is_##NAME(const struct bpf_program *prog) \
3536 return bpf_program__is_type(prog, TYPE); \
3539 BPF_PROG_TYPE_FNS(socket_filter, BPF_PROG_TYPE_SOCKET_FILTER);
3540 BPF_PROG_TYPE_FNS(kprobe, BPF_PROG_TYPE_KPROBE);
3541 BPF_PROG_TYPE_FNS(sched_cls, BPF_PROG_TYPE_SCHED_CLS);
3542 BPF_PROG_TYPE_FNS(sched_act, BPF_PROG_TYPE_SCHED_ACT);
3543 BPF_PROG_TYPE_FNS(tracepoint, BPF_PROG_TYPE_TRACEPOINT);
3544 BPF_PROG_TYPE_FNS(raw_tracepoint, BPF_PROG_TYPE_RAW_TRACEPOINT);
3545 BPF_PROG_TYPE_FNS(xdp, BPF_PROG_TYPE_XDP);
3546 BPF_PROG_TYPE_FNS(perf_event, BPF_PROG_TYPE_PERF_EVENT);
3548 void bpf_program__set_expected_attach_type(struct bpf_program *prog,
3549 enum bpf_attach_type type)
3551 prog->expected_attach_type = type;
3554 #define BPF_PROG_SEC_IMPL(string, ptype, eatype, is_attachable, atype) \
3555 { string, sizeof(string) - 1, ptype, eatype, is_attachable, atype }
3557 /* Programs that can NOT be attached. */
3558 #define BPF_PROG_SEC(string, ptype) BPF_PROG_SEC_IMPL(string, ptype, 0, 0, 0)
3560 /* Programs that can be attached. */
3561 #define BPF_APROG_SEC(string, ptype, atype) \
3562 BPF_PROG_SEC_IMPL(string, ptype, 0, 1, atype)
3564 /* Programs that must specify expected attach type at load time. */
3565 #define BPF_EAPROG_SEC(string, ptype, eatype) \
3566 BPF_PROG_SEC_IMPL(string, ptype, eatype, 1, eatype)
3568 /* Programs that can be attached but attach type can't be identified by section
3569 * name. Kept for backward compatibility.
3571 #define BPF_APROG_COMPAT(string, ptype) BPF_PROG_SEC(string, ptype)
3573 static const struct {
3576 enum bpf_prog_type prog_type;
3577 enum bpf_attach_type expected_attach_type;
3579 enum bpf_attach_type attach_type;
3580 } section_names[] = {
3581 BPF_PROG_SEC("socket", BPF_PROG_TYPE_SOCKET_FILTER),
3582 BPF_PROG_SEC("kprobe/", BPF_PROG_TYPE_KPROBE),
3583 BPF_PROG_SEC("kretprobe/", BPF_PROG_TYPE_KPROBE),
3584 BPF_PROG_SEC("classifier", BPF_PROG_TYPE_SCHED_CLS),
3585 BPF_PROG_SEC("action", BPF_PROG_TYPE_SCHED_ACT),
3586 BPF_PROG_SEC("tracepoint/", BPF_PROG_TYPE_TRACEPOINT),
3587 BPF_PROG_SEC("raw_tracepoint/", BPF_PROG_TYPE_RAW_TRACEPOINT),
3588 BPF_PROG_SEC("xdp", BPF_PROG_TYPE_XDP),
3589 BPF_PROG_SEC("perf_event", BPF_PROG_TYPE_PERF_EVENT),
3590 BPF_PROG_SEC("lwt_in", BPF_PROG_TYPE_LWT_IN),
3591 BPF_PROG_SEC("lwt_out", BPF_PROG_TYPE_LWT_OUT),
3592 BPF_PROG_SEC("lwt_xmit", BPF_PROG_TYPE_LWT_XMIT),
3593 BPF_PROG_SEC("lwt_seg6local", BPF_PROG_TYPE_LWT_SEG6LOCAL),
3594 BPF_APROG_SEC("cgroup_skb/ingress", BPF_PROG_TYPE_CGROUP_SKB,
3595 BPF_CGROUP_INET_INGRESS),
3596 BPF_APROG_SEC("cgroup_skb/egress", BPF_PROG_TYPE_CGROUP_SKB,
3597 BPF_CGROUP_INET_EGRESS),
3598 BPF_APROG_COMPAT("cgroup/skb", BPF_PROG_TYPE_CGROUP_SKB),
3599 BPF_APROG_SEC("cgroup/sock", BPF_PROG_TYPE_CGROUP_SOCK,
3600 BPF_CGROUP_INET_SOCK_CREATE),
3601 BPF_EAPROG_SEC("cgroup/post_bind4", BPF_PROG_TYPE_CGROUP_SOCK,
3602 BPF_CGROUP_INET4_POST_BIND),
3603 BPF_EAPROG_SEC("cgroup/post_bind6", BPF_PROG_TYPE_CGROUP_SOCK,
3604 BPF_CGROUP_INET6_POST_BIND),
3605 BPF_APROG_SEC("cgroup/dev", BPF_PROG_TYPE_CGROUP_DEVICE,
3607 BPF_APROG_SEC("sockops", BPF_PROG_TYPE_SOCK_OPS,
3608 BPF_CGROUP_SOCK_OPS),
3609 BPF_APROG_SEC("sk_skb/stream_parser", BPF_PROG_TYPE_SK_SKB,
3610 BPF_SK_SKB_STREAM_PARSER),
3611 BPF_APROG_SEC("sk_skb/stream_verdict", BPF_PROG_TYPE_SK_SKB,
3612 BPF_SK_SKB_STREAM_VERDICT),
3613 BPF_APROG_COMPAT("sk_skb", BPF_PROG_TYPE_SK_SKB),
3614 BPF_APROG_SEC("sk_msg", BPF_PROG_TYPE_SK_MSG,
3615 BPF_SK_MSG_VERDICT),
3616 BPF_APROG_SEC("lirc_mode2", BPF_PROG_TYPE_LIRC_MODE2,
3618 BPF_APROG_SEC("flow_dissector", BPF_PROG_TYPE_FLOW_DISSECTOR,
3619 BPF_FLOW_DISSECTOR),
3620 BPF_EAPROG_SEC("cgroup/bind4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
3621 BPF_CGROUP_INET4_BIND),
3622 BPF_EAPROG_SEC("cgroup/bind6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
3623 BPF_CGROUP_INET6_BIND),
3624 BPF_EAPROG_SEC("cgroup/connect4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
3625 BPF_CGROUP_INET4_CONNECT),
3626 BPF_EAPROG_SEC("cgroup/connect6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
3627 BPF_CGROUP_INET6_CONNECT),
3628 BPF_EAPROG_SEC("cgroup/sendmsg4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
3629 BPF_CGROUP_UDP4_SENDMSG),
3630 BPF_EAPROG_SEC("cgroup/sendmsg6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
3631 BPF_CGROUP_UDP6_SENDMSG),
3632 BPF_EAPROG_SEC("cgroup/recvmsg4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
3633 BPF_CGROUP_UDP4_RECVMSG),
3634 BPF_EAPROG_SEC("cgroup/recvmsg6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
3635 BPF_CGROUP_UDP6_RECVMSG),
3636 BPF_EAPROG_SEC("cgroup/sysctl", BPF_PROG_TYPE_CGROUP_SYSCTL,
3638 BPF_EAPROG_SEC("cgroup/getsockopt", BPF_PROG_TYPE_CGROUP_SOCKOPT,
3639 BPF_CGROUP_GETSOCKOPT),
3640 BPF_EAPROG_SEC("cgroup/setsockopt", BPF_PROG_TYPE_CGROUP_SOCKOPT,
3641 BPF_CGROUP_SETSOCKOPT),
3644 #undef BPF_PROG_SEC_IMPL
3646 #undef BPF_APROG_SEC
3647 #undef BPF_EAPROG_SEC
3648 #undef BPF_APROG_COMPAT
3650 #define MAX_TYPE_NAME_SIZE 32
3652 static char *libbpf_get_type_names(bool attach_type)
3654 int i, len = ARRAY_SIZE(section_names) * MAX_TYPE_NAME_SIZE;
3662 /* Forge string buf with all available names */
3663 for (i = 0; i < ARRAY_SIZE(section_names); i++) {
3664 if (attach_type && !section_names[i].is_attachable)
3667 if (strlen(buf) + strlen(section_names[i].sec) + 2 > len) {
3672 strcat(buf, section_names[i].sec);
3678 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
3679 enum bpf_attach_type *expected_attach_type)
3687 for (i = 0; i < ARRAY_SIZE(section_names); i++) {
3688 if (strncmp(name, section_names[i].sec, section_names[i].len))
3690 *prog_type = section_names[i].prog_type;
3691 *expected_attach_type = section_names[i].expected_attach_type;
3694 pr_warning("failed to guess program type based on ELF section name '%s'\n", name);
3695 type_names = libbpf_get_type_names(false);
3696 if (type_names != NULL) {
3697 pr_info("supported section(type) names are:%s\n", type_names);
3704 int libbpf_attach_type_by_name(const char *name,
3705 enum bpf_attach_type *attach_type)
3713 for (i = 0; i < ARRAY_SIZE(section_names); i++) {
3714 if (strncmp(name, section_names[i].sec, section_names[i].len))
3716 if (!section_names[i].is_attachable)
3718 *attach_type = section_names[i].attach_type;
3721 pr_warning("failed to guess attach type based on ELF section name '%s'\n", name);
3722 type_names = libbpf_get_type_names(true);
3723 if (type_names != NULL) {
3724 pr_info("attachable section(type) names are:%s\n", type_names);
3732 bpf_program__identify_section(struct bpf_program *prog,
3733 enum bpf_prog_type *prog_type,
3734 enum bpf_attach_type *expected_attach_type)
3736 return libbpf_prog_type_by_name(prog->section_name, prog_type,
3737 expected_attach_type);
3740 int bpf_map__fd(const struct bpf_map *map)
3742 return map ? map->fd : -EINVAL;
3745 const struct bpf_map_def *bpf_map__def(const struct bpf_map *map)
3747 return map ? &map->def : ERR_PTR(-EINVAL);
3750 const char *bpf_map__name(const struct bpf_map *map)
3752 return map ? map->name : NULL;
3755 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
3757 return map ? map->btf_key_type_id : 0;
3760 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
3762 return map ? map->btf_value_type_id : 0;
3765 int bpf_map__set_priv(struct bpf_map *map, void *priv,
3766 bpf_map_clear_priv_t clear_priv)
3772 if (map->clear_priv)
3773 map->clear_priv(map, map->priv);
3777 map->clear_priv = clear_priv;
3781 void *bpf_map__priv(const struct bpf_map *map)
3783 return map ? map->priv : ERR_PTR(-EINVAL);
3786 bool bpf_map__is_offload_neutral(const struct bpf_map *map)
3788 return map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY;
3791 bool bpf_map__is_internal(const struct bpf_map *map)
3793 return map->libbpf_type != LIBBPF_MAP_UNSPEC;
3796 void bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
3798 map->map_ifindex = ifindex;
3801 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
3803 if (!bpf_map_type__is_map_in_map(map->def.type)) {
3804 pr_warning("error: unsupported map type\n");
3807 if (map->inner_map_fd != -1) {
3808 pr_warning("error: inner_map_fd already specified\n");
3811 map->inner_map_fd = fd;
3815 static struct bpf_map *
3816 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
3819 struct bpf_map *s, *e;
3821 if (!obj || !obj->maps)
3825 e = obj->maps + obj->nr_maps;
3827 if ((m < s) || (m >= e)) {
3828 pr_warning("error in %s: map handler doesn't belong to object\n",
3833 idx = (m - obj->maps) + i;
3834 if (idx >= obj->nr_maps || idx < 0)
3836 return &obj->maps[idx];
3840 bpf_map__next(const struct bpf_map *prev, const struct bpf_object *obj)
3845 return __bpf_map__iter(prev, obj, 1);
3849 bpf_map__prev(const struct bpf_map *next, const struct bpf_object *obj)
3854 return obj->maps + obj->nr_maps - 1;
3857 return __bpf_map__iter(next, obj, -1);
3861 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
3863 struct bpf_map *pos;
3865 bpf_object__for_each_map(pos, obj) {
3866 if (pos->name && !strcmp(pos->name, name))
3873 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
3875 return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
3879 bpf_object__find_map_by_offset(struct bpf_object *obj, size_t offset)
3881 return ERR_PTR(-ENOTSUP);
3884 long libbpf_get_error(const void *ptr)
3886 return PTR_ERR_OR_ZERO(ptr);
3889 int bpf_prog_load(const char *file, enum bpf_prog_type type,
3890 struct bpf_object **pobj, int *prog_fd)
3892 struct bpf_prog_load_attr attr;
3894 memset(&attr, 0, sizeof(struct bpf_prog_load_attr));
3896 attr.prog_type = type;
3897 attr.expected_attach_type = 0;
3899 return bpf_prog_load_xattr(&attr, pobj, prog_fd);
3902 int bpf_prog_load_xattr(const struct bpf_prog_load_attr *attr,
3903 struct bpf_object **pobj, int *prog_fd)
3905 struct bpf_object_open_attr open_attr = {};
3906 struct bpf_program *prog, *first_prog = NULL;
3907 enum bpf_attach_type expected_attach_type;
3908 enum bpf_prog_type prog_type;
3909 struct bpf_object *obj;
3910 struct bpf_map *map;
3918 open_attr.file = attr->file;
3919 open_attr.prog_type = attr->prog_type;
3921 obj = bpf_object__open_xattr(&open_attr);
3922 if (IS_ERR_OR_NULL(obj))
3925 bpf_object__for_each_program(prog, obj) {
3927 * If type is not specified, try to guess it based on
3930 prog_type = attr->prog_type;
3931 prog->prog_ifindex = attr->ifindex;
3932 expected_attach_type = attr->expected_attach_type;
3933 if (prog_type == BPF_PROG_TYPE_UNSPEC) {
3934 err = bpf_program__identify_section(prog, &prog_type,
3935 &expected_attach_type);
3937 bpf_object__close(obj);
3942 bpf_program__set_type(prog, prog_type);
3943 bpf_program__set_expected_attach_type(prog,
3944 expected_attach_type);
3946 prog->log_level = attr->log_level;
3947 prog->prog_flags = attr->prog_flags;
3952 bpf_object__for_each_map(map, obj) {
3953 if (!bpf_map__is_offload_neutral(map))
3954 map->map_ifindex = attr->ifindex;
3958 pr_warning("object file doesn't contain bpf program\n");
3959 bpf_object__close(obj);
3963 err = bpf_object__load(obj);
3965 bpf_object__close(obj);
3970 *prog_fd = bpf_program__fd(first_prog);
3975 int (*destroy)(struct bpf_link *link);
3978 int bpf_link__destroy(struct bpf_link *link)
3985 err = link->destroy(link);
3991 struct bpf_link_fd {
3992 struct bpf_link link; /* has to be at the top of struct */
3993 int fd; /* hook FD */
3996 static int bpf_link__destroy_perf_event(struct bpf_link *link)
3998 struct bpf_link_fd *l = (void *)link;
4001 err = ioctl(l->fd, PERF_EVENT_IOC_DISABLE, 0);
4009 struct bpf_link *bpf_program__attach_perf_event(struct bpf_program *prog,
4012 char errmsg[STRERR_BUFSIZE];
4013 struct bpf_link_fd *link;
4017 pr_warning("program '%s': invalid perf event FD %d\n",
4018 bpf_program__title(prog, false), pfd);
4019 return ERR_PTR(-EINVAL);
4021 prog_fd = bpf_program__fd(prog);
4023 pr_warning("program '%s': can't attach BPF program w/o FD (did you load it?)\n",
4024 bpf_program__title(prog, false));
4025 return ERR_PTR(-EINVAL);
4028 link = malloc(sizeof(*link));
4030 return ERR_PTR(-ENOMEM);
4031 link->link.destroy = &bpf_link__destroy_perf_event;
4034 if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
4037 pr_warning("program '%s': failed to attach to pfd %d: %s\n",
4038 bpf_program__title(prog, false), pfd,
4039 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
4040 return ERR_PTR(err);
4042 if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
4045 pr_warning("program '%s': failed to enable pfd %d: %s\n",
4046 bpf_program__title(prog, false), pfd,
4047 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
4048 return ERR_PTR(err);
4050 return (struct bpf_link *)link;
4054 * this function is expected to parse integer in the range of [0, 2^31-1] from
4055 * given file using scanf format string fmt. If actual parsed value is
4056 * negative, the result might be indistinguishable from error
4058 static int parse_uint_from_file(const char *file, const char *fmt)
4060 char buf[STRERR_BUFSIZE];
4064 f = fopen(file, "r");
4067 pr_debug("failed to open '%s': %s\n", file,
4068 libbpf_strerror_r(err, buf, sizeof(buf)));
4071 err = fscanf(f, fmt, &ret);
4073 err = err == EOF ? -EIO : -errno;
4074 pr_debug("failed to parse '%s': %s\n", file,
4075 libbpf_strerror_r(err, buf, sizeof(buf)));
4083 static int determine_kprobe_perf_type(void)
4085 const char *file = "/sys/bus/event_source/devices/kprobe/type";
4087 return parse_uint_from_file(file, "%d\n");
4090 static int determine_uprobe_perf_type(void)
4092 const char *file = "/sys/bus/event_source/devices/uprobe/type";
4094 return parse_uint_from_file(file, "%d\n");
4097 static int determine_kprobe_retprobe_bit(void)
4099 const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
4101 return parse_uint_from_file(file, "config:%d\n");
4104 static int determine_uprobe_retprobe_bit(void)
4106 const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
4108 return parse_uint_from_file(file, "config:%d\n");
4111 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
4112 uint64_t offset, int pid)
4114 struct perf_event_attr attr = {};
4115 char errmsg[STRERR_BUFSIZE];
4118 type = uprobe ? determine_uprobe_perf_type()
4119 : determine_kprobe_perf_type();
4121 pr_warning("failed to determine %s perf type: %s\n",
4122 uprobe ? "uprobe" : "kprobe",
4123 libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
4127 int bit = uprobe ? determine_uprobe_retprobe_bit()
4128 : determine_kprobe_retprobe_bit();
4131 pr_warning("failed to determine %s retprobe bit: %s\n",
4132 uprobe ? "uprobe" : "kprobe",
4133 libbpf_strerror_r(bit, errmsg,
4137 attr.config |= 1 << bit;
4139 attr.size = sizeof(attr);
4141 attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
4142 attr.config2 = offset; /* kprobe_addr or probe_offset */
4144 /* pid filter is meaningful only for uprobes */
4145 pfd = syscall(__NR_perf_event_open, &attr,
4146 pid < 0 ? -1 : pid /* pid */,
4147 pid == -1 ? 0 : -1 /* cpu */,
4148 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
4151 pr_warning("%s perf_event_open() failed: %s\n",
4152 uprobe ? "uprobe" : "kprobe",
4153 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
4159 struct bpf_link *bpf_program__attach_kprobe(struct bpf_program *prog,
4161 const char *func_name)
4163 char errmsg[STRERR_BUFSIZE];
4164 struct bpf_link *link;
4167 pfd = perf_event_open_probe(false /* uprobe */, retprobe, func_name,
4168 0 /* offset */, -1 /* pid */);
4170 pr_warning("program '%s': failed to create %s '%s' perf event: %s\n",
4171 bpf_program__title(prog, false),
4172 retprobe ? "kretprobe" : "kprobe", func_name,
4173 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
4174 return ERR_PTR(pfd);
4176 link = bpf_program__attach_perf_event(prog, pfd);
4179 err = PTR_ERR(link);
4180 pr_warning("program '%s': failed to attach to %s '%s': %s\n",
4181 bpf_program__title(prog, false),
4182 retprobe ? "kretprobe" : "kprobe", func_name,
4183 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
4189 struct bpf_link *bpf_program__attach_uprobe(struct bpf_program *prog,
4190 bool retprobe, pid_t pid,
4191 const char *binary_path,
4194 char errmsg[STRERR_BUFSIZE];
4195 struct bpf_link *link;
4198 pfd = perf_event_open_probe(true /* uprobe */, retprobe,
4199 binary_path, func_offset, pid);
4201 pr_warning("program '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
4202 bpf_program__title(prog, false),
4203 retprobe ? "uretprobe" : "uprobe",
4204 binary_path, func_offset,
4205 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
4206 return ERR_PTR(pfd);
4208 link = bpf_program__attach_perf_event(prog, pfd);
4211 err = PTR_ERR(link);
4212 pr_warning("program '%s': failed to attach to %s '%s:0x%zx': %s\n",
4213 bpf_program__title(prog, false),
4214 retprobe ? "uretprobe" : "uprobe",
4215 binary_path, func_offset,
4216 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
4222 static int determine_tracepoint_id(const char *tp_category,
4223 const char *tp_name)
4225 char file[PATH_MAX];
4228 ret = snprintf(file, sizeof(file),
4229 "/sys/kernel/debug/tracing/events/%s/%s/id",
4230 tp_category, tp_name);
4233 if (ret >= sizeof(file)) {
4234 pr_debug("tracepoint %s/%s path is too long\n",
4235 tp_category, tp_name);
4238 return parse_uint_from_file(file, "%d\n");
4241 static int perf_event_open_tracepoint(const char *tp_category,
4242 const char *tp_name)
4244 struct perf_event_attr attr = {};
4245 char errmsg[STRERR_BUFSIZE];
4246 int tp_id, pfd, err;
4248 tp_id = determine_tracepoint_id(tp_category, tp_name);
4250 pr_warning("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
4251 tp_category, tp_name,
4252 libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
4256 attr.type = PERF_TYPE_TRACEPOINT;
4257 attr.size = sizeof(attr);
4258 attr.config = tp_id;
4260 pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
4261 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
4264 pr_warning("tracepoint '%s/%s' perf_event_open() failed: %s\n",
4265 tp_category, tp_name,
4266 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
4272 struct bpf_link *bpf_program__attach_tracepoint(struct bpf_program *prog,
4273 const char *tp_category,
4274 const char *tp_name)
4276 char errmsg[STRERR_BUFSIZE];
4277 struct bpf_link *link;
4280 pfd = perf_event_open_tracepoint(tp_category, tp_name);
4282 pr_warning("program '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
4283 bpf_program__title(prog, false),
4284 tp_category, tp_name,
4285 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
4286 return ERR_PTR(pfd);
4288 link = bpf_program__attach_perf_event(prog, pfd);
4291 err = PTR_ERR(link);
4292 pr_warning("program '%s': failed to attach to tracepoint '%s/%s': %s\n",
4293 bpf_program__title(prog, false),
4294 tp_category, tp_name,
4295 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
4301 static int bpf_link__destroy_fd(struct bpf_link *link)
4303 struct bpf_link_fd *l = (void *)link;
4305 return close(l->fd);
4308 struct bpf_link *bpf_program__attach_raw_tracepoint(struct bpf_program *prog,
4309 const char *tp_name)
4311 char errmsg[STRERR_BUFSIZE];
4312 struct bpf_link_fd *link;
4315 prog_fd = bpf_program__fd(prog);
4317 pr_warning("program '%s': can't attach before loaded\n",
4318 bpf_program__title(prog, false));
4319 return ERR_PTR(-EINVAL);
4322 link = malloc(sizeof(*link));
4324 return ERR_PTR(-ENOMEM);
4325 link->link.destroy = &bpf_link__destroy_fd;
4327 pfd = bpf_raw_tracepoint_open(tp_name, prog_fd);
4331 pr_warning("program '%s': failed to attach to raw tracepoint '%s': %s\n",
4332 bpf_program__title(prog, false), tp_name,
4333 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
4334 return ERR_PTR(pfd);
4337 return (struct bpf_link *)link;
4340 enum bpf_perf_event_ret
4341 bpf_perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
4342 void **copy_mem, size_t *copy_size,
4343 bpf_perf_event_print_t fn, void *private_data)
4345 struct perf_event_mmap_page *header = mmap_mem;
4346 __u64 data_head = ring_buffer_read_head(header);
4347 __u64 data_tail = header->data_tail;
4348 void *base = ((__u8 *)header) + page_size;
4349 int ret = LIBBPF_PERF_EVENT_CONT;
4350 struct perf_event_header *ehdr;
4353 while (data_head != data_tail) {
4354 ehdr = base + (data_tail & (mmap_size - 1));
4355 ehdr_size = ehdr->size;
4357 if (((void *)ehdr) + ehdr_size > base + mmap_size) {
4358 void *copy_start = ehdr;
4359 size_t len_first = base + mmap_size - copy_start;
4360 size_t len_secnd = ehdr_size - len_first;
4362 if (*copy_size < ehdr_size) {
4364 *copy_mem = malloc(ehdr_size);
4367 ret = LIBBPF_PERF_EVENT_ERROR;
4370 *copy_size = ehdr_size;
4373 memcpy(*copy_mem, copy_start, len_first);
4374 memcpy(*copy_mem + len_first, base, len_secnd);
4378 ret = fn(ehdr, private_data);
4379 data_tail += ehdr_size;
4380 if (ret != LIBBPF_PERF_EVENT_CONT)
4384 ring_buffer_write_tail(header, data_tail);
4390 struct perf_buffer_params {
4391 struct perf_event_attr *attr;
4392 /* if event_cb is specified, it takes precendence */
4393 perf_buffer_event_fn event_cb;
4394 /* sample_cb and lost_cb are higher-level common-case callbacks */
4395 perf_buffer_sample_fn sample_cb;
4396 perf_buffer_lost_fn lost_cb;
4403 struct perf_cpu_buf {
4404 struct perf_buffer *pb;
4405 void *base; /* mmap()'ed memory */
4406 void *buf; /* for reconstructing segmented data */
4413 struct perf_buffer {
4414 perf_buffer_event_fn event_cb;
4415 perf_buffer_sample_fn sample_cb;
4416 perf_buffer_lost_fn lost_cb;
4417 void *ctx; /* passed into callbacks */
4421 struct perf_cpu_buf **cpu_bufs;
4422 struct epoll_event *events;
4424 int epoll_fd; /* perf event FD */
4425 int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
4428 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
4429 struct perf_cpu_buf *cpu_buf)
4433 if (cpu_buf->base &&
4434 munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
4435 pr_warning("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
4436 if (cpu_buf->fd >= 0) {
4437 ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
4444 void perf_buffer__free(struct perf_buffer *pb)
4451 for (i = 0; i < pb->cpu_cnt && pb->cpu_bufs[i]; i++) {
4452 struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
4454 bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
4455 perf_buffer__free_cpu_buf(pb, cpu_buf);
4459 if (pb->epoll_fd >= 0)
4460 close(pb->epoll_fd);
4465 static struct perf_cpu_buf *
4466 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
4467 int cpu, int map_key)
4469 struct perf_cpu_buf *cpu_buf;
4470 char msg[STRERR_BUFSIZE];
4473 cpu_buf = calloc(1, sizeof(*cpu_buf));
4475 return ERR_PTR(-ENOMEM);
4479 cpu_buf->map_key = map_key;
4481 cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
4482 -1, PERF_FLAG_FD_CLOEXEC);
4483 if (cpu_buf->fd < 0) {
4485 pr_warning("failed to open perf buffer event on cpu #%d: %s\n",
4486 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
4490 cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
4491 PROT_READ | PROT_WRITE, MAP_SHARED,
4493 if (cpu_buf->base == MAP_FAILED) {
4494 cpu_buf->base = NULL;
4496 pr_warning("failed to mmap perf buffer on cpu #%d: %s\n",
4497 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
4501 if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
4503 pr_warning("failed to enable perf buffer event on cpu #%d: %s\n",
4504 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
4511 perf_buffer__free_cpu_buf(pb, cpu_buf);
4512 return (struct perf_cpu_buf *)ERR_PTR(err);
4515 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
4516 struct perf_buffer_params *p);
4518 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
4519 const struct perf_buffer_opts *opts)
4521 struct perf_buffer_params p = {};
4522 struct perf_event_attr attr = { 0, };
4524 attr.config = PERF_COUNT_SW_BPF_OUTPUT,
4525 attr.type = PERF_TYPE_SOFTWARE;
4526 attr.sample_type = PERF_SAMPLE_RAW;
4527 attr.sample_period = 1;
4528 attr.wakeup_events = 1;
4531 p.sample_cb = opts ? opts->sample_cb : NULL;
4532 p.lost_cb = opts ? opts->lost_cb : NULL;
4533 p.ctx = opts ? opts->ctx : NULL;
4535 return __perf_buffer__new(map_fd, page_cnt, &p);
4538 struct perf_buffer *
4539 perf_buffer__new_raw(int map_fd, size_t page_cnt,
4540 const struct perf_buffer_raw_opts *opts)
4542 struct perf_buffer_params p = {};
4544 p.attr = opts->attr;
4545 p.event_cb = opts->event_cb;
4547 p.cpu_cnt = opts->cpu_cnt;
4548 p.cpus = opts->cpus;
4549 p.map_keys = opts->map_keys;
4551 return __perf_buffer__new(map_fd, page_cnt, &p);
4554 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
4555 struct perf_buffer_params *p)
4557 struct bpf_map_info map = {};
4558 char msg[STRERR_BUFSIZE];
4559 struct perf_buffer *pb;
4563 if (page_cnt & (page_cnt - 1)) {
4564 pr_warning("page count should be power of two, but is %zu\n",
4566 return ERR_PTR(-EINVAL);
4569 map_info_len = sizeof(map);
4570 err = bpf_obj_get_info_by_fd(map_fd, &map, &map_info_len);
4573 pr_warning("failed to get map info for map FD %d: %s\n",
4574 map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
4575 return ERR_PTR(err);
4578 if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
4579 pr_warning("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
4581 return ERR_PTR(-EINVAL);
4584 pb = calloc(1, sizeof(*pb));
4586 return ERR_PTR(-ENOMEM);
4588 pb->event_cb = p->event_cb;
4589 pb->sample_cb = p->sample_cb;
4590 pb->lost_cb = p->lost_cb;
4593 pb->page_size = getpagesize();
4594 pb->mmap_size = pb->page_size * page_cnt;
4595 pb->map_fd = map_fd;
4597 pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
4598 if (pb->epoll_fd < 0) {
4600 pr_warning("failed to create epoll instance: %s\n",
4601 libbpf_strerror_r(err, msg, sizeof(msg)));
4605 if (p->cpu_cnt > 0) {
4606 pb->cpu_cnt = p->cpu_cnt;
4608 pb->cpu_cnt = libbpf_num_possible_cpus();
4609 if (pb->cpu_cnt < 0) {
4613 if (map.max_entries < pb->cpu_cnt)
4614 pb->cpu_cnt = map.max_entries;
4617 pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
4620 pr_warning("failed to allocate events: out of memory\n");
4623 pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
4624 if (!pb->cpu_bufs) {
4626 pr_warning("failed to allocate buffers: out of memory\n");
4630 for (i = 0; i < pb->cpu_cnt; i++) {
4631 struct perf_cpu_buf *cpu_buf;
4634 cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
4635 map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
4637 cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
4638 if (IS_ERR(cpu_buf)) {
4639 err = PTR_ERR(cpu_buf);
4643 pb->cpu_bufs[i] = cpu_buf;
4645 err = bpf_map_update_elem(pb->map_fd, &map_key,
4649 pr_warning("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
4650 cpu, map_key, cpu_buf->fd,
4651 libbpf_strerror_r(err, msg, sizeof(msg)));
4655 pb->events[i].events = EPOLLIN;
4656 pb->events[i].data.ptr = cpu_buf;
4657 if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
4658 &pb->events[i]) < 0) {
4660 pr_warning("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
4662 libbpf_strerror_r(err, msg, sizeof(msg)));
4671 perf_buffer__free(pb);
4672 return ERR_PTR(err);
4675 struct perf_sample_raw {
4676 struct perf_event_header header;
4681 struct perf_sample_lost {
4682 struct perf_event_header header;
4688 static enum bpf_perf_event_ret
4689 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
4691 struct perf_cpu_buf *cpu_buf = ctx;
4692 struct perf_buffer *pb = cpu_buf->pb;
4695 /* user wants full control over parsing perf event */
4697 return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
4700 case PERF_RECORD_SAMPLE: {
4701 struct perf_sample_raw *s = data;
4704 pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
4707 case PERF_RECORD_LOST: {
4708 struct perf_sample_lost *s = data;
4711 pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
4715 pr_warning("unknown perf sample type %d\n", e->type);
4716 return LIBBPF_PERF_EVENT_ERROR;
4718 return LIBBPF_PERF_EVENT_CONT;
4721 static int perf_buffer__process_records(struct perf_buffer *pb,
4722 struct perf_cpu_buf *cpu_buf)
4724 enum bpf_perf_event_ret ret;
4726 ret = bpf_perf_event_read_simple(cpu_buf->base, pb->mmap_size,
4727 pb->page_size, &cpu_buf->buf,
4729 perf_buffer__process_record, cpu_buf);
4730 if (ret != LIBBPF_PERF_EVENT_CONT)
4735 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
4739 cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
4740 for (i = 0; i < cnt; i++) {
4741 struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
4743 err = perf_buffer__process_records(pb, cpu_buf);
4745 pr_warning("error while processing records: %d\n", err);
4749 return cnt < 0 ? -errno : cnt;
4752 struct bpf_prog_info_array_desc {
4753 int array_offset; /* e.g. offset of jited_prog_insns */
4754 int count_offset; /* e.g. offset of jited_prog_len */
4755 int size_offset; /* > 0: offset of rec size,
4756 * < 0: fix size of -size_offset
4760 static struct bpf_prog_info_array_desc bpf_prog_info_array_desc[] = {
4761 [BPF_PROG_INFO_JITED_INSNS] = {
4762 offsetof(struct bpf_prog_info, jited_prog_insns),
4763 offsetof(struct bpf_prog_info, jited_prog_len),
4766 [BPF_PROG_INFO_XLATED_INSNS] = {
4767 offsetof(struct bpf_prog_info, xlated_prog_insns),
4768 offsetof(struct bpf_prog_info, xlated_prog_len),
4771 [BPF_PROG_INFO_MAP_IDS] = {
4772 offsetof(struct bpf_prog_info, map_ids),
4773 offsetof(struct bpf_prog_info, nr_map_ids),
4774 -(int)sizeof(__u32),
4776 [BPF_PROG_INFO_JITED_KSYMS] = {
4777 offsetof(struct bpf_prog_info, jited_ksyms),
4778 offsetof(struct bpf_prog_info, nr_jited_ksyms),
4779 -(int)sizeof(__u64),
4781 [BPF_PROG_INFO_JITED_FUNC_LENS] = {
4782 offsetof(struct bpf_prog_info, jited_func_lens),
4783 offsetof(struct bpf_prog_info, nr_jited_func_lens),
4784 -(int)sizeof(__u32),
4786 [BPF_PROG_INFO_FUNC_INFO] = {
4787 offsetof(struct bpf_prog_info, func_info),
4788 offsetof(struct bpf_prog_info, nr_func_info),
4789 offsetof(struct bpf_prog_info, func_info_rec_size),
4791 [BPF_PROG_INFO_LINE_INFO] = {
4792 offsetof(struct bpf_prog_info, line_info),
4793 offsetof(struct bpf_prog_info, nr_line_info),
4794 offsetof(struct bpf_prog_info, line_info_rec_size),
4796 [BPF_PROG_INFO_JITED_LINE_INFO] = {
4797 offsetof(struct bpf_prog_info, jited_line_info),
4798 offsetof(struct bpf_prog_info, nr_jited_line_info),
4799 offsetof(struct bpf_prog_info, jited_line_info_rec_size),
4801 [BPF_PROG_INFO_PROG_TAGS] = {
4802 offsetof(struct bpf_prog_info, prog_tags),
4803 offsetof(struct bpf_prog_info, nr_prog_tags),
4804 -(int)sizeof(__u8) * BPF_TAG_SIZE,
4809 static __u32 bpf_prog_info_read_offset_u32(struct bpf_prog_info *info, int offset)
4811 __u32 *array = (__u32 *)info;
4814 return array[offset / sizeof(__u32)];
4815 return -(int)offset;
4818 static __u64 bpf_prog_info_read_offset_u64(struct bpf_prog_info *info, int offset)
4820 __u64 *array = (__u64 *)info;
4823 return array[offset / sizeof(__u64)];
4824 return -(int)offset;
4827 static void bpf_prog_info_set_offset_u32(struct bpf_prog_info *info, int offset,
4830 __u32 *array = (__u32 *)info;
4833 array[offset / sizeof(__u32)] = val;
4836 static void bpf_prog_info_set_offset_u64(struct bpf_prog_info *info, int offset,
4839 __u64 *array = (__u64 *)info;
4842 array[offset / sizeof(__u64)] = val;
4845 struct bpf_prog_info_linear *
4846 bpf_program__get_prog_info_linear(int fd, __u64 arrays)
4848 struct bpf_prog_info_linear *info_linear;
4849 struct bpf_prog_info info = {};
4850 __u32 info_len = sizeof(info);
4855 if (arrays >> BPF_PROG_INFO_LAST_ARRAY)
4856 return ERR_PTR(-EINVAL);
4858 /* step 1: get array dimensions */
4859 err = bpf_obj_get_info_by_fd(fd, &info, &info_len);
4861 pr_debug("can't get prog info: %s", strerror(errno));
4862 return ERR_PTR(-EFAULT);
4865 /* step 2: calculate total size of all arrays */
4866 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
4867 bool include_array = (arrays & (1UL << i)) > 0;
4868 struct bpf_prog_info_array_desc *desc;
4871 desc = bpf_prog_info_array_desc + i;
4873 /* kernel is too old to support this field */
4874 if (info_len < desc->array_offset + sizeof(__u32) ||
4875 info_len < desc->count_offset + sizeof(__u32) ||
4876 (desc->size_offset > 0 && info_len < desc->size_offset))
4877 include_array = false;
4879 if (!include_array) {
4880 arrays &= ~(1UL << i); /* clear the bit */
4884 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
4885 size = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
4887 data_len += count * size;
4890 /* step 3: allocate continuous memory */
4891 data_len = roundup(data_len, sizeof(__u64));
4892 info_linear = malloc(sizeof(struct bpf_prog_info_linear) + data_len);
4894 return ERR_PTR(-ENOMEM);
4896 /* step 4: fill data to info_linear->info */
4897 info_linear->arrays = arrays;
4898 memset(&info_linear->info, 0, sizeof(info));
4899 ptr = info_linear->data;
4901 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
4902 struct bpf_prog_info_array_desc *desc;
4905 if ((arrays & (1UL << i)) == 0)
4908 desc = bpf_prog_info_array_desc + i;
4909 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
4910 size = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
4911 bpf_prog_info_set_offset_u32(&info_linear->info,
4912 desc->count_offset, count);
4913 bpf_prog_info_set_offset_u32(&info_linear->info,
4914 desc->size_offset, size);
4915 bpf_prog_info_set_offset_u64(&info_linear->info,
4918 ptr += count * size;
4921 /* step 5: call syscall again to get required arrays */
4922 err = bpf_obj_get_info_by_fd(fd, &info_linear->info, &info_len);
4924 pr_debug("can't get prog info: %s", strerror(errno));
4926 return ERR_PTR(-EFAULT);
4929 /* step 6: verify the data */
4930 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
4931 struct bpf_prog_info_array_desc *desc;
4934 if ((arrays & (1UL << i)) == 0)
4937 desc = bpf_prog_info_array_desc + i;
4938 v1 = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
4939 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
4940 desc->count_offset);
4942 pr_warning("%s: mismatch in element count\n", __func__);
4944 v1 = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
4945 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
4948 pr_warning("%s: mismatch in rec size\n", __func__);
4951 /* step 7: update info_len and data_len */
4952 info_linear->info_len = sizeof(struct bpf_prog_info);
4953 info_linear->data_len = data_len;
4958 void bpf_program__bpil_addr_to_offs(struct bpf_prog_info_linear *info_linear)
4962 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
4963 struct bpf_prog_info_array_desc *desc;
4966 if ((info_linear->arrays & (1UL << i)) == 0)
4969 desc = bpf_prog_info_array_desc + i;
4970 addr = bpf_prog_info_read_offset_u64(&info_linear->info,
4971 desc->array_offset);
4972 offs = addr - ptr_to_u64(info_linear->data);
4973 bpf_prog_info_set_offset_u64(&info_linear->info,
4974 desc->array_offset, offs);
4978 void bpf_program__bpil_offs_to_addr(struct bpf_prog_info_linear *info_linear)
4982 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
4983 struct bpf_prog_info_array_desc *desc;
4986 if ((info_linear->arrays & (1UL << i)) == 0)
4989 desc = bpf_prog_info_array_desc + i;
4990 offs = bpf_prog_info_read_offset_u64(&info_linear->info,
4991 desc->array_offset);
4992 addr = offs + ptr_to_u64(info_linear->data);
4993 bpf_prog_info_set_offset_u64(&info_linear->info,
4994 desc->array_offset, addr);
4998 int libbpf_num_possible_cpus(void)
5000 static const char *fcpu = "/sys/devices/system/cpu/possible";
5001 int len = 0, n = 0, il = 0, ir = 0;
5002 unsigned int start = 0, end = 0;
5011 fd = open(fcpu, O_RDONLY);
5014 pr_warning("Failed to open file %s: %s\n",
5015 fcpu, strerror(error));
5018 len = read(fd, buf, sizeof(buf));
5021 error = len ? errno : EINVAL;
5022 pr_warning("Failed to read # of possible cpus from %s: %s\n",
5023 fcpu, strerror(error));
5026 if (len == sizeof(buf)) {
5027 pr_warning("File %s size overflow\n", fcpu);
5032 for (ir = 0, cpus = 0; ir <= len; ir++) {
5033 /* Each sub string separated by ',' has format \d+-\d+ or \d+ */
5034 if (buf[ir] == ',' || buf[ir] == '\0') {
5036 n = sscanf(&buf[il], "%u-%u", &start, &end);
5038 pr_warning("Failed to get # CPUs from %s\n",
5041 } else if (n == 1) {
5044 cpus += end - start + 1;
5049 pr_warning("Invalid #CPUs %d from %s\n", cpus, fcpu);