1 // SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
4 * Common eBPF ELF object loading operations.
6 * Copyright (C) 2013-2015 Alexei Starovoitov <ast@kernel.org>
7 * Copyright (C) 2015 Wang Nan <wangnan0@huawei.com>
8 * Copyright (C) 2015 Huawei Inc.
9 * Copyright (C) 2017 Nicira, Inc.
10 * Copyright (C) 2019 Isovalent, Inc.
25 #include <asm/unistd.h>
26 #include <linux/err.h>
27 #include <linux/kernel.h>
28 #include <linux/bpf.h>
29 #include <linux/btf.h>
30 #include <linux/filter.h>
31 #include <linux/list.h>
32 #include <linux/limits.h>
33 #include <linux/perf_event.h>
34 #include <linux/ring_buffer.h>
35 #include <sys/epoll.h>
36 #include <sys/ioctl.h>
39 #include <sys/types.h>
41 #include <tools/libc_compat.h>
48 #include "str_error.h"
49 #include "libbpf_internal.h"
56 #define BPF_FS_MAGIC 0xcafe4a11
59 /* vsprintf() in __base_pr() uses nonliteral format string. It may break
60 * compilation if user enables corresponding warning. Disable it explicitly.
62 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
64 #define __printf(a, b) __attribute__((format(printf, a, b)))
66 static int __base_pr(enum libbpf_print_level level, const char *format,
69 if (level == LIBBPF_DEBUG)
72 return vfprintf(stderr, format, args);
75 static libbpf_print_fn_t __libbpf_pr = __base_pr;
77 libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn)
79 libbpf_print_fn_t old_print_fn = __libbpf_pr;
86 void libbpf_print(enum libbpf_print_level level, const char *format, ...)
93 va_start(args, format);
94 __libbpf_pr(level, format, args);
98 #define STRERR_BUFSIZE 128
100 #define CHECK_ERR(action, err, out) do { \
107 /* Copied from tools/perf/util/util.h */
109 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
113 # define zclose(fd) ({ \
116 ___err = close((fd)); \
121 #ifdef HAVE_LIBELF_MMAP_SUPPORT
122 # define LIBBPF_ELF_C_READ_MMAP ELF_C_READ_MMAP
124 # define LIBBPF_ELF_C_READ_MMAP ELF_C_READ
127 static inline __u64 ptr_to_u64(const void *ptr)
129 return (__u64) (unsigned long) ptr;
132 struct bpf_capabilities {
133 /* v4.14: kernel support for program & map names. */
135 /* v5.2: kernel support for global data sections. */
137 /* BTF_KIND_FUNC and BTF_KIND_FUNC_PROTO support */
139 /* BTF_KIND_VAR and BTF_KIND_DATASEC support */
144 * bpf_prog should be a better name but it has been used in
148 /* Index in elf obj file, for relocation use. */
153 /* section_name with / replaced by _; makes recursive pinning
154 * in bpf_object__pin_programs easier
157 struct bpf_insn *insns;
158 size_t insns_cnt, main_prog_cnt;
159 enum bpf_prog_type type;
180 bpf_program_prep_t preprocessor;
182 struct bpf_object *obj;
184 bpf_program_clear_priv_t clear_priv;
186 enum bpf_attach_type expected_attach_type;
189 __u32 func_info_rec_size;
192 struct bpf_capabilities *caps;
195 __u32 line_info_rec_size;
200 enum libbpf_map_type {
207 static const char * const libbpf_type_to_btf_name[] = {
208 [LIBBPF_MAP_DATA] = ".data",
209 [LIBBPF_MAP_BSS] = ".bss",
210 [LIBBPF_MAP_RODATA] = ".rodata",
220 struct bpf_map_def def;
221 __u32 btf_key_type_id;
222 __u32 btf_value_type_id;
224 bpf_map_clear_priv_t clear_priv;
225 enum libbpf_map_type libbpf_type;
233 static LIST_HEAD(bpf_objects_list);
236 char name[BPF_OBJ_NAME_LEN];
240 struct bpf_program *programs;
242 struct bpf_map *maps;
245 struct bpf_secdata sections;
248 bool has_pseudo_calls;
251 * Information when doing elf related work. Only valid if fd
278 * All loaded bpf_object is linked in a list, which is
279 * hidden to caller. bpf_objects__<func> handlers deal with
282 struct list_head list;
285 struct btf_ext *btf_ext;
288 bpf_object_clear_priv_t clear_priv;
290 struct bpf_capabilities caps;
294 #define obj_elf_valid(o) ((o)->efile.elf)
296 void bpf_program__unload(struct bpf_program *prog)
304 * If the object is opened but the program was never loaded,
305 * it is possible that prog->instances.nr == -1.
307 if (prog->instances.nr > 0) {
308 for (i = 0; i < prog->instances.nr; i++)
309 zclose(prog->instances.fds[i]);
310 } else if (prog->instances.nr != -1) {
311 pr_warning("Internal error: instances.nr is %d\n",
315 prog->instances.nr = -1;
316 zfree(&prog->instances.fds);
318 zclose(prog->btf_fd);
319 zfree(&prog->func_info);
320 zfree(&prog->line_info);
323 static void bpf_program__exit(struct bpf_program *prog)
328 if (prog->clear_priv)
329 prog->clear_priv(prog, prog->priv);
332 prog->clear_priv = NULL;
334 bpf_program__unload(prog);
336 zfree(&prog->section_name);
337 zfree(&prog->pin_name);
339 zfree(&prog->reloc_desc);
346 static char *__bpf_program__pin_name(struct bpf_program *prog)
350 name = p = strdup(prog->section_name);
351 while ((p = strchr(p, '/')))
358 bpf_program__init(void *data, size_t size, char *section_name, int idx,
359 struct bpf_program *prog)
361 const size_t bpf_insn_sz = sizeof(struct bpf_insn);
363 if (size == 0 || size % bpf_insn_sz) {
364 pr_warning("corrupted section '%s', size: %zu\n",
369 memset(prog, 0, sizeof(*prog));
371 prog->section_name = strdup(section_name);
372 if (!prog->section_name) {
373 pr_warning("failed to alloc name for prog under section(%d) %s\n",
378 prog->pin_name = __bpf_program__pin_name(prog);
379 if (!prog->pin_name) {
380 pr_warning("failed to alloc pin name for prog under section(%d) %s\n",
385 prog->insns = malloc(size);
387 pr_warning("failed to alloc insns for prog under section %s\n",
391 prog->insns_cnt = size / bpf_insn_sz;
392 memcpy(prog->insns, data, size);
394 prog->instances.fds = NULL;
395 prog->instances.nr = -1;
396 prog->type = BPF_PROG_TYPE_UNSPEC;
401 bpf_program__exit(prog);
406 bpf_object__add_program(struct bpf_object *obj, void *data, size_t size,
407 char *section_name, int idx)
409 struct bpf_program prog, *progs;
412 err = bpf_program__init(data, size, section_name, idx, &prog);
416 prog.caps = &obj->caps;
417 progs = obj->programs;
418 nr_progs = obj->nr_programs;
420 progs = reallocarray(progs, nr_progs + 1, sizeof(progs[0]));
423 * In this case the original obj->programs
424 * is still valid, so don't need special treat for
425 * bpf_close_object().
427 pr_warning("failed to alloc a new program under section '%s'\n",
429 bpf_program__exit(&prog);
433 pr_debug("found program %s\n", prog.section_name);
434 obj->programs = progs;
435 obj->nr_programs = nr_progs + 1;
437 progs[nr_progs] = prog;
442 bpf_object__init_prog_names(struct bpf_object *obj)
444 Elf_Data *symbols = obj->efile.symbols;
445 struct bpf_program *prog;
448 for (pi = 0; pi < obj->nr_programs; pi++) {
449 const char *name = NULL;
451 prog = &obj->programs[pi];
453 for (si = 0; si < symbols->d_size / sizeof(GElf_Sym) && !name;
457 if (!gelf_getsym(symbols, si, &sym))
459 if (sym.st_shndx != prog->idx)
461 if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL)
464 name = elf_strptr(obj->efile.elf,
465 obj->efile.strtabidx,
468 pr_warning("failed to get sym name string for prog %s\n",
470 return -LIBBPF_ERRNO__LIBELF;
474 if (!name && prog->idx == obj->efile.text_shndx)
478 pr_warning("failed to find sym for prog %s\n",
483 prog->name = strdup(name);
485 pr_warning("failed to allocate memory for prog sym %s\n",
494 static struct bpf_object *bpf_object__new(const char *path,
498 struct bpf_object *obj;
501 obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
503 pr_warning("alloc memory failed for %s\n", path);
504 return ERR_PTR(-ENOMEM);
507 strcpy(obj->path, path);
508 /* Using basename() GNU version which doesn't modify arg. */
509 strncpy(obj->name, basename((void *)path), sizeof(obj->name) - 1);
510 end = strchr(obj->name, '.');
516 * Caller of this function should also call
517 * bpf_object__elf_finish() after data collection to return
518 * obj_buf to user. If not, we should duplicate the buffer to
519 * avoid user freeing them before elf finish.
521 obj->efile.obj_buf = obj_buf;
522 obj->efile.obj_buf_sz = obj_buf_sz;
523 obj->efile.maps_shndx = -1;
524 obj->efile.btf_maps_shndx = -1;
525 obj->efile.data_shndx = -1;
526 obj->efile.rodata_shndx = -1;
527 obj->efile.bss_shndx = -1;
531 INIT_LIST_HEAD(&obj->list);
532 list_add(&obj->list, &bpf_objects_list);
536 static void bpf_object__elf_finish(struct bpf_object *obj)
538 if (!obj_elf_valid(obj))
541 if (obj->efile.elf) {
542 elf_end(obj->efile.elf);
543 obj->efile.elf = NULL;
545 obj->efile.symbols = NULL;
546 obj->efile.data = NULL;
547 obj->efile.rodata = NULL;
548 obj->efile.bss = NULL;
550 zfree(&obj->efile.reloc);
551 obj->efile.nr_reloc = 0;
552 zclose(obj->efile.fd);
553 obj->efile.obj_buf = NULL;
554 obj->efile.obj_buf_sz = 0;
557 static int bpf_object__elf_init(struct bpf_object *obj)
562 if (obj_elf_valid(obj)) {
563 pr_warning("elf init: internal error\n");
564 return -LIBBPF_ERRNO__LIBELF;
567 if (obj->efile.obj_buf_sz > 0) {
569 * obj_buf should have been validated by
570 * bpf_object__open_buffer().
572 obj->efile.elf = elf_memory(obj->efile.obj_buf,
573 obj->efile.obj_buf_sz);
575 obj->efile.fd = open(obj->path, O_RDONLY);
576 if (obj->efile.fd < 0) {
577 char errmsg[STRERR_BUFSIZE], *cp;
580 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
581 pr_warning("failed to open %s: %s\n", obj->path, cp);
585 obj->efile.elf = elf_begin(obj->efile.fd,
586 LIBBPF_ELF_C_READ_MMAP, NULL);
589 if (!obj->efile.elf) {
590 pr_warning("failed to open %s as ELF file\n", obj->path);
591 err = -LIBBPF_ERRNO__LIBELF;
595 if (!gelf_getehdr(obj->efile.elf, &obj->efile.ehdr)) {
596 pr_warning("failed to get EHDR from %s\n", obj->path);
597 err = -LIBBPF_ERRNO__FORMAT;
600 ep = &obj->efile.ehdr;
602 /* Old LLVM set e_machine to EM_NONE */
603 if (ep->e_type != ET_REL ||
604 (ep->e_machine && ep->e_machine != EM_BPF)) {
605 pr_warning("%s is not an eBPF object file\n", obj->path);
606 err = -LIBBPF_ERRNO__FORMAT;
612 bpf_object__elf_finish(obj);
616 static int bpf_object__check_endianness(struct bpf_object *obj)
618 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
619 if (obj->efile.ehdr.e_ident[EI_DATA] == ELFDATA2LSB)
621 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
622 if (obj->efile.ehdr.e_ident[EI_DATA] == ELFDATA2MSB)
625 # error "Unrecognized __BYTE_ORDER__"
627 pr_warning("endianness mismatch.\n");
628 return -LIBBPF_ERRNO__ENDIAN;
632 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
634 memcpy(obj->license, data, min(size, sizeof(obj->license) - 1));
635 pr_debug("license of %s is %s\n", obj->path, obj->license);
640 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
644 if (size != sizeof(kver)) {
645 pr_warning("invalid kver section in %s\n", obj->path);
646 return -LIBBPF_ERRNO__FORMAT;
648 memcpy(&kver, data, sizeof(kver));
649 obj->kern_version = kver;
650 pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
654 static int compare_bpf_map(const void *_a, const void *_b)
656 const struct bpf_map *a = _a;
657 const struct bpf_map *b = _b;
659 if (a->sec_idx != b->sec_idx)
660 return a->sec_idx - b->sec_idx;
661 return a->sec_offset - b->sec_offset;
664 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
666 if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
667 type == BPF_MAP_TYPE_HASH_OF_MAPS)
672 static int bpf_object_search_section_size(const struct bpf_object *obj,
673 const char *name, size_t *d_size)
675 const GElf_Ehdr *ep = &obj->efile.ehdr;
676 Elf *elf = obj->efile.elf;
680 while ((scn = elf_nextscn(elf, scn)) != NULL) {
681 const char *sec_name;
686 if (gelf_getshdr(scn, &sh) != &sh) {
687 pr_warning("failed to get section(%d) header from %s\n",
692 sec_name = elf_strptr(elf, ep->e_shstrndx, sh.sh_name);
694 pr_warning("failed to get section(%d) name from %s\n",
699 if (strcmp(name, sec_name))
702 data = elf_getdata(scn, 0);
704 pr_warning("failed to get section(%d) data from %s(%s)\n",
705 idx, name, obj->path);
709 *d_size = data->d_size;
716 int bpf_object__section_size(const struct bpf_object *obj, const char *name,
725 } else if (!strcmp(name, ".data")) {
727 *size = obj->efile.data->d_size;
728 } else if (!strcmp(name, ".bss")) {
730 *size = obj->efile.bss->d_size;
731 } else if (!strcmp(name, ".rodata")) {
732 if (obj->efile.rodata)
733 *size = obj->efile.rodata->d_size;
735 ret = bpf_object_search_section_size(obj, name, &d_size);
740 return *size ? 0 : ret;
743 int bpf_object__variable_offset(const struct bpf_object *obj, const char *name,
746 Elf_Data *symbols = obj->efile.symbols;
753 for (si = 0; si < symbols->d_size / sizeof(GElf_Sym); si++) {
756 if (!gelf_getsym(symbols, si, &sym))
758 if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL ||
759 GELF_ST_TYPE(sym.st_info) != STT_OBJECT)
762 sname = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
765 pr_warning("failed to get sym name string for var %s\n",
769 if (strcmp(name, sname) == 0) {
778 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
780 struct bpf_map *new_maps;
784 if (obj->nr_maps < obj->maps_cap)
785 return &obj->maps[obj->nr_maps++];
787 new_cap = max((size_t)4, obj->maps_cap * 3 / 2);
788 new_maps = realloc(obj->maps, new_cap * sizeof(*obj->maps));
790 pr_warning("alloc maps for object failed\n");
791 return ERR_PTR(-ENOMEM);
794 obj->maps_cap = new_cap;
795 obj->maps = new_maps;
797 /* zero out new maps */
798 memset(obj->maps + obj->nr_maps, 0,
799 (obj->maps_cap - obj->nr_maps) * sizeof(*obj->maps));
801 * fill all fd with -1 so won't close incorrect fd (fd=0 is stdin)
802 * when failure (zclose won't close negative fd)).
804 for (i = obj->nr_maps; i < obj->maps_cap; i++) {
805 obj->maps[i].fd = -1;
806 obj->maps[i].inner_map_fd = -1;
809 return &obj->maps[obj->nr_maps++];
813 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
814 int sec_idx, Elf_Data *data, void **data_buff)
816 char map_name[BPF_OBJ_NAME_LEN];
817 struct bpf_map_def *def;
820 map = bpf_object__add_map(obj);
824 map->libbpf_type = type;
825 map->sec_idx = sec_idx;
827 snprintf(map_name, sizeof(map_name), "%.8s%.7s", obj->name,
828 libbpf_type_to_btf_name[type]);
829 map->name = strdup(map_name);
831 pr_warning("failed to alloc map name\n");
834 pr_debug("map '%s' (global data): at sec_idx %d, offset %zu.\n",
835 map_name, map->sec_idx, map->sec_offset);
838 def->type = BPF_MAP_TYPE_ARRAY;
839 def->key_size = sizeof(int);
840 def->value_size = data->d_size;
841 def->max_entries = 1;
842 def->map_flags = type == LIBBPF_MAP_RODATA ? BPF_F_RDONLY_PROG : 0;
844 *data_buff = malloc(data->d_size);
847 pr_warning("failed to alloc map content buffer\n");
850 memcpy(*data_buff, data->d_buf, data->d_size);
853 pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
857 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
861 if (!obj->caps.global_data)
864 * Populate obj->maps with libbpf internal maps.
866 if (obj->efile.data_shndx >= 0) {
867 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
868 obj->efile.data_shndx,
870 &obj->sections.data);
874 if (obj->efile.rodata_shndx >= 0) {
875 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
876 obj->efile.rodata_shndx,
878 &obj->sections.rodata);
882 if (obj->efile.bss_shndx >= 0) {
883 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
884 obj->efile.bss_shndx,
885 obj->efile.bss, NULL);
892 static int bpf_object__init_user_maps(struct bpf_object *obj, bool strict)
894 Elf_Data *symbols = obj->efile.symbols;
895 int i, map_def_sz = 0, nr_maps = 0, nr_syms;
896 Elf_Data *data = NULL;
899 if (obj->efile.maps_shndx < 0)
905 scn = elf_getscn(obj->efile.elf, obj->efile.maps_shndx);
907 data = elf_getdata(scn, NULL);
909 pr_warning("failed to get Elf_Data from map section %d\n",
910 obj->efile.maps_shndx);
915 * Count number of maps. Each map has a name.
916 * Array of maps is not supported: only the first element is
919 * TODO: Detect array of map and report error.
921 nr_syms = symbols->d_size / sizeof(GElf_Sym);
922 for (i = 0; i < nr_syms; i++) {
925 if (!gelf_getsym(symbols, i, &sym))
927 if (sym.st_shndx != obj->efile.maps_shndx)
931 /* Assume equally sized map definitions */
932 pr_debug("maps in %s: %d maps in %zd bytes\n",
933 obj->path, nr_maps, data->d_size);
935 map_def_sz = data->d_size / nr_maps;
936 if (!data->d_size || (data->d_size % nr_maps) != 0) {
937 pr_warning("unable to determine map definition size "
938 "section %s, %d maps in %zd bytes\n",
939 obj->path, nr_maps, data->d_size);
943 /* Fill obj->maps using data in "maps" section. */
944 for (i = 0; i < nr_syms; i++) {
946 const char *map_name;
947 struct bpf_map_def *def;
950 if (!gelf_getsym(symbols, i, &sym))
952 if (sym.st_shndx != obj->efile.maps_shndx)
955 map = bpf_object__add_map(obj);
959 map_name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
962 pr_warning("failed to get map #%d name sym string for obj %s\n",
964 return -LIBBPF_ERRNO__FORMAT;
967 map->libbpf_type = LIBBPF_MAP_UNSPEC;
968 map->sec_idx = sym.st_shndx;
969 map->sec_offset = sym.st_value;
970 pr_debug("map '%s' (legacy): at sec_idx %d, offset %zu.\n",
971 map_name, map->sec_idx, map->sec_offset);
972 if (sym.st_value + map_def_sz > data->d_size) {
973 pr_warning("corrupted maps section in %s: last map \"%s\" too small\n",
974 obj->path, map_name);
978 map->name = strdup(map_name);
980 pr_warning("failed to alloc map name\n");
983 pr_debug("map %d is \"%s\"\n", i, map->name);
984 def = (struct bpf_map_def *)(data->d_buf + sym.st_value);
986 * If the definition of the map in the object file fits in
987 * bpf_map_def, copy it. Any extra fields in our version
988 * of bpf_map_def will default to zero as a result of the
991 if (map_def_sz <= sizeof(struct bpf_map_def)) {
992 memcpy(&map->def, def, map_def_sz);
995 * Here the map structure being read is bigger than what
996 * we expect, truncate if the excess bits are all zero.
997 * If they are not zero, reject this map as
1001 for (b = ((char *)def) + sizeof(struct bpf_map_def);
1002 b < ((char *)def) + map_def_sz; b++) {
1004 pr_warning("maps section in %s: \"%s\" "
1005 "has unrecognized, non-zero "
1007 obj->path, map_name);
1012 memcpy(&map->def, def, sizeof(struct bpf_map_def));
1018 static const struct btf_type *skip_mods_and_typedefs(const struct btf *btf,
1021 const struct btf_type *t = btf__type_by_id(btf, id);
1024 switch (BTF_INFO_KIND(t->info)) {
1025 case BTF_KIND_VOLATILE:
1026 case BTF_KIND_CONST:
1027 case BTF_KIND_RESTRICT:
1028 case BTF_KIND_TYPEDEF:
1029 t = btf__type_by_id(btf, t->type);
1038 * Fetch integer attribute of BTF map definition. Such attributes are
1039 * represented using a pointer to an array, in which dimensionality of array
1040 * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
1041 * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
1042 * type definition, while using only sizeof(void *) space in ELF data section.
1044 static bool get_map_field_int(const char *map_name, const struct btf *btf,
1045 const struct btf_type *def,
1046 const struct btf_member *m, __u32 *res) {
1047 const struct btf_type *t = skip_mods_and_typedefs(btf, m->type);
1048 const char *name = btf__name_by_offset(btf, m->name_off);
1049 const struct btf_array *arr_info;
1050 const struct btf_type *arr_t;
1052 if (!btf_is_ptr(t)) {
1053 pr_warning("map '%s': attr '%s': expected PTR, got %u.\n",
1054 map_name, name, btf_kind(t));
1058 arr_t = btf__type_by_id(btf, t->type);
1060 pr_warning("map '%s': attr '%s': type [%u] not found.\n",
1061 map_name, name, t->type);
1064 if (!btf_is_array(arr_t)) {
1065 pr_warning("map '%s': attr '%s': expected ARRAY, got %u.\n",
1066 map_name, name, btf_kind(arr_t));
1069 arr_info = btf_array(arr_t);
1070 *res = arr_info->nelems;
1074 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
1075 const struct btf_type *sec,
1076 int var_idx, int sec_idx,
1077 const Elf_Data *data, bool strict)
1079 const struct btf_type *var, *def, *t;
1080 const struct btf_var_secinfo *vi;
1081 const struct btf_var *var_extra;
1082 const struct btf_member *m;
1083 const char *map_name;
1084 struct bpf_map *map;
1087 vi = btf_var_secinfos(sec) + var_idx;
1088 var = btf__type_by_id(obj->btf, vi->type);
1089 var_extra = btf_var(var);
1090 map_name = btf__name_by_offset(obj->btf, var->name_off);
1091 vlen = btf_vlen(var);
1093 if (map_name == NULL || map_name[0] == '\0') {
1094 pr_warning("map #%d: empty name.\n", var_idx);
1097 if ((__u64)vi->offset + vi->size > data->d_size) {
1098 pr_warning("map '%s' BTF data is corrupted.\n", map_name);
1101 if (!btf_is_var(var)) {
1102 pr_warning("map '%s': unexpected var kind %u.\n",
1103 map_name, btf_kind(var));
1106 if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED &&
1107 var_extra->linkage != BTF_VAR_STATIC) {
1108 pr_warning("map '%s': unsupported var linkage %u.\n",
1109 map_name, var_extra->linkage);
1113 def = skip_mods_and_typedefs(obj->btf, var->type);
1114 if (!btf_is_struct(def)) {
1115 pr_warning("map '%s': unexpected def kind %u.\n",
1116 map_name, btf_kind(var));
1119 if (def->size > vi->size) {
1120 pr_warning("map '%s': invalid def size.\n", map_name);
1124 map = bpf_object__add_map(obj);
1126 return PTR_ERR(map);
1127 map->name = strdup(map_name);
1129 pr_warning("map '%s': failed to alloc map name.\n", map_name);
1132 map->libbpf_type = LIBBPF_MAP_UNSPEC;
1133 map->def.type = BPF_MAP_TYPE_UNSPEC;
1134 map->sec_idx = sec_idx;
1135 map->sec_offset = vi->offset;
1136 pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
1137 map_name, map->sec_idx, map->sec_offset);
1139 vlen = btf_vlen(def);
1140 m = btf_members(def);
1141 for (i = 0; i < vlen; i++, m++) {
1142 const char *name = btf__name_by_offset(obj->btf, m->name_off);
1145 pr_warning("map '%s': invalid field #%d.\n",
1149 if (strcmp(name, "type") == 0) {
1150 if (!get_map_field_int(map_name, obj->btf, def, m,
1153 pr_debug("map '%s': found type = %u.\n",
1154 map_name, map->def.type);
1155 } else if (strcmp(name, "max_entries") == 0) {
1156 if (!get_map_field_int(map_name, obj->btf, def, m,
1157 &map->def.max_entries))
1159 pr_debug("map '%s': found max_entries = %u.\n",
1160 map_name, map->def.max_entries);
1161 } else if (strcmp(name, "map_flags") == 0) {
1162 if (!get_map_field_int(map_name, obj->btf, def, m,
1163 &map->def.map_flags))
1165 pr_debug("map '%s': found map_flags = %u.\n",
1166 map_name, map->def.map_flags);
1167 } else if (strcmp(name, "key_size") == 0) {
1170 if (!get_map_field_int(map_name, obj->btf, def, m,
1173 pr_debug("map '%s': found key_size = %u.\n",
1175 if (map->def.key_size && map->def.key_size != sz) {
1176 pr_warning("map '%s': conflicting key size %u != %u.\n",
1177 map_name, map->def.key_size, sz);
1180 map->def.key_size = sz;
1181 } else if (strcmp(name, "key") == 0) {
1184 t = btf__type_by_id(obj->btf, m->type);
1186 pr_warning("map '%s': key type [%d] not found.\n",
1190 if (!btf_is_ptr(t)) {
1191 pr_warning("map '%s': key spec is not PTR: %u.\n",
1192 map_name, btf_kind(t));
1195 sz = btf__resolve_size(obj->btf, t->type);
1197 pr_warning("map '%s': can't determine key size for type [%u]: %lld.\n",
1198 map_name, t->type, sz);
1201 pr_debug("map '%s': found key [%u], sz = %lld.\n",
1202 map_name, t->type, sz);
1203 if (map->def.key_size && map->def.key_size != sz) {
1204 pr_warning("map '%s': conflicting key size %u != %lld.\n",
1205 map_name, map->def.key_size, sz);
1208 map->def.key_size = sz;
1209 map->btf_key_type_id = t->type;
1210 } else if (strcmp(name, "value_size") == 0) {
1213 if (!get_map_field_int(map_name, obj->btf, def, m,
1216 pr_debug("map '%s': found value_size = %u.\n",
1218 if (map->def.value_size && map->def.value_size != sz) {
1219 pr_warning("map '%s': conflicting value size %u != %u.\n",
1220 map_name, map->def.value_size, sz);
1223 map->def.value_size = sz;
1224 } else if (strcmp(name, "value") == 0) {
1227 t = btf__type_by_id(obj->btf, m->type);
1229 pr_warning("map '%s': value type [%d] not found.\n",
1233 if (!btf_is_ptr(t)) {
1234 pr_warning("map '%s': value spec is not PTR: %u.\n",
1235 map_name, btf_kind(t));
1238 sz = btf__resolve_size(obj->btf, t->type);
1240 pr_warning("map '%s': can't determine value size for type [%u]: %lld.\n",
1241 map_name, t->type, sz);
1244 pr_debug("map '%s': found value [%u], sz = %lld.\n",
1245 map_name, t->type, sz);
1246 if (map->def.value_size && map->def.value_size != sz) {
1247 pr_warning("map '%s': conflicting value size %u != %lld.\n",
1248 map_name, map->def.value_size, sz);
1251 map->def.value_size = sz;
1252 map->btf_value_type_id = t->type;
1255 pr_warning("map '%s': unknown field '%s'.\n",
1259 pr_debug("map '%s': ignoring unknown field '%s'.\n",
1264 if (map->def.type == BPF_MAP_TYPE_UNSPEC) {
1265 pr_warning("map '%s': map type isn't specified.\n", map_name);
1272 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict)
1274 const struct btf_type *sec = NULL;
1275 int nr_types, i, vlen, err;
1276 const struct btf_type *t;
1281 if (obj->efile.btf_maps_shndx < 0)
1284 scn = elf_getscn(obj->efile.elf, obj->efile.btf_maps_shndx);
1286 data = elf_getdata(scn, NULL);
1287 if (!scn || !data) {
1288 pr_warning("failed to get Elf_Data from map section %d (%s)\n",
1289 obj->efile.maps_shndx, MAPS_ELF_SEC);
1293 nr_types = btf__get_nr_types(obj->btf);
1294 for (i = 1; i <= nr_types; i++) {
1295 t = btf__type_by_id(obj->btf, i);
1296 if (!btf_is_datasec(t))
1298 name = btf__name_by_offset(obj->btf, t->name_off);
1299 if (strcmp(name, MAPS_ELF_SEC) == 0) {
1306 pr_warning("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
1310 vlen = btf_vlen(sec);
1311 for (i = 0; i < vlen; i++) {
1312 err = bpf_object__init_user_btf_map(obj, sec, i,
1313 obj->efile.btf_maps_shndx,
1322 static int bpf_object__init_maps(struct bpf_object *obj, int flags)
1324 bool strict = !(flags & MAPS_RELAX_COMPAT);
1327 err = bpf_object__init_user_maps(obj, strict);
1331 err = bpf_object__init_user_btf_maps(obj, strict);
1335 err = bpf_object__init_global_data_maps(obj);
1340 qsort(obj->maps, obj->nr_maps, sizeof(obj->maps[0]),
1346 static bool section_have_execinstr(struct bpf_object *obj, int idx)
1351 scn = elf_getscn(obj->efile.elf, idx);
1355 if (gelf_getshdr(scn, &sh) != &sh)
1358 if (sh.sh_flags & SHF_EXECINSTR)
1364 static void bpf_object__sanitize_btf(struct bpf_object *obj)
1366 bool has_datasec = obj->caps.btf_datasec;
1367 bool has_func = obj->caps.btf_func;
1368 struct btf *btf = obj->btf;
1372 if (!obj->btf || (has_func && has_datasec))
1375 for (i = 1; i <= btf__get_nr_types(btf); i++) {
1376 t = (struct btf_type *)btf__type_by_id(btf, i);
1378 if (!has_datasec && btf_is_var(t)) {
1379 /* replace VAR with INT */
1380 t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
1381 t->size = sizeof(int);
1382 *(int *)(t + 1) = BTF_INT_ENC(0, 0, 32);
1383 } else if (!has_datasec && btf_is_datasec(t)) {
1384 /* replace DATASEC with STRUCT */
1385 const struct btf_var_secinfo *v = btf_var_secinfos(t);
1386 struct btf_member *m = btf_members(t);
1387 struct btf_type *vt;
1390 name = (char *)btf__name_by_offset(btf, t->name_off);
1398 t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
1399 for (j = 0; j < vlen; j++, v++, m++) {
1400 /* order of field assignments is important */
1401 m->offset = v->offset * 8;
1403 /* preserve variable name as member name */
1404 vt = (void *)btf__type_by_id(btf, v->type);
1405 m->name_off = vt->name_off;
1407 } else if (!has_func && btf_is_func_proto(t)) {
1408 /* replace FUNC_PROTO with ENUM */
1410 t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
1411 t->size = sizeof(__u32); /* kernel enforced */
1412 } else if (!has_func && btf_is_func(t)) {
1413 /* replace FUNC with TYPEDEF */
1414 t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
1419 static void bpf_object__sanitize_btf_ext(struct bpf_object *obj)
1424 if (!obj->caps.btf_func) {
1425 btf_ext__free(obj->btf_ext);
1426 obj->btf_ext = NULL;
1430 static bool bpf_object__is_btf_mandatory(const struct bpf_object *obj)
1432 return obj->efile.btf_maps_shndx >= 0;
1435 static int bpf_object__init_btf(struct bpf_object *obj,
1437 Elf_Data *btf_ext_data)
1439 bool btf_required = bpf_object__is_btf_mandatory(obj);
1443 obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
1444 if (IS_ERR(obj->btf)) {
1445 pr_warning("Error loading ELF section %s: %d.\n",
1449 err = btf__finalize_data(obj, obj->btf);
1451 pr_warning("Error finalizing %s: %d.\n",
1458 pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
1459 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
1462 obj->btf_ext = btf_ext__new(btf_ext_data->d_buf,
1463 btf_ext_data->d_size);
1464 if (IS_ERR(obj->btf_ext)) {
1465 pr_warning("Error loading ELF section %s: %ld. Ignored and continue.\n",
1466 BTF_EXT_ELF_SEC, PTR_ERR(obj->btf_ext));
1467 obj->btf_ext = NULL;
1472 if (err || IS_ERR(obj->btf)) {
1474 err = err ? : PTR_ERR(obj->btf);
1477 if (!IS_ERR_OR_NULL(obj->btf))
1478 btf__free(obj->btf);
1481 if (btf_required && !obj->btf) {
1482 pr_warning("BTF is required, but is missing or corrupted.\n");
1483 return err == 0 ? -ENOENT : err;
1488 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
1495 bpf_object__sanitize_btf(obj);
1496 bpf_object__sanitize_btf_ext(obj);
1498 err = btf__load(obj->btf);
1500 pr_warning("Error loading %s into kernel: %d.\n",
1502 btf__free(obj->btf);
1504 if (bpf_object__is_btf_mandatory(obj))
1510 static int bpf_object__elf_collect(struct bpf_object *obj, int flags)
1512 Elf *elf = obj->efile.elf;
1513 GElf_Ehdr *ep = &obj->efile.ehdr;
1514 Elf_Data *btf_ext_data = NULL;
1515 Elf_Data *btf_data = NULL;
1516 Elf_Scn *scn = NULL;
1517 int idx = 0, err = 0;
1519 /* Elf is corrupted/truncated, avoid calling elf_strptr. */
1520 if (!elf_rawdata(elf_getscn(elf, ep->e_shstrndx), NULL)) {
1521 pr_warning("failed to get e_shstrndx from %s\n", obj->path);
1522 return -LIBBPF_ERRNO__FORMAT;
1525 while ((scn = elf_nextscn(elf, scn)) != NULL) {
1531 if (gelf_getshdr(scn, &sh) != &sh) {
1532 pr_warning("failed to get section(%d) header from %s\n",
1534 return -LIBBPF_ERRNO__FORMAT;
1537 name = elf_strptr(elf, ep->e_shstrndx, sh.sh_name);
1539 pr_warning("failed to get section(%d) name from %s\n",
1541 return -LIBBPF_ERRNO__FORMAT;
1544 data = elf_getdata(scn, 0);
1546 pr_warning("failed to get section(%d) data from %s(%s)\n",
1547 idx, name, obj->path);
1548 return -LIBBPF_ERRNO__FORMAT;
1550 pr_debug("section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
1551 idx, name, (unsigned long)data->d_size,
1552 (int)sh.sh_link, (unsigned long)sh.sh_flags,
1555 if (strcmp(name, "license") == 0) {
1556 err = bpf_object__init_license(obj,
1561 } else if (strcmp(name, "version") == 0) {
1562 err = bpf_object__init_kversion(obj,
1567 } else if (strcmp(name, "maps") == 0) {
1568 obj->efile.maps_shndx = idx;
1569 } else if (strcmp(name, MAPS_ELF_SEC) == 0) {
1570 obj->efile.btf_maps_shndx = idx;
1571 } else if (strcmp(name, BTF_ELF_SEC) == 0) {
1573 } else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
1574 btf_ext_data = data;
1575 } else if (sh.sh_type == SHT_SYMTAB) {
1576 if (obj->efile.symbols) {
1577 pr_warning("bpf: multiple SYMTAB in %s\n",
1579 return -LIBBPF_ERRNO__FORMAT;
1581 obj->efile.symbols = data;
1582 obj->efile.strtabidx = sh.sh_link;
1583 } else if (sh.sh_type == SHT_PROGBITS && data->d_size > 0) {
1584 if (sh.sh_flags & SHF_EXECINSTR) {
1585 if (strcmp(name, ".text") == 0)
1586 obj->efile.text_shndx = idx;
1587 err = bpf_object__add_program(obj, data->d_buf,
1588 data->d_size, name, idx);
1590 char errmsg[STRERR_BUFSIZE];
1591 char *cp = libbpf_strerror_r(-err, errmsg,
1594 pr_warning("failed to alloc program %s (%s): %s",
1595 name, obj->path, cp);
1598 } else if (strcmp(name, ".data") == 0) {
1599 obj->efile.data = data;
1600 obj->efile.data_shndx = idx;
1601 } else if (strcmp(name, ".rodata") == 0) {
1602 obj->efile.rodata = data;
1603 obj->efile.rodata_shndx = idx;
1605 pr_debug("skip section(%d) %s\n", idx, name);
1607 } else if (sh.sh_type == SHT_REL) {
1608 int nr_reloc = obj->efile.nr_reloc;
1609 void *reloc = obj->efile.reloc;
1610 int sec = sh.sh_info; /* points to other section */
1612 /* Only do relo for section with exec instructions */
1613 if (!section_have_execinstr(obj, sec)) {
1614 pr_debug("skip relo %s(%d) for section(%d)\n",
1619 reloc = reallocarray(reloc, nr_reloc + 1,
1620 sizeof(*obj->efile.reloc));
1622 pr_warning("realloc failed\n");
1626 obj->efile.reloc = reloc;
1627 obj->efile.nr_reloc++;
1629 obj->efile.reloc[nr_reloc].shdr = sh;
1630 obj->efile.reloc[nr_reloc].data = data;
1631 } else if (sh.sh_type == SHT_NOBITS && strcmp(name, ".bss") == 0) {
1632 obj->efile.bss = data;
1633 obj->efile.bss_shndx = idx;
1635 pr_debug("skip section(%d) %s\n", idx, name);
1639 if (!obj->efile.strtabidx || obj->efile.strtabidx >= idx) {
1640 pr_warning("Corrupted ELF file: index of strtab invalid\n");
1641 return -LIBBPF_ERRNO__FORMAT;
1643 err = bpf_object__init_btf(obj, btf_data, btf_ext_data);
1645 err = bpf_object__init_maps(obj, flags);
1647 err = bpf_object__sanitize_and_load_btf(obj);
1649 err = bpf_object__init_prog_names(obj);
1653 static struct bpf_program *
1654 bpf_object__find_prog_by_idx(struct bpf_object *obj, int idx)
1656 struct bpf_program *prog;
1659 for (i = 0; i < obj->nr_programs; i++) {
1660 prog = &obj->programs[i];
1661 if (prog->idx == idx)
1667 struct bpf_program *
1668 bpf_object__find_program_by_title(const struct bpf_object *obj,
1671 struct bpf_program *pos;
1673 bpf_object__for_each_program(pos, obj) {
1674 if (pos->section_name && !strcmp(pos->section_name, title))
1680 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
1683 return shndx == obj->efile.data_shndx ||
1684 shndx == obj->efile.bss_shndx ||
1685 shndx == obj->efile.rodata_shndx;
1688 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
1691 return shndx == obj->efile.maps_shndx ||
1692 shndx == obj->efile.btf_maps_shndx;
1695 static bool bpf_object__relo_in_known_section(const struct bpf_object *obj,
1698 return shndx == obj->efile.text_shndx ||
1699 bpf_object__shndx_is_maps(obj, shndx) ||
1700 bpf_object__shndx_is_data(obj, shndx);
1703 static enum libbpf_map_type
1704 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
1706 if (shndx == obj->efile.data_shndx)
1707 return LIBBPF_MAP_DATA;
1708 else if (shndx == obj->efile.bss_shndx)
1709 return LIBBPF_MAP_BSS;
1710 else if (shndx == obj->efile.rodata_shndx)
1711 return LIBBPF_MAP_RODATA;
1713 return LIBBPF_MAP_UNSPEC;
1717 bpf_program__collect_reloc(struct bpf_program *prog, GElf_Shdr *shdr,
1718 Elf_Data *data, struct bpf_object *obj)
1720 Elf_Data *symbols = obj->efile.symbols;
1721 struct bpf_map *maps = obj->maps;
1722 size_t nr_maps = obj->nr_maps;
1725 pr_debug("collecting relocating info for: '%s'\n", prog->section_name);
1726 nrels = shdr->sh_size / shdr->sh_entsize;
1728 prog->reloc_desc = malloc(sizeof(*prog->reloc_desc) * nrels);
1729 if (!prog->reloc_desc) {
1730 pr_warning("failed to alloc memory in relocation\n");
1733 prog->nr_reloc = nrels;
1735 for (i = 0; i < nrels; i++) {
1736 struct bpf_insn *insns = prog->insns;
1737 enum libbpf_map_type type;
1738 unsigned int insn_idx;
1739 unsigned int shdr_idx;
1745 if (!gelf_getrel(data, i, &rel)) {
1746 pr_warning("relocation: failed to get %d reloc\n", i);
1747 return -LIBBPF_ERRNO__FORMAT;
1750 if (!gelf_getsym(symbols, GELF_R_SYM(rel.r_info), &sym)) {
1751 pr_warning("relocation: symbol %"PRIx64" not found\n",
1752 GELF_R_SYM(rel.r_info));
1753 return -LIBBPF_ERRNO__FORMAT;
1756 name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
1757 sym.st_name) ? : "<?>";
1759 pr_debug("relo for %lld value %lld name %d (\'%s\')\n",
1760 (long long) (rel.r_info >> 32),
1761 (long long) sym.st_value, sym.st_name, name);
1763 shdr_idx = sym.st_shndx;
1764 insn_idx = rel.r_offset / sizeof(struct bpf_insn);
1765 pr_debug("relocation: insn_idx=%u, shdr_idx=%u\n",
1766 insn_idx, shdr_idx);
1768 if (shdr_idx >= SHN_LORESERVE) {
1769 pr_warning("relocation: not yet supported relo for non-static global \'%s\' variable in special section (0x%x) found in insns[%d].code 0x%x\n",
1770 name, shdr_idx, insn_idx,
1771 insns[insn_idx].code);
1772 return -LIBBPF_ERRNO__RELOC;
1774 if (!bpf_object__relo_in_known_section(obj, shdr_idx)) {
1775 pr_warning("Program '%s' contains unrecognized relo data pointing to section %u\n",
1776 prog->section_name, shdr_idx);
1777 return -LIBBPF_ERRNO__RELOC;
1780 if (insns[insn_idx].code == (BPF_JMP | BPF_CALL)) {
1781 if (insns[insn_idx].src_reg != BPF_PSEUDO_CALL) {
1782 pr_warning("incorrect bpf_call opcode\n");
1783 return -LIBBPF_ERRNO__RELOC;
1785 prog->reloc_desc[i].type = RELO_CALL;
1786 prog->reloc_desc[i].insn_idx = insn_idx;
1787 prog->reloc_desc[i].text_off = sym.st_value;
1788 obj->has_pseudo_calls = true;
1792 if (insns[insn_idx].code != (BPF_LD | BPF_IMM | BPF_DW)) {
1793 pr_warning("bpf: relocation: invalid relo for insns[%d].code 0x%x\n",
1794 insn_idx, insns[insn_idx].code);
1795 return -LIBBPF_ERRNO__RELOC;
1798 if (bpf_object__shndx_is_maps(obj, shdr_idx) ||
1799 bpf_object__shndx_is_data(obj, shdr_idx)) {
1800 type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
1801 if (type != LIBBPF_MAP_UNSPEC) {
1802 if (GELF_ST_BIND(sym.st_info) == STB_GLOBAL) {
1803 pr_warning("bpf: relocation: not yet supported relo for non-static global \'%s\' variable found in insns[%d].code 0x%x\n",
1804 name, insn_idx, insns[insn_idx].code);
1805 return -LIBBPF_ERRNO__RELOC;
1807 if (!obj->caps.global_data) {
1808 pr_warning("bpf: relocation: kernel does not support global \'%s\' variable access in insns[%d]\n",
1810 return -LIBBPF_ERRNO__RELOC;
1814 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
1815 if (maps[map_idx].libbpf_type != type)
1817 if (type != LIBBPF_MAP_UNSPEC ||
1818 (maps[map_idx].sec_idx == sym.st_shndx &&
1819 maps[map_idx].sec_offset == sym.st_value)) {
1820 pr_debug("relocation: found map %zd (%s, sec_idx %d, offset %zu) for insn %u\n",
1821 map_idx, maps[map_idx].name,
1822 maps[map_idx].sec_idx,
1823 maps[map_idx].sec_offset,
1829 if (map_idx >= nr_maps) {
1830 pr_warning("bpf relocation: map_idx %d larger than %d\n",
1831 (int)map_idx, (int)nr_maps - 1);
1832 return -LIBBPF_ERRNO__RELOC;
1835 prog->reloc_desc[i].type = type != LIBBPF_MAP_UNSPEC ?
1836 RELO_DATA : RELO_LD64;
1837 prog->reloc_desc[i].insn_idx = insn_idx;
1838 prog->reloc_desc[i].map_idx = map_idx;
1844 static int bpf_map_find_btf_info(struct bpf_object *obj, struct bpf_map *map)
1846 struct bpf_map_def *def = &map->def;
1847 __u32 key_type_id = 0, value_type_id = 0;
1850 /* if it's BTF-defined map, we don't need to search for type IDs */
1851 if (map->sec_idx == obj->efile.btf_maps_shndx)
1854 if (!bpf_map__is_internal(map)) {
1855 ret = btf__get_map_kv_tids(obj->btf, map->name, def->key_size,
1856 def->value_size, &key_type_id,
1860 * LLVM annotates global data differently in BTF, that is,
1861 * only as '.data', '.bss' or '.rodata'.
1863 ret = btf__find_by_name(obj->btf,
1864 libbpf_type_to_btf_name[map->libbpf_type]);
1869 map->btf_key_type_id = key_type_id;
1870 map->btf_value_type_id = bpf_map__is_internal(map) ?
1871 ret : value_type_id;
1875 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
1877 struct bpf_map_info info = {};
1878 __u32 len = sizeof(info);
1882 err = bpf_obj_get_info_by_fd(fd, &info, &len);
1886 new_name = strdup(info.name);
1890 new_fd = open("/", O_RDONLY | O_CLOEXEC);
1892 goto err_free_new_name;
1894 new_fd = dup3(fd, new_fd, O_CLOEXEC);
1896 goto err_close_new_fd;
1898 err = zclose(map->fd);
1900 goto err_close_new_fd;
1904 map->name = new_name;
1905 map->def.type = info.type;
1906 map->def.key_size = info.key_size;
1907 map->def.value_size = info.value_size;
1908 map->def.max_entries = info.max_entries;
1909 map->def.map_flags = info.map_flags;
1910 map->btf_key_type_id = info.btf_key_type_id;
1911 map->btf_value_type_id = info.btf_value_type_id;
1922 int bpf_map__resize(struct bpf_map *map, __u32 max_entries)
1924 if (!map || !max_entries)
1927 /* If map already created, its attributes can't be changed. */
1931 map->def.max_entries = max_entries;
1937 bpf_object__probe_name(struct bpf_object *obj)
1939 struct bpf_load_program_attr attr;
1940 char *cp, errmsg[STRERR_BUFSIZE];
1941 struct bpf_insn insns[] = {
1942 BPF_MOV64_IMM(BPF_REG_0, 0),
1947 /* make sure basic loading works */
1949 memset(&attr, 0, sizeof(attr));
1950 attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
1952 attr.insns_cnt = ARRAY_SIZE(insns);
1953 attr.license = "GPL";
1955 ret = bpf_load_program_xattr(&attr, NULL, 0);
1957 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
1958 pr_warning("Error in %s():%s(%d). Couldn't load basic 'r0 = 0' BPF program.\n",
1959 __func__, cp, errno);
1964 /* now try the same program, but with the name */
1967 ret = bpf_load_program_xattr(&attr, NULL, 0);
1977 bpf_object__probe_global_data(struct bpf_object *obj)
1979 struct bpf_load_program_attr prg_attr;
1980 struct bpf_create_map_attr map_attr;
1981 char *cp, errmsg[STRERR_BUFSIZE];
1982 struct bpf_insn insns[] = {
1983 BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16),
1984 BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42),
1985 BPF_MOV64_IMM(BPF_REG_0, 0),
1990 memset(&map_attr, 0, sizeof(map_attr));
1991 map_attr.map_type = BPF_MAP_TYPE_ARRAY;
1992 map_attr.key_size = sizeof(int);
1993 map_attr.value_size = 32;
1994 map_attr.max_entries = 1;
1996 map = bpf_create_map_xattr(&map_attr);
1998 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
1999 pr_warning("Error in %s():%s(%d). Couldn't create simple array map.\n",
2000 __func__, cp, errno);
2006 memset(&prg_attr, 0, sizeof(prg_attr));
2007 prg_attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
2008 prg_attr.insns = insns;
2009 prg_attr.insns_cnt = ARRAY_SIZE(insns);
2010 prg_attr.license = "GPL";
2012 ret = bpf_load_program_xattr(&prg_attr, NULL, 0);
2014 obj->caps.global_data = 1;
2022 static int bpf_object__probe_btf_func(struct bpf_object *obj)
2024 const char strs[] = "\0int\0x\0a";
2025 /* void x(int a) {} */
2028 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
2029 /* FUNC_PROTO */ /* [2] */
2030 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
2031 BTF_PARAM_ENC(7, 1),
2032 /* FUNC x */ /* [3] */
2033 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0), 2),
2037 btf_fd = libbpf__load_raw_btf((char *)types, sizeof(types),
2038 strs, sizeof(strs));
2040 obj->caps.btf_func = 1;
2048 static int bpf_object__probe_btf_datasec(struct bpf_object *obj)
2050 const char strs[] = "\0x\0.data";
2054 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
2055 /* VAR x */ /* [2] */
2056 BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
2058 /* DATASEC val */ /* [3] */
2059 BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC, 0, 1), 4),
2060 BTF_VAR_SECINFO_ENC(2, 0, 4),
2064 btf_fd = libbpf__load_raw_btf((char *)types, sizeof(types),
2065 strs, sizeof(strs));
2067 obj->caps.btf_datasec = 1;
2076 bpf_object__probe_caps(struct bpf_object *obj)
2078 int (*probe_fn[])(struct bpf_object *obj) = {
2079 bpf_object__probe_name,
2080 bpf_object__probe_global_data,
2081 bpf_object__probe_btf_func,
2082 bpf_object__probe_btf_datasec,
2086 for (i = 0; i < ARRAY_SIZE(probe_fn); i++) {
2087 ret = probe_fn[i](obj);
2089 pr_debug("Probe #%d failed with %d.\n", i, ret);
2096 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
2098 char *cp, errmsg[STRERR_BUFSIZE];
2102 /* Nothing to do here since kernel already zero-initializes .bss map. */
2103 if (map->libbpf_type == LIBBPF_MAP_BSS)
2106 data = map->libbpf_type == LIBBPF_MAP_DATA ?
2107 obj->sections.data : obj->sections.rodata;
2109 err = bpf_map_update_elem(map->fd, &zero, data, 0);
2110 /* Freeze .rodata map as read-only from syscall side. */
2111 if (!err && map->libbpf_type == LIBBPF_MAP_RODATA) {
2112 err = bpf_map_freeze(map->fd);
2114 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
2115 pr_warning("Error freezing map(%s) as read-only: %s\n",
2124 bpf_object__create_maps(struct bpf_object *obj)
2126 struct bpf_create_map_attr create_attr = {};
2131 for (i = 0; i < obj->nr_maps; i++) {
2132 struct bpf_map *map = &obj->maps[i];
2133 struct bpf_map_def *def = &map->def;
2134 char *cp, errmsg[STRERR_BUFSIZE];
2135 int *pfd = &map->fd;
2138 pr_debug("skip map create (preset) %s: fd=%d\n",
2139 map->name, map->fd);
2144 create_attr.name = map->name;
2145 create_attr.map_ifindex = map->map_ifindex;
2146 create_attr.map_type = def->type;
2147 create_attr.map_flags = def->map_flags;
2148 create_attr.key_size = def->key_size;
2149 create_attr.value_size = def->value_size;
2150 if (def->type == BPF_MAP_TYPE_PERF_EVENT_ARRAY &&
2151 !def->max_entries) {
2153 nr_cpus = libbpf_num_possible_cpus();
2155 pr_warning("failed to determine number of system CPUs: %d\n",
2160 pr_debug("map '%s': setting size to %d\n",
2161 map->name, nr_cpus);
2162 create_attr.max_entries = nr_cpus;
2164 create_attr.max_entries = def->max_entries;
2166 create_attr.btf_fd = 0;
2167 create_attr.btf_key_type_id = 0;
2168 create_attr.btf_value_type_id = 0;
2169 if (bpf_map_type__is_map_in_map(def->type) &&
2170 map->inner_map_fd >= 0)
2171 create_attr.inner_map_fd = map->inner_map_fd;
2173 if (obj->btf && !bpf_map_find_btf_info(obj, map)) {
2174 create_attr.btf_fd = btf__fd(obj->btf);
2175 create_attr.btf_key_type_id = map->btf_key_type_id;
2176 create_attr.btf_value_type_id = map->btf_value_type_id;
2179 *pfd = bpf_create_map_xattr(&create_attr);
2180 if (*pfd < 0 && (create_attr.btf_key_type_id ||
2181 create_attr.btf_value_type_id)) {
2183 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
2184 pr_warning("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
2185 map->name, cp, err);
2186 create_attr.btf_fd = 0;
2187 create_attr.btf_key_type_id = 0;
2188 create_attr.btf_value_type_id = 0;
2189 map->btf_key_type_id = 0;
2190 map->btf_value_type_id = 0;
2191 *pfd = bpf_create_map_xattr(&create_attr);
2199 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
2200 pr_warning("failed to create map (name: '%s'): %s(%d)\n",
2201 map->name, cp, err);
2202 for (j = 0; j < i; j++)
2203 zclose(obj->maps[j].fd);
2207 if (bpf_map__is_internal(map)) {
2208 err = bpf_object__populate_internal_map(obj, map);
2215 pr_debug("created map %s: fd=%d\n", map->name, *pfd);
2222 check_btf_ext_reloc_err(struct bpf_program *prog, int err,
2223 void *btf_prog_info, const char *info_name)
2225 if (err != -ENOENT) {
2226 pr_warning("Error in loading %s for sec %s.\n",
2227 info_name, prog->section_name);
2231 /* err == -ENOENT (i.e. prog->section_name not found in btf_ext) */
2233 if (btf_prog_info) {
2235 * Some info has already been found but has problem
2236 * in the last btf_ext reloc. Must have to error out.
2238 pr_warning("Error in relocating %s for sec %s.\n",
2239 info_name, prog->section_name);
2243 /* Have problem loading the very first info. Ignore the rest. */
2244 pr_warning("Cannot find %s for main program sec %s. Ignore all %s.\n",
2245 info_name, prog->section_name, info_name);
2250 bpf_program_reloc_btf_ext(struct bpf_program *prog, struct bpf_object *obj,
2251 const char *section_name, __u32 insn_offset)
2255 if (!insn_offset || prog->func_info) {
2257 * !insn_offset => main program
2259 * For sub prog, the main program's func_info has to
2260 * be loaded first (i.e. prog->func_info != NULL)
2262 err = btf_ext__reloc_func_info(obj->btf, obj->btf_ext,
2263 section_name, insn_offset,
2265 &prog->func_info_cnt);
2267 return check_btf_ext_reloc_err(prog, err,
2271 prog->func_info_rec_size = btf_ext__func_info_rec_size(obj->btf_ext);
2274 if (!insn_offset || prog->line_info) {
2275 err = btf_ext__reloc_line_info(obj->btf, obj->btf_ext,
2276 section_name, insn_offset,
2278 &prog->line_info_cnt);
2280 return check_btf_ext_reloc_err(prog, err,
2284 prog->line_info_rec_size = btf_ext__line_info_rec_size(obj->btf_ext);
2288 prog->btf_fd = btf__fd(obj->btf);
2294 bpf_program__reloc_text(struct bpf_program *prog, struct bpf_object *obj,
2295 struct reloc_desc *relo)
2297 struct bpf_insn *insn, *new_insn;
2298 struct bpf_program *text;
2302 if (relo->type != RELO_CALL)
2303 return -LIBBPF_ERRNO__RELOC;
2305 if (prog->idx == obj->efile.text_shndx) {
2306 pr_warning("relo in .text insn %d into off %d\n",
2307 relo->insn_idx, relo->text_off);
2308 return -LIBBPF_ERRNO__RELOC;
2311 if (prog->main_prog_cnt == 0) {
2312 text = bpf_object__find_prog_by_idx(obj, obj->efile.text_shndx);
2314 pr_warning("no .text section found yet relo into text exist\n");
2315 return -LIBBPF_ERRNO__RELOC;
2317 new_cnt = prog->insns_cnt + text->insns_cnt;
2318 new_insn = reallocarray(prog->insns, new_cnt, sizeof(*insn));
2320 pr_warning("oom in prog realloc\n");
2325 err = bpf_program_reloc_btf_ext(prog, obj,
2332 memcpy(new_insn + prog->insns_cnt, text->insns,
2333 text->insns_cnt * sizeof(*insn));
2334 prog->insns = new_insn;
2335 prog->main_prog_cnt = prog->insns_cnt;
2336 prog->insns_cnt = new_cnt;
2337 pr_debug("added %zd insn from %s to prog %s\n",
2338 text->insns_cnt, text->section_name,
2339 prog->section_name);
2341 insn = &prog->insns[relo->insn_idx];
2342 insn->imm += prog->main_prog_cnt - relo->insn_idx;
2347 bpf_program__relocate(struct bpf_program *prog, struct bpf_object *obj)
2355 err = bpf_program_reloc_btf_ext(prog, obj,
2356 prog->section_name, 0);
2361 if (!prog->reloc_desc)
2364 for (i = 0; i < prog->nr_reloc; i++) {
2365 if (prog->reloc_desc[i].type == RELO_LD64 ||
2366 prog->reloc_desc[i].type == RELO_DATA) {
2367 bool relo_data = prog->reloc_desc[i].type == RELO_DATA;
2368 struct bpf_insn *insns = prog->insns;
2369 int insn_idx, map_idx;
2371 insn_idx = prog->reloc_desc[i].insn_idx;
2372 map_idx = prog->reloc_desc[i].map_idx;
2374 if (insn_idx + 1 >= (int)prog->insns_cnt) {
2375 pr_warning("relocation out of range: '%s'\n",
2376 prog->section_name);
2377 return -LIBBPF_ERRNO__RELOC;
2381 insns[insn_idx].src_reg = BPF_PSEUDO_MAP_FD;
2383 insns[insn_idx].src_reg = BPF_PSEUDO_MAP_VALUE;
2384 insns[insn_idx + 1].imm = insns[insn_idx].imm;
2386 insns[insn_idx].imm = obj->maps[map_idx].fd;
2387 } else if (prog->reloc_desc[i].type == RELO_CALL) {
2388 err = bpf_program__reloc_text(prog, obj,
2389 &prog->reloc_desc[i]);
2395 zfree(&prog->reloc_desc);
2402 bpf_object__relocate(struct bpf_object *obj)
2404 struct bpf_program *prog;
2408 for (i = 0; i < obj->nr_programs; i++) {
2409 prog = &obj->programs[i];
2411 err = bpf_program__relocate(prog, obj);
2413 pr_warning("failed to relocate '%s'\n",
2414 prog->section_name);
2421 static int bpf_object__collect_reloc(struct bpf_object *obj)
2425 if (!obj_elf_valid(obj)) {
2426 pr_warning("Internal error: elf object is closed\n");
2427 return -LIBBPF_ERRNO__INTERNAL;
2430 for (i = 0; i < obj->efile.nr_reloc; i++) {
2431 GElf_Shdr *shdr = &obj->efile.reloc[i].shdr;
2432 Elf_Data *data = obj->efile.reloc[i].data;
2433 int idx = shdr->sh_info;
2434 struct bpf_program *prog;
2436 if (shdr->sh_type != SHT_REL) {
2437 pr_warning("internal error at %d\n", __LINE__);
2438 return -LIBBPF_ERRNO__INTERNAL;
2441 prog = bpf_object__find_prog_by_idx(obj, idx);
2443 pr_warning("relocation failed: no section(%d)\n", idx);
2444 return -LIBBPF_ERRNO__RELOC;
2447 err = bpf_program__collect_reloc(prog, shdr, data, obj);
2455 load_program(struct bpf_program *prog, struct bpf_insn *insns, int insns_cnt,
2456 char *license, __u32 kern_version, int *pfd)
2458 struct bpf_load_program_attr load_attr;
2459 char *cp, errmsg[STRERR_BUFSIZE];
2460 int log_buf_size = BPF_LOG_BUF_SIZE;
2464 if (!insns || !insns_cnt)
2467 memset(&load_attr, 0, sizeof(struct bpf_load_program_attr));
2468 load_attr.prog_type = prog->type;
2469 load_attr.expected_attach_type = prog->expected_attach_type;
2470 if (prog->caps->name)
2471 load_attr.name = prog->name;
2472 load_attr.insns = insns;
2473 load_attr.insns_cnt = insns_cnt;
2474 load_attr.license = license;
2475 load_attr.kern_version = kern_version;
2476 load_attr.prog_ifindex = prog->prog_ifindex;
2477 load_attr.prog_btf_fd = prog->btf_fd >= 0 ? prog->btf_fd : 0;
2478 load_attr.func_info = prog->func_info;
2479 load_attr.func_info_rec_size = prog->func_info_rec_size;
2480 load_attr.func_info_cnt = prog->func_info_cnt;
2481 load_attr.line_info = prog->line_info;
2482 load_attr.line_info_rec_size = prog->line_info_rec_size;
2483 load_attr.line_info_cnt = prog->line_info_cnt;
2484 load_attr.log_level = prog->log_level;
2485 load_attr.prog_flags = prog->prog_flags;
2488 log_buf = malloc(log_buf_size);
2490 pr_warning("Alloc log buffer for bpf loader error, continue without log\n");
2492 ret = bpf_load_program_xattr(&load_attr, log_buf, log_buf_size);
2495 if (load_attr.log_level)
2496 pr_debug("verifier log:\n%s", log_buf);
2502 if (errno == ENOSPC) {
2507 ret = -LIBBPF_ERRNO__LOAD;
2508 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
2509 pr_warning("load bpf program failed: %s\n", cp);
2511 if (log_buf && log_buf[0] != '\0') {
2512 ret = -LIBBPF_ERRNO__VERIFY;
2513 pr_warning("-- BEGIN DUMP LOG ---\n");
2514 pr_warning("\n%s\n", log_buf);
2515 pr_warning("-- END LOG --\n");
2516 } else if (load_attr.insns_cnt >= BPF_MAXINSNS) {
2517 pr_warning("Program too large (%zu insns), at most %d insns\n",
2518 load_attr.insns_cnt, BPF_MAXINSNS);
2519 ret = -LIBBPF_ERRNO__PROG2BIG;
2521 /* Wrong program type? */
2522 if (load_attr.prog_type != BPF_PROG_TYPE_KPROBE) {
2525 load_attr.prog_type = BPF_PROG_TYPE_KPROBE;
2526 load_attr.expected_attach_type = 0;
2527 fd = bpf_load_program_xattr(&load_attr, NULL, 0);
2530 ret = -LIBBPF_ERRNO__PROGTYPE;
2536 ret = -LIBBPF_ERRNO__KVER;
2545 bpf_program__load(struct bpf_program *prog,
2546 char *license, __u32 kern_version)
2550 if (prog->instances.nr < 0 || !prog->instances.fds) {
2551 if (prog->preprocessor) {
2552 pr_warning("Internal error: can't load program '%s'\n",
2553 prog->section_name);
2554 return -LIBBPF_ERRNO__INTERNAL;
2557 prog->instances.fds = malloc(sizeof(int));
2558 if (!prog->instances.fds) {
2559 pr_warning("Not enough memory for BPF fds\n");
2562 prog->instances.nr = 1;
2563 prog->instances.fds[0] = -1;
2566 if (!prog->preprocessor) {
2567 if (prog->instances.nr != 1) {
2568 pr_warning("Program '%s' is inconsistent: nr(%d) != 1\n",
2569 prog->section_name, prog->instances.nr);
2571 err = load_program(prog, prog->insns, prog->insns_cnt,
2572 license, kern_version, &fd);
2574 prog->instances.fds[0] = fd;
2578 for (i = 0; i < prog->instances.nr; i++) {
2579 struct bpf_prog_prep_result result;
2580 bpf_program_prep_t preprocessor = prog->preprocessor;
2582 memset(&result, 0, sizeof(result));
2583 err = preprocessor(prog, i, prog->insns,
2584 prog->insns_cnt, &result);
2586 pr_warning("Preprocessing the %dth instance of program '%s' failed\n",
2587 i, prog->section_name);
2591 if (!result.new_insn_ptr || !result.new_insn_cnt) {
2592 pr_debug("Skip loading the %dth instance of program '%s'\n",
2593 i, prog->section_name);
2594 prog->instances.fds[i] = -1;
2600 err = load_program(prog, result.new_insn_ptr,
2601 result.new_insn_cnt,
2602 license, kern_version, &fd);
2605 pr_warning("Loading the %dth instance of program '%s' failed\n",
2606 i, prog->section_name);
2612 prog->instances.fds[i] = fd;
2616 pr_warning("failed to load program '%s'\n",
2617 prog->section_name);
2618 zfree(&prog->insns);
2619 prog->insns_cnt = 0;
2623 static bool bpf_program__is_function_storage(const struct bpf_program *prog,
2624 const struct bpf_object *obj)
2626 return prog->idx == obj->efile.text_shndx && obj->has_pseudo_calls;
2630 bpf_object__load_progs(struct bpf_object *obj, int log_level)
2635 for (i = 0; i < obj->nr_programs; i++) {
2636 if (bpf_program__is_function_storage(&obj->programs[i], obj))
2638 obj->programs[i].log_level |= log_level;
2639 err = bpf_program__load(&obj->programs[i],
2648 static bool bpf_prog_type__needs_kver(enum bpf_prog_type type)
2651 case BPF_PROG_TYPE_SOCKET_FILTER:
2652 case BPF_PROG_TYPE_SCHED_CLS:
2653 case BPF_PROG_TYPE_SCHED_ACT:
2654 case BPF_PROG_TYPE_XDP:
2655 case BPF_PROG_TYPE_CGROUP_SKB:
2656 case BPF_PROG_TYPE_CGROUP_SOCK:
2657 case BPF_PROG_TYPE_LWT_IN:
2658 case BPF_PROG_TYPE_LWT_OUT:
2659 case BPF_PROG_TYPE_LWT_XMIT:
2660 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
2661 case BPF_PROG_TYPE_SOCK_OPS:
2662 case BPF_PROG_TYPE_SK_SKB:
2663 case BPF_PROG_TYPE_CGROUP_DEVICE:
2664 case BPF_PROG_TYPE_SK_MSG:
2665 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
2666 case BPF_PROG_TYPE_LIRC_MODE2:
2667 case BPF_PROG_TYPE_SK_REUSEPORT:
2668 case BPF_PROG_TYPE_FLOW_DISSECTOR:
2669 case BPF_PROG_TYPE_UNSPEC:
2670 case BPF_PROG_TYPE_TRACEPOINT:
2671 case BPF_PROG_TYPE_RAW_TRACEPOINT:
2672 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
2673 case BPF_PROG_TYPE_PERF_EVENT:
2674 case BPF_PROG_TYPE_CGROUP_SYSCTL:
2675 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
2677 case BPF_PROG_TYPE_KPROBE:
2683 static int bpf_object__validate(struct bpf_object *obj, bool needs_kver)
2685 if (needs_kver && obj->kern_version == 0) {
2686 pr_warning("%s doesn't provide kernel version\n",
2688 return -LIBBPF_ERRNO__KVERSION;
2693 static struct bpf_object *
2694 __bpf_object__open(const char *path, void *obj_buf, size_t obj_buf_sz,
2695 bool needs_kver, int flags)
2697 struct bpf_object *obj;
2700 if (elf_version(EV_CURRENT) == EV_NONE) {
2701 pr_warning("failed to init libelf for %s\n", path);
2702 return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
2705 obj = bpf_object__new(path, obj_buf, obj_buf_sz);
2709 CHECK_ERR(bpf_object__elf_init(obj), err, out);
2710 CHECK_ERR(bpf_object__check_endianness(obj), err, out);
2711 CHECK_ERR(bpf_object__probe_caps(obj), err, out);
2712 CHECK_ERR(bpf_object__elf_collect(obj, flags), err, out);
2713 CHECK_ERR(bpf_object__collect_reloc(obj), err, out);
2714 CHECK_ERR(bpf_object__validate(obj, needs_kver), err, out);
2716 bpf_object__elf_finish(obj);
2719 bpf_object__close(obj);
2720 return ERR_PTR(err);
2723 struct bpf_object *__bpf_object__open_xattr(struct bpf_object_open_attr *attr,
2726 /* param validation */
2730 pr_debug("loading %s\n", attr->file);
2732 return __bpf_object__open(attr->file, NULL, 0,
2733 bpf_prog_type__needs_kver(attr->prog_type),
2737 struct bpf_object *bpf_object__open_xattr(struct bpf_object_open_attr *attr)
2739 return __bpf_object__open_xattr(attr, 0);
2742 struct bpf_object *bpf_object__open(const char *path)
2744 struct bpf_object_open_attr attr = {
2746 .prog_type = BPF_PROG_TYPE_UNSPEC,
2749 return bpf_object__open_xattr(&attr);
2752 struct bpf_object *bpf_object__open_buffer(void *obj_buf,
2758 /* param validation */
2759 if (!obj_buf || obj_buf_sz <= 0)
2763 snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
2764 (unsigned long)obj_buf,
2765 (unsigned long)obj_buf_sz);
2768 pr_debug("loading object '%s' from buffer\n", name);
2770 return __bpf_object__open(name, obj_buf, obj_buf_sz, true, true);
2773 int bpf_object__unload(struct bpf_object *obj)
2780 for (i = 0; i < obj->nr_maps; i++)
2781 zclose(obj->maps[i].fd);
2783 for (i = 0; i < obj->nr_programs; i++)
2784 bpf_program__unload(&obj->programs[i]);
2789 int bpf_object__load_xattr(struct bpf_object_load_attr *attr)
2791 struct bpf_object *obj;
2801 pr_warning("object should not be loaded twice\n");
2807 CHECK_ERR(bpf_object__create_maps(obj), err, out);
2808 CHECK_ERR(bpf_object__relocate(obj), err, out);
2809 CHECK_ERR(bpf_object__load_progs(obj, attr->log_level), err, out);
2813 bpf_object__unload(obj);
2814 pr_warning("failed to load object '%s'\n", obj->path);
2818 int bpf_object__load(struct bpf_object *obj)
2820 struct bpf_object_load_attr attr = {
2824 return bpf_object__load_xattr(&attr);
2827 static int check_path(const char *path)
2829 char *cp, errmsg[STRERR_BUFSIZE];
2830 struct statfs st_fs;
2837 dname = strdup(path);
2841 dir = dirname(dname);
2842 if (statfs(dir, &st_fs)) {
2843 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
2844 pr_warning("failed to statfs %s: %s\n", dir, cp);
2849 if (!err && st_fs.f_type != BPF_FS_MAGIC) {
2850 pr_warning("specified path %s is not on BPF FS\n", path);
2857 int bpf_program__pin_instance(struct bpf_program *prog, const char *path,
2860 char *cp, errmsg[STRERR_BUFSIZE];
2863 err = check_path(path);
2868 pr_warning("invalid program pointer\n");
2872 if (instance < 0 || instance >= prog->instances.nr) {
2873 pr_warning("invalid prog instance %d of prog %s (max %d)\n",
2874 instance, prog->section_name, prog->instances.nr);
2878 if (bpf_obj_pin(prog->instances.fds[instance], path)) {
2879 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
2880 pr_warning("failed to pin program: %s\n", cp);
2883 pr_debug("pinned program '%s'\n", path);
2888 int bpf_program__unpin_instance(struct bpf_program *prog, const char *path,
2893 err = check_path(path);
2898 pr_warning("invalid program pointer\n");
2902 if (instance < 0 || instance >= prog->instances.nr) {
2903 pr_warning("invalid prog instance %d of prog %s (max %d)\n",
2904 instance, prog->section_name, prog->instances.nr);
2911 pr_debug("unpinned program '%s'\n", path);
2916 static int make_dir(const char *path)
2918 char *cp, errmsg[STRERR_BUFSIZE];
2921 if (mkdir(path, 0700) && errno != EEXIST)
2925 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
2926 pr_warning("failed to mkdir %s: %s\n", path, cp);
2931 int bpf_program__pin(struct bpf_program *prog, const char *path)
2935 err = check_path(path);
2940 pr_warning("invalid program pointer\n");
2944 if (prog->instances.nr <= 0) {
2945 pr_warning("no instances of prog %s to pin\n",
2946 prog->section_name);
2950 if (prog->instances.nr == 1) {
2951 /* don't create subdirs when pinning single instance */
2952 return bpf_program__pin_instance(prog, path, 0);
2955 err = make_dir(path);
2959 for (i = 0; i < prog->instances.nr; i++) {
2963 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
2967 } else if (len >= PATH_MAX) {
2968 err = -ENAMETOOLONG;
2972 err = bpf_program__pin_instance(prog, buf, i);
2980 for (i = i - 1; i >= 0; i--) {
2984 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
2987 else if (len >= PATH_MAX)
2990 bpf_program__unpin_instance(prog, buf, i);
2998 int bpf_program__unpin(struct bpf_program *prog, const char *path)
3002 err = check_path(path);
3007 pr_warning("invalid program pointer\n");
3011 if (prog->instances.nr <= 0) {
3012 pr_warning("no instances of prog %s to pin\n",
3013 prog->section_name);
3017 if (prog->instances.nr == 1) {
3018 /* don't create subdirs when pinning single instance */
3019 return bpf_program__unpin_instance(prog, path, 0);
3022 for (i = 0; i < prog->instances.nr; i++) {
3026 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
3029 else if (len >= PATH_MAX)
3030 return -ENAMETOOLONG;
3032 err = bpf_program__unpin_instance(prog, buf, i);
3044 int bpf_map__pin(struct bpf_map *map, const char *path)
3046 char *cp, errmsg[STRERR_BUFSIZE];
3049 err = check_path(path);
3054 pr_warning("invalid map pointer\n");
3058 if (bpf_obj_pin(map->fd, path)) {
3059 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
3060 pr_warning("failed to pin map: %s\n", cp);
3064 pr_debug("pinned map '%s'\n", path);
3069 int bpf_map__unpin(struct bpf_map *map, const char *path)
3073 err = check_path(path);
3078 pr_warning("invalid map pointer\n");
3085 pr_debug("unpinned map '%s'\n", path);
3090 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
3092 struct bpf_map *map;
3099 pr_warning("object not yet loaded; load it first\n");
3103 err = make_dir(path);
3107 bpf_object__for_each_map(map, obj) {
3111 len = snprintf(buf, PATH_MAX, "%s/%s", path,
3112 bpf_map__name(map));
3115 goto err_unpin_maps;
3116 } else if (len >= PATH_MAX) {
3117 err = -ENAMETOOLONG;
3118 goto err_unpin_maps;
3121 err = bpf_map__pin(map, buf);
3123 goto err_unpin_maps;
3129 while ((map = bpf_map__prev(map, obj))) {
3133 len = snprintf(buf, PATH_MAX, "%s/%s", path,
3134 bpf_map__name(map));
3137 else if (len >= PATH_MAX)
3140 bpf_map__unpin(map, buf);
3146 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
3148 struct bpf_map *map;
3154 bpf_object__for_each_map(map, obj) {
3158 len = snprintf(buf, PATH_MAX, "%s/%s", path,
3159 bpf_map__name(map));
3162 else if (len >= PATH_MAX)
3163 return -ENAMETOOLONG;
3165 err = bpf_map__unpin(map, buf);
3173 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
3175 struct bpf_program *prog;
3182 pr_warning("object not yet loaded; load it first\n");
3186 err = make_dir(path);
3190 bpf_object__for_each_program(prog, obj) {
3194 len = snprintf(buf, PATH_MAX, "%s/%s", path,
3198 goto err_unpin_programs;
3199 } else if (len >= PATH_MAX) {
3200 err = -ENAMETOOLONG;
3201 goto err_unpin_programs;
3204 err = bpf_program__pin(prog, buf);
3206 goto err_unpin_programs;
3212 while ((prog = bpf_program__prev(prog, obj))) {
3216 len = snprintf(buf, PATH_MAX, "%s/%s", path,
3220 else if (len >= PATH_MAX)
3223 bpf_program__unpin(prog, buf);
3229 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
3231 struct bpf_program *prog;
3237 bpf_object__for_each_program(prog, obj) {
3241 len = snprintf(buf, PATH_MAX, "%s/%s", path,
3245 else if (len >= PATH_MAX)
3246 return -ENAMETOOLONG;
3248 err = bpf_program__unpin(prog, buf);
3256 int bpf_object__pin(struct bpf_object *obj, const char *path)
3260 err = bpf_object__pin_maps(obj, path);
3264 err = bpf_object__pin_programs(obj, path);
3266 bpf_object__unpin_maps(obj, path);
3273 void bpf_object__close(struct bpf_object *obj)
3280 if (obj->clear_priv)
3281 obj->clear_priv(obj, obj->priv);
3283 bpf_object__elf_finish(obj);
3284 bpf_object__unload(obj);
3285 btf__free(obj->btf);
3286 btf_ext__free(obj->btf_ext);
3288 for (i = 0; i < obj->nr_maps; i++) {
3289 zfree(&obj->maps[i].name);
3290 if (obj->maps[i].clear_priv)
3291 obj->maps[i].clear_priv(&obj->maps[i],
3293 obj->maps[i].priv = NULL;
3294 obj->maps[i].clear_priv = NULL;
3297 zfree(&obj->sections.rodata);
3298 zfree(&obj->sections.data);
3302 if (obj->programs && obj->nr_programs) {
3303 for (i = 0; i < obj->nr_programs; i++)
3304 bpf_program__exit(&obj->programs[i]);
3306 zfree(&obj->programs);
3308 list_del(&obj->list);
3313 bpf_object__next(struct bpf_object *prev)
3315 struct bpf_object *next;
3318 next = list_first_entry(&bpf_objects_list,
3322 next = list_next_entry(prev, list);
3324 /* Empty list is noticed here so don't need checking on entry. */
3325 if (&next->list == &bpf_objects_list)
3331 const char *bpf_object__name(const struct bpf_object *obj)
3333 return obj ? obj->path : ERR_PTR(-EINVAL);
3336 unsigned int bpf_object__kversion(const struct bpf_object *obj)
3338 return obj ? obj->kern_version : 0;
3341 struct btf *bpf_object__btf(const struct bpf_object *obj)
3343 return obj ? obj->btf : NULL;
3346 int bpf_object__btf_fd(const struct bpf_object *obj)
3348 return obj->btf ? btf__fd(obj->btf) : -1;
3351 int bpf_object__set_priv(struct bpf_object *obj, void *priv,
3352 bpf_object_clear_priv_t clear_priv)
3354 if (obj->priv && obj->clear_priv)
3355 obj->clear_priv(obj, obj->priv);
3358 obj->clear_priv = clear_priv;
3362 void *bpf_object__priv(const struct bpf_object *obj)
3364 return obj ? obj->priv : ERR_PTR(-EINVAL);
3367 static struct bpf_program *
3368 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
3371 size_t nr_programs = obj->nr_programs;
3378 /* Iter from the beginning */
3379 return forward ? &obj->programs[0] :
3380 &obj->programs[nr_programs - 1];
3382 if (p->obj != obj) {
3383 pr_warning("error: program handler doesn't match object\n");
3387 idx = (p - obj->programs) + (forward ? 1 : -1);
3388 if (idx >= obj->nr_programs || idx < 0)
3390 return &obj->programs[idx];
3393 struct bpf_program *
3394 bpf_program__next(struct bpf_program *prev, const struct bpf_object *obj)
3396 struct bpf_program *prog = prev;
3399 prog = __bpf_program__iter(prog, obj, true);
3400 } while (prog && bpf_program__is_function_storage(prog, obj));
3405 struct bpf_program *
3406 bpf_program__prev(struct bpf_program *next, const struct bpf_object *obj)
3408 struct bpf_program *prog = next;
3411 prog = __bpf_program__iter(prog, obj, false);
3412 } while (prog && bpf_program__is_function_storage(prog, obj));
3417 int bpf_program__set_priv(struct bpf_program *prog, void *priv,
3418 bpf_program_clear_priv_t clear_priv)
3420 if (prog->priv && prog->clear_priv)
3421 prog->clear_priv(prog, prog->priv);
3424 prog->clear_priv = clear_priv;
3428 void *bpf_program__priv(const struct bpf_program *prog)
3430 return prog ? prog->priv : ERR_PTR(-EINVAL);
3433 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
3435 prog->prog_ifindex = ifindex;
3438 const char *bpf_program__title(const struct bpf_program *prog, bool needs_copy)
3442 title = prog->section_name;
3444 title = strdup(title);
3446 pr_warning("failed to strdup program title\n");
3447 return ERR_PTR(-ENOMEM);
3454 int bpf_program__fd(const struct bpf_program *prog)
3456 return bpf_program__nth_fd(prog, 0);
3459 int bpf_program__set_prep(struct bpf_program *prog, int nr_instances,
3460 bpf_program_prep_t prep)
3464 if (nr_instances <= 0 || !prep)
3467 if (prog->instances.nr > 0 || prog->instances.fds) {
3468 pr_warning("Can't set pre-processor after loading\n");
3472 instances_fds = malloc(sizeof(int) * nr_instances);
3473 if (!instances_fds) {
3474 pr_warning("alloc memory failed for fds\n");
3478 /* fill all fd with -1 */
3479 memset(instances_fds, -1, sizeof(int) * nr_instances);
3481 prog->instances.nr = nr_instances;
3482 prog->instances.fds = instances_fds;
3483 prog->preprocessor = prep;
3487 int bpf_program__nth_fd(const struct bpf_program *prog, int n)
3494 if (n >= prog->instances.nr || n < 0) {
3495 pr_warning("Can't get the %dth fd from program %s: only %d instances\n",
3496 n, prog->section_name, prog->instances.nr);
3500 fd = prog->instances.fds[n];
3502 pr_warning("%dth instance of program '%s' is invalid\n",
3503 n, prog->section_name);
3510 void bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
3515 static bool bpf_program__is_type(const struct bpf_program *prog,
3516 enum bpf_prog_type type)
3518 return prog ? (prog->type == type) : false;
3521 #define BPF_PROG_TYPE_FNS(NAME, TYPE) \
3522 int bpf_program__set_##NAME(struct bpf_program *prog) \
3526 bpf_program__set_type(prog, TYPE); \
3530 bool bpf_program__is_##NAME(const struct bpf_program *prog) \
3532 return bpf_program__is_type(prog, TYPE); \
3535 BPF_PROG_TYPE_FNS(socket_filter, BPF_PROG_TYPE_SOCKET_FILTER);
3536 BPF_PROG_TYPE_FNS(kprobe, BPF_PROG_TYPE_KPROBE);
3537 BPF_PROG_TYPE_FNS(sched_cls, BPF_PROG_TYPE_SCHED_CLS);
3538 BPF_PROG_TYPE_FNS(sched_act, BPF_PROG_TYPE_SCHED_ACT);
3539 BPF_PROG_TYPE_FNS(tracepoint, BPF_PROG_TYPE_TRACEPOINT);
3540 BPF_PROG_TYPE_FNS(raw_tracepoint, BPF_PROG_TYPE_RAW_TRACEPOINT);
3541 BPF_PROG_TYPE_FNS(xdp, BPF_PROG_TYPE_XDP);
3542 BPF_PROG_TYPE_FNS(perf_event, BPF_PROG_TYPE_PERF_EVENT);
3544 void bpf_program__set_expected_attach_type(struct bpf_program *prog,
3545 enum bpf_attach_type type)
3547 prog->expected_attach_type = type;
3550 #define BPF_PROG_SEC_IMPL(string, ptype, eatype, is_attachable, atype) \
3551 { string, sizeof(string) - 1, ptype, eatype, is_attachable, atype }
3553 /* Programs that can NOT be attached. */
3554 #define BPF_PROG_SEC(string, ptype) BPF_PROG_SEC_IMPL(string, ptype, 0, 0, 0)
3556 /* Programs that can be attached. */
3557 #define BPF_APROG_SEC(string, ptype, atype) \
3558 BPF_PROG_SEC_IMPL(string, ptype, 0, 1, atype)
3560 /* Programs that must specify expected attach type at load time. */
3561 #define BPF_EAPROG_SEC(string, ptype, eatype) \
3562 BPF_PROG_SEC_IMPL(string, ptype, eatype, 1, eatype)
3564 /* Programs that can be attached but attach type can't be identified by section
3565 * name. Kept for backward compatibility.
3567 #define BPF_APROG_COMPAT(string, ptype) BPF_PROG_SEC(string, ptype)
3569 static const struct {
3572 enum bpf_prog_type prog_type;
3573 enum bpf_attach_type expected_attach_type;
3575 enum bpf_attach_type attach_type;
3576 } section_names[] = {
3577 BPF_PROG_SEC("socket", BPF_PROG_TYPE_SOCKET_FILTER),
3578 BPF_PROG_SEC("kprobe/", BPF_PROG_TYPE_KPROBE),
3579 BPF_PROG_SEC("kretprobe/", BPF_PROG_TYPE_KPROBE),
3580 BPF_PROG_SEC("classifier", BPF_PROG_TYPE_SCHED_CLS),
3581 BPF_PROG_SEC("action", BPF_PROG_TYPE_SCHED_ACT),
3582 BPF_PROG_SEC("tracepoint/", BPF_PROG_TYPE_TRACEPOINT),
3583 BPF_PROG_SEC("raw_tracepoint/", BPF_PROG_TYPE_RAW_TRACEPOINT),
3584 BPF_PROG_SEC("xdp", BPF_PROG_TYPE_XDP),
3585 BPF_PROG_SEC("perf_event", BPF_PROG_TYPE_PERF_EVENT),
3586 BPF_PROG_SEC("lwt_in", BPF_PROG_TYPE_LWT_IN),
3587 BPF_PROG_SEC("lwt_out", BPF_PROG_TYPE_LWT_OUT),
3588 BPF_PROG_SEC("lwt_xmit", BPF_PROG_TYPE_LWT_XMIT),
3589 BPF_PROG_SEC("lwt_seg6local", BPF_PROG_TYPE_LWT_SEG6LOCAL),
3590 BPF_APROG_SEC("cgroup_skb/ingress", BPF_PROG_TYPE_CGROUP_SKB,
3591 BPF_CGROUP_INET_INGRESS),
3592 BPF_APROG_SEC("cgroup_skb/egress", BPF_PROG_TYPE_CGROUP_SKB,
3593 BPF_CGROUP_INET_EGRESS),
3594 BPF_APROG_COMPAT("cgroup/skb", BPF_PROG_TYPE_CGROUP_SKB),
3595 BPF_APROG_SEC("cgroup/sock", BPF_PROG_TYPE_CGROUP_SOCK,
3596 BPF_CGROUP_INET_SOCK_CREATE),
3597 BPF_EAPROG_SEC("cgroup/post_bind4", BPF_PROG_TYPE_CGROUP_SOCK,
3598 BPF_CGROUP_INET4_POST_BIND),
3599 BPF_EAPROG_SEC("cgroup/post_bind6", BPF_PROG_TYPE_CGROUP_SOCK,
3600 BPF_CGROUP_INET6_POST_BIND),
3601 BPF_APROG_SEC("cgroup/dev", BPF_PROG_TYPE_CGROUP_DEVICE,
3603 BPF_APROG_SEC("sockops", BPF_PROG_TYPE_SOCK_OPS,
3604 BPF_CGROUP_SOCK_OPS),
3605 BPF_APROG_SEC("sk_skb/stream_parser", BPF_PROG_TYPE_SK_SKB,
3606 BPF_SK_SKB_STREAM_PARSER),
3607 BPF_APROG_SEC("sk_skb/stream_verdict", BPF_PROG_TYPE_SK_SKB,
3608 BPF_SK_SKB_STREAM_VERDICT),
3609 BPF_APROG_COMPAT("sk_skb", BPF_PROG_TYPE_SK_SKB),
3610 BPF_APROG_SEC("sk_msg", BPF_PROG_TYPE_SK_MSG,
3611 BPF_SK_MSG_VERDICT),
3612 BPF_APROG_SEC("lirc_mode2", BPF_PROG_TYPE_LIRC_MODE2,
3614 BPF_APROG_SEC("flow_dissector", BPF_PROG_TYPE_FLOW_DISSECTOR,
3615 BPF_FLOW_DISSECTOR),
3616 BPF_EAPROG_SEC("cgroup/bind4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
3617 BPF_CGROUP_INET4_BIND),
3618 BPF_EAPROG_SEC("cgroup/bind6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
3619 BPF_CGROUP_INET6_BIND),
3620 BPF_EAPROG_SEC("cgroup/connect4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
3621 BPF_CGROUP_INET4_CONNECT),
3622 BPF_EAPROG_SEC("cgroup/connect6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
3623 BPF_CGROUP_INET6_CONNECT),
3624 BPF_EAPROG_SEC("cgroup/sendmsg4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
3625 BPF_CGROUP_UDP4_SENDMSG),
3626 BPF_EAPROG_SEC("cgroup/sendmsg6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
3627 BPF_CGROUP_UDP6_SENDMSG),
3628 BPF_EAPROG_SEC("cgroup/recvmsg4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
3629 BPF_CGROUP_UDP4_RECVMSG),
3630 BPF_EAPROG_SEC("cgroup/recvmsg6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
3631 BPF_CGROUP_UDP6_RECVMSG),
3632 BPF_EAPROG_SEC("cgroup/sysctl", BPF_PROG_TYPE_CGROUP_SYSCTL,
3634 BPF_EAPROG_SEC("cgroup/getsockopt", BPF_PROG_TYPE_CGROUP_SOCKOPT,
3635 BPF_CGROUP_GETSOCKOPT),
3636 BPF_EAPROG_SEC("cgroup/setsockopt", BPF_PROG_TYPE_CGROUP_SOCKOPT,
3637 BPF_CGROUP_SETSOCKOPT),
3640 #undef BPF_PROG_SEC_IMPL
3642 #undef BPF_APROG_SEC
3643 #undef BPF_EAPROG_SEC
3644 #undef BPF_APROG_COMPAT
3646 #define MAX_TYPE_NAME_SIZE 32
3648 static char *libbpf_get_type_names(bool attach_type)
3650 int i, len = ARRAY_SIZE(section_names) * MAX_TYPE_NAME_SIZE;
3658 /* Forge string buf with all available names */
3659 for (i = 0; i < ARRAY_SIZE(section_names); i++) {
3660 if (attach_type && !section_names[i].is_attachable)
3663 if (strlen(buf) + strlen(section_names[i].sec) + 2 > len) {
3668 strcat(buf, section_names[i].sec);
3674 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
3675 enum bpf_attach_type *expected_attach_type)
3683 for (i = 0; i < ARRAY_SIZE(section_names); i++) {
3684 if (strncmp(name, section_names[i].sec, section_names[i].len))
3686 *prog_type = section_names[i].prog_type;
3687 *expected_attach_type = section_names[i].expected_attach_type;
3690 pr_warning("failed to guess program type based on ELF section name '%s'\n", name);
3691 type_names = libbpf_get_type_names(false);
3692 if (type_names != NULL) {
3693 pr_info("supported section(type) names are:%s\n", type_names);
3700 int libbpf_attach_type_by_name(const char *name,
3701 enum bpf_attach_type *attach_type)
3709 for (i = 0; i < ARRAY_SIZE(section_names); i++) {
3710 if (strncmp(name, section_names[i].sec, section_names[i].len))
3712 if (!section_names[i].is_attachable)
3714 *attach_type = section_names[i].attach_type;
3717 pr_warning("failed to guess attach type based on ELF section name '%s'\n", name);
3718 type_names = libbpf_get_type_names(true);
3719 if (type_names != NULL) {
3720 pr_info("attachable section(type) names are:%s\n", type_names);
3728 bpf_program__identify_section(struct bpf_program *prog,
3729 enum bpf_prog_type *prog_type,
3730 enum bpf_attach_type *expected_attach_type)
3732 return libbpf_prog_type_by_name(prog->section_name, prog_type,
3733 expected_attach_type);
3736 int bpf_map__fd(const struct bpf_map *map)
3738 return map ? map->fd : -EINVAL;
3741 const struct bpf_map_def *bpf_map__def(const struct bpf_map *map)
3743 return map ? &map->def : ERR_PTR(-EINVAL);
3746 const char *bpf_map__name(const struct bpf_map *map)
3748 return map ? map->name : NULL;
3751 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
3753 return map ? map->btf_key_type_id : 0;
3756 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
3758 return map ? map->btf_value_type_id : 0;
3761 int bpf_map__set_priv(struct bpf_map *map, void *priv,
3762 bpf_map_clear_priv_t clear_priv)
3768 if (map->clear_priv)
3769 map->clear_priv(map, map->priv);
3773 map->clear_priv = clear_priv;
3777 void *bpf_map__priv(const struct bpf_map *map)
3779 return map ? map->priv : ERR_PTR(-EINVAL);
3782 bool bpf_map__is_offload_neutral(const struct bpf_map *map)
3784 return map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY;
3787 bool bpf_map__is_internal(const struct bpf_map *map)
3789 return map->libbpf_type != LIBBPF_MAP_UNSPEC;
3792 void bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
3794 map->map_ifindex = ifindex;
3797 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
3799 if (!bpf_map_type__is_map_in_map(map->def.type)) {
3800 pr_warning("error: unsupported map type\n");
3803 if (map->inner_map_fd != -1) {
3804 pr_warning("error: inner_map_fd already specified\n");
3807 map->inner_map_fd = fd;
3811 static struct bpf_map *
3812 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
3815 struct bpf_map *s, *e;
3817 if (!obj || !obj->maps)
3821 e = obj->maps + obj->nr_maps;
3823 if ((m < s) || (m >= e)) {
3824 pr_warning("error in %s: map handler doesn't belong to object\n",
3829 idx = (m - obj->maps) + i;
3830 if (idx >= obj->nr_maps || idx < 0)
3832 return &obj->maps[idx];
3836 bpf_map__next(const struct bpf_map *prev, const struct bpf_object *obj)
3841 return __bpf_map__iter(prev, obj, 1);
3845 bpf_map__prev(const struct bpf_map *next, const struct bpf_object *obj)
3850 return obj->maps + obj->nr_maps - 1;
3853 return __bpf_map__iter(next, obj, -1);
3857 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
3859 struct bpf_map *pos;
3861 bpf_object__for_each_map(pos, obj) {
3862 if (pos->name && !strcmp(pos->name, name))
3869 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
3871 return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
3875 bpf_object__find_map_by_offset(struct bpf_object *obj, size_t offset)
3877 return ERR_PTR(-ENOTSUP);
3880 long libbpf_get_error(const void *ptr)
3882 return PTR_ERR_OR_ZERO(ptr);
3885 int bpf_prog_load(const char *file, enum bpf_prog_type type,
3886 struct bpf_object **pobj, int *prog_fd)
3888 struct bpf_prog_load_attr attr;
3890 memset(&attr, 0, sizeof(struct bpf_prog_load_attr));
3892 attr.prog_type = type;
3893 attr.expected_attach_type = 0;
3895 return bpf_prog_load_xattr(&attr, pobj, prog_fd);
3898 int bpf_prog_load_xattr(const struct bpf_prog_load_attr *attr,
3899 struct bpf_object **pobj, int *prog_fd)
3901 struct bpf_object_open_attr open_attr = {};
3902 struct bpf_program *prog, *first_prog = NULL;
3903 enum bpf_attach_type expected_attach_type;
3904 enum bpf_prog_type prog_type;
3905 struct bpf_object *obj;
3906 struct bpf_map *map;
3914 open_attr.file = attr->file;
3915 open_attr.prog_type = attr->prog_type;
3917 obj = bpf_object__open_xattr(&open_attr);
3918 if (IS_ERR_OR_NULL(obj))
3921 bpf_object__for_each_program(prog, obj) {
3923 * If type is not specified, try to guess it based on
3926 prog_type = attr->prog_type;
3927 prog->prog_ifindex = attr->ifindex;
3928 expected_attach_type = attr->expected_attach_type;
3929 if (prog_type == BPF_PROG_TYPE_UNSPEC) {
3930 err = bpf_program__identify_section(prog, &prog_type,
3931 &expected_attach_type);
3933 bpf_object__close(obj);
3938 bpf_program__set_type(prog, prog_type);
3939 bpf_program__set_expected_attach_type(prog,
3940 expected_attach_type);
3942 prog->log_level = attr->log_level;
3943 prog->prog_flags = attr->prog_flags;
3948 bpf_object__for_each_map(map, obj) {
3949 if (!bpf_map__is_offload_neutral(map))
3950 map->map_ifindex = attr->ifindex;
3954 pr_warning("object file doesn't contain bpf program\n");
3955 bpf_object__close(obj);
3959 err = bpf_object__load(obj);
3961 bpf_object__close(obj);
3966 *prog_fd = bpf_program__fd(first_prog);
3971 int (*destroy)(struct bpf_link *link);
3974 int bpf_link__destroy(struct bpf_link *link)
3981 err = link->destroy(link);
3987 struct bpf_link_fd {
3988 struct bpf_link link; /* has to be at the top of struct */
3989 int fd; /* hook FD */
3992 static int bpf_link__destroy_perf_event(struct bpf_link *link)
3994 struct bpf_link_fd *l = (void *)link;
3997 err = ioctl(l->fd, PERF_EVENT_IOC_DISABLE, 0);
4005 struct bpf_link *bpf_program__attach_perf_event(struct bpf_program *prog,
4008 char errmsg[STRERR_BUFSIZE];
4009 struct bpf_link_fd *link;
4013 pr_warning("program '%s': invalid perf event FD %d\n",
4014 bpf_program__title(prog, false), pfd);
4015 return ERR_PTR(-EINVAL);
4017 prog_fd = bpf_program__fd(prog);
4019 pr_warning("program '%s': can't attach BPF program w/o FD (did you load it?)\n",
4020 bpf_program__title(prog, false));
4021 return ERR_PTR(-EINVAL);
4024 link = malloc(sizeof(*link));
4026 return ERR_PTR(-ENOMEM);
4027 link->link.destroy = &bpf_link__destroy_perf_event;
4030 if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
4033 pr_warning("program '%s': failed to attach to pfd %d: %s\n",
4034 bpf_program__title(prog, false), pfd,
4035 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
4036 return ERR_PTR(err);
4038 if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
4041 pr_warning("program '%s': failed to enable pfd %d: %s\n",
4042 bpf_program__title(prog, false), pfd,
4043 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
4044 return ERR_PTR(err);
4046 return (struct bpf_link *)link;
4050 * this function is expected to parse integer in the range of [0, 2^31-1] from
4051 * given file using scanf format string fmt. If actual parsed value is
4052 * negative, the result might be indistinguishable from error
4054 static int parse_uint_from_file(const char *file, const char *fmt)
4056 char buf[STRERR_BUFSIZE];
4060 f = fopen(file, "r");
4063 pr_debug("failed to open '%s': %s\n", file,
4064 libbpf_strerror_r(err, buf, sizeof(buf)));
4067 err = fscanf(f, fmt, &ret);
4069 err = err == EOF ? -EIO : -errno;
4070 pr_debug("failed to parse '%s': %s\n", file,
4071 libbpf_strerror_r(err, buf, sizeof(buf)));
4079 static int determine_kprobe_perf_type(void)
4081 const char *file = "/sys/bus/event_source/devices/kprobe/type";
4083 return parse_uint_from_file(file, "%d\n");
4086 static int determine_uprobe_perf_type(void)
4088 const char *file = "/sys/bus/event_source/devices/uprobe/type";
4090 return parse_uint_from_file(file, "%d\n");
4093 static int determine_kprobe_retprobe_bit(void)
4095 const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
4097 return parse_uint_from_file(file, "config:%d\n");
4100 static int determine_uprobe_retprobe_bit(void)
4102 const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
4104 return parse_uint_from_file(file, "config:%d\n");
4107 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
4108 uint64_t offset, int pid)
4110 struct perf_event_attr attr = {};
4111 char errmsg[STRERR_BUFSIZE];
4114 type = uprobe ? determine_uprobe_perf_type()
4115 : determine_kprobe_perf_type();
4117 pr_warning("failed to determine %s perf type: %s\n",
4118 uprobe ? "uprobe" : "kprobe",
4119 libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
4123 int bit = uprobe ? determine_uprobe_retprobe_bit()
4124 : determine_kprobe_retprobe_bit();
4127 pr_warning("failed to determine %s retprobe bit: %s\n",
4128 uprobe ? "uprobe" : "kprobe",
4129 libbpf_strerror_r(bit, errmsg,
4133 attr.config |= 1 << bit;
4135 attr.size = sizeof(attr);
4137 attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
4138 attr.config2 = offset; /* kprobe_addr or probe_offset */
4140 /* pid filter is meaningful only for uprobes */
4141 pfd = syscall(__NR_perf_event_open, &attr,
4142 pid < 0 ? -1 : pid /* pid */,
4143 pid == -1 ? 0 : -1 /* cpu */,
4144 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
4147 pr_warning("%s perf_event_open() failed: %s\n",
4148 uprobe ? "uprobe" : "kprobe",
4149 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
4155 struct bpf_link *bpf_program__attach_kprobe(struct bpf_program *prog,
4157 const char *func_name)
4159 char errmsg[STRERR_BUFSIZE];
4160 struct bpf_link *link;
4163 pfd = perf_event_open_probe(false /* uprobe */, retprobe, func_name,
4164 0 /* offset */, -1 /* pid */);
4166 pr_warning("program '%s': failed to create %s '%s' perf event: %s\n",
4167 bpf_program__title(prog, false),
4168 retprobe ? "kretprobe" : "kprobe", func_name,
4169 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
4170 return ERR_PTR(pfd);
4172 link = bpf_program__attach_perf_event(prog, pfd);
4175 err = PTR_ERR(link);
4176 pr_warning("program '%s': failed to attach to %s '%s': %s\n",
4177 bpf_program__title(prog, false),
4178 retprobe ? "kretprobe" : "kprobe", func_name,
4179 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
4185 struct bpf_link *bpf_program__attach_uprobe(struct bpf_program *prog,
4186 bool retprobe, pid_t pid,
4187 const char *binary_path,
4190 char errmsg[STRERR_BUFSIZE];
4191 struct bpf_link *link;
4194 pfd = perf_event_open_probe(true /* uprobe */, retprobe,
4195 binary_path, func_offset, pid);
4197 pr_warning("program '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
4198 bpf_program__title(prog, false),
4199 retprobe ? "uretprobe" : "uprobe",
4200 binary_path, func_offset,
4201 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
4202 return ERR_PTR(pfd);
4204 link = bpf_program__attach_perf_event(prog, pfd);
4207 err = PTR_ERR(link);
4208 pr_warning("program '%s': failed to attach to %s '%s:0x%zx': %s\n",
4209 bpf_program__title(prog, false),
4210 retprobe ? "uretprobe" : "uprobe",
4211 binary_path, func_offset,
4212 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
4218 static int determine_tracepoint_id(const char *tp_category,
4219 const char *tp_name)
4221 char file[PATH_MAX];
4224 ret = snprintf(file, sizeof(file),
4225 "/sys/kernel/debug/tracing/events/%s/%s/id",
4226 tp_category, tp_name);
4229 if (ret >= sizeof(file)) {
4230 pr_debug("tracepoint %s/%s path is too long\n",
4231 tp_category, tp_name);
4234 return parse_uint_from_file(file, "%d\n");
4237 static int perf_event_open_tracepoint(const char *tp_category,
4238 const char *tp_name)
4240 struct perf_event_attr attr = {};
4241 char errmsg[STRERR_BUFSIZE];
4242 int tp_id, pfd, err;
4244 tp_id = determine_tracepoint_id(tp_category, tp_name);
4246 pr_warning("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
4247 tp_category, tp_name,
4248 libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
4252 attr.type = PERF_TYPE_TRACEPOINT;
4253 attr.size = sizeof(attr);
4254 attr.config = tp_id;
4256 pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
4257 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
4260 pr_warning("tracepoint '%s/%s' perf_event_open() failed: %s\n",
4261 tp_category, tp_name,
4262 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
4268 struct bpf_link *bpf_program__attach_tracepoint(struct bpf_program *prog,
4269 const char *tp_category,
4270 const char *tp_name)
4272 char errmsg[STRERR_BUFSIZE];
4273 struct bpf_link *link;
4276 pfd = perf_event_open_tracepoint(tp_category, tp_name);
4278 pr_warning("program '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
4279 bpf_program__title(prog, false),
4280 tp_category, tp_name,
4281 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
4282 return ERR_PTR(pfd);
4284 link = bpf_program__attach_perf_event(prog, pfd);
4287 err = PTR_ERR(link);
4288 pr_warning("program '%s': failed to attach to tracepoint '%s/%s': %s\n",
4289 bpf_program__title(prog, false),
4290 tp_category, tp_name,
4291 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
4297 static int bpf_link__destroy_fd(struct bpf_link *link)
4299 struct bpf_link_fd *l = (void *)link;
4301 return close(l->fd);
4304 struct bpf_link *bpf_program__attach_raw_tracepoint(struct bpf_program *prog,
4305 const char *tp_name)
4307 char errmsg[STRERR_BUFSIZE];
4308 struct bpf_link_fd *link;
4311 prog_fd = bpf_program__fd(prog);
4313 pr_warning("program '%s': can't attach before loaded\n",
4314 bpf_program__title(prog, false));
4315 return ERR_PTR(-EINVAL);
4318 link = malloc(sizeof(*link));
4320 return ERR_PTR(-ENOMEM);
4321 link->link.destroy = &bpf_link__destroy_fd;
4323 pfd = bpf_raw_tracepoint_open(tp_name, prog_fd);
4327 pr_warning("program '%s': failed to attach to raw tracepoint '%s': %s\n",
4328 bpf_program__title(prog, false), tp_name,
4329 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
4330 return ERR_PTR(pfd);
4333 return (struct bpf_link *)link;
4336 enum bpf_perf_event_ret
4337 bpf_perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
4338 void **copy_mem, size_t *copy_size,
4339 bpf_perf_event_print_t fn, void *private_data)
4341 struct perf_event_mmap_page *header = mmap_mem;
4342 __u64 data_head = ring_buffer_read_head(header);
4343 __u64 data_tail = header->data_tail;
4344 void *base = ((__u8 *)header) + page_size;
4345 int ret = LIBBPF_PERF_EVENT_CONT;
4346 struct perf_event_header *ehdr;
4349 while (data_head != data_tail) {
4350 ehdr = base + (data_tail & (mmap_size - 1));
4351 ehdr_size = ehdr->size;
4353 if (((void *)ehdr) + ehdr_size > base + mmap_size) {
4354 void *copy_start = ehdr;
4355 size_t len_first = base + mmap_size - copy_start;
4356 size_t len_secnd = ehdr_size - len_first;
4358 if (*copy_size < ehdr_size) {
4360 *copy_mem = malloc(ehdr_size);
4363 ret = LIBBPF_PERF_EVENT_ERROR;
4366 *copy_size = ehdr_size;
4369 memcpy(*copy_mem, copy_start, len_first);
4370 memcpy(*copy_mem + len_first, base, len_secnd);
4374 ret = fn(ehdr, private_data);
4375 data_tail += ehdr_size;
4376 if (ret != LIBBPF_PERF_EVENT_CONT)
4380 ring_buffer_write_tail(header, data_tail);
4386 struct perf_buffer_params {
4387 struct perf_event_attr *attr;
4388 /* if event_cb is specified, it takes precendence */
4389 perf_buffer_event_fn event_cb;
4390 /* sample_cb and lost_cb are higher-level common-case callbacks */
4391 perf_buffer_sample_fn sample_cb;
4392 perf_buffer_lost_fn lost_cb;
4399 struct perf_cpu_buf {
4400 struct perf_buffer *pb;
4401 void *base; /* mmap()'ed memory */
4402 void *buf; /* for reconstructing segmented data */
4409 struct perf_buffer {
4410 perf_buffer_event_fn event_cb;
4411 perf_buffer_sample_fn sample_cb;
4412 perf_buffer_lost_fn lost_cb;
4413 void *ctx; /* passed into callbacks */
4417 struct perf_cpu_buf **cpu_bufs;
4418 struct epoll_event *events;
4420 int epoll_fd; /* perf event FD */
4421 int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
4424 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
4425 struct perf_cpu_buf *cpu_buf)
4429 if (cpu_buf->base &&
4430 munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
4431 pr_warning("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
4432 if (cpu_buf->fd >= 0) {
4433 ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
4440 void perf_buffer__free(struct perf_buffer *pb)
4447 for (i = 0; i < pb->cpu_cnt && pb->cpu_bufs[i]; i++) {
4448 struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
4450 bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
4451 perf_buffer__free_cpu_buf(pb, cpu_buf);
4455 if (pb->epoll_fd >= 0)
4456 close(pb->epoll_fd);
4461 static struct perf_cpu_buf *
4462 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
4463 int cpu, int map_key)
4465 struct perf_cpu_buf *cpu_buf;
4466 char msg[STRERR_BUFSIZE];
4469 cpu_buf = calloc(1, sizeof(*cpu_buf));
4471 return ERR_PTR(-ENOMEM);
4475 cpu_buf->map_key = map_key;
4477 cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
4478 -1, PERF_FLAG_FD_CLOEXEC);
4479 if (cpu_buf->fd < 0) {
4481 pr_warning("failed to open perf buffer event on cpu #%d: %s\n",
4482 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
4486 cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
4487 PROT_READ | PROT_WRITE, MAP_SHARED,
4489 if (cpu_buf->base == MAP_FAILED) {
4490 cpu_buf->base = NULL;
4492 pr_warning("failed to mmap perf buffer on cpu #%d: %s\n",
4493 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
4497 if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
4499 pr_warning("failed to enable perf buffer event on cpu #%d: %s\n",
4500 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
4507 perf_buffer__free_cpu_buf(pb, cpu_buf);
4508 return (struct perf_cpu_buf *)ERR_PTR(err);
4511 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
4512 struct perf_buffer_params *p);
4514 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
4515 const struct perf_buffer_opts *opts)
4517 struct perf_buffer_params p = {};
4518 struct perf_event_attr attr = {
4519 .config = PERF_COUNT_SW_BPF_OUTPUT,
4520 .type = PERF_TYPE_SOFTWARE,
4521 .sample_type = PERF_SAMPLE_RAW,
4527 p.sample_cb = opts ? opts->sample_cb : NULL;
4528 p.lost_cb = opts ? opts->lost_cb : NULL;
4529 p.ctx = opts ? opts->ctx : NULL;
4531 return __perf_buffer__new(map_fd, page_cnt, &p);
4534 struct perf_buffer *
4535 perf_buffer__new_raw(int map_fd, size_t page_cnt,
4536 const struct perf_buffer_raw_opts *opts)
4538 struct perf_buffer_params p = {};
4540 p.attr = opts->attr;
4541 p.event_cb = opts->event_cb;
4543 p.cpu_cnt = opts->cpu_cnt;
4544 p.cpus = opts->cpus;
4545 p.map_keys = opts->map_keys;
4547 return __perf_buffer__new(map_fd, page_cnt, &p);
4550 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
4551 struct perf_buffer_params *p)
4553 struct bpf_map_info map = {};
4554 char msg[STRERR_BUFSIZE];
4555 struct perf_buffer *pb;
4559 if (page_cnt & (page_cnt - 1)) {
4560 pr_warning("page count should be power of two, but is %zu\n",
4562 return ERR_PTR(-EINVAL);
4565 map_info_len = sizeof(map);
4566 err = bpf_obj_get_info_by_fd(map_fd, &map, &map_info_len);
4569 pr_warning("failed to get map info for map FD %d: %s\n",
4570 map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
4571 return ERR_PTR(err);
4574 if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
4575 pr_warning("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
4577 return ERR_PTR(-EINVAL);
4580 pb = calloc(1, sizeof(*pb));
4582 return ERR_PTR(-ENOMEM);
4584 pb->event_cb = p->event_cb;
4585 pb->sample_cb = p->sample_cb;
4586 pb->lost_cb = p->lost_cb;
4589 pb->page_size = getpagesize();
4590 pb->mmap_size = pb->page_size * page_cnt;
4591 pb->map_fd = map_fd;
4593 pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
4594 if (pb->epoll_fd < 0) {
4596 pr_warning("failed to create epoll instance: %s\n",
4597 libbpf_strerror_r(err, msg, sizeof(msg)));
4601 if (p->cpu_cnt > 0) {
4602 pb->cpu_cnt = p->cpu_cnt;
4604 pb->cpu_cnt = libbpf_num_possible_cpus();
4605 if (pb->cpu_cnt < 0) {
4609 if (map.max_entries < pb->cpu_cnt)
4610 pb->cpu_cnt = map.max_entries;
4613 pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
4616 pr_warning("failed to allocate events: out of memory\n");
4619 pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
4620 if (!pb->cpu_bufs) {
4622 pr_warning("failed to allocate buffers: out of memory\n");
4626 for (i = 0; i < pb->cpu_cnt; i++) {
4627 struct perf_cpu_buf *cpu_buf;
4630 cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
4631 map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
4633 cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
4634 if (IS_ERR(cpu_buf)) {
4635 err = PTR_ERR(cpu_buf);
4639 pb->cpu_bufs[i] = cpu_buf;
4641 err = bpf_map_update_elem(pb->map_fd, &map_key,
4645 pr_warning("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
4646 cpu, map_key, cpu_buf->fd,
4647 libbpf_strerror_r(err, msg, sizeof(msg)));
4651 pb->events[i].events = EPOLLIN;
4652 pb->events[i].data.ptr = cpu_buf;
4653 if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
4654 &pb->events[i]) < 0) {
4656 pr_warning("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
4658 libbpf_strerror_r(err, msg, sizeof(msg)));
4667 perf_buffer__free(pb);
4668 return ERR_PTR(err);
4671 struct perf_sample_raw {
4672 struct perf_event_header header;
4677 struct perf_sample_lost {
4678 struct perf_event_header header;
4684 static enum bpf_perf_event_ret
4685 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
4687 struct perf_cpu_buf *cpu_buf = ctx;
4688 struct perf_buffer *pb = cpu_buf->pb;
4691 /* user wants full control over parsing perf event */
4693 return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
4696 case PERF_RECORD_SAMPLE: {
4697 struct perf_sample_raw *s = data;
4700 pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
4703 case PERF_RECORD_LOST: {
4704 struct perf_sample_lost *s = data;
4707 pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
4711 pr_warning("unknown perf sample type %d\n", e->type);
4712 return LIBBPF_PERF_EVENT_ERROR;
4714 return LIBBPF_PERF_EVENT_CONT;
4717 static int perf_buffer__process_records(struct perf_buffer *pb,
4718 struct perf_cpu_buf *cpu_buf)
4720 enum bpf_perf_event_ret ret;
4722 ret = bpf_perf_event_read_simple(cpu_buf->base, pb->mmap_size,
4723 pb->page_size, &cpu_buf->buf,
4725 perf_buffer__process_record, cpu_buf);
4726 if (ret != LIBBPF_PERF_EVENT_CONT)
4731 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
4735 cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
4736 for (i = 0; i < cnt; i++) {
4737 struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
4739 err = perf_buffer__process_records(pb, cpu_buf);
4741 pr_warning("error while processing records: %d\n", err);
4745 return cnt < 0 ? -errno : cnt;
4748 struct bpf_prog_info_array_desc {
4749 int array_offset; /* e.g. offset of jited_prog_insns */
4750 int count_offset; /* e.g. offset of jited_prog_len */
4751 int size_offset; /* > 0: offset of rec size,
4752 * < 0: fix size of -size_offset
4756 static struct bpf_prog_info_array_desc bpf_prog_info_array_desc[] = {
4757 [BPF_PROG_INFO_JITED_INSNS] = {
4758 offsetof(struct bpf_prog_info, jited_prog_insns),
4759 offsetof(struct bpf_prog_info, jited_prog_len),
4762 [BPF_PROG_INFO_XLATED_INSNS] = {
4763 offsetof(struct bpf_prog_info, xlated_prog_insns),
4764 offsetof(struct bpf_prog_info, xlated_prog_len),
4767 [BPF_PROG_INFO_MAP_IDS] = {
4768 offsetof(struct bpf_prog_info, map_ids),
4769 offsetof(struct bpf_prog_info, nr_map_ids),
4770 -(int)sizeof(__u32),
4772 [BPF_PROG_INFO_JITED_KSYMS] = {
4773 offsetof(struct bpf_prog_info, jited_ksyms),
4774 offsetof(struct bpf_prog_info, nr_jited_ksyms),
4775 -(int)sizeof(__u64),
4777 [BPF_PROG_INFO_JITED_FUNC_LENS] = {
4778 offsetof(struct bpf_prog_info, jited_func_lens),
4779 offsetof(struct bpf_prog_info, nr_jited_func_lens),
4780 -(int)sizeof(__u32),
4782 [BPF_PROG_INFO_FUNC_INFO] = {
4783 offsetof(struct bpf_prog_info, func_info),
4784 offsetof(struct bpf_prog_info, nr_func_info),
4785 offsetof(struct bpf_prog_info, func_info_rec_size),
4787 [BPF_PROG_INFO_LINE_INFO] = {
4788 offsetof(struct bpf_prog_info, line_info),
4789 offsetof(struct bpf_prog_info, nr_line_info),
4790 offsetof(struct bpf_prog_info, line_info_rec_size),
4792 [BPF_PROG_INFO_JITED_LINE_INFO] = {
4793 offsetof(struct bpf_prog_info, jited_line_info),
4794 offsetof(struct bpf_prog_info, nr_jited_line_info),
4795 offsetof(struct bpf_prog_info, jited_line_info_rec_size),
4797 [BPF_PROG_INFO_PROG_TAGS] = {
4798 offsetof(struct bpf_prog_info, prog_tags),
4799 offsetof(struct bpf_prog_info, nr_prog_tags),
4800 -(int)sizeof(__u8) * BPF_TAG_SIZE,
4805 static __u32 bpf_prog_info_read_offset_u32(struct bpf_prog_info *info, int offset)
4807 __u32 *array = (__u32 *)info;
4810 return array[offset / sizeof(__u32)];
4811 return -(int)offset;
4814 static __u64 bpf_prog_info_read_offset_u64(struct bpf_prog_info *info, int offset)
4816 __u64 *array = (__u64 *)info;
4819 return array[offset / sizeof(__u64)];
4820 return -(int)offset;
4823 static void bpf_prog_info_set_offset_u32(struct bpf_prog_info *info, int offset,
4826 __u32 *array = (__u32 *)info;
4829 array[offset / sizeof(__u32)] = val;
4832 static void bpf_prog_info_set_offset_u64(struct bpf_prog_info *info, int offset,
4835 __u64 *array = (__u64 *)info;
4838 array[offset / sizeof(__u64)] = val;
4841 struct bpf_prog_info_linear *
4842 bpf_program__get_prog_info_linear(int fd, __u64 arrays)
4844 struct bpf_prog_info_linear *info_linear;
4845 struct bpf_prog_info info = {};
4846 __u32 info_len = sizeof(info);
4851 if (arrays >> BPF_PROG_INFO_LAST_ARRAY)
4852 return ERR_PTR(-EINVAL);
4854 /* step 1: get array dimensions */
4855 err = bpf_obj_get_info_by_fd(fd, &info, &info_len);
4857 pr_debug("can't get prog info: %s", strerror(errno));
4858 return ERR_PTR(-EFAULT);
4861 /* step 2: calculate total size of all arrays */
4862 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
4863 bool include_array = (arrays & (1UL << i)) > 0;
4864 struct bpf_prog_info_array_desc *desc;
4867 desc = bpf_prog_info_array_desc + i;
4869 /* kernel is too old to support this field */
4870 if (info_len < desc->array_offset + sizeof(__u32) ||
4871 info_len < desc->count_offset + sizeof(__u32) ||
4872 (desc->size_offset > 0 && info_len < desc->size_offset))
4873 include_array = false;
4875 if (!include_array) {
4876 arrays &= ~(1UL << i); /* clear the bit */
4880 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
4881 size = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
4883 data_len += count * size;
4886 /* step 3: allocate continuous memory */
4887 data_len = roundup(data_len, sizeof(__u64));
4888 info_linear = malloc(sizeof(struct bpf_prog_info_linear) + data_len);
4890 return ERR_PTR(-ENOMEM);
4892 /* step 4: fill data to info_linear->info */
4893 info_linear->arrays = arrays;
4894 memset(&info_linear->info, 0, sizeof(info));
4895 ptr = info_linear->data;
4897 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
4898 struct bpf_prog_info_array_desc *desc;
4901 if ((arrays & (1UL << i)) == 0)
4904 desc = bpf_prog_info_array_desc + i;
4905 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
4906 size = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
4907 bpf_prog_info_set_offset_u32(&info_linear->info,
4908 desc->count_offset, count);
4909 bpf_prog_info_set_offset_u32(&info_linear->info,
4910 desc->size_offset, size);
4911 bpf_prog_info_set_offset_u64(&info_linear->info,
4914 ptr += count * size;
4917 /* step 5: call syscall again to get required arrays */
4918 err = bpf_obj_get_info_by_fd(fd, &info_linear->info, &info_len);
4920 pr_debug("can't get prog info: %s", strerror(errno));
4922 return ERR_PTR(-EFAULT);
4925 /* step 6: verify the data */
4926 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
4927 struct bpf_prog_info_array_desc *desc;
4930 if ((arrays & (1UL << i)) == 0)
4933 desc = bpf_prog_info_array_desc + i;
4934 v1 = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
4935 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
4936 desc->count_offset);
4938 pr_warning("%s: mismatch in element count\n", __func__);
4940 v1 = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
4941 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
4944 pr_warning("%s: mismatch in rec size\n", __func__);
4947 /* step 7: update info_len and data_len */
4948 info_linear->info_len = sizeof(struct bpf_prog_info);
4949 info_linear->data_len = data_len;
4954 void bpf_program__bpil_addr_to_offs(struct bpf_prog_info_linear *info_linear)
4958 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
4959 struct bpf_prog_info_array_desc *desc;
4962 if ((info_linear->arrays & (1UL << i)) == 0)
4965 desc = bpf_prog_info_array_desc + i;
4966 addr = bpf_prog_info_read_offset_u64(&info_linear->info,
4967 desc->array_offset);
4968 offs = addr - ptr_to_u64(info_linear->data);
4969 bpf_prog_info_set_offset_u64(&info_linear->info,
4970 desc->array_offset, offs);
4974 void bpf_program__bpil_offs_to_addr(struct bpf_prog_info_linear *info_linear)
4978 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
4979 struct bpf_prog_info_array_desc *desc;
4982 if ((info_linear->arrays & (1UL << i)) == 0)
4985 desc = bpf_prog_info_array_desc + i;
4986 offs = bpf_prog_info_read_offset_u64(&info_linear->info,
4987 desc->array_offset);
4988 addr = offs + ptr_to_u64(info_linear->data);
4989 bpf_prog_info_set_offset_u64(&info_linear->info,
4990 desc->array_offset, addr);
4994 int libbpf_num_possible_cpus(void)
4996 static const char *fcpu = "/sys/devices/system/cpu/possible";
4997 int len = 0, n = 0, il = 0, ir = 0;
4998 unsigned int start = 0, end = 0;
5007 fd = open(fcpu, O_RDONLY);
5010 pr_warning("Failed to open file %s: %s\n",
5011 fcpu, strerror(error));
5014 len = read(fd, buf, sizeof(buf));
5017 error = len ? errno : EINVAL;
5018 pr_warning("Failed to read # of possible cpus from %s: %s\n",
5019 fcpu, strerror(error));
5022 if (len == sizeof(buf)) {
5023 pr_warning("File %s size overflow\n", fcpu);
5028 for (ir = 0, cpus = 0; ir <= len; ir++) {
5029 /* Each sub string separated by ',' has format \d+-\d+ or \d+ */
5030 if (buf[ir] == ',' || buf[ir] == '\0') {
5032 n = sscanf(&buf[il], "%u-%u", &start, &end);
5034 pr_warning("Failed to get # CPUs from %s\n",
5037 } else if (n == 1) {
5040 cpus += end - start + 1;
5045 pr_warning("Invalid #CPUs %d from %s\n", cpus, fcpu);