1 // SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
4 * Common eBPF ELF object loading operations.
6 * Copyright (C) 2013-2015 Alexei Starovoitov <ast@kernel.org>
7 * Copyright (C) 2015 Wang Nan <wangnan0@huawei.com>
8 * Copyright (C) 2015 Huawei Inc.
9 * Copyright (C) 2017 Nicira, Inc.
10 * Copyright (C) 2019 Isovalent, Inc.
26 #include <asm/unistd.h>
27 #include <linux/err.h>
28 #include <linux/kernel.h>
29 #include <linux/bpf.h>
30 #include <linux/btf.h>
31 #include <linux/filter.h>
32 #include <linux/list.h>
33 #include <linux/limits.h>
34 #include <linux/perf_event.h>
35 #include <linux/ring_buffer.h>
36 #include <linux/version.h>
37 #include <sys/epoll.h>
38 #include <sys/ioctl.h>
41 #include <sys/types.h>
43 #include <sys/utsname.h>
44 #include <tools/libc_compat.h>
51 #include "str_error.h"
52 #include "libbpf_internal.h"
60 #define BPF_FS_MAGIC 0xcafe4a11
63 /* vsprintf() in __base_pr() uses nonliteral format string. It may break
64 * compilation if user enables corresponding warning. Disable it explicitly.
66 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
68 #define __printf(a, b) __attribute__((format(printf, a, b)))
70 static int __base_pr(enum libbpf_print_level level, const char *format,
73 if (level == LIBBPF_DEBUG)
76 return vfprintf(stderr, format, args);
79 static libbpf_print_fn_t __libbpf_pr = __base_pr;
81 libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn)
83 libbpf_print_fn_t old_print_fn = __libbpf_pr;
90 void libbpf_print(enum libbpf_print_level level, const char *format, ...)
97 va_start(args, format);
98 __libbpf_pr(level, format, args);
102 #define STRERR_BUFSIZE 128
104 #define CHECK_ERR(action, err, out) do { \
111 /* Copied from tools/perf/util/util.h */
113 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
117 # define zclose(fd) ({ \
120 ___err = close((fd)); \
125 #ifdef HAVE_LIBELF_MMAP_SUPPORT
126 # define LIBBPF_ELF_C_READ_MMAP ELF_C_READ_MMAP
128 # define LIBBPF_ELF_C_READ_MMAP ELF_C_READ
131 static inline __u64 ptr_to_u64(const void *ptr)
133 return (__u64) (unsigned long) ptr;
136 struct bpf_capabilities {
137 /* v4.14: kernel support for program & map names. */
139 /* v5.2: kernel support for global data sections. */
141 /* BTF_KIND_FUNC and BTF_KIND_FUNC_PROTO support */
143 /* BTF_KIND_VAR and BTF_KIND_DATASEC support */
148 * bpf_prog should be a better name but it has been used in
152 /* Index in elf obj file, for relocation use. */
157 /* section_name with / replaced by _; makes recursive pinning
158 * in bpf_object__pin_programs easier
161 struct bpf_insn *insns;
162 size_t insns_cnt, main_prog_cnt;
163 enum bpf_prog_type type;
184 bpf_program_prep_t preprocessor;
186 struct bpf_object *obj;
188 bpf_program_clear_priv_t clear_priv;
190 enum bpf_attach_type expected_attach_type;
192 __u32 func_info_rec_size;
195 struct bpf_capabilities *caps;
198 __u32 line_info_rec_size;
203 enum libbpf_map_type {
210 static const char * const libbpf_type_to_btf_name[] = {
211 [LIBBPF_MAP_DATA] = ".data",
212 [LIBBPF_MAP_BSS] = ".bss",
213 [LIBBPF_MAP_RODATA] = ".rodata",
223 struct bpf_map_def def;
224 __u32 btf_key_type_id;
225 __u32 btf_value_type_id;
227 bpf_map_clear_priv_t clear_priv;
228 enum libbpf_map_type libbpf_type;
236 static LIST_HEAD(bpf_objects_list);
239 char name[BPF_OBJ_NAME_LEN];
243 struct bpf_program *programs;
245 struct bpf_map *maps;
248 struct bpf_secdata sections;
251 bool has_pseudo_calls;
252 bool relaxed_core_relocs;
255 * Information when doing elf related work. Only valid if fd
282 * All loaded bpf_object is linked in a list, which is
283 * hidden to caller. bpf_objects__<func> handlers deal with
286 struct list_head list;
289 struct btf_ext *btf_ext;
292 bpf_object_clear_priv_t clear_priv;
294 struct bpf_capabilities caps;
298 #define obj_elf_valid(o) ((o)->efile.elf)
300 void bpf_program__unload(struct bpf_program *prog)
308 * If the object is opened but the program was never loaded,
309 * it is possible that prog->instances.nr == -1.
311 if (prog->instances.nr > 0) {
312 for (i = 0; i < prog->instances.nr; i++)
313 zclose(prog->instances.fds[i]);
314 } else if (prog->instances.nr != -1) {
315 pr_warning("Internal error: instances.nr is %d\n",
319 prog->instances.nr = -1;
320 zfree(&prog->instances.fds);
322 zfree(&prog->func_info);
323 zfree(&prog->line_info);
326 static void bpf_program__exit(struct bpf_program *prog)
331 if (prog->clear_priv)
332 prog->clear_priv(prog, prog->priv);
335 prog->clear_priv = NULL;
337 bpf_program__unload(prog);
339 zfree(&prog->section_name);
340 zfree(&prog->pin_name);
342 zfree(&prog->reloc_desc);
349 static char *__bpf_program__pin_name(struct bpf_program *prog)
353 name = p = strdup(prog->section_name);
354 while ((p = strchr(p, '/')))
361 bpf_program__init(void *data, size_t size, char *section_name, int idx,
362 struct bpf_program *prog)
364 const size_t bpf_insn_sz = sizeof(struct bpf_insn);
366 if (size == 0 || size % bpf_insn_sz) {
367 pr_warning("corrupted section '%s', size: %zu\n",
372 memset(prog, 0, sizeof(*prog));
374 prog->section_name = strdup(section_name);
375 if (!prog->section_name) {
376 pr_warning("failed to alloc name for prog under section(%d) %s\n",
381 prog->pin_name = __bpf_program__pin_name(prog);
382 if (!prog->pin_name) {
383 pr_warning("failed to alloc pin name for prog under section(%d) %s\n",
388 prog->insns = malloc(size);
390 pr_warning("failed to alloc insns for prog under section %s\n",
394 prog->insns_cnt = size / bpf_insn_sz;
395 memcpy(prog->insns, data, size);
397 prog->instances.fds = NULL;
398 prog->instances.nr = -1;
399 prog->type = BPF_PROG_TYPE_UNSPEC;
403 bpf_program__exit(prog);
408 bpf_object__add_program(struct bpf_object *obj, void *data, size_t size,
409 char *section_name, int idx)
411 struct bpf_program prog, *progs;
414 err = bpf_program__init(data, size, section_name, idx, &prog);
418 prog.caps = &obj->caps;
419 progs = obj->programs;
420 nr_progs = obj->nr_programs;
422 progs = reallocarray(progs, nr_progs + 1, sizeof(progs[0]));
425 * In this case the original obj->programs
426 * is still valid, so don't need special treat for
427 * bpf_close_object().
429 pr_warning("failed to alloc a new program under section '%s'\n",
431 bpf_program__exit(&prog);
435 pr_debug("found program %s\n", prog.section_name);
436 obj->programs = progs;
437 obj->nr_programs = nr_progs + 1;
439 progs[nr_progs] = prog;
444 bpf_object__init_prog_names(struct bpf_object *obj)
446 Elf_Data *symbols = obj->efile.symbols;
447 struct bpf_program *prog;
450 for (pi = 0; pi < obj->nr_programs; pi++) {
451 const char *name = NULL;
453 prog = &obj->programs[pi];
455 for (si = 0; si < symbols->d_size / sizeof(GElf_Sym) && !name;
459 if (!gelf_getsym(symbols, si, &sym))
461 if (sym.st_shndx != prog->idx)
463 if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL)
466 name = elf_strptr(obj->efile.elf,
467 obj->efile.strtabidx,
470 pr_warning("failed to get sym name string for prog %s\n",
472 return -LIBBPF_ERRNO__LIBELF;
476 if (!name && prog->idx == obj->efile.text_shndx)
480 pr_warning("failed to find sym for prog %s\n",
485 prog->name = strdup(name);
487 pr_warning("failed to allocate memory for prog sym %s\n",
496 static __u32 get_kernel_version(void)
498 __u32 major, minor, patch;
502 if (sscanf(info.release, "%u.%u.%u", &major, &minor, &patch) != 3)
504 return KERNEL_VERSION(major, minor, patch);
507 static struct bpf_object *bpf_object__new(const char *path,
510 const char *obj_name)
512 struct bpf_object *obj;
515 obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
517 pr_warning("alloc memory failed for %s\n", path);
518 return ERR_PTR(-ENOMEM);
521 strcpy(obj->path, path);
523 strncpy(obj->name, obj_name, sizeof(obj->name) - 1);
524 obj->name[sizeof(obj->name) - 1] = 0;
526 /* Using basename() GNU version which doesn't modify arg. */
527 strncpy(obj->name, basename((void *)path),
528 sizeof(obj->name) - 1);
529 end = strchr(obj->name, '.');
536 * Caller of this function should also call
537 * bpf_object__elf_finish() after data collection to return
538 * obj_buf to user. If not, we should duplicate the buffer to
539 * avoid user freeing them before elf finish.
541 obj->efile.obj_buf = obj_buf;
542 obj->efile.obj_buf_sz = obj_buf_sz;
543 obj->efile.maps_shndx = -1;
544 obj->efile.btf_maps_shndx = -1;
545 obj->efile.data_shndx = -1;
546 obj->efile.rodata_shndx = -1;
547 obj->efile.bss_shndx = -1;
549 obj->kern_version = get_kernel_version();
552 INIT_LIST_HEAD(&obj->list);
553 list_add(&obj->list, &bpf_objects_list);
557 static void bpf_object__elf_finish(struct bpf_object *obj)
559 if (!obj_elf_valid(obj))
562 if (obj->efile.elf) {
563 elf_end(obj->efile.elf);
564 obj->efile.elf = NULL;
566 obj->efile.symbols = NULL;
567 obj->efile.data = NULL;
568 obj->efile.rodata = NULL;
569 obj->efile.bss = NULL;
571 zfree(&obj->efile.reloc);
572 obj->efile.nr_reloc = 0;
573 zclose(obj->efile.fd);
574 obj->efile.obj_buf = NULL;
575 obj->efile.obj_buf_sz = 0;
578 static int bpf_object__elf_init(struct bpf_object *obj)
583 if (obj_elf_valid(obj)) {
584 pr_warning("elf init: internal error\n");
585 return -LIBBPF_ERRNO__LIBELF;
588 if (obj->efile.obj_buf_sz > 0) {
590 * obj_buf should have been validated by
591 * bpf_object__open_buffer().
593 obj->efile.elf = elf_memory((char *)obj->efile.obj_buf,
594 obj->efile.obj_buf_sz);
596 obj->efile.fd = open(obj->path, O_RDONLY);
597 if (obj->efile.fd < 0) {
598 char errmsg[STRERR_BUFSIZE], *cp;
601 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
602 pr_warning("failed to open %s: %s\n", obj->path, cp);
606 obj->efile.elf = elf_begin(obj->efile.fd,
607 LIBBPF_ELF_C_READ_MMAP, NULL);
610 if (!obj->efile.elf) {
611 pr_warning("failed to open %s as ELF file\n", obj->path);
612 err = -LIBBPF_ERRNO__LIBELF;
616 if (!gelf_getehdr(obj->efile.elf, &obj->efile.ehdr)) {
617 pr_warning("failed to get EHDR from %s\n", obj->path);
618 err = -LIBBPF_ERRNO__FORMAT;
621 ep = &obj->efile.ehdr;
623 /* Old LLVM set e_machine to EM_NONE */
624 if (ep->e_type != ET_REL ||
625 (ep->e_machine && ep->e_machine != EM_BPF)) {
626 pr_warning("%s is not an eBPF object file\n", obj->path);
627 err = -LIBBPF_ERRNO__FORMAT;
633 bpf_object__elf_finish(obj);
637 static int bpf_object__check_endianness(struct bpf_object *obj)
639 #if __BYTE_ORDER == __LITTLE_ENDIAN
640 if (obj->efile.ehdr.e_ident[EI_DATA] == ELFDATA2LSB)
642 #elif __BYTE_ORDER == __BIG_ENDIAN
643 if (obj->efile.ehdr.e_ident[EI_DATA] == ELFDATA2MSB)
646 # error "Unrecognized __BYTE_ORDER__"
648 pr_warning("endianness mismatch.\n");
649 return -LIBBPF_ERRNO__ENDIAN;
653 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
655 memcpy(obj->license, data, min(size, sizeof(obj->license) - 1));
656 pr_debug("license of %s is %s\n", obj->path, obj->license);
661 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
665 if (size != sizeof(kver)) {
666 pr_warning("invalid kver section in %s\n", obj->path);
667 return -LIBBPF_ERRNO__FORMAT;
669 memcpy(&kver, data, sizeof(kver));
670 obj->kern_version = kver;
671 pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
675 static int compare_bpf_map(const void *_a, const void *_b)
677 const struct bpf_map *a = _a;
678 const struct bpf_map *b = _b;
680 if (a->sec_idx != b->sec_idx)
681 return a->sec_idx - b->sec_idx;
682 return a->sec_offset - b->sec_offset;
685 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
687 if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
688 type == BPF_MAP_TYPE_HASH_OF_MAPS)
693 static int bpf_object_search_section_size(const struct bpf_object *obj,
694 const char *name, size_t *d_size)
696 const GElf_Ehdr *ep = &obj->efile.ehdr;
697 Elf *elf = obj->efile.elf;
701 while ((scn = elf_nextscn(elf, scn)) != NULL) {
702 const char *sec_name;
707 if (gelf_getshdr(scn, &sh) != &sh) {
708 pr_warning("failed to get section(%d) header from %s\n",
713 sec_name = elf_strptr(elf, ep->e_shstrndx, sh.sh_name);
715 pr_warning("failed to get section(%d) name from %s\n",
720 if (strcmp(name, sec_name))
723 data = elf_getdata(scn, 0);
725 pr_warning("failed to get section(%d) data from %s(%s)\n",
726 idx, name, obj->path);
730 *d_size = data->d_size;
737 int bpf_object__section_size(const struct bpf_object *obj, const char *name,
746 } else if (!strcmp(name, ".data")) {
748 *size = obj->efile.data->d_size;
749 } else if (!strcmp(name, ".bss")) {
751 *size = obj->efile.bss->d_size;
752 } else if (!strcmp(name, ".rodata")) {
753 if (obj->efile.rodata)
754 *size = obj->efile.rodata->d_size;
756 ret = bpf_object_search_section_size(obj, name, &d_size);
761 return *size ? 0 : ret;
764 int bpf_object__variable_offset(const struct bpf_object *obj, const char *name,
767 Elf_Data *symbols = obj->efile.symbols;
774 for (si = 0; si < symbols->d_size / sizeof(GElf_Sym); si++) {
777 if (!gelf_getsym(symbols, si, &sym))
779 if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL ||
780 GELF_ST_TYPE(sym.st_info) != STT_OBJECT)
783 sname = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
786 pr_warning("failed to get sym name string for var %s\n",
790 if (strcmp(name, sname) == 0) {
799 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
801 struct bpf_map *new_maps;
805 if (obj->nr_maps < obj->maps_cap)
806 return &obj->maps[obj->nr_maps++];
808 new_cap = max((size_t)4, obj->maps_cap * 3 / 2);
809 new_maps = realloc(obj->maps, new_cap * sizeof(*obj->maps));
811 pr_warning("alloc maps for object failed\n");
812 return ERR_PTR(-ENOMEM);
815 obj->maps_cap = new_cap;
816 obj->maps = new_maps;
818 /* zero out new maps */
819 memset(obj->maps + obj->nr_maps, 0,
820 (obj->maps_cap - obj->nr_maps) * sizeof(*obj->maps));
822 * fill all fd with -1 so won't close incorrect fd (fd=0 is stdin)
823 * when failure (zclose won't close negative fd)).
825 for (i = obj->nr_maps; i < obj->maps_cap; i++) {
826 obj->maps[i].fd = -1;
827 obj->maps[i].inner_map_fd = -1;
830 return &obj->maps[obj->nr_maps++];
834 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
835 int sec_idx, Elf_Data *data, void **data_buff)
837 char map_name[BPF_OBJ_NAME_LEN];
838 struct bpf_map_def *def;
841 map = bpf_object__add_map(obj);
845 map->libbpf_type = type;
846 map->sec_idx = sec_idx;
848 snprintf(map_name, sizeof(map_name), "%.8s%.7s", obj->name,
849 libbpf_type_to_btf_name[type]);
850 map->name = strdup(map_name);
852 pr_warning("failed to alloc map name\n");
855 pr_debug("map '%s' (global data): at sec_idx %d, offset %zu.\n",
856 map_name, map->sec_idx, map->sec_offset);
859 def->type = BPF_MAP_TYPE_ARRAY;
860 def->key_size = sizeof(int);
861 def->value_size = data->d_size;
862 def->max_entries = 1;
863 def->map_flags = type == LIBBPF_MAP_RODATA ? BPF_F_RDONLY_PROG : 0;
865 *data_buff = malloc(data->d_size);
868 pr_warning("failed to alloc map content buffer\n");
871 memcpy(*data_buff, data->d_buf, data->d_size);
874 pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
878 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
882 if (!obj->caps.global_data)
885 * Populate obj->maps with libbpf internal maps.
887 if (obj->efile.data_shndx >= 0) {
888 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
889 obj->efile.data_shndx,
891 &obj->sections.data);
895 if (obj->efile.rodata_shndx >= 0) {
896 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
897 obj->efile.rodata_shndx,
899 &obj->sections.rodata);
903 if (obj->efile.bss_shndx >= 0) {
904 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
905 obj->efile.bss_shndx,
906 obj->efile.bss, NULL);
913 static int bpf_object__init_user_maps(struct bpf_object *obj, bool strict)
915 Elf_Data *symbols = obj->efile.symbols;
916 int i, map_def_sz = 0, nr_maps = 0, nr_syms;
917 Elf_Data *data = NULL;
920 if (obj->efile.maps_shndx < 0)
926 scn = elf_getscn(obj->efile.elf, obj->efile.maps_shndx);
928 data = elf_getdata(scn, NULL);
930 pr_warning("failed to get Elf_Data from map section %d\n",
931 obj->efile.maps_shndx);
936 * Count number of maps. Each map has a name.
937 * Array of maps is not supported: only the first element is
940 * TODO: Detect array of map and report error.
942 nr_syms = symbols->d_size / sizeof(GElf_Sym);
943 for (i = 0; i < nr_syms; i++) {
946 if (!gelf_getsym(symbols, i, &sym))
948 if (sym.st_shndx != obj->efile.maps_shndx)
952 /* Assume equally sized map definitions */
953 pr_debug("maps in %s: %d maps in %zd bytes\n",
954 obj->path, nr_maps, data->d_size);
956 map_def_sz = data->d_size / nr_maps;
957 if (!data->d_size || (data->d_size % nr_maps) != 0) {
958 pr_warning("unable to determine map definition size "
959 "section %s, %d maps in %zd bytes\n",
960 obj->path, nr_maps, data->d_size);
964 /* Fill obj->maps using data in "maps" section. */
965 for (i = 0; i < nr_syms; i++) {
967 const char *map_name;
968 struct bpf_map_def *def;
971 if (!gelf_getsym(symbols, i, &sym))
973 if (sym.st_shndx != obj->efile.maps_shndx)
976 map = bpf_object__add_map(obj);
980 map_name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
983 pr_warning("failed to get map #%d name sym string for obj %s\n",
985 return -LIBBPF_ERRNO__FORMAT;
988 map->libbpf_type = LIBBPF_MAP_UNSPEC;
989 map->sec_idx = sym.st_shndx;
990 map->sec_offset = sym.st_value;
991 pr_debug("map '%s' (legacy): at sec_idx %d, offset %zu.\n",
992 map_name, map->sec_idx, map->sec_offset);
993 if (sym.st_value + map_def_sz > data->d_size) {
994 pr_warning("corrupted maps section in %s: last map \"%s\" too small\n",
995 obj->path, map_name);
999 map->name = strdup(map_name);
1001 pr_warning("failed to alloc map name\n");
1004 pr_debug("map %d is \"%s\"\n", i, map->name);
1005 def = (struct bpf_map_def *)(data->d_buf + sym.st_value);
1007 * If the definition of the map in the object file fits in
1008 * bpf_map_def, copy it. Any extra fields in our version
1009 * of bpf_map_def will default to zero as a result of the
1012 if (map_def_sz <= sizeof(struct bpf_map_def)) {
1013 memcpy(&map->def, def, map_def_sz);
1016 * Here the map structure being read is bigger than what
1017 * we expect, truncate if the excess bits are all zero.
1018 * If they are not zero, reject this map as
1022 for (b = ((char *)def) + sizeof(struct bpf_map_def);
1023 b < ((char *)def) + map_def_sz; b++) {
1025 pr_warning("maps section in %s: \"%s\" "
1026 "has unrecognized, non-zero "
1028 obj->path, map_name);
1033 memcpy(&map->def, def, sizeof(struct bpf_map_def));
1039 static const struct btf_type *
1040 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
1042 const struct btf_type *t = btf__type_by_id(btf, id);
1047 while (btf_is_mod(t) || btf_is_typedef(t)) {
1050 t = btf__type_by_id(btf, t->type);
1057 * Fetch integer attribute of BTF map definition. Such attributes are
1058 * represented using a pointer to an array, in which dimensionality of array
1059 * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
1060 * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
1061 * type definition, while using only sizeof(void *) space in ELF data section.
1063 static bool get_map_field_int(const char *map_name, const struct btf *btf,
1064 const struct btf_type *def,
1065 const struct btf_member *m, __u32 *res) {
1066 const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
1067 const char *name = btf__name_by_offset(btf, m->name_off);
1068 const struct btf_array *arr_info;
1069 const struct btf_type *arr_t;
1071 if (!btf_is_ptr(t)) {
1072 pr_warning("map '%s': attr '%s': expected PTR, got %u.\n",
1073 map_name, name, btf_kind(t));
1077 arr_t = btf__type_by_id(btf, t->type);
1079 pr_warning("map '%s': attr '%s': type [%u] not found.\n",
1080 map_name, name, t->type);
1083 if (!btf_is_array(arr_t)) {
1084 pr_warning("map '%s': attr '%s': expected ARRAY, got %u.\n",
1085 map_name, name, btf_kind(arr_t));
1088 arr_info = btf_array(arr_t);
1089 *res = arr_info->nelems;
1093 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
1094 const struct btf_type *sec,
1095 int var_idx, int sec_idx,
1096 const Elf_Data *data, bool strict)
1098 const struct btf_type *var, *def, *t;
1099 const struct btf_var_secinfo *vi;
1100 const struct btf_var *var_extra;
1101 const struct btf_member *m;
1102 const char *map_name;
1103 struct bpf_map *map;
1106 vi = btf_var_secinfos(sec) + var_idx;
1107 var = btf__type_by_id(obj->btf, vi->type);
1108 var_extra = btf_var(var);
1109 map_name = btf__name_by_offset(obj->btf, var->name_off);
1110 vlen = btf_vlen(var);
1112 if (map_name == NULL || map_name[0] == '\0') {
1113 pr_warning("map #%d: empty name.\n", var_idx);
1116 if ((__u64)vi->offset + vi->size > data->d_size) {
1117 pr_warning("map '%s' BTF data is corrupted.\n", map_name);
1120 if (!btf_is_var(var)) {
1121 pr_warning("map '%s': unexpected var kind %u.\n",
1122 map_name, btf_kind(var));
1125 if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED &&
1126 var_extra->linkage != BTF_VAR_STATIC) {
1127 pr_warning("map '%s': unsupported var linkage %u.\n",
1128 map_name, var_extra->linkage);
1132 def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
1133 if (!btf_is_struct(def)) {
1134 pr_warning("map '%s': unexpected def kind %u.\n",
1135 map_name, btf_kind(var));
1138 if (def->size > vi->size) {
1139 pr_warning("map '%s': invalid def size.\n", map_name);
1143 map = bpf_object__add_map(obj);
1145 return PTR_ERR(map);
1146 map->name = strdup(map_name);
1148 pr_warning("map '%s': failed to alloc map name.\n", map_name);
1151 map->libbpf_type = LIBBPF_MAP_UNSPEC;
1152 map->def.type = BPF_MAP_TYPE_UNSPEC;
1153 map->sec_idx = sec_idx;
1154 map->sec_offset = vi->offset;
1155 pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
1156 map_name, map->sec_idx, map->sec_offset);
1158 vlen = btf_vlen(def);
1159 m = btf_members(def);
1160 for (i = 0; i < vlen; i++, m++) {
1161 const char *name = btf__name_by_offset(obj->btf, m->name_off);
1164 pr_warning("map '%s': invalid field #%d.\n",
1168 if (strcmp(name, "type") == 0) {
1169 if (!get_map_field_int(map_name, obj->btf, def, m,
1172 pr_debug("map '%s': found type = %u.\n",
1173 map_name, map->def.type);
1174 } else if (strcmp(name, "max_entries") == 0) {
1175 if (!get_map_field_int(map_name, obj->btf, def, m,
1176 &map->def.max_entries))
1178 pr_debug("map '%s': found max_entries = %u.\n",
1179 map_name, map->def.max_entries);
1180 } else if (strcmp(name, "map_flags") == 0) {
1181 if (!get_map_field_int(map_name, obj->btf, def, m,
1182 &map->def.map_flags))
1184 pr_debug("map '%s': found map_flags = %u.\n",
1185 map_name, map->def.map_flags);
1186 } else if (strcmp(name, "key_size") == 0) {
1189 if (!get_map_field_int(map_name, obj->btf, def, m,
1192 pr_debug("map '%s': found key_size = %u.\n",
1194 if (map->def.key_size && map->def.key_size != sz) {
1195 pr_warning("map '%s': conflicting key size %u != %u.\n",
1196 map_name, map->def.key_size, sz);
1199 map->def.key_size = sz;
1200 } else if (strcmp(name, "key") == 0) {
1203 t = btf__type_by_id(obj->btf, m->type);
1205 pr_warning("map '%s': key type [%d] not found.\n",
1209 if (!btf_is_ptr(t)) {
1210 pr_warning("map '%s': key spec is not PTR: %u.\n",
1211 map_name, btf_kind(t));
1214 sz = btf__resolve_size(obj->btf, t->type);
1216 pr_warning("map '%s': can't determine key size for type [%u]: %lld.\n",
1217 map_name, t->type, sz);
1220 pr_debug("map '%s': found key [%u], sz = %lld.\n",
1221 map_name, t->type, sz);
1222 if (map->def.key_size && map->def.key_size != sz) {
1223 pr_warning("map '%s': conflicting key size %u != %lld.\n",
1224 map_name, map->def.key_size, sz);
1227 map->def.key_size = sz;
1228 map->btf_key_type_id = t->type;
1229 } else if (strcmp(name, "value_size") == 0) {
1232 if (!get_map_field_int(map_name, obj->btf, def, m,
1235 pr_debug("map '%s': found value_size = %u.\n",
1237 if (map->def.value_size && map->def.value_size != sz) {
1238 pr_warning("map '%s': conflicting value size %u != %u.\n",
1239 map_name, map->def.value_size, sz);
1242 map->def.value_size = sz;
1243 } else if (strcmp(name, "value") == 0) {
1246 t = btf__type_by_id(obj->btf, m->type);
1248 pr_warning("map '%s': value type [%d] not found.\n",
1252 if (!btf_is_ptr(t)) {
1253 pr_warning("map '%s': value spec is not PTR: %u.\n",
1254 map_name, btf_kind(t));
1257 sz = btf__resolve_size(obj->btf, t->type);
1259 pr_warning("map '%s': can't determine value size for type [%u]: %lld.\n",
1260 map_name, t->type, sz);
1263 pr_debug("map '%s': found value [%u], sz = %lld.\n",
1264 map_name, t->type, sz);
1265 if (map->def.value_size && map->def.value_size != sz) {
1266 pr_warning("map '%s': conflicting value size %u != %lld.\n",
1267 map_name, map->def.value_size, sz);
1270 map->def.value_size = sz;
1271 map->btf_value_type_id = t->type;
1274 pr_warning("map '%s': unknown field '%s'.\n",
1278 pr_debug("map '%s': ignoring unknown field '%s'.\n",
1283 if (map->def.type == BPF_MAP_TYPE_UNSPEC) {
1284 pr_warning("map '%s': map type isn't specified.\n", map_name);
1291 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict)
1293 const struct btf_type *sec = NULL;
1294 int nr_types, i, vlen, err;
1295 const struct btf_type *t;
1300 if (obj->efile.btf_maps_shndx < 0)
1303 scn = elf_getscn(obj->efile.elf, obj->efile.btf_maps_shndx);
1305 data = elf_getdata(scn, NULL);
1306 if (!scn || !data) {
1307 pr_warning("failed to get Elf_Data from map section %d (%s)\n",
1308 obj->efile.maps_shndx, MAPS_ELF_SEC);
1312 nr_types = btf__get_nr_types(obj->btf);
1313 for (i = 1; i <= nr_types; i++) {
1314 t = btf__type_by_id(obj->btf, i);
1315 if (!btf_is_datasec(t))
1317 name = btf__name_by_offset(obj->btf, t->name_off);
1318 if (strcmp(name, MAPS_ELF_SEC) == 0) {
1325 pr_warning("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
1329 vlen = btf_vlen(sec);
1330 for (i = 0; i < vlen; i++) {
1331 err = bpf_object__init_user_btf_map(obj, sec, i,
1332 obj->efile.btf_maps_shndx,
1341 static int bpf_object__init_maps(struct bpf_object *obj, bool relaxed_maps)
1343 bool strict = !relaxed_maps;
1346 err = bpf_object__init_user_maps(obj, strict);
1350 err = bpf_object__init_user_btf_maps(obj, strict);
1354 err = bpf_object__init_global_data_maps(obj);
1359 qsort(obj->maps, obj->nr_maps, sizeof(obj->maps[0]),
1365 static bool section_have_execinstr(struct bpf_object *obj, int idx)
1370 scn = elf_getscn(obj->efile.elf, idx);
1374 if (gelf_getshdr(scn, &sh) != &sh)
1377 if (sh.sh_flags & SHF_EXECINSTR)
1383 static void bpf_object__sanitize_btf(struct bpf_object *obj)
1385 bool has_datasec = obj->caps.btf_datasec;
1386 bool has_func = obj->caps.btf_func;
1387 struct btf *btf = obj->btf;
1391 if (!obj->btf || (has_func && has_datasec))
1394 for (i = 1; i <= btf__get_nr_types(btf); i++) {
1395 t = (struct btf_type *)btf__type_by_id(btf, i);
1397 if (!has_datasec && btf_is_var(t)) {
1398 /* replace VAR with INT */
1399 t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
1401 * using size = 1 is the safest choice, 4 will be too
1402 * big and cause kernel BTF validation failure if
1403 * original variable took less than 4 bytes
1406 *(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
1407 } else if (!has_datasec && btf_is_datasec(t)) {
1408 /* replace DATASEC with STRUCT */
1409 const struct btf_var_secinfo *v = btf_var_secinfos(t);
1410 struct btf_member *m = btf_members(t);
1411 struct btf_type *vt;
1414 name = (char *)btf__name_by_offset(btf, t->name_off);
1422 t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
1423 for (j = 0; j < vlen; j++, v++, m++) {
1424 /* order of field assignments is important */
1425 m->offset = v->offset * 8;
1427 /* preserve variable name as member name */
1428 vt = (void *)btf__type_by_id(btf, v->type);
1429 m->name_off = vt->name_off;
1431 } else if (!has_func && btf_is_func_proto(t)) {
1432 /* replace FUNC_PROTO with ENUM */
1434 t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
1435 t->size = sizeof(__u32); /* kernel enforced */
1436 } else if (!has_func && btf_is_func(t)) {
1437 /* replace FUNC with TYPEDEF */
1438 t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
1443 static void bpf_object__sanitize_btf_ext(struct bpf_object *obj)
1448 if (!obj->caps.btf_func) {
1449 btf_ext__free(obj->btf_ext);
1450 obj->btf_ext = NULL;
1454 static bool bpf_object__is_btf_mandatory(const struct bpf_object *obj)
1456 return obj->efile.btf_maps_shndx >= 0;
1459 static int bpf_object__init_btf(struct bpf_object *obj,
1461 Elf_Data *btf_ext_data)
1463 bool btf_required = bpf_object__is_btf_mandatory(obj);
1467 obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
1468 if (IS_ERR(obj->btf)) {
1469 pr_warning("Error loading ELF section %s: %d.\n",
1473 err = btf__finalize_data(obj, obj->btf);
1475 pr_warning("Error finalizing %s: %d.\n",
1482 pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
1483 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
1486 obj->btf_ext = btf_ext__new(btf_ext_data->d_buf,
1487 btf_ext_data->d_size);
1488 if (IS_ERR(obj->btf_ext)) {
1489 pr_warning("Error loading ELF section %s: %ld. Ignored and continue.\n",
1490 BTF_EXT_ELF_SEC, PTR_ERR(obj->btf_ext));
1491 obj->btf_ext = NULL;
1496 if (err || IS_ERR(obj->btf)) {
1498 err = err ? : PTR_ERR(obj->btf);
1501 if (!IS_ERR_OR_NULL(obj->btf))
1502 btf__free(obj->btf);
1505 if (btf_required && !obj->btf) {
1506 pr_warning("BTF is required, but is missing or corrupted.\n");
1507 return err == 0 ? -ENOENT : err;
1512 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
1519 bpf_object__sanitize_btf(obj);
1520 bpf_object__sanitize_btf_ext(obj);
1522 err = btf__load(obj->btf);
1524 pr_warning("Error loading %s into kernel: %d.\n",
1526 btf__free(obj->btf);
1528 /* btf_ext can't exist without btf, so free it as well */
1530 btf_ext__free(obj->btf_ext);
1531 obj->btf_ext = NULL;
1534 if (bpf_object__is_btf_mandatory(obj))
1540 static int bpf_object__elf_collect(struct bpf_object *obj, bool relaxed_maps)
1542 Elf *elf = obj->efile.elf;
1543 GElf_Ehdr *ep = &obj->efile.ehdr;
1544 Elf_Data *btf_ext_data = NULL;
1545 Elf_Data *btf_data = NULL;
1546 Elf_Scn *scn = NULL;
1547 int idx = 0, err = 0;
1549 /* Elf is corrupted/truncated, avoid calling elf_strptr. */
1550 if (!elf_rawdata(elf_getscn(elf, ep->e_shstrndx), NULL)) {
1551 pr_warning("failed to get e_shstrndx from %s\n", obj->path);
1552 return -LIBBPF_ERRNO__FORMAT;
1555 while ((scn = elf_nextscn(elf, scn)) != NULL) {
1561 if (gelf_getshdr(scn, &sh) != &sh) {
1562 pr_warning("failed to get section(%d) header from %s\n",
1564 return -LIBBPF_ERRNO__FORMAT;
1567 name = elf_strptr(elf, ep->e_shstrndx, sh.sh_name);
1569 pr_warning("failed to get section(%d) name from %s\n",
1571 return -LIBBPF_ERRNO__FORMAT;
1574 data = elf_getdata(scn, 0);
1576 pr_warning("failed to get section(%d) data from %s(%s)\n",
1577 idx, name, obj->path);
1578 return -LIBBPF_ERRNO__FORMAT;
1580 pr_debug("section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
1581 idx, name, (unsigned long)data->d_size,
1582 (int)sh.sh_link, (unsigned long)sh.sh_flags,
1585 if (strcmp(name, "license") == 0) {
1586 err = bpf_object__init_license(obj,
1591 } else if (strcmp(name, "version") == 0) {
1592 err = bpf_object__init_kversion(obj,
1597 } else if (strcmp(name, "maps") == 0) {
1598 obj->efile.maps_shndx = idx;
1599 } else if (strcmp(name, MAPS_ELF_SEC) == 0) {
1600 obj->efile.btf_maps_shndx = idx;
1601 } else if (strcmp(name, BTF_ELF_SEC) == 0) {
1603 } else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
1604 btf_ext_data = data;
1605 } else if (sh.sh_type == SHT_SYMTAB) {
1606 if (obj->efile.symbols) {
1607 pr_warning("bpf: multiple SYMTAB in %s\n",
1609 return -LIBBPF_ERRNO__FORMAT;
1611 obj->efile.symbols = data;
1612 obj->efile.strtabidx = sh.sh_link;
1613 } else if (sh.sh_type == SHT_PROGBITS && data->d_size > 0) {
1614 if (sh.sh_flags & SHF_EXECINSTR) {
1615 if (strcmp(name, ".text") == 0)
1616 obj->efile.text_shndx = idx;
1617 err = bpf_object__add_program(obj, data->d_buf,
1618 data->d_size, name, idx);
1620 char errmsg[STRERR_BUFSIZE];
1621 char *cp = libbpf_strerror_r(-err, errmsg,
1624 pr_warning("failed to alloc program %s (%s): %s",
1625 name, obj->path, cp);
1628 } else if (strcmp(name, ".data") == 0) {
1629 obj->efile.data = data;
1630 obj->efile.data_shndx = idx;
1631 } else if (strcmp(name, ".rodata") == 0) {
1632 obj->efile.rodata = data;
1633 obj->efile.rodata_shndx = idx;
1635 pr_debug("skip section(%d) %s\n", idx, name);
1637 } else if (sh.sh_type == SHT_REL) {
1638 int nr_reloc = obj->efile.nr_reloc;
1639 void *reloc = obj->efile.reloc;
1640 int sec = sh.sh_info; /* points to other section */
1642 /* Only do relo for section with exec instructions */
1643 if (!section_have_execinstr(obj, sec)) {
1644 pr_debug("skip relo %s(%d) for section(%d)\n",
1649 reloc = reallocarray(reloc, nr_reloc + 1,
1650 sizeof(*obj->efile.reloc));
1652 pr_warning("realloc failed\n");
1656 obj->efile.reloc = reloc;
1657 obj->efile.nr_reloc++;
1659 obj->efile.reloc[nr_reloc].shdr = sh;
1660 obj->efile.reloc[nr_reloc].data = data;
1661 } else if (sh.sh_type == SHT_NOBITS && strcmp(name, ".bss") == 0) {
1662 obj->efile.bss = data;
1663 obj->efile.bss_shndx = idx;
1665 pr_debug("skip section(%d) %s\n", idx, name);
1669 if (!obj->efile.strtabidx || obj->efile.strtabidx >= idx) {
1670 pr_warning("Corrupted ELF file: index of strtab invalid\n");
1671 return -LIBBPF_ERRNO__FORMAT;
1673 err = bpf_object__init_btf(obj, btf_data, btf_ext_data);
1675 err = bpf_object__init_maps(obj, relaxed_maps);
1677 err = bpf_object__sanitize_and_load_btf(obj);
1679 err = bpf_object__init_prog_names(obj);
1683 static struct bpf_program *
1684 bpf_object__find_prog_by_idx(struct bpf_object *obj, int idx)
1686 struct bpf_program *prog;
1689 for (i = 0; i < obj->nr_programs; i++) {
1690 prog = &obj->programs[i];
1691 if (prog->idx == idx)
1697 struct bpf_program *
1698 bpf_object__find_program_by_title(const struct bpf_object *obj,
1701 struct bpf_program *pos;
1703 bpf_object__for_each_program(pos, obj) {
1704 if (pos->section_name && !strcmp(pos->section_name, title))
1710 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
1713 return shndx == obj->efile.data_shndx ||
1714 shndx == obj->efile.bss_shndx ||
1715 shndx == obj->efile.rodata_shndx;
1718 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
1721 return shndx == obj->efile.maps_shndx ||
1722 shndx == obj->efile.btf_maps_shndx;
1725 static bool bpf_object__relo_in_known_section(const struct bpf_object *obj,
1728 return shndx == obj->efile.text_shndx ||
1729 bpf_object__shndx_is_maps(obj, shndx) ||
1730 bpf_object__shndx_is_data(obj, shndx);
1733 static enum libbpf_map_type
1734 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
1736 if (shndx == obj->efile.data_shndx)
1737 return LIBBPF_MAP_DATA;
1738 else if (shndx == obj->efile.bss_shndx)
1739 return LIBBPF_MAP_BSS;
1740 else if (shndx == obj->efile.rodata_shndx)
1741 return LIBBPF_MAP_RODATA;
1743 return LIBBPF_MAP_UNSPEC;
1747 bpf_program__collect_reloc(struct bpf_program *prog, GElf_Shdr *shdr,
1748 Elf_Data *data, struct bpf_object *obj)
1750 Elf_Data *symbols = obj->efile.symbols;
1751 struct bpf_map *maps = obj->maps;
1752 size_t nr_maps = obj->nr_maps;
1755 pr_debug("collecting relocating info for: '%s'\n", prog->section_name);
1756 nrels = shdr->sh_size / shdr->sh_entsize;
1758 prog->reloc_desc = malloc(sizeof(*prog->reloc_desc) * nrels);
1759 if (!prog->reloc_desc) {
1760 pr_warning("failed to alloc memory in relocation\n");
1763 prog->nr_reloc = nrels;
1765 for (i = 0; i < nrels; i++) {
1766 struct bpf_insn *insns = prog->insns;
1767 enum libbpf_map_type type;
1768 unsigned int insn_idx;
1769 unsigned int shdr_idx;
1775 if (!gelf_getrel(data, i, &rel)) {
1776 pr_warning("relocation: failed to get %d reloc\n", i);
1777 return -LIBBPF_ERRNO__FORMAT;
1780 if (!gelf_getsym(symbols, GELF_R_SYM(rel.r_info), &sym)) {
1781 pr_warning("relocation: symbol %"PRIx64" not found\n",
1782 GELF_R_SYM(rel.r_info));
1783 return -LIBBPF_ERRNO__FORMAT;
1786 name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
1787 sym.st_name) ? : "<?>";
1789 pr_debug("relo for %lld value %lld name %d (\'%s\')\n",
1790 (long long) (rel.r_info >> 32),
1791 (long long) sym.st_value, sym.st_name, name);
1793 shdr_idx = sym.st_shndx;
1794 insn_idx = rel.r_offset / sizeof(struct bpf_insn);
1795 pr_debug("relocation: insn_idx=%u, shdr_idx=%u\n",
1796 insn_idx, shdr_idx);
1798 if (shdr_idx >= SHN_LORESERVE) {
1799 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",
1800 name, shdr_idx, insn_idx,
1801 insns[insn_idx].code);
1802 return -LIBBPF_ERRNO__RELOC;
1804 if (!bpf_object__relo_in_known_section(obj, shdr_idx)) {
1805 pr_warning("Program '%s' contains unrecognized relo data pointing to section %u\n",
1806 prog->section_name, shdr_idx);
1807 return -LIBBPF_ERRNO__RELOC;
1810 if (insns[insn_idx].code == (BPF_JMP | BPF_CALL)) {
1811 if (insns[insn_idx].src_reg != BPF_PSEUDO_CALL) {
1812 pr_warning("incorrect bpf_call opcode\n");
1813 return -LIBBPF_ERRNO__RELOC;
1815 prog->reloc_desc[i].type = RELO_CALL;
1816 prog->reloc_desc[i].insn_idx = insn_idx;
1817 prog->reloc_desc[i].text_off = sym.st_value;
1818 obj->has_pseudo_calls = true;
1822 if (insns[insn_idx].code != (BPF_LD | BPF_IMM | BPF_DW)) {
1823 pr_warning("bpf: relocation: invalid relo for insns[%d].code 0x%x\n",
1824 insn_idx, insns[insn_idx].code);
1825 return -LIBBPF_ERRNO__RELOC;
1828 if (bpf_object__shndx_is_maps(obj, shdr_idx) ||
1829 bpf_object__shndx_is_data(obj, shdr_idx)) {
1830 type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
1831 if (type != LIBBPF_MAP_UNSPEC) {
1832 if (GELF_ST_BIND(sym.st_info) == STB_GLOBAL) {
1833 pr_warning("bpf: relocation: not yet supported relo for non-static global \'%s\' variable found in insns[%d].code 0x%x\n",
1834 name, insn_idx, insns[insn_idx].code);
1835 return -LIBBPF_ERRNO__RELOC;
1837 if (!obj->caps.global_data) {
1838 pr_warning("bpf: relocation: kernel does not support global \'%s\' variable access in insns[%d]\n",
1840 return -LIBBPF_ERRNO__RELOC;
1844 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
1845 if (maps[map_idx].libbpf_type != type)
1847 if (type != LIBBPF_MAP_UNSPEC ||
1848 (maps[map_idx].sec_idx == sym.st_shndx &&
1849 maps[map_idx].sec_offset == sym.st_value)) {
1850 pr_debug("relocation: found map %zd (%s, sec_idx %d, offset %zu) for insn %u\n",
1851 map_idx, maps[map_idx].name,
1852 maps[map_idx].sec_idx,
1853 maps[map_idx].sec_offset,
1859 if (map_idx >= nr_maps) {
1860 pr_warning("bpf relocation: map_idx %d larger than %d\n",
1861 (int)map_idx, (int)nr_maps - 1);
1862 return -LIBBPF_ERRNO__RELOC;
1865 prog->reloc_desc[i].type = type != LIBBPF_MAP_UNSPEC ?
1866 RELO_DATA : RELO_LD64;
1867 prog->reloc_desc[i].insn_idx = insn_idx;
1868 prog->reloc_desc[i].map_idx = map_idx;
1874 static int bpf_map_find_btf_info(struct bpf_object *obj, struct bpf_map *map)
1876 struct bpf_map_def *def = &map->def;
1877 __u32 key_type_id = 0, value_type_id = 0;
1880 /* if it's BTF-defined map, we don't need to search for type IDs */
1881 if (map->sec_idx == obj->efile.btf_maps_shndx)
1884 if (!bpf_map__is_internal(map)) {
1885 ret = btf__get_map_kv_tids(obj->btf, map->name, def->key_size,
1886 def->value_size, &key_type_id,
1890 * LLVM annotates global data differently in BTF, that is,
1891 * only as '.data', '.bss' or '.rodata'.
1893 ret = btf__find_by_name(obj->btf,
1894 libbpf_type_to_btf_name[map->libbpf_type]);
1899 map->btf_key_type_id = key_type_id;
1900 map->btf_value_type_id = bpf_map__is_internal(map) ?
1901 ret : value_type_id;
1905 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
1907 struct bpf_map_info info = {};
1908 __u32 len = sizeof(info);
1912 err = bpf_obj_get_info_by_fd(fd, &info, &len);
1916 new_name = strdup(info.name);
1920 new_fd = open("/", O_RDONLY | O_CLOEXEC);
1922 goto err_free_new_name;
1924 new_fd = dup3(fd, new_fd, O_CLOEXEC);
1926 goto err_close_new_fd;
1928 err = zclose(map->fd);
1930 goto err_close_new_fd;
1934 map->name = new_name;
1935 map->def.type = info.type;
1936 map->def.key_size = info.key_size;
1937 map->def.value_size = info.value_size;
1938 map->def.max_entries = info.max_entries;
1939 map->def.map_flags = info.map_flags;
1940 map->btf_key_type_id = info.btf_key_type_id;
1941 map->btf_value_type_id = info.btf_value_type_id;
1952 int bpf_map__resize(struct bpf_map *map, __u32 max_entries)
1954 if (!map || !max_entries)
1957 /* If map already created, its attributes can't be changed. */
1961 map->def.max_entries = max_entries;
1967 bpf_object__probe_name(struct bpf_object *obj)
1969 struct bpf_load_program_attr attr;
1970 char *cp, errmsg[STRERR_BUFSIZE];
1971 struct bpf_insn insns[] = {
1972 BPF_MOV64_IMM(BPF_REG_0, 0),
1977 /* make sure basic loading works */
1979 memset(&attr, 0, sizeof(attr));
1980 attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
1982 attr.insns_cnt = ARRAY_SIZE(insns);
1983 attr.license = "GPL";
1985 ret = bpf_load_program_xattr(&attr, NULL, 0);
1987 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
1988 pr_warning("Error in %s():%s(%d). Couldn't load basic 'r0 = 0' BPF program.\n",
1989 __func__, cp, errno);
1994 /* now try the same program, but with the name */
1997 ret = bpf_load_program_xattr(&attr, NULL, 0);
2007 bpf_object__probe_global_data(struct bpf_object *obj)
2009 struct bpf_load_program_attr prg_attr;
2010 struct bpf_create_map_attr map_attr;
2011 char *cp, errmsg[STRERR_BUFSIZE];
2012 struct bpf_insn insns[] = {
2013 BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16),
2014 BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42),
2015 BPF_MOV64_IMM(BPF_REG_0, 0),
2020 memset(&map_attr, 0, sizeof(map_attr));
2021 map_attr.map_type = BPF_MAP_TYPE_ARRAY;
2022 map_attr.key_size = sizeof(int);
2023 map_attr.value_size = 32;
2024 map_attr.max_entries = 1;
2026 map = bpf_create_map_xattr(&map_attr);
2028 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
2029 pr_warning("Error in %s():%s(%d). Couldn't create simple array map.\n",
2030 __func__, cp, errno);
2036 memset(&prg_attr, 0, sizeof(prg_attr));
2037 prg_attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
2038 prg_attr.insns = insns;
2039 prg_attr.insns_cnt = ARRAY_SIZE(insns);
2040 prg_attr.license = "GPL";
2042 ret = bpf_load_program_xattr(&prg_attr, NULL, 0);
2044 obj->caps.global_data = 1;
2052 static int bpf_object__probe_btf_func(struct bpf_object *obj)
2054 const char strs[] = "\0int\0x\0a";
2055 /* void x(int a) {} */
2058 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
2059 /* FUNC_PROTO */ /* [2] */
2060 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
2061 BTF_PARAM_ENC(7, 1),
2062 /* FUNC x */ /* [3] */
2063 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0), 2),
2067 btf_fd = libbpf__load_raw_btf((char *)types, sizeof(types),
2068 strs, sizeof(strs));
2070 obj->caps.btf_func = 1;
2078 static int bpf_object__probe_btf_datasec(struct bpf_object *obj)
2080 const char strs[] = "\0x\0.data";
2084 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
2085 /* VAR x */ /* [2] */
2086 BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
2088 /* DATASEC val */ /* [3] */
2089 BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC, 0, 1), 4),
2090 BTF_VAR_SECINFO_ENC(2, 0, 4),
2094 btf_fd = libbpf__load_raw_btf((char *)types, sizeof(types),
2095 strs, sizeof(strs));
2097 obj->caps.btf_datasec = 1;
2106 bpf_object__probe_caps(struct bpf_object *obj)
2108 int (*probe_fn[])(struct bpf_object *obj) = {
2109 bpf_object__probe_name,
2110 bpf_object__probe_global_data,
2111 bpf_object__probe_btf_func,
2112 bpf_object__probe_btf_datasec,
2116 for (i = 0; i < ARRAY_SIZE(probe_fn); i++) {
2117 ret = probe_fn[i](obj);
2119 pr_debug("Probe #%d failed with %d.\n", i, ret);
2126 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
2128 char *cp, errmsg[STRERR_BUFSIZE];
2132 /* Nothing to do here since kernel already zero-initializes .bss map. */
2133 if (map->libbpf_type == LIBBPF_MAP_BSS)
2136 data = map->libbpf_type == LIBBPF_MAP_DATA ?
2137 obj->sections.data : obj->sections.rodata;
2139 err = bpf_map_update_elem(map->fd, &zero, data, 0);
2140 /* Freeze .rodata map as read-only from syscall side. */
2141 if (!err && map->libbpf_type == LIBBPF_MAP_RODATA) {
2142 err = bpf_map_freeze(map->fd);
2144 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
2145 pr_warning("Error freezing map(%s) as read-only: %s\n",
2154 bpf_object__create_maps(struct bpf_object *obj)
2156 struct bpf_create_map_attr create_attr = {};
2161 for (i = 0; i < obj->nr_maps; i++) {
2162 struct bpf_map *map = &obj->maps[i];
2163 struct bpf_map_def *def = &map->def;
2164 char *cp, errmsg[STRERR_BUFSIZE];
2165 int *pfd = &map->fd;
2168 pr_debug("skip map create (preset) %s: fd=%d\n",
2169 map->name, map->fd);
2174 create_attr.name = map->name;
2175 create_attr.map_ifindex = map->map_ifindex;
2176 create_attr.map_type = def->type;
2177 create_attr.map_flags = def->map_flags;
2178 create_attr.key_size = def->key_size;
2179 create_attr.value_size = def->value_size;
2180 if (def->type == BPF_MAP_TYPE_PERF_EVENT_ARRAY &&
2181 !def->max_entries) {
2183 nr_cpus = libbpf_num_possible_cpus();
2185 pr_warning("failed to determine number of system CPUs: %d\n",
2190 pr_debug("map '%s': setting size to %d\n",
2191 map->name, nr_cpus);
2192 create_attr.max_entries = nr_cpus;
2194 create_attr.max_entries = def->max_entries;
2196 create_attr.btf_fd = 0;
2197 create_attr.btf_key_type_id = 0;
2198 create_attr.btf_value_type_id = 0;
2199 if (bpf_map_type__is_map_in_map(def->type) &&
2200 map->inner_map_fd >= 0)
2201 create_attr.inner_map_fd = map->inner_map_fd;
2203 if (obj->btf && !bpf_map_find_btf_info(obj, map)) {
2204 create_attr.btf_fd = btf__fd(obj->btf);
2205 create_attr.btf_key_type_id = map->btf_key_type_id;
2206 create_attr.btf_value_type_id = map->btf_value_type_id;
2209 *pfd = bpf_create_map_xattr(&create_attr);
2210 if (*pfd < 0 && (create_attr.btf_key_type_id ||
2211 create_attr.btf_value_type_id)) {
2213 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
2214 pr_warning("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
2215 map->name, cp, err);
2216 create_attr.btf_fd = 0;
2217 create_attr.btf_key_type_id = 0;
2218 create_attr.btf_value_type_id = 0;
2219 map->btf_key_type_id = 0;
2220 map->btf_value_type_id = 0;
2221 *pfd = bpf_create_map_xattr(&create_attr);
2229 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
2230 pr_warning("failed to create map (name: '%s'): %s(%d)\n",
2231 map->name, cp, err);
2232 for (j = 0; j < i; j++)
2233 zclose(obj->maps[j].fd);
2237 if (bpf_map__is_internal(map)) {
2238 err = bpf_object__populate_internal_map(obj, map);
2245 pr_debug("created map %s: fd=%d\n", map->name, *pfd);
2252 check_btf_ext_reloc_err(struct bpf_program *prog, int err,
2253 void *btf_prog_info, const char *info_name)
2255 if (err != -ENOENT) {
2256 pr_warning("Error in loading %s for sec %s.\n",
2257 info_name, prog->section_name);
2261 /* err == -ENOENT (i.e. prog->section_name not found in btf_ext) */
2263 if (btf_prog_info) {
2265 * Some info has already been found but has problem
2266 * in the last btf_ext reloc. Must have to error out.
2268 pr_warning("Error in relocating %s for sec %s.\n",
2269 info_name, prog->section_name);
2273 /* Have problem loading the very first info. Ignore the rest. */
2274 pr_warning("Cannot find %s for main program sec %s. Ignore all %s.\n",
2275 info_name, prog->section_name, info_name);
2280 bpf_program_reloc_btf_ext(struct bpf_program *prog, struct bpf_object *obj,
2281 const char *section_name, __u32 insn_offset)
2285 if (!insn_offset || prog->func_info) {
2287 * !insn_offset => main program
2289 * For sub prog, the main program's func_info has to
2290 * be loaded first (i.e. prog->func_info != NULL)
2292 err = btf_ext__reloc_func_info(obj->btf, obj->btf_ext,
2293 section_name, insn_offset,
2295 &prog->func_info_cnt);
2297 return check_btf_ext_reloc_err(prog, err,
2301 prog->func_info_rec_size = btf_ext__func_info_rec_size(obj->btf_ext);
2304 if (!insn_offset || prog->line_info) {
2305 err = btf_ext__reloc_line_info(obj->btf, obj->btf_ext,
2306 section_name, insn_offset,
2308 &prog->line_info_cnt);
2310 return check_btf_ext_reloc_err(prog, err,
2314 prog->line_info_rec_size = btf_ext__line_info_rec_size(obj->btf_ext);
2320 #define BPF_CORE_SPEC_MAX_LEN 64
2322 /* represents BPF CO-RE field or array element accessor */
2323 struct bpf_core_accessor {
2324 __u32 type_id; /* struct/union type or array element type */
2325 __u32 idx; /* field index or array index */
2326 const char *name; /* field name or NULL for array accessor */
2329 struct bpf_core_spec {
2330 const struct btf *btf;
2331 /* high-level spec: named fields and array indices only */
2332 struct bpf_core_accessor spec[BPF_CORE_SPEC_MAX_LEN];
2333 /* high-level spec length */
2335 /* raw, low-level spec: 1-to-1 with accessor spec string */
2336 int raw_spec[BPF_CORE_SPEC_MAX_LEN];
2337 /* raw spec length */
2339 /* field byte offset represented by spec */
2343 static bool str_is_empty(const char *s)
2349 * Turn bpf_field_reloc into a low- and high-level spec representation,
2350 * validating correctness along the way, as well as calculating resulting
2351 * field offset (in bytes), specified by accessor string. Low-level spec
2352 * captures every single level of nestedness, including traversing anonymous
2353 * struct/union members. High-level one only captures semantically meaningful
2354 * "turning points": named fields and array indicies.
2355 * E.g., for this case:
2358 * int __unimportant;
2366 * struct sample *s = ...;
2368 * int x = &s->a[3]; // access string = '0:1:2:3'
2370 * Low-level spec has 1:1 mapping with each element of access string (it's
2371 * just a parsed access string representation): [0, 1, 2, 3].
2373 * High-level spec will capture only 3 points:
2374 * - intial zero-index access by pointer (&s->... is the same as &s[0]...);
2375 * - field 'a' access (corresponds to '2' in low-level spec);
2376 * - array element #3 access (corresponds to '3' in low-level spec).
2379 static int bpf_core_spec_parse(const struct btf *btf,
2381 const char *spec_str,
2382 struct bpf_core_spec *spec)
2384 int access_idx, parsed_len, i;
2385 const struct btf_type *t;
2390 if (str_is_empty(spec_str) || *spec_str == ':')
2393 memset(spec, 0, sizeof(*spec));
2396 /* parse spec_str="0:1:2:3:4" into array raw_spec=[0, 1, 2, 3, 4] */
2398 if (*spec_str == ':')
2400 if (sscanf(spec_str, "%d%n", &access_idx, &parsed_len) != 1)
2402 if (spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
2404 spec_str += parsed_len;
2405 spec->raw_spec[spec->raw_len++] = access_idx;
2408 if (spec->raw_len == 0)
2411 /* first spec value is always reloc type array index */
2412 t = skip_mods_and_typedefs(btf, type_id, &id);
2416 access_idx = spec->raw_spec[0];
2417 spec->spec[0].type_id = id;
2418 spec->spec[0].idx = access_idx;
2421 sz = btf__resolve_size(btf, id);
2424 spec->offset = access_idx * sz;
2426 for (i = 1; i < spec->raw_len; i++) {
2427 t = skip_mods_and_typedefs(btf, id, &id);
2431 access_idx = spec->raw_spec[i];
2433 if (btf_is_composite(t)) {
2434 const struct btf_member *m;
2437 if (access_idx >= btf_vlen(t))
2439 if (btf_member_bitfield_size(t, access_idx))
2442 offset = btf_member_bit_offset(t, access_idx);
2445 spec->offset += offset / 8;
2447 m = btf_members(t) + access_idx;
2449 name = btf__name_by_offset(btf, m->name_off);
2450 if (str_is_empty(name))
2453 spec->spec[spec->len].type_id = id;
2454 spec->spec[spec->len].idx = access_idx;
2455 spec->spec[spec->len].name = name;
2460 } else if (btf_is_array(t)) {
2461 const struct btf_array *a = btf_array(t);
2463 t = skip_mods_and_typedefs(btf, a->type, &id);
2464 if (!t || access_idx >= a->nelems)
2467 spec->spec[spec->len].type_id = id;
2468 spec->spec[spec->len].idx = access_idx;
2471 sz = btf__resolve_size(btf, id);
2474 spec->offset += access_idx * sz;
2476 pr_warning("relo for [%u] %s (at idx %d) captures type [%d] of unexpected kind %d\n",
2477 type_id, spec_str, i, id, btf_kind(t));
2485 static bool bpf_core_is_flavor_sep(const char *s)
2487 /* check X___Y name pattern, where X and Y are not underscores */
2488 return s[0] != '_' && /* X */
2489 s[1] == '_' && s[2] == '_' && s[3] == '_' && /* ___ */
2490 s[4] != '_'; /* Y */
2493 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
2494 * before last triple underscore. Struct name part after last triple
2495 * underscore is ignored by BPF CO-RE relocation during relocation matching.
2497 static size_t bpf_core_essential_name_len(const char *name)
2499 size_t n = strlen(name);
2502 for (i = n - 5; i >= 0; i--) {
2503 if (bpf_core_is_flavor_sep(name + i))
2509 /* dynamically sized list of type IDs */
2515 static void bpf_core_free_cands(struct ids_vec *cand_ids)
2517 free(cand_ids->data);
2521 static struct ids_vec *bpf_core_find_cands(const struct btf *local_btf,
2522 __u32 local_type_id,
2523 const struct btf *targ_btf)
2525 size_t local_essent_len, targ_essent_len;
2526 const char *local_name, *targ_name;
2527 const struct btf_type *t;
2528 struct ids_vec *cand_ids;
2532 t = btf__type_by_id(local_btf, local_type_id);
2534 return ERR_PTR(-EINVAL);
2536 local_name = btf__name_by_offset(local_btf, t->name_off);
2537 if (str_is_empty(local_name))
2538 return ERR_PTR(-EINVAL);
2539 local_essent_len = bpf_core_essential_name_len(local_name);
2541 cand_ids = calloc(1, sizeof(*cand_ids));
2543 return ERR_PTR(-ENOMEM);
2545 n = btf__get_nr_types(targ_btf);
2546 for (i = 1; i <= n; i++) {
2547 t = btf__type_by_id(targ_btf, i);
2548 targ_name = btf__name_by_offset(targ_btf, t->name_off);
2549 if (str_is_empty(targ_name))
2552 targ_essent_len = bpf_core_essential_name_len(targ_name);
2553 if (targ_essent_len != local_essent_len)
2556 if (strncmp(local_name, targ_name, local_essent_len) == 0) {
2557 pr_debug("[%d] %s: found candidate [%d] %s\n",
2558 local_type_id, local_name, i, targ_name);
2559 new_ids = realloc(cand_ids->data, cand_ids->len + 1);
2564 cand_ids->data = new_ids;
2565 cand_ids->data[cand_ids->len++] = i;
2570 bpf_core_free_cands(cand_ids);
2571 return ERR_PTR(err);
2574 /* Check two types for compatibility, skipping const/volatile/restrict and
2575 * typedefs, to ensure we are relocating offset to the compatible entities:
2576 * - any two STRUCTs/UNIONs are compatible and can be mixed;
2577 * - any two FWDs are compatible;
2578 * - any two PTRs are always compatible;
2579 * - for ENUMs, check sizes, names are ignored;
2580 * - for INT, size and bitness should match, signedness is ignored;
2581 * - for ARRAY, dimensionality is ignored, element types are checked for
2582 * compatibility recursively;
2583 * - everything else shouldn't be ever a target of relocation.
2584 * These rules are not set in stone and probably will be adjusted as we get
2585 * more experience with using BPF CO-RE relocations.
2587 static int bpf_core_fields_are_compat(const struct btf *local_btf,
2589 const struct btf *targ_btf,
2592 const struct btf_type *local_type, *targ_type;
2595 local_type = skip_mods_and_typedefs(local_btf, local_id, &local_id);
2596 targ_type = skip_mods_and_typedefs(targ_btf, targ_id, &targ_id);
2597 if (!local_type || !targ_type)
2600 if (btf_is_composite(local_type) && btf_is_composite(targ_type))
2602 if (btf_kind(local_type) != btf_kind(targ_type))
2605 switch (btf_kind(local_type)) {
2610 return local_type->size == targ_type->size;
2612 return btf_int_offset(local_type) == 0 &&
2613 btf_int_offset(targ_type) == 0 &&
2614 local_type->size == targ_type->size &&
2615 btf_int_bits(local_type) == btf_int_bits(targ_type);
2616 case BTF_KIND_ARRAY:
2617 local_id = btf_array(local_type)->type;
2618 targ_id = btf_array(targ_type)->type;
2621 pr_warning("unexpected kind %d relocated, local [%d], target [%d]\n",
2622 btf_kind(local_type), local_id, targ_id);
2628 * Given single high-level named field accessor in local type, find
2629 * corresponding high-level accessor for a target type. Along the way,
2630 * maintain low-level spec for target as well. Also keep updating target
2633 * Searching is performed through recursive exhaustive enumeration of all
2634 * fields of a struct/union. If there are any anonymous (embedded)
2635 * structs/unions, they are recursively searched as well. If field with
2636 * desired name is found, check compatibility between local and target types,
2637 * before returning result.
2639 * 1 is returned, if field is found.
2640 * 0 is returned if no compatible field is found.
2641 * <0 is returned on error.
2643 static int bpf_core_match_member(const struct btf *local_btf,
2644 const struct bpf_core_accessor *local_acc,
2645 const struct btf *targ_btf,
2647 struct bpf_core_spec *spec,
2648 __u32 *next_targ_id)
2650 const struct btf_type *local_type, *targ_type;
2651 const struct btf_member *local_member, *m;
2652 const char *local_name, *targ_name;
2656 targ_type = skip_mods_and_typedefs(targ_btf, targ_id, &targ_id);
2659 if (!btf_is_composite(targ_type))
2662 local_id = local_acc->type_id;
2663 local_type = btf__type_by_id(local_btf, local_id);
2664 local_member = btf_members(local_type) + local_acc->idx;
2665 local_name = btf__name_by_offset(local_btf, local_member->name_off);
2667 n = btf_vlen(targ_type);
2668 m = btf_members(targ_type);
2669 for (i = 0; i < n; i++, m++) {
2672 /* bitfield relocations not supported */
2673 if (btf_member_bitfield_size(targ_type, i))
2675 offset = btf_member_bit_offset(targ_type, i);
2679 /* too deep struct/union/array nesting */
2680 if (spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
2683 /* speculate this member will be the good one */
2684 spec->offset += offset / 8;
2685 spec->raw_spec[spec->raw_len++] = i;
2687 targ_name = btf__name_by_offset(targ_btf, m->name_off);
2688 if (str_is_empty(targ_name)) {
2689 /* embedded struct/union, we need to go deeper */
2690 found = bpf_core_match_member(local_btf, local_acc,
2692 spec, next_targ_id);
2693 if (found) /* either found or error */
2695 } else if (strcmp(local_name, targ_name) == 0) {
2696 /* matching named field */
2697 struct bpf_core_accessor *targ_acc;
2699 targ_acc = &spec->spec[spec->len++];
2700 targ_acc->type_id = targ_id;
2702 targ_acc->name = targ_name;
2704 *next_targ_id = m->type;
2705 found = bpf_core_fields_are_compat(local_btf,
2709 spec->len--; /* pop accessor */
2712 /* member turned out not to be what we looked for */
2713 spec->offset -= offset / 8;
2721 * Try to match local spec to a target type and, if successful, produce full
2722 * target spec (high-level, low-level + offset).
2724 static int bpf_core_spec_match(struct bpf_core_spec *local_spec,
2725 const struct btf *targ_btf, __u32 targ_id,
2726 struct bpf_core_spec *targ_spec)
2728 const struct btf_type *targ_type;
2729 const struct bpf_core_accessor *local_acc;
2730 struct bpf_core_accessor *targ_acc;
2733 memset(targ_spec, 0, sizeof(*targ_spec));
2734 targ_spec->btf = targ_btf;
2736 local_acc = &local_spec->spec[0];
2737 targ_acc = &targ_spec->spec[0];
2739 for (i = 0; i < local_spec->len; i++, local_acc++, targ_acc++) {
2740 targ_type = skip_mods_and_typedefs(targ_spec->btf, targ_id,
2745 if (local_acc->name) {
2746 matched = bpf_core_match_member(local_spec->btf,
2749 targ_spec, &targ_id);
2753 /* for i=0, targ_id is already treated as array element
2754 * type (because it's the original struct), for others
2755 * we should find array element type first
2758 const struct btf_array *a;
2760 if (!btf_is_array(targ_type))
2763 a = btf_array(targ_type);
2764 if (local_acc->idx >= a->nelems)
2766 if (!skip_mods_and_typedefs(targ_btf, a->type,
2771 /* too deep struct/union/array nesting */
2772 if (targ_spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
2775 targ_acc->type_id = targ_id;
2776 targ_acc->idx = local_acc->idx;
2777 targ_acc->name = NULL;
2779 targ_spec->raw_spec[targ_spec->raw_len] = targ_acc->idx;
2780 targ_spec->raw_len++;
2782 sz = btf__resolve_size(targ_btf, targ_id);
2785 targ_spec->offset += local_acc->idx * sz;
2793 * Patch relocatable BPF instruction.
2795 * Patched value is determined by relocation kind and target specification.
2796 * For field existence relocation target spec will be NULL if field is not
2798 * Expected insn->imm value is determined using relocation kind and local
2799 * spec, and is checked before patching instruction. If actual insn->imm value
2800 * is wrong, bail out with error.
2802 * Currently three kinds of BPF instructions are supported:
2803 * 1. rX = <imm> (assignment with immediate operand);
2804 * 2. rX += <imm> (arithmetic operations with immediate operand);
2806 static int bpf_core_reloc_insn(struct bpf_program *prog,
2807 const struct bpf_field_reloc *relo,
2808 const struct bpf_core_spec *local_spec,
2809 const struct bpf_core_spec *targ_spec)
2811 __u32 orig_val, new_val;
2812 struct bpf_insn *insn;
2816 if (relo->insn_off % sizeof(struct bpf_insn))
2818 insn_idx = relo->insn_off / sizeof(struct bpf_insn);
2820 switch (relo->kind) {
2821 case BPF_FIELD_BYTE_OFFSET:
2822 orig_val = local_spec->offset;
2824 new_val = targ_spec->offset;
2826 pr_warning("prog '%s': patching insn #%d w/ failed reloc, imm %d -> %d\n",
2827 bpf_program__title(prog, false), insn_idx,
2829 new_val = (__u32)-1;
2832 case BPF_FIELD_EXISTS:
2833 orig_val = 1; /* can't generate EXISTS relo w/o local field */
2834 new_val = targ_spec ? 1 : 0;
2837 pr_warning("prog '%s': unknown relo %d at insn #%d'\n",
2838 bpf_program__title(prog, false),
2839 relo->kind, insn_idx);
2843 insn = &prog->insns[insn_idx];
2844 class = BPF_CLASS(insn->code);
2846 if (class == BPF_ALU || class == BPF_ALU64) {
2847 if (BPF_SRC(insn->code) != BPF_K)
2849 if (insn->imm != orig_val)
2851 insn->imm = new_val;
2852 pr_debug("prog '%s': patched insn #%d (ALU/ALU64) imm %d -> %d\n",
2853 bpf_program__title(prog, false),
2854 insn_idx, orig_val, new_val);
2856 pr_warning("prog '%s': trying to relocate unrecognized insn #%d, code:%x, src:%x, dst:%x, off:%x, imm:%x\n",
2857 bpf_program__title(prog, false),
2858 insn_idx, insn->code, insn->src_reg, insn->dst_reg,
2859 insn->off, insn->imm);
2866 static struct btf *btf_load_raw(const char *path)
2874 if (stat(path, &st))
2875 return ERR_PTR(-errno);
2877 data = malloc(st.st_size);
2879 return ERR_PTR(-ENOMEM);
2881 f = fopen(path, "rb");
2883 btf = ERR_PTR(-errno);
2887 read_cnt = fread(data, 1, st.st_size, f);
2889 if (read_cnt < st.st_size) {
2890 btf = ERR_PTR(-EBADF);
2894 btf = btf__new(data, read_cnt);
2902 * Probe few well-known locations for vmlinux kernel image and try to load BTF
2903 * data out of it to use for target BTF.
2905 static struct btf *bpf_core_find_kernel_btf(void)
2908 const char *path_fmt;
2911 /* try canonical vmlinux BTF through sysfs first */
2912 { "/sys/kernel/btf/vmlinux", true /* raw BTF */ },
2913 /* fall back to trying to find vmlinux ELF on disk otherwise */
2914 { "/boot/vmlinux-%1$s" },
2915 { "/lib/modules/%1$s/vmlinux-%1$s" },
2916 { "/lib/modules/%1$s/build/vmlinux" },
2917 { "/usr/lib/modules/%1$s/kernel/vmlinux" },
2918 { "/usr/lib/debug/boot/vmlinux-%1$s" },
2919 { "/usr/lib/debug/boot/vmlinux-%1$s.debug" },
2920 { "/usr/lib/debug/lib/modules/%1$s/vmlinux" },
2922 char path[PATH_MAX + 1];
2929 for (i = 0; i < ARRAY_SIZE(locations); i++) {
2930 snprintf(path, PATH_MAX, locations[i].path_fmt, buf.release);
2932 if (access(path, R_OK))
2935 if (locations[i].raw_btf)
2936 btf = btf_load_raw(path);
2938 btf = btf__parse_elf(path, NULL);
2940 pr_debug("loading kernel BTF '%s': %ld\n",
2941 path, IS_ERR(btf) ? PTR_ERR(btf) : 0);
2948 pr_warning("failed to find valid kernel BTF\n");
2949 return ERR_PTR(-ESRCH);
2952 /* Output spec definition in the format:
2953 * [<type-id>] (<type-name>) + <raw-spec> => <offset>@<spec>,
2954 * where <spec> is a C-syntax view of recorded field access, e.g.: x.a[3].b
2956 static void bpf_core_dump_spec(int level, const struct bpf_core_spec *spec)
2958 const struct btf_type *t;
2963 type_id = spec->spec[0].type_id;
2964 t = btf__type_by_id(spec->btf, type_id);
2965 s = btf__name_by_offset(spec->btf, t->name_off);
2966 libbpf_print(level, "[%u] %s + ", type_id, s);
2968 for (i = 0; i < spec->raw_len; i++)
2969 libbpf_print(level, "%d%s", spec->raw_spec[i],
2970 i == spec->raw_len - 1 ? " => " : ":");
2972 libbpf_print(level, "%u @ &x", spec->offset);
2974 for (i = 0; i < spec->len; i++) {
2975 if (spec->spec[i].name)
2976 libbpf_print(level, ".%s", spec->spec[i].name);
2978 libbpf_print(level, "[%u]", spec->spec[i].idx);
2983 static size_t bpf_core_hash_fn(const void *key, void *ctx)
2988 static bool bpf_core_equal_fn(const void *k1, const void *k2, void *ctx)
2993 static void *u32_as_hash_key(__u32 x)
2995 return (void *)(uintptr_t)x;
2999 * CO-RE relocate single instruction.
3001 * The outline and important points of the algorithm:
3002 * 1. For given local type, find corresponding candidate target types.
3003 * Candidate type is a type with the same "essential" name, ignoring
3004 * everything after last triple underscore (___). E.g., `sample`,
3005 * `sample___flavor_one`, `sample___flavor_another_one`, are all candidates
3006 * for each other. Names with triple underscore are referred to as
3007 * "flavors" and are useful, among other things, to allow to
3008 * specify/support incompatible variations of the same kernel struct, which
3009 * might differ between different kernel versions and/or build
3012 * N.B. Struct "flavors" could be generated by bpftool's BTF-to-C
3013 * converter, when deduplicated BTF of a kernel still contains more than
3014 * one different types with the same name. In that case, ___2, ___3, etc
3015 * are appended starting from second name conflict. But start flavors are
3016 * also useful to be defined "locally", in BPF program, to extract same
3017 * data from incompatible changes between different kernel
3018 * versions/configurations. For instance, to handle field renames between
3019 * kernel versions, one can use two flavors of the struct name with the
3020 * same common name and use conditional relocations to extract that field,
3021 * depending on target kernel version.
3022 * 2. For each candidate type, try to match local specification to this
3023 * candidate target type. Matching involves finding corresponding
3024 * high-level spec accessors, meaning that all named fields should match,
3025 * as well as all array accesses should be within the actual bounds. Also,
3026 * types should be compatible (see bpf_core_fields_are_compat for details).
3027 * 3. It is supported and expected that there might be multiple flavors
3028 * matching the spec. As long as all the specs resolve to the same set of
3029 * offsets across all candidates, there is no error. If there is any
3030 * ambiguity, CO-RE relocation will fail. This is necessary to accomodate
3031 * imprefection of BTF deduplication, which can cause slight duplication of
3032 * the same BTF type, if some directly or indirectly referenced (by
3033 * pointer) type gets resolved to different actual types in different
3034 * object files. If such situation occurs, deduplicated BTF will end up
3035 * with two (or more) structurally identical types, which differ only in
3036 * types they refer to through pointer. This should be OK in most cases and
3038 * 4. Candidate types search is performed by linearly scanning through all
3039 * types in target BTF. It is anticipated that this is overall more
3040 * efficient memory-wise and not significantly worse (if not better)
3041 * CPU-wise compared to prebuilding a map from all local type names to
3042 * a list of candidate type names. It's also sped up by caching resolved
3043 * list of matching candidates per each local "root" type ID, that has at
3044 * least one bpf_field_reloc associated with it. This list is shared
3045 * between multiple relocations for the same type ID and is updated as some
3046 * of the candidates are pruned due to structural incompatibility.
3048 static int bpf_core_reloc_field(struct bpf_program *prog,
3049 const struct bpf_field_reloc *relo,
3051 const struct btf *local_btf,
3052 const struct btf *targ_btf,
3053 struct hashmap *cand_cache)
3055 const char *prog_name = bpf_program__title(prog, false);
3056 struct bpf_core_spec local_spec, cand_spec, targ_spec;
3057 const void *type_key = u32_as_hash_key(relo->type_id);
3058 const struct btf_type *local_type, *cand_type;
3059 const char *local_name, *cand_name;
3060 struct ids_vec *cand_ids;
3061 __u32 local_id, cand_id;
3062 const char *spec_str;
3065 local_id = relo->type_id;
3066 local_type = btf__type_by_id(local_btf, local_id);
3070 local_name = btf__name_by_offset(local_btf, local_type->name_off);
3071 if (str_is_empty(local_name))
3074 spec_str = btf__name_by_offset(local_btf, relo->access_str_off);
3075 if (str_is_empty(spec_str))
3078 err = bpf_core_spec_parse(local_btf, local_id, spec_str, &local_spec);
3080 pr_warning("prog '%s': relo #%d: parsing [%d] %s + %s failed: %d\n",
3081 prog_name, relo_idx, local_id, local_name, spec_str,
3086 pr_debug("prog '%s': relo #%d: spec is ", prog_name, relo_idx);
3087 bpf_core_dump_spec(LIBBPF_DEBUG, &local_spec);
3088 libbpf_print(LIBBPF_DEBUG, "\n");
3090 if (!hashmap__find(cand_cache, type_key, (void **)&cand_ids)) {
3091 cand_ids = bpf_core_find_cands(local_btf, local_id, targ_btf);
3092 if (IS_ERR(cand_ids)) {
3093 pr_warning("prog '%s': relo #%d: target candidate search failed for [%d] %s: %ld",
3094 prog_name, relo_idx, local_id, local_name,
3096 return PTR_ERR(cand_ids);
3098 err = hashmap__set(cand_cache, type_key, cand_ids, NULL, NULL);
3100 bpf_core_free_cands(cand_ids);
3105 for (i = 0, j = 0; i < cand_ids->len; i++) {
3106 cand_id = cand_ids->data[i];
3107 cand_type = btf__type_by_id(targ_btf, cand_id);
3108 cand_name = btf__name_by_offset(targ_btf, cand_type->name_off);
3110 err = bpf_core_spec_match(&local_spec, targ_btf,
3111 cand_id, &cand_spec);
3112 pr_debug("prog '%s': relo #%d: matching candidate #%d %s against spec ",
3113 prog_name, relo_idx, i, cand_name);
3114 bpf_core_dump_spec(LIBBPF_DEBUG, &cand_spec);
3115 libbpf_print(LIBBPF_DEBUG, ": %d\n", err);
3117 pr_warning("prog '%s': relo #%d: matching error: %d\n",
3118 prog_name, relo_idx, err);
3125 targ_spec = cand_spec;
3126 } else if (cand_spec.offset != targ_spec.offset) {
3127 /* if there are many candidates, they should all
3128 * resolve to the same offset
3130 pr_warning("prog '%s': relo #%d: offset ambiguity: %u != %u\n",
3131 prog_name, relo_idx, cand_spec.offset,
3136 cand_ids->data[j++] = cand_spec.spec[0].type_id;
3140 * For BPF_FIELD_EXISTS relo or when relaxed CO-RE reloc mode is
3141 * requested, it's expected that we might not find any candidates.
3142 * In this case, if field wasn't found in any candidate, the list of
3143 * candidates shouldn't change at all, we'll just handle relocating
3144 * appropriately, depending on relo's kind.
3149 if (j == 0 && !prog->obj->relaxed_core_relocs &&
3150 relo->kind != BPF_FIELD_EXISTS) {
3151 pr_warning("prog '%s': relo #%d: no matching targets found for [%d] %s + %s\n",
3152 prog_name, relo_idx, local_id, local_name, spec_str);
3156 /* bpf_core_reloc_insn should know how to handle missing targ_spec */
3157 err = bpf_core_reloc_insn(prog, relo, &local_spec,
3158 j ? &targ_spec : NULL);
3160 pr_warning("prog '%s': relo #%d: failed to patch insn at offset %d: %d\n",
3161 prog_name, relo_idx, relo->insn_off, err);
3169 bpf_core_reloc_fields(struct bpf_object *obj, const char *targ_btf_path)
3171 const struct btf_ext_info_sec *sec;
3172 const struct bpf_field_reloc *rec;
3173 const struct btf_ext_info *seg;
3174 struct hashmap_entry *entry;
3175 struct hashmap *cand_cache = NULL;
3176 struct bpf_program *prog;
3177 struct btf *targ_btf;
3178 const char *sec_name;
3182 targ_btf = btf__parse_elf(targ_btf_path, NULL);
3184 targ_btf = bpf_core_find_kernel_btf();
3185 if (IS_ERR(targ_btf)) {
3186 pr_warning("failed to get target BTF: %ld\n",
3188 return PTR_ERR(targ_btf);
3191 cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
3192 if (IS_ERR(cand_cache)) {
3193 err = PTR_ERR(cand_cache);
3197 seg = &obj->btf_ext->field_reloc_info;
3198 for_each_btf_ext_sec(seg, sec) {
3199 sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
3200 if (str_is_empty(sec_name)) {
3204 prog = bpf_object__find_program_by_title(obj, sec_name);
3206 pr_warning("failed to find program '%s' for CO-RE offset relocation\n",
3212 pr_debug("prog '%s': performing %d CO-RE offset relocs\n",
3213 sec_name, sec->num_info);
3215 for_each_btf_ext_rec(seg, sec, i, rec) {
3216 err = bpf_core_reloc_field(prog, rec, i, obj->btf,
3217 targ_btf, cand_cache);
3219 pr_warning("prog '%s': relo #%d: failed to relocate: %d\n",
3227 btf__free(targ_btf);
3228 if (!IS_ERR_OR_NULL(cand_cache)) {
3229 hashmap__for_each_entry(cand_cache, entry, i) {
3230 bpf_core_free_cands(entry->value);
3232 hashmap__free(cand_cache);
3238 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
3242 if (obj->btf_ext->field_reloc_info.len)
3243 err = bpf_core_reloc_fields(obj, targ_btf_path);
3249 bpf_program__reloc_text(struct bpf_program *prog, struct bpf_object *obj,
3250 struct reloc_desc *relo)
3252 struct bpf_insn *insn, *new_insn;
3253 struct bpf_program *text;
3257 if (relo->type != RELO_CALL)
3258 return -LIBBPF_ERRNO__RELOC;
3260 if (prog->idx == obj->efile.text_shndx) {
3261 pr_warning("relo in .text insn %d into off %d\n",
3262 relo->insn_idx, relo->text_off);
3263 return -LIBBPF_ERRNO__RELOC;
3266 if (prog->main_prog_cnt == 0) {
3267 text = bpf_object__find_prog_by_idx(obj, obj->efile.text_shndx);
3269 pr_warning("no .text section found yet relo into text exist\n");
3270 return -LIBBPF_ERRNO__RELOC;
3272 new_cnt = prog->insns_cnt + text->insns_cnt;
3273 new_insn = reallocarray(prog->insns, new_cnt, sizeof(*insn));
3275 pr_warning("oom in prog realloc\n");
3280 err = bpf_program_reloc_btf_ext(prog, obj,
3287 memcpy(new_insn + prog->insns_cnt, text->insns,
3288 text->insns_cnt * sizeof(*insn));
3289 prog->insns = new_insn;
3290 prog->main_prog_cnt = prog->insns_cnt;
3291 prog->insns_cnt = new_cnt;
3292 pr_debug("added %zd insn from %s to prog %s\n",
3293 text->insns_cnt, text->section_name,
3294 prog->section_name);
3296 insn = &prog->insns[relo->insn_idx];
3297 insn->imm += prog->main_prog_cnt - relo->insn_idx;
3302 bpf_program__relocate(struct bpf_program *prog, struct bpf_object *obj)
3310 err = bpf_program_reloc_btf_ext(prog, obj,
3311 prog->section_name, 0);
3316 if (!prog->reloc_desc)
3319 for (i = 0; i < prog->nr_reloc; i++) {
3320 if (prog->reloc_desc[i].type == RELO_LD64 ||
3321 prog->reloc_desc[i].type == RELO_DATA) {
3322 bool relo_data = prog->reloc_desc[i].type == RELO_DATA;
3323 struct bpf_insn *insns = prog->insns;
3324 int insn_idx, map_idx;
3326 insn_idx = prog->reloc_desc[i].insn_idx;
3327 map_idx = prog->reloc_desc[i].map_idx;
3329 if (insn_idx + 1 >= (int)prog->insns_cnt) {
3330 pr_warning("relocation out of range: '%s'\n",
3331 prog->section_name);
3332 return -LIBBPF_ERRNO__RELOC;
3336 insns[insn_idx].src_reg = BPF_PSEUDO_MAP_FD;
3338 insns[insn_idx].src_reg = BPF_PSEUDO_MAP_VALUE;
3339 insns[insn_idx + 1].imm = insns[insn_idx].imm;
3341 insns[insn_idx].imm = obj->maps[map_idx].fd;
3342 } else if (prog->reloc_desc[i].type == RELO_CALL) {
3343 err = bpf_program__reloc_text(prog, obj,
3344 &prog->reloc_desc[i]);
3350 zfree(&prog->reloc_desc);
3356 bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
3358 struct bpf_program *prog;
3363 err = bpf_object__relocate_core(obj, targ_btf_path);
3365 pr_warning("failed to perform CO-RE relocations: %d\n",
3370 for (i = 0; i < obj->nr_programs; i++) {
3371 prog = &obj->programs[i];
3373 err = bpf_program__relocate(prog, obj);
3375 pr_warning("failed to relocate '%s'\n",
3376 prog->section_name);
3383 static int bpf_object__collect_reloc(struct bpf_object *obj)
3387 if (!obj_elf_valid(obj)) {
3388 pr_warning("Internal error: elf object is closed\n");
3389 return -LIBBPF_ERRNO__INTERNAL;
3392 for (i = 0; i < obj->efile.nr_reloc; i++) {
3393 GElf_Shdr *shdr = &obj->efile.reloc[i].shdr;
3394 Elf_Data *data = obj->efile.reloc[i].data;
3395 int idx = shdr->sh_info;
3396 struct bpf_program *prog;
3398 if (shdr->sh_type != SHT_REL) {
3399 pr_warning("internal error at %d\n", __LINE__);
3400 return -LIBBPF_ERRNO__INTERNAL;
3403 prog = bpf_object__find_prog_by_idx(obj, idx);
3405 pr_warning("relocation failed: no section(%d)\n", idx);
3406 return -LIBBPF_ERRNO__RELOC;
3409 err = bpf_program__collect_reloc(prog, shdr, data, obj);
3417 load_program(struct bpf_program *prog, struct bpf_insn *insns, int insns_cnt,
3418 char *license, __u32 kern_version, int *pfd)
3420 struct bpf_load_program_attr load_attr;
3421 char *cp, errmsg[STRERR_BUFSIZE];
3422 int log_buf_size = BPF_LOG_BUF_SIZE;
3426 if (!insns || !insns_cnt)
3429 memset(&load_attr, 0, sizeof(struct bpf_load_program_attr));
3430 load_attr.prog_type = prog->type;
3431 load_attr.expected_attach_type = prog->expected_attach_type;
3432 if (prog->caps->name)
3433 load_attr.name = prog->name;
3434 load_attr.insns = insns;
3435 load_attr.insns_cnt = insns_cnt;
3436 load_attr.license = license;
3437 load_attr.kern_version = kern_version;
3438 load_attr.prog_ifindex = prog->prog_ifindex;
3439 /* if .BTF.ext was loaded, kernel supports associated BTF for prog */
3440 if (prog->obj->btf_ext)
3441 btf_fd = bpf_object__btf_fd(prog->obj);
3444 load_attr.prog_btf_fd = btf_fd >= 0 ? btf_fd : 0;
3445 load_attr.func_info = prog->func_info;
3446 load_attr.func_info_rec_size = prog->func_info_rec_size;
3447 load_attr.func_info_cnt = prog->func_info_cnt;
3448 load_attr.line_info = prog->line_info;
3449 load_attr.line_info_rec_size = prog->line_info_rec_size;
3450 load_attr.line_info_cnt = prog->line_info_cnt;
3451 load_attr.log_level = prog->log_level;
3452 load_attr.prog_flags = prog->prog_flags;
3455 log_buf = malloc(log_buf_size);
3457 pr_warning("Alloc log buffer for bpf loader error, continue without log\n");
3459 ret = bpf_load_program_xattr(&load_attr, log_buf, log_buf_size);
3462 if (load_attr.log_level)
3463 pr_debug("verifier log:\n%s", log_buf);
3469 if (errno == ENOSPC) {
3474 ret = -LIBBPF_ERRNO__LOAD;
3475 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
3476 pr_warning("load bpf program failed: %s\n", cp);
3478 if (log_buf && log_buf[0] != '\0') {
3479 ret = -LIBBPF_ERRNO__VERIFY;
3480 pr_warning("-- BEGIN DUMP LOG ---\n");
3481 pr_warning("\n%s\n", log_buf);
3482 pr_warning("-- END LOG --\n");
3483 } else if (load_attr.insns_cnt >= BPF_MAXINSNS) {
3484 pr_warning("Program too large (%zu insns), at most %d insns\n",
3485 load_attr.insns_cnt, BPF_MAXINSNS);
3486 ret = -LIBBPF_ERRNO__PROG2BIG;
3488 /* Wrong program type? */
3489 if (load_attr.prog_type != BPF_PROG_TYPE_KPROBE) {
3492 load_attr.prog_type = BPF_PROG_TYPE_KPROBE;
3493 load_attr.expected_attach_type = 0;
3494 fd = bpf_load_program_xattr(&load_attr, NULL, 0);
3497 ret = -LIBBPF_ERRNO__PROGTYPE;
3503 ret = -LIBBPF_ERRNO__KVER;
3512 bpf_program__load(struct bpf_program *prog,
3513 char *license, __u32 kern_version)
3517 if (prog->instances.nr < 0 || !prog->instances.fds) {
3518 if (prog->preprocessor) {
3519 pr_warning("Internal error: can't load program '%s'\n",
3520 prog->section_name);
3521 return -LIBBPF_ERRNO__INTERNAL;
3524 prog->instances.fds = malloc(sizeof(int));
3525 if (!prog->instances.fds) {
3526 pr_warning("Not enough memory for BPF fds\n");
3529 prog->instances.nr = 1;
3530 prog->instances.fds[0] = -1;
3533 if (!prog->preprocessor) {
3534 if (prog->instances.nr != 1) {
3535 pr_warning("Program '%s' is inconsistent: nr(%d) != 1\n",
3536 prog->section_name, prog->instances.nr);
3538 err = load_program(prog, prog->insns, prog->insns_cnt,
3539 license, kern_version, &fd);
3541 prog->instances.fds[0] = fd;
3545 for (i = 0; i < prog->instances.nr; i++) {
3546 struct bpf_prog_prep_result result;
3547 bpf_program_prep_t preprocessor = prog->preprocessor;
3549 memset(&result, 0, sizeof(result));
3550 err = preprocessor(prog, i, prog->insns,
3551 prog->insns_cnt, &result);
3553 pr_warning("Preprocessing the %dth instance of program '%s' failed\n",
3554 i, prog->section_name);
3558 if (!result.new_insn_ptr || !result.new_insn_cnt) {
3559 pr_debug("Skip loading the %dth instance of program '%s'\n",
3560 i, prog->section_name);
3561 prog->instances.fds[i] = -1;
3567 err = load_program(prog, result.new_insn_ptr,
3568 result.new_insn_cnt,
3569 license, kern_version, &fd);
3572 pr_warning("Loading the %dth instance of program '%s' failed\n",
3573 i, prog->section_name);
3579 prog->instances.fds[i] = fd;
3583 pr_warning("failed to load program '%s'\n",
3584 prog->section_name);
3585 zfree(&prog->insns);
3586 prog->insns_cnt = 0;
3590 static bool bpf_program__is_function_storage(const struct bpf_program *prog,
3591 const struct bpf_object *obj)
3593 return prog->idx == obj->efile.text_shndx && obj->has_pseudo_calls;
3597 bpf_object__load_progs(struct bpf_object *obj, int log_level)
3602 for (i = 0; i < obj->nr_programs; i++) {
3603 if (bpf_program__is_function_storage(&obj->programs[i], obj))
3605 obj->programs[i].log_level |= log_level;
3606 err = bpf_program__load(&obj->programs[i],
3615 static struct bpf_object *
3616 __bpf_object__open(const char *path, const void *obj_buf, size_t obj_buf_sz,
3617 struct bpf_object_open_opts *opts)
3619 struct bpf_object *obj;
3620 const char *obj_name;
3625 if (elf_version(EV_CURRENT) == EV_NONE) {
3626 pr_warning("failed to init libelf for %s\n",
3627 path ? : "(mem buf)");
3628 return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
3631 if (!OPTS_VALID(opts, bpf_object_open_opts))
3632 return ERR_PTR(-EINVAL);
3634 obj_name = OPTS_GET(opts, object_name, path);
3637 snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
3638 (unsigned long)obj_buf,
3639 (unsigned long)obj_buf_sz);
3640 obj_name = tmp_name;
3643 pr_debug("loading object '%s' from buffer\n", obj_name);
3646 obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
3650 obj->relaxed_core_relocs = OPTS_GET(opts, relaxed_core_relocs, false);
3651 relaxed_maps = OPTS_GET(opts, relaxed_maps, false);
3653 CHECK_ERR(bpf_object__elf_init(obj), err, out);
3654 CHECK_ERR(bpf_object__check_endianness(obj), err, out);
3655 CHECK_ERR(bpf_object__probe_caps(obj), err, out);
3656 CHECK_ERR(bpf_object__elf_collect(obj, relaxed_maps), err, out);
3657 CHECK_ERR(bpf_object__collect_reloc(obj), err, out);
3659 bpf_object__elf_finish(obj);
3662 bpf_object__close(obj);
3663 return ERR_PTR(err);
3666 static struct bpf_object *
3667 __bpf_object__open_xattr(struct bpf_object_open_attr *attr, int flags)
3669 LIBBPF_OPTS(bpf_object_open_opts, opts,
3670 .relaxed_maps = flags & MAPS_RELAX_COMPAT,
3673 /* param validation */
3677 pr_debug("loading %s\n", attr->file);
3678 return __bpf_object__open(attr->file, NULL, 0, &opts);
3681 struct bpf_object *bpf_object__open_xattr(struct bpf_object_open_attr *attr)
3683 return __bpf_object__open_xattr(attr, 0);
3686 struct bpf_object *bpf_object__open(const char *path)
3688 struct bpf_object_open_attr attr = {
3690 .prog_type = BPF_PROG_TYPE_UNSPEC,
3693 return bpf_object__open_xattr(&attr);
3697 bpf_object__open_file(const char *path, struct bpf_object_open_opts *opts)
3700 return ERR_PTR(-EINVAL);
3702 pr_debug("loading %s\n", path);
3704 return __bpf_object__open(path, NULL, 0, opts);
3708 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
3709 struct bpf_object_open_opts *opts)
3711 if (!obj_buf || obj_buf_sz == 0)
3712 return ERR_PTR(-EINVAL);
3714 return __bpf_object__open(NULL, obj_buf, obj_buf_sz, opts);
3718 bpf_object__open_buffer(const void *obj_buf, size_t obj_buf_sz,
3721 LIBBPF_OPTS(bpf_object_open_opts, opts,
3722 .object_name = name,
3723 /* wrong default, but backwards-compatible */
3724 .relaxed_maps = true,
3727 /* returning NULL is wrong, but backwards-compatible */
3728 if (!obj_buf || obj_buf_sz == 0)
3731 return bpf_object__open_mem(obj_buf, obj_buf_sz, &opts);
3734 int bpf_object__unload(struct bpf_object *obj)
3741 for (i = 0; i < obj->nr_maps; i++)
3742 zclose(obj->maps[i].fd);
3744 for (i = 0; i < obj->nr_programs; i++)
3745 bpf_program__unload(&obj->programs[i]);
3750 int bpf_object__load_xattr(struct bpf_object_load_attr *attr)
3752 struct bpf_object *obj;
3762 pr_warning("object should not be loaded twice\n");
3768 CHECK_ERR(bpf_object__create_maps(obj), err, out);
3769 CHECK_ERR(bpf_object__relocate(obj, attr->target_btf_path), err, out);
3770 CHECK_ERR(bpf_object__load_progs(obj, attr->log_level), err, out);
3774 bpf_object__unload(obj);
3775 pr_warning("failed to load object '%s'\n", obj->path);
3779 int bpf_object__load(struct bpf_object *obj)
3781 struct bpf_object_load_attr attr = {
3785 return bpf_object__load_xattr(&attr);
3788 static int check_path(const char *path)
3790 char *cp, errmsg[STRERR_BUFSIZE];
3791 struct statfs st_fs;
3798 dname = strdup(path);
3802 dir = dirname(dname);
3803 if (statfs(dir, &st_fs)) {
3804 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
3805 pr_warning("failed to statfs %s: %s\n", dir, cp);
3810 if (!err && st_fs.f_type != BPF_FS_MAGIC) {
3811 pr_warning("specified path %s is not on BPF FS\n", path);
3818 int bpf_program__pin_instance(struct bpf_program *prog, const char *path,
3821 char *cp, errmsg[STRERR_BUFSIZE];
3824 err = check_path(path);
3829 pr_warning("invalid program pointer\n");
3833 if (instance < 0 || instance >= prog->instances.nr) {
3834 pr_warning("invalid prog instance %d of prog %s (max %d)\n",
3835 instance, prog->section_name, prog->instances.nr);
3839 if (bpf_obj_pin(prog->instances.fds[instance], path)) {
3840 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
3841 pr_warning("failed to pin program: %s\n", cp);
3844 pr_debug("pinned program '%s'\n", path);
3849 int bpf_program__unpin_instance(struct bpf_program *prog, const char *path,
3854 err = check_path(path);
3859 pr_warning("invalid program pointer\n");
3863 if (instance < 0 || instance >= prog->instances.nr) {
3864 pr_warning("invalid prog instance %d of prog %s (max %d)\n",
3865 instance, prog->section_name, prog->instances.nr);
3872 pr_debug("unpinned program '%s'\n", path);
3877 static int make_dir(const char *path)
3879 char *cp, errmsg[STRERR_BUFSIZE];
3882 if (mkdir(path, 0700) && errno != EEXIST)
3886 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
3887 pr_warning("failed to mkdir %s: %s\n", path, cp);
3892 int bpf_program__pin(struct bpf_program *prog, const char *path)
3896 err = check_path(path);
3901 pr_warning("invalid program pointer\n");
3905 if (prog->instances.nr <= 0) {
3906 pr_warning("no instances of prog %s to pin\n",
3907 prog->section_name);
3911 if (prog->instances.nr == 1) {
3912 /* don't create subdirs when pinning single instance */
3913 return bpf_program__pin_instance(prog, path, 0);
3916 err = make_dir(path);
3920 for (i = 0; i < prog->instances.nr; i++) {
3924 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
3928 } else if (len >= PATH_MAX) {
3929 err = -ENAMETOOLONG;
3933 err = bpf_program__pin_instance(prog, buf, i);
3941 for (i = i - 1; i >= 0; i--) {
3945 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
3948 else if (len >= PATH_MAX)
3951 bpf_program__unpin_instance(prog, buf, i);
3959 int bpf_program__unpin(struct bpf_program *prog, const char *path)
3963 err = check_path(path);
3968 pr_warning("invalid program pointer\n");
3972 if (prog->instances.nr <= 0) {
3973 pr_warning("no instances of prog %s to pin\n",
3974 prog->section_name);
3978 if (prog->instances.nr == 1) {
3979 /* don't create subdirs when pinning single instance */
3980 return bpf_program__unpin_instance(prog, path, 0);
3983 for (i = 0; i < prog->instances.nr; i++) {
3987 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
3990 else if (len >= PATH_MAX)
3991 return -ENAMETOOLONG;
3993 err = bpf_program__unpin_instance(prog, buf, i);
4005 int bpf_map__pin(struct bpf_map *map, const char *path)
4007 char *cp, errmsg[STRERR_BUFSIZE];
4010 err = check_path(path);
4015 pr_warning("invalid map pointer\n");
4019 if (bpf_obj_pin(map->fd, path)) {
4020 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
4021 pr_warning("failed to pin map: %s\n", cp);
4025 pr_debug("pinned map '%s'\n", path);
4030 int bpf_map__unpin(struct bpf_map *map, const char *path)
4034 err = check_path(path);
4039 pr_warning("invalid map pointer\n");
4046 pr_debug("unpinned map '%s'\n", path);
4051 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
4053 struct bpf_map *map;
4060 pr_warning("object not yet loaded; load it first\n");
4064 err = make_dir(path);
4068 bpf_object__for_each_map(map, obj) {
4072 len = snprintf(buf, PATH_MAX, "%s/%s", path,
4073 bpf_map__name(map));
4076 goto err_unpin_maps;
4077 } else if (len >= PATH_MAX) {
4078 err = -ENAMETOOLONG;
4079 goto err_unpin_maps;
4082 err = bpf_map__pin(map, buf);
4084 goto err_unpin_maps;
4090 while ((map = bpf_map__prev(map, obj))) {
4094 len = snprintf(buf, PATH_MAX, "%s/%s", path,
4095 bpf_map__name(map));
4098 else if (len >= PATH_MAX)
4101 bpf_map__unpin(map, buf);
4107 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
4109 struct bpf_map *map;
4115 bpf_object__for_each_map(map, obj) {
4119 len = snprintf(buf, PATH_MAX, "%s/%s", path,
4120 bpf_map__name(map));
4123 else if (len >= PATH_MAX)
4124 return -ENAMETOOLONG;
4126 err = bpf_map__unpin(map, buf);
4134 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
4136 struct bpf_program *prog;
4143 pr_warning("object not yet loaded; load it first\n");
4147 err = make_dir(path);
4151 bpf_object__for_each_program(prog, obj) {
4155 len = snprintf(buf, PATH_MAX, "%s/%s", path,
4159 goto err_unpin_programs;
4160 } else if (len >= PATH_MAX) {
4161 err = -ENAMETOOLONG;
4162 goto err_unpin_programs;
4165 err = bpf_program__pin(prog, buf);
4167 goto err_unpin_programs;
4173 while ((prog = bpf_program__prev(prog, obj))) {
4177 len = snprintf(buf, PATH_MAX, "%s/%s", path,
4181 else if (len >= PATH_MAX)
4184 bpf_program__unpin(prog, buf);
4190 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
4192 struct bpf_program *prog;
4198 bpf_object__for_each_program(prog, obj) {
4202 len = snprintf(buf, PATH_MAX, "%s/%s", path,
4206 else if (len >= PATH_MAX)
4207 return -ENAMETOOLONG;
4209 err = bpf_program__unpin(prog, buf);
4217 int bpf_object__pin(struct bpf_object *obj, const char *path)
4221 err = bpf_object__pin_maps(obj, path);
4225 err = bpf_object__pin_programs(obj, path);
4227 bpf_object__unpin_maps(obj, path);
4234 void bpf_object__close(struct bpf_object *obj)
4241 if (obj->clear_priv)
4242 obj->clear_priv(obj, obj->priv);
4244 bpf_object__elf_finish(obj);
4245 bpf_object__unload(obj);
4246 btf__free(obj->btf);
4247 btf_ext__free(obj->btf_ext);
4249 for (i = 0; i < obj->nr_maps; i++) {
4250 zfree(&obj->maps[i].name);
4251 if (obj->maps[i].clear_priv)
4252 obj->maps[i].clear_priv(&obj->maps[i],
4254 obj->maps[i].priv = NULL;
4255 obj->maps[i].clear_priv = NULL;
4258 zfree(&obj->sections.rodata);
4259 zfree(&obj->sections.data);
4263 if (obj->programs && obj->nr_programs) {
4264 for (i = 0; i < obj->nr_programs; i++)
4265 bpf_program__exit(&obj->programs[i]);
4267 zfree(&obj->programs);
4269 list_del(&obj->list);
4274 bpf_object__next(struct bpf_object *prev)
4276 struct bpf_object *next;
4279 next = list_first_entry(&bpf_objects_list,
4283 next = list_next_entry(prev, list);
4285 /* Empty list is noticed here so don't need checking on entry. */
4286 if (&next->list == &bpf_objects_list)
4292 const char *bpf_object__name(const struct bpf_object *obj)
4294 return obj ? obj->name : ERR_PTR(-EINVAL);
4297 unsigned int bpf_object__kversion(const struct bpf_object *obj)
4299 return obj ? obj->kern_version : 0;
4302 struct btf *bpf_object__btf(const struct bpf_object *obj)
4304 return obj ? obj->btf : NULL;
4307 int bpf_object__btf_fd(const struct bpf_object *obj)
4309 return obj->btf ? btf__fd(obj->btf) : -1;
4312 int bpf_object__set_priv(struct bpf_object *obj, void *priv,
4313 bpf_object_clear_priv_t clear_priv)
4315 if (obj->priv && obj->clear_priv)
4316 obj->clear_priv(obj, obj->priv);
4319 obj->clear_priv = clear_priv;
4323 void *bpf_object__priv(const struct bpf_object *obj)
4325 return obj ? obj->priv : ERR_PTR(-EINVAL);
4328 static struct bpf_program *
4329 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
4332 size_t nr_programs = obj->nr_programs;
4339 /* Iter from the beginning */
4340 return forward ? &obj->programs[0] :
4341 &obj->programs[nr_programs - 1];
4343 if (p->obj != obj) {
4344 pr_warning("error: program handler doesn't match object\n");
4348 idx = (p - obj->programs) + (forward ? 1 : -1);
4349 if (idx >= obj->nr_programs || idx < 0)
4351 return &obj->programs[idx];
4354 struct bpf_program *
4355 bpf_program__next(struct bpf_program *prev, const struct bpf_object *obj)
4357 struct bpf_program *prog = prev;
4360 prog = __bpf_program__iter(prog, obj, true);
4361 } while (prog && bpf_program__is_function_storage(prog, obj));
4366 struct bpf_program *
4367 bpf_program__prev(struct bpf_program *next, const struct bpf_object *obj)
4369 struct bpf_program *prog = next;
4372 prog = __bpf_program__iter(prog, obj, false);
4373 } while (prog && bpf_program__is_function_storage(prog, obj));
4378 int bpf_program__set_priv(struct bpf_program *prog, void *priv,
4379 bpf_program_clear_priv_t clear_priv)
4381 if (prog->priv && prog->clear_priv)
4382 prog->clear_priv(prog, prog->priv);
4385 prog->clear_priv = clear_priv;
4389 void *bpf_program__priv(const struct bpf_program *prog)
4391 return prog ? prog->priv : ERR_PTR(-EINVAL);
4394 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
4396 prog->prog_ifindex = ifindex;
4399 const char *bpf_program__title(const struct bpf_program *prog, bool needs_copy)
4403 title = prog->section_name;
4405 title = strdup(title);
4407 pr_warning("failed to strdup program title\n");
4408 return ERR_PTR(-ENOMEM);
4415 int bpf_program__fd(const struct bpf_program *prog)
4417 return bpf_program__nth_fd(prog, 0);
4420 int bpf_program__set_prep(struct bpf_program *prog, int nr_instances,
4421 bpf_program_prep_t prep)
4425 if (nr_instances <= 0 || !prep)
4428 if (prog->instances.nr > 0 || prog->instances.fds) {
4429 pr_warning("Can't set pre-processor after loading\n");
4433 instances_fds = malloc(sizeof(int) * nr_instances);
4434 if (!instances_fds) {
4435 pr_warning("alloc memory failed for fds\n");
4439 /* fill all fd with -1 */
4440 memset(instances_fds, -1, sizeof(int) * nr_instances);
4442 prog->instances.nr = nr_instances;
4443 prog->instances.fds = instances_fds;
4444 prog->preprocessor = prep;
4448 int bpf_program__nth_fd(const struct bpf_program *prog, int n)
4455 if (n >= prog->instances.nr || n < 0) {
4456 pr_warning("Can't get the %dth fd from program %s: only %d instances\n",
4457 n, prog->section_name, prog->instances.nr);
4461 fd = prog->instances.fds[n];
4463 pr_warning("%dth instance of program '%s' is invalid\n",
4464 n, prog->section_name);
4471 void bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
4476 static bool bpf_program__is_type(const struct bpf_program *prog,
4477 enum bpf_prog_type type)
4479 return prog ? (prog->type == type) : false;
4482 #define BPF_PROG_TYPE_FNS(NAME, TYPE) \
4483 int bpf_program__set_##NAME(struct bpf_program *prog) \
4487 bpf_program__set_type(prog, TYPE); \
4491 bool bpf_program__is_##NAME(const struct bpf_program *prog) \
4493 return bpf_program__is_type(prog, TYPE); \
4496 BPF_PROG_TYPE_FNS(socket_filter, BPF_PROG_TYPE_SOCKET_FILTER);
4497 BPF_PROG_TYPE_FNS(kprobe, BPF_PROG_TYPE_KPROBE);
4498 BPF_PROG_TYPE_FNS(sched_cls, BPF_PROG_TYPE_SCHED_CLS);
4499 BPF_PROG_TYPE_FNS(sched_act, BPF_PROG_TYPE_SCHED_ACT);
4500 BPF_PROG_TYPE_FNS(tracepoint, BPF_PROG_TYPE_TRACEPOINT);
4501 BPF_PROG_TYPE_FNS(raw_tracepoint, BPF_PROG_TYPE_RAW_TRACEPOINT);
4502 BPF_PROG_TYPE_FNS(xdp, BPF_PROG_TYPE_XDP);
4503 BPF_PROG_TYPE_FNS(perf_event, BPF_PROG_TYPE_PERF_EVENT);
4505 void bpf_program__set_expected_attach_type(struct bpf_program *prog,
4506 enum bpf_attach_type type)
4508 prog->expected_attach_type = type;
4511 #define BPF_PROG_SEC_IMPL(string, ptype, eatype, is_attachable, btf, atype) \
4512 { string, sizeof(string) - 1, ptype, eatype, is_attachable, btf, atype }
4514 /* Programs that can NOT be attached. */
4515 #define BPF_PROG_SEC(string, ptype) BPF_PROG_SEC_IMPL(string, ptype, 0, 0, 0, 0)
4517 /* Programs that can be attached. */
4518 #define BPF_APROG_SEC(string, ptype, atype) \
4519 BPF_PROG_SEC_IMPL(string, ptype, 0, 1, 0, atype)
4521 /* Programs that must specify expected attach type at load time. */
4522 #define BPF_EAPROG_SEC(string, ptype, eatype) \
4523 BPF_PROG_SEC_IMPL(string, ptype, eatype, 1, 0, eatype)
4525 /* Programs that use BTF to identify attach point */
4526 #define BPF_PROG_BTF(string, ptype) BPF_PROG_SEC_IMPL(string, ptype, 0, 0, 1, 0)
4528 /* Programs that can be attached but attach type can't be identified by section
4529 * name. Kept for backward compatibility.
4531 #define BPF_APROG_COMPAT(string, ptype) BPF_PROG_SEC(string, ptype)
4533 static const struct {
4536 enum bpf_prog_type prog_type;
4537 enum bpf_attach_type expected_attach_type;
4540 enum bpf_attach_type attach_type;
4541 } section_names[] = {
4542 BPF_PROG_SEC("socket", BPF_PROG_TYPE_SOCKET_FILTER),
4543 BPF_PROG_SEC("kprobe/", BPF_PROG_TYPE_KPROBE),
4544 BPF_PROG_SEC("kretprobe/", BPF_PROG_TYPE_KPROBE),
4545 BPF_PROG_SEC("classifier", BPF_PROG_TYPE_SCHED_CLS),
4546 BPF_PROG_SEC("action", BPF_PROG_TYPE_SCHED_ACT),
4547 BPF_PROG_SEC("tracepoint/", BPF_PROG_TYPE_TRACEPOINT),
4548 BPF_PROG_SEC("raw_tracepoint/", BPF_PROG_TYPE_RAW_TRACEPOINT),
4549 BPF_PROG_BTF("tp_btf/", BPF_PROG_TYPE_RAW_TRACEPOINT),
4550 BPF_PROG_SEC("xdp", BPF_PROG_TYPE_XDP),
4551 BPF_PROG_SEC("perf_event", BPF_PROG_TYPE_PERF_EVENT),
4552 BPF_PROG_SEC("lwt_in", BPF_PROG_TYPE_LWT_IN),
4553 BPF_PROG_SEC("lwt_out", BPF_PROG_TYPE_LWT_OUT),
4554 BPF_PROG_SEC("lwt_xmit", BPF_PROG_TYPE_LWT_XMIT),
4555 BPF_PROG_SEC("lwt_seg6local", BPF_PROG_TYPE_LWT_SEG6LOCAL),
4556 BPF_APROG_SEC("cgroup_skb/ingress", BPF_PROG_TYPE_CGROUP_SKB,
4557 BPF_CGROUP_INET_INGRESS),
4558 BPF_APROG_SEC("cgroup_skb/egress", BPF_PROG_TYPE_CGROUP_SKB,
4559 BPF_CGROUP_INET_EGRESS),
4560 BPF_APROG_COMPAT("cgroup/skb", BPF_PROG_TYPE_CGROUP_SKB),
4561 BPF_APROG_SEC("cgroup/sock", BPF_PROG_TYPE_CGROUP_SOCK,
4562 BPF_CGROUP_INET_SOCK_CREATE),
4563 BPF_EAPROG_SEC("cgroup/post_bind4", BPF_PROG_TYPE_CGROUP_SOCK,
4564 BPF_CGROUP_INET4_POST_BIND),
4565 BPF_EAPROG_SEC("cgroup/post_bind6", BPF_PROG_TYPE_CGROUP_SOCK,
4566 BPF_CGROUP_INET6_POST_BIND),
4567 BPF_APROG_SEC("cgroup/dev", BPF_PROG_TYPE_CGROUP_DEVICE,
4569 BPF_APROG_SEC("sockops", BPF_PROG_TYPE_SOCK_OPS,
4570 BPF_CGROUP_SOCK_OPS),
4571 BPF_APROG_SEC("sk_skb/stream_parser", BPF_PROG_TYPE_SK_SKB,
4572 BPF_SK_SKB_STREAM_PARSER),
4573 BPF_APROG_SEC("sk_skb/stream_verdict", BPF_PROG_TYPE_SK_SKB,
4574 BPF_SK_SKB_STREAM_VERDICT),
4575 BPF_APROG_COMPAT("sk_skb", BPF_PROG_TYPE_SK_SKB),
4576 BPF_APROG_SEC("sk_msg", BPF_PROG_TYPE_SK_MSG,
4577 BPF_SK_MSG_VERDICT),
4578 BPF_APROG_SEC("lirc_mode2", BPF_PROG_TYPE_LIRC_MODE2,
4580 BPF_APROG_SEC("flow_dissector", BPF_PROG_TYPE_FLOW_DISSECTOR,
4581 BPF_FLOW_DISSECTOR),
4582 BPF_EAPROG_SEC("cgroup/bind4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
4583 BPF_CGROUP_INET4_BIND),
4584 BPF_EAPROG_SEC("cgroup/bind6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
4585 BPF_CGROUP_INET6_BIND),
4586 BPF_EAPROG_SEC("cgroup/connect4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
4587 BPF_CGROUP_INET4_CONNECT),
4588 BPF_EAPROG_SEC("cgroup/connect6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
4589 BPF_CGROUP_INET6_CONNECT),
4590 BPF_EAPROG_SEC("cgroup/sendmsg4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
4591 BPF_CGROUP_UDP4_SENDMSG),
4592 BPF_EAPROG_SEC("cgroup/sendmsg6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
4593 BPF_CGROUP_UDP6_SENDMSG),
4594 BPF_EAPROG_SEC("cgroup/recvmsg4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
4595 BPF_CGROUP_UDP4_RECVMSG),
4596 BPF_EAPROG_SEC("cgroup/recvmsg6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
4597 BPF_CGROUP_UDP6_RECVMSG),
4598 BPF_EAPROG_SEC("cgroup/sysctl", BPF_PROG_TYPE_CGROUP_SYSCTL,
4600 BPF_EAPROG_SEC("cgroup/getsockopt", BPF_PROG_TYPE_CGROUP_SOCKOPT,
4601 BPF_CGROUP_GETSOCKOPT),
4602 BPF_EAPROG_SEC("cgroup/setsockopt", BPF_PROG_TYPE_CGROUP_SOCKOPT,
4603 BPF_CGROUP_SETSOCKOPT),
4606 #undef BPF_PROG_SEC_IMPL
4608 #undef BPF_APROG_SEC
4609 #undef BPF_EAPROG_SEC
4610 #undef BPF_APROG_COMPAT
4612 #define MAX_TYPE_NAME_SIZE 32
4614 static char *libbpf_get_type_names(bool attach_type)
4616 int i, len = ARRAY_SIZE(section_names) * MAX_TYPE_NAME_SIZE;
4624 /* Forge string buf with all available names */
4625 for (i = 0; i < ARRAY_SIZE(section_names); i++) {
4626 if (attach_type && !section_names[i].is_attachable)
4629 if (strlen(buf) + strlen(section_names[i].sec) + 2 > len) {
4634 strcat(buf, section_names[i].sec);
4640 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
4641 enum bpf_attach_type *expected_attach_type)
4649 for (i = 0; i < ARRAY_SIZE(section_names); i++) {
4650 if (strncmp(name, section_names[i].sec, section_names[i].len))
4652 *prog_type = section_names[i].prog_type;
4653 *expected_attach_type = section_names[i].expected_attach_type;
4654 if (section_names[i].is_attach_btf) {
4655 struct btf *btf = bpf_core_find_kernel_btf();
4656 char raw_tp_btf_name[128] = "btf_trace_";
4657 char *dst = raw_tp_btf_name + sizeof("btf_trace_") - 1;
4661 pr_warning("vmlinux BTF is not found\n");
4664 /* prepend "btf_trace_" prefix per kernel convention */
4665 strncat(dst, name + section_names[i].len,
4666 sizeof(raw_tp_btf_name) - (dst - raw_tp_btf_name));
4667 ret = btf__find_by_name(btf, raw_tp_btf_name);
4670 pr_warning("%s is not found in vmlinux BTF\n", dst);
4673 *expected_attach_type = ret;
4677 pr_warning("failed to guess program type based on ELF section name '%s'\n", name);
4678 type_names = libbpf_get_type_names(false);
4679 if (type_names != NULL) {
4680 pr_info("supported section(type) names are:%s\n", type_names);
4687 int libbpf_attach_type_by_name(const char *name,
4688 enum bpf_attach_type *attach_type)
4696 for (i = 0; i < ARRAY_SIZE(section_names); i++) {
4697 if (strncmp(name, section_names[i].sec, section_names[i].len))
4699 if (!section_names[i].is_attachable)
4701 *attach_type = section_names[i].attach_type;
4704 pr_warning("failed to guess attach type based on ELF section name '%s'\n", name);
4705 type_names = libbpf_get_type_names(true);
4706 if (type_names != NULL) {
4707 pr_info("attachable section(type) names are:%s\n", type_names);
4715 bpf_program__identify_section(struct bpf_program *prog,
4716 enum bpf_prog_type *prog_type,
4717 enum bpf_attach_type *expected_attach_type)
4719 return libbpf_prog_type_by_name(prog->section_name, prog_type,
4720 expected_attach_type);
4723 int bpf_map__fd(const struct bpf_map *map)
4725 return map ? map->fd : -EINVAL;
4728 const struct bpf_map_def *bpf_map__def(const struct bpf_map *map)
4730 return map ? &map->def : ERR_PTR(-EINVAL);
4733 const char *bpf_map__name(const struct bpf_map *map)
4735 return map ? map->name : NULL;
4738 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
4740 return map ? map->btf_key_type_id : 0;
4743 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
4745 return map ? map->btf_value_type_id : 0;
4748 int bpf_map__set_priv(struct bpf_map *map, void *priv,
4749 bpf_map_clear_priv_t clear_priv)
4755 if (map->clear_priv)
4756 map->clear_priv(map, map->priv);
4760 map->clear_priv = clear_priv;
4764 void *bpf_map__priv(const struct bpf_map *map)
4766 return map ? map->priv : ERR_PTR(-EINVAL);
4769 bool bpf_map__is_offload_neutral(const struct bpf_map *map)
4771 return map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY;
4774 bool bpf_map__is_internal(const struct bpf_map *map)
4776 return map->libbpf_type != LIBBPF_MAP_UNSPEC;
4779 void bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
4781 map->map_ifindex = ifindex;
4784 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
4786 if (!bpf_map_type__is_map_in_map(map->def.type)) {
4787 pr_warning("error: unsupported map type\n");
4790 if (map->inner_map_fd != -1) {
4791 pr_warning("error: inner_map_fd already specified\n");
4794 map->inner_map_fd = fd;
4798 static struct bpf_map *
4799 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
4802 struct bpf_map *s, *e;
4804 if (!obj || !obj->maps)
4808 e = obj->maps + obj->nr_maps;
4810 if ((m < s) || (m >= e)) {
4811 pr_warning("error in %s: map handler doesn't belong to object\n",
4816 idx = (m - obj->maps) + i;
4817 if (idx >= obj->nr_maps || idx < 0)
4819 return &obj->maps[idx];
4823 bpf_map__next(const struct bpf_map *prev, const struct bpf_object *obj)
4828 return __bpf_map__iter(prev, obj, 1);
4832 bpf_map__prev(const struct bpf_map *next, const struct bpf_object *obj)
4837 return obj->maps + obj->nr_maps - 1;
4840 return __bpf_map__iter(next, obj, -1);
4844 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
4846 struct bpf_map *pos;
4848 bpf_object__for_each_map(pos, obj) {
4849 if (pos->name && !strcmp(pos->name, name))
4856 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
4858 return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
4862 bpf_object__find_map_by_offset(struct bpf_object *obj, size_t offset)
4864 return ERR_PTR(-ENOTSUP);
4867 long libbpf_get_error(const void *ptr)
4869 return PTR_ERR_OR_ZERO(ptr);
4872 int bpf_prog_load(const char *file, enum bpf_prog_type type,
4873 struct bpf_object **pobj, int *prog_fd)
4875 struct bpf_prog_load_attr attr;
4877 memset(&attr, 0, sizeof(struct bpf_prog_load_attr));
4879 attr.prog_type = type;
4880 attr.expected_attach_type = 0;
4882 return bpf_prog_load_xattr(&attr, pobj, prog_fd);
4885 int bpf_prog_load_xattr(const struct bpf_prog_load_attr *attr,
4886 struct bpf_object **pobj, int *prog_fd)
4888 struct bpf_object_open_attr open_attr = {};
4889 struct bpf_program *prog, *first_prog = NULL;
4890 enum bpf_attach_type expected_attach_type;
4891 enum bpf_prog_type prog_type;
4892 struct bpf_object *obj;
4893 struct bpf_map *map;
4901 open_attr.file = attr->file;
4902 open_attr.prog_type = attr->prog_type;
4904 obj = bpf_object__open_xattr(&open_attr);
4905 if (IS_ERR_OR_NULL(obj))
4908 bpf_object__for_each_program(prog, obj) {
4910 * If type is not specified, try to guess it based on
4913 prog_type = attr->prog_type;
4914 prog->prog_ifindex = attr->ifindex;
4915 expected_attach_type = attr->expected_attach_type;
4916 if (prog_type == BPF_PROG_TYPE_UNSPEC) {
4917 err = bpf_program__identify_section(prog, &prog_type,
4918 &expected_attach_type);
4920 bpf_object__close(obj);
4925 bpf_program__set_type(prog, prog_type);
4926 bpf_program__set_expected_attach_type(prog,
4927 expected_attach_type);
4929 prog->log_level = attr->log_level;
4930 prog->prog_flags = attr->prog_flags;
4935 bpf_object__for_each_map(map, obj) {
4936 if (!bpf_map__is_offload_neutral(map))
4937 map->map_ifindex = attr->ifindex;
4941 pr_warning("object file doesn't contain bpf program\n");
4942 bpf_object__close(obj);
4946 err = bpf_object__load(obj);
4948 bpf_object__close(obj);
4953 *prog_fd = bpf_program__fd(first_prog);
4958 int (*destroy)(struct bpf_link *link);
4961 int bpf_link__destroy(struct bpf_link *link)
4968 err = link->destroy(link);
4974 struct bpf_link_fd {
4975 struct bpf_link link; /* has to be at the top of struct */
4976 int fd; /* hook FD */
4979 static int bpf_link__destroy_perf_event(struct bpf_link *link)
4981 struct bpf_link_fd *l = (void *)link;
4984 err = ioctl(l->fd, PERF_EVENT_IOC_DISABLE, 0);
4992 struct bpf_link *bpf_program__attach_perf_event(struct bpf_program *prog,
4995 char errmsg[STRERR_BUFSIZE];
4996 struct bpf_link_fd *link;
5000 pr_warning("program '%s': invalid perf event FD %d\n",
5001 bpf_program__title(prog, false), pfd);
5002 return ERR_PTR(-EINVAL);
5004 prog_fd = bpf_program__fd(prog);
5006 pr_warning("program '%s': can't attach BPF program w/o FD (did you load it?)\n",
5007 bpf_program__title(prog, false));
5008 return ERR_PTR(-EINVAL);
5011 link = malloc(sizeof(*link));
5013 return ERR_PTR(-ENOMEM);
5014 link->link.destroy = &bpf_link__destroy_perf_event;
5017 if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
5020 pr_warning("program '%s': failed to attach to pfd %d: %s\n",
5021 bpf_program__title(prog, false), pfd,
5022 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
5023 return ERR_PTR(err);
5025 if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
5028 pr_warning("program '%s': failed to enable pfd %d: %s\n",
5029 bpf_program__title(prog, false), pfd,
5030 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
5031 return ERR_PTR(err);
5033 return (struct bpf_link *)link;
5037 * this function is expected to parse integer in the range of [0, 2^31-1] from
5038 * given file using scanf format string fmt. If actual parsed value is
5039 * negative, the result might be indistinguishable from error
5041 static int parse_uint_from_file(const char *file, const char *fmt)
5043 char buf[STRERR_BUFSIZE];
5047 f = fopen(file, "r");
5050 pr_debug("failed to open '%s': %s\n", file,
5051 libbpf_strerror_r(err, buf, sizeof(buf)));
5054 err = fscanf(f, fmt, &ret);
5056 err = err == EOF ? -EIO : -errno;
5057 pr_debug("failed to parse '%s': %s\n", file,
5058 libbpf_strerror_r(err, buf, sizeof(buf)));
5066 static int determine_kprobe_perf_type(void)
5068 const char *file = "/sys/bus/event_source/devices/kprobe/type";
5070 return parse_uint_from_file(file, "%d\n");
5073 static int determine_uprobe_perf_type(void)
5075 const char *file = "/sys/bus/event_source/devices/uprobe/type";
5077 return parse_uint_from_file(file, "%d\n");
5080 static int determine_kprobe_retprobe_bit(void)
5082 const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
5084 return parse_uint_from_file(file, "config:%d\n");
5087 static int determine_uprobe_retprobe_bit(void)
5089 const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
5091 return parse_uint_from_file(file, "config:%d\n");
5094 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
5095 uint64_t offset, int pid)
5097 struct perf_event_attr attr = {};
5098 char errmsg[STRERR_BUFSIZE];
5101 type = uprobe ? determine_uprobe_perf_type()
5102 : determine_kprobe_perf_type();
5104 pr_warning("failed to determine %s perf type: %s\n",
5105 uprobe ? "uprobe" : "kprobe",
5106 libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
5110 int bit = uprobe ? determine_uprobe_retprobe_bit()
5111 : determine_kprobe_retprobe_bit();
5114 pr_warning("failed to determine %s retprobe bit: %s\n",
5115 uprobe ? "uprobe" : "kprobe",
5116 libbpf_strerror_r(bit, errmsg,
5120 attr.config |= 1 << bit;
5122 attr.size = sizeof(attr);
5124 attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
5125 attr.config2 = offset; /* kprobe_addr or probe_offset */
5127 /* pid filter is meaningful only for uprobes */
5128 pfd = syscall(__NR_perf_event_open, &attr,
5129 pid < 0 ? -1 : pid /* pid */,
5130 pid == -1 ? 0 : -1 /* cpu */,
5131 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
5134 pr_warning("%s perf_event_open() failed: %s\n",
5135 uprobe ? "uprobe" : "kprobe",
5136 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
5142 struct bpf_link *bpf_program__attach_kprobe(struct bpf_program *prog,
5144 const char *func_name)
5146 char errmsg[STRERR_BUFSIZE];
5147 struct bpf_link *link;
5150 pfd = perf_event_open_probe(false /* uprobe */, retprobe, func_name,
5151 0 /* offset */, -1 /* pid */);
5153 pr_warning("program '%s': failed to create %s '%s' perf event: %s\n",
5154 bpf_program__title(prog, false),
5155 retprobe ? "kretprobe" : "kprobe", func_name,
5156 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
5157 return ERR_PTR(pfd);
5159 link = bpf_program__attach_perf_event(prog, pfd);
5162 err = PTR_ERR(link);
5163 pr_warning("program '%s': failed to attach to %s '%s': %s\n",
5164 bpf_program__title(prog, false),
5165 retprobe ? "kretprobe" : "kprobe", func_name,
5166 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
5172 struct bpf_link *bpf_program__attach_uprobe(struct bpf_program *prog,
5173 bool retprobe, pid_t pid,
5174 const char *binary_path,
5177 char errmsg[STRERR_BUFSIZE];
5178 struct bpf_link *link;
5181 pfd = perf_event_open_probe(true /* uprobe */, retprobe,
5182 binary_path, func_offset, pid);
5184 pr_warning("program '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
5185 bpf_program__title(prog, false),
5186 retprobe ? "uretprobe" : "uprobe",
5187 binary_path, func_offset,
5188 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
5189 return ERR_PTR(pfd);
5191 link = bpf_program__attach_perf_event(prog, pfd);
5194 err = PTR_ERR(link);
5195 pr_warning("program '%s': failed to attach to %s '%s:0x%zx': %s\n",
5196 bpf_program__title(prog, false),
5197 retprobe ? "uretprobe" : "uprobe",
5198 binary_path, func_offset,
5199 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
5205 static int determine_tracepoint_id(const char *tp_category,
5206 const char *tp_name)
5208 char file[PATH_MAX];
5211 ret = snprintf(file, sizeof(file),
5212 "/sys/kernel/debug/tracing/events/%s/%s/id",
5213 tp_category, tp_name);
5216 if (ret >= sizeof(file)) {
5217 pr_debug("tracepoint %s/%s path is too long\n",
5218 tp_category, tp_name);
5221 return parse_uint_from_file(file, "%d\n");
5224 static int perf_event_open_tracepoint(const char *tp_category,
5225 const char *tp_name)
5227 struct perf_event_attr attr = {};
5228 char errmsg[STRERR_BUFSIZE];
5229 int tp_id, pfd, err;
5231 tp_id = determine_tracepoint_id(tp_category, tp_name);
5233 pr_warning("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
5234 tp_category, tp_name,
5235 libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
5239 attr.type = PERF_TYPE_TRACEPOINT;
5240 attr.size = sizeof(attr);
5241 attr.config = tp_id;
5243 pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
5244 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
5247 pr_warning("tracepoint '%s/%s' perf_event_open() failed: %s\n",
5248 tp_category, tp_name,
5249 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
5255 struct bpf_link *bpf_program__attach_tracepoint(struct bpf_program *prog,
5256 const char *tp_category,
5257 const char *tp_name)
5259 char errmsg[STRERR_BUFSIZE];
5260 struct bpf_link *link;
5263 pfd = perf_event_open_tracepoint(tp_category, tp_name);
5265 pr_warning("program '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
5266 bpf_program__title(prog, false),
5267 tp_category, tp_name,
5268 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
5269 return ERR_PTR(pfd);
5271 link = bpf_program__attach_perf_event(prog, pfd);
5274 err = PTR_ERR(link);
5275 pr_warning("program '%s': failed to attach to tracepoint '%s/%s': %s\n",
5276 bpf_program__title(prog, false),
5277 tp_category, tp_name,
5278 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
5284 static int bpf_link__destroy_fd(struct bpf_link *link)
5286 struct bpf_link_fd *l = (void *)link;
5288 return close(l->fd);
5291 struct bpf_link *bpf_program__attach_raw_tracepoint(struct bpf_program *prog,
5292 const char *tp_name)
5294 char errmsg[STRERR_BUFSIZE];
5295 struct bpf_link_fd *link;
5298 prog_fd = bpf_program__fd(prog);
5300 pr_warning("program '%s': can't attach before loaded\n",
5301 bpf_program__title(prog, false));
5302 return ERR_PTR(-EINVAL);
5305 link = malloc(sizeof(*link));
5307 return ERR_PTR(-ENOMEM);
5308 link->link.destroy = &bpf_link__destroy_fd;
5310 pfd = bpf_raw_tracepoint_open(tp_name, prog_fd);
5314 pr_warning("program '%s': failed to attach to raw tracepoint '%s': %s\n",
5315 bpf_program__title(prog, false), tp_name,
5316 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
5317 return ERR_PTR(pfd);
5320 return (struct bpf_link *)link;
5323 enum bpf_perf_event_ret
5324 bpf_perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
5325 void **copy_mem, size_t *copy_size,
5326 bpf_perf_event_print_t fn, void *private_data)
5328 struct perf_event_mmap_page *header = mmap_mem;
5329 __u64 data_head = ring_buffer_read_head(header);
5330 __u64 data_tail = header->data_tail;
5331 void *base = ((__u8 *)header) + page_size;
5332 int ret = LIBBPF_PERF_EVENT_CONT;
5333 struct perf_event_header *ehdr;
5336 while (data_head != data_tail) {
5337 ehdr = base + (data_tail & (mmap_size - 1));
5338 ehdr_size = ehdr->size;
5340 if (((void *)ehdr) + ehdr_size > base + mmap_size) {
5341 void *copy_start = ehdr;
5342 size_t len_first = base + mmap_size - copy_start;
5343 size_t len_secnd = ehdr_size - len_first;
5345 if (*copy_size < ehdr_size) {
5347 *copy_mem = malloc(ehdr_size);
5350 ret = LIBBPF_PERF_EVENT_ERROR;
5353 *copy_size = ehdr_size;
5356 memcpy(*copy_mem, copy_start, len_first);
5357 memcpy(*copy_mem + len_first, base, len_secnd);
5361 ret = fn(ehdr, private_data);
5362 data_tail += ehdr_size;
5363 if (ret != LIBBPF_PERF_EVENT_CONT)
5367 ring_buffer_write_tail(header, data_tail);
5373 struct perf_buffer_params {
5374 struct perf_event_attr *attr;
5375 /* if event_cb is specified, it takes precendence */
5376 perf_buffer_event_fn event_cb;
5377 /* sample_cb and lost_cb are higher-level common-case callbacks */
5378 perf_buffer_sample_fn sample_cb;
5379 perf_buffer_lost_fn lost_cb;
5386 struct perf_cpu_buf {
5387 struct perf_buffer *pb;
5388 void *base; /* mmap()'ed memory */
5389 void *buf; /* for reconstructing segmented data */
5396 struct perf_buffer {
5397 perf_buffer_event_fn event_cb;
5398 perf_buffer_sample_fn sample_cb;
5399 perf_buffer_lost_fn lost_cb;
5400 void *ctx; /* passed into callbacks */
5404 struct perf_cpu_buf **cpu_bufs;
5405 struct epoll_event *events;
5407 int epoll_fd; /* perf event FD */
5408 int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
5411 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
5412 struct perf_cpu_buf *cpu_buf)
5416 if (cpu_buf->base &&
5417 munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
5418 pr_warning("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
5419 if (cpu_buf->fd >= 0) {
5420 ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
5427 void perf_buffer__free(struct perf_buffer *pb)
5434 for (i = 0; i < pb->cpu_cnt && pb->cpu_bufs[i]; i++) {
5435 struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
5437 bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
5438 perf_buffer__free_cpu_buf(pb, cpu_buf);
5442 if (pb->epoll_fd >= 0)
5443 close(pb->epoll_fd);
5448 static struct perf_cpu_buf *
5449 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
5450 int cpu, int map_key)
5452 struct perf_cpu_buf *cpu_buf;
5453 char msg[STRERR_BUFSIZE];
5456 cpu_buf = calloc(1, sizeof(*cpu_buf));
5458 return ERR_PTR(-ENOMEM);
5462 cpu_buf->map_key = map_key;
5464 cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
5465 -1, PERF_FLAG_FD_CLOEXEC);
5466 if (cpu_buf->fd < 0) {
5468 pr_warning("failed to open perf buffer event on cpu #%d: %s\n",
5469 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
5473 cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
5474 PROT_READ | PROT_WRITE, MAP_SHARED,
5476 if (cpu_buf->base == MAP_FAILED) {
5477 cpu_buf->base = NULL;
5479 pr_warning("failed to mmap perf buffer on cpu #%d: %s\n",
5480 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
5484 if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
5486 pr_warning("failed to enable perf buffer event on cpu #%d: %s\n",
5487 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
5494 perf_buffer__free_cpu_buf(pb, cpu_buf);
5495 return (struct perf_cpu_buf *)ERR_PTR(err);
5498 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
5499 struct perf_buffer_params *p);
5501 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
5502 const struct perf_buffer_opts *opts)
5504 struct perf_buffer_params p = {};
5505 struct perf_event_attr attr = { 0, };
5507 attr.config = PERF_COUNT_SW_BPF_OUTPUT,
5508 attr.type = PERF_TYPE_SOFTWARE;
5509 attr.sample_type = PERF_SAMPLE_RAW;
5510 attr.sample_period = 1;
5511 attr.wakeup_events = 1;
5514 p.sample_cb = opts ? opts->sample_cb : NULL;
5515 p.lost_cb = opts ? opts->lost_cb : NULL;
5516 p.ctx = opts ? opts->ctx : NULL;
5518 return __perf_buffer__new(map_fd, page_cnt, &p);
5521 struct perf_buffer *
5522 perf_buffer__new_raw(int map_fd, size_t page_cnt,
5523 const struct perf_buffer_raw_opts *opts)
5525 struct perf_buffer_params p = {};
5527 p.attr = opts->attr;
5528 p.event_cb = opts->event_cb;
5530 p.cpu_cnt = opts->cpu_cnt;
5531 p.cpus = opts->cpus;
5532 p.map_keys = opts->map_keys;
5534 return __perf_buffer__new(map_fd, page_cnt, &p);
5537 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
5538 struct perf_buffer_params *p)
5540 struct bpf_map_info map = {};
5541 char msg[STRERR_BUFSIZE];
5542 struct perf_buffer *pb;
5546 if (page_cnt & (page_cnt - 1)) {
5547 pr_warning("page count should be power of two, but is %zu\n",
5549 return ERR_PTR(-EINVAL);
5552 map_info_len = sizeof(map);
5553 err = bpf_obj_get_info_by_fd(map_fd, &map, &map_info_len);
5556 pr_warning("failed to get map info for map FD %d: %s\n",
5557 map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
5558 return ERR_PTR(err);
5561 if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
5562 pr_warning("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
5564 return ERR_PTR(-EINVAL);
5567 pb = calloc(1, sizeof(*pb));
5569 return ERR_PTR(-ENOMEM);
5571 pb->event_cb = p->event_cb;
5572 pb->sample_cb = p->sample_cb;
5573 pb->lost_cb = p->lost_cb;
5576 pb->page_size = getpagesize();
5577 pb->mmap_size = pb->page_size * page_cnt;
5578 pb->map_fd = map_fd;
5580 pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
5581 if (pb->epoll_fd < 0) {
5583 pr_warning("failed to create epoll instance: %s\n",
5584 libbpf_strerror_r(err, msg, sizeof(msg)));
5588 if (p->cpu_cnt > 0) {
5589 pb->cpu_cnt = p->cpu_cnt;
5591 pb->cpu_cnt = libbpf_num_possible_cpus();
5592 if (pb->cpu_cnt < 0) {
5596 if (map.max_entries < pb->cpu_cnt)
5597 pb->cpu_cnt = map.max_entries;
5600 pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
5603 pr_warning("failed to allocate events: out of memory\n");
5606 pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
5607 if (!pb->cpu_bufs) {
5609 pr_warning("failed to allocate buffers: out of memory\n");
5613 for (i = 0; i < pb->cpu_cnt; i++) {
5614 struct perf_cpu_buf *cpu_buf;
5617 cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
5618 map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
5620 cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
5621 if (IS_ERR(cpu_buf)) {
5622 err = PTR_ERR(cpu_buf);
5626 pb->cpu_bufs[i] = cpu_buf;
5628 err = bpf_map_update_elem(pb->map_fd, &map_key,
5632 pr_warning("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
5633 cpu, map_key, cpu_buf->fd,
5634 libbpf_strerror_r(err, msg, sizeof(msg)));
5638 pb->events[i].events = EPOLLIN;
5639 pb->events[i].data.ptr = cpu_buf;
5640 if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
5641 &pb->events[i]) < 0) {
5643 pr_warning("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
5645 libbpf_strerror_r(err, msg, sizeof(msg)));
5654 perf_buffer__free(pb);
5655 return ERR_PTR(err);
5658 struct perf_sample_raw {
5659 struct perf_event_header header;
5664 struct perf_sample_lost {
5665 struct perf_event_header header;
5671 static enum bpf_perf_event_ret
5672 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
5674 struct perf_cpu_buf *cpu_buf = ctx;
5675 struct perf_buffer *pb = cpu_buf->pb;
5678 /* user wants full control over parsing perf event */
5680 return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
5683 case PERF_RECORD_SAMPLE: {
5684 struct perf_sample_raw *s = data;
5687 pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
5690 case PERF_RECORD_LOST: {
5691 struct perf_sample_lost *s = data;
5694 pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
5698 pr_warning("unknown perf sample type %d\n", e->type);
5699 return LIBBPF_PERF_EVENT_ERROR;
5701 return LIBBPF_PERF_EVENT_CONT;
5704 static int perf_buffer__process_records(struct perf_buffer *pb,
5705 struct perf_cpu_buf *cpu_buf)
5707 enum bpf_perf_event_ret ret;
5709 ret = bpf_perf_event_read_simple(cpu_buf->base, pb->mmap_size,
5710 pb->page_size, &cpu_buf->buf,
5712 perf_buffer__process_record, cpu_buf);
5713 if (ret != LIBBPF_PERF_EVENT_CONT)
5718 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
5722 cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
5723 for (i = 0; i < cnt; i++) {
5724 struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
5726 err = perf_buffer__process_records(pb, cpu_buf);
5728 pr_warning("error while processing records: %d\n", err);
5732 return cnt < 0 ? -errno : cnt;
5735 struct bpf_prog_info_array_desc {
5736 int array_offset; /* e.g. offset of jited_prog_insns */
5737 int count_offset; /* e.g. offset of jited_prog_len */
5738 int size_offset; /* > 0: offset of rec size,
5739 * < 0: fix size of -size_offset
5743 static struct bpf_prog_info_array_desc bpf_prog_info_array_desc[] = {
5744 [BPF_PROG_INFO_JITED_INSNS] = {
5745 offsetof(struct bpf_prog_info, jited_prog_insns),
5746 offsetof(struct bpf_prog_info, jited_prog_len),
5749 [BPF_PROG_INFO_XLATED_INSNS] = {
5750 offsetof(struct bpf_prog_info, xlated_prog_insns),
5751 offsetof(struct bpf_prog_info, xlated_prog_len),
5754 [BPF_PROG_INFO_MAP_IDS] = {
5755 offsetof(struct bpf_prog_info, map_ids),
5756 offsetof(struct bpf_prog_info, nr_map_ids),
5757 -(int)sizeof(__u32),
5759 [BPF_PROG_INFO_JITED_KSYMS] = {
5760 offsetof(struct bpf_prog_info, jited_ksyms),
5761 offsetof(struct bpf_prog_info, nr_jited_ksyms),
5762 -(int)sizeof(__u64),
5764 [BPF_PROG_INFO_JITED_FUNC_LENS] = {
5765 offsetof(struct bpf_prog_info, jited_func_lens),
5766 offsetof(struct bpf_prog_info, nr_jited_func_lens),
5767 -(int)sizeof(__u32),
5769 [BPF_PROG_INFO_FUNC_INFO] = {
5770 offsetof(struct bpf_prog_info, func_info),
5771 offsetof(struct bpf_prog_info, nr_func_info),
5772 offsetof(struct bpf_prog_info, func_info_rec_size),
5774 [BPF_PROG_INFO_LINE_INFO] = {
5775 offsetof(struct bpf_prog_info, line_info),
5776 offsetof(struct bpf_prog_info, nr_line_info),
5777 offsetof(struct bpf_prog_info, line_info_rec_size),
5779 [BPF_PROG_INFO_JITED_LINE_INFO] = {
5780 offsetof(struct bpf_prog_info, jited_line_info),
5781 offsetof(struct bpf_prog_info, nr_jited_line_info),
5782 offsetof(struct bpf_prog_info, jited_line_info_rec_size),
5784 [BPF_PROG_INFO_PROG_TAGS] = {
5785 offsetof(struct bpf_prog_info, prog_tags),
5786 offsetof(struct bpf_prog_info, nr_prog_tags),
5787 -(int)sizeof(__u8) * BPF_TAG_SIZE,
5792 static __u32 bpf_prog_info_read_offset_u32(struct bpf_prog_info *info, int offset)
5794 __u32 *array = (__u32 *)info;
5797 return array[offset / sizeof(__u32)];
5798 return -(int)offset;
5801 static __u64 bpf_prog_info_read_offset_u64(struct bpf_prog_info *info, int offset)
5803 __u64 *array = (__u64 *)info;
5806 return array[offset / sizeof(__u64)];
5807 return -(int)offset;
5810 static void bpf_prog_info_set_offset_u32(struct bpf_prog_info *info, int offset,
5813 __u32 *array = (__u32 *)info;
5816 array[offset / sizeof(__u32)] = val;
5819 static void bpf_prog_info_set_offset_u64(struct bpf_prog_info *info, int offset,
5822 __u64 *array = (__u64 *)info;
5825 array[offset / sizeof(__u64)] = val;
5828 struct bpf_prog_info_linear *
5829 bpf_program__get_prog_info_linear(int fd, __u64 arrays)
5831 struct bpf_prog_info_linear *info_linear;
5832 struct bpf_prog_info info = {};
5833 __u32 info_len = sizeof(info);
5838 if (arrays >> BPF_PROG_INFO_LAST_ARRAY)
5839 return ERR_PTR(-EINVAL);
5841 /* step 1: get array dimensions */
5842 err = bpf_obj_get_info_by_fd(fd, &info, &info_len);
5844 pr_debug("can't get prog info: %s", strerror(errno));
5845 return ERR_PTR(-EFAULT);
5848 /* step 2: calculate total size of all arrays */
5849 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
5850 bool include_array = (arrays & (1UL << i)) > 0;
5851 struct bpf_prog_info_array_desc *desc;
5854 desc = bpf_prog_info_array_desc + i;
5856 /* kernel is too old to support this field */
5857 if (info_len < desc->array_offset + sizeof(__u32) ||
5858 info_len < desc->count_offset + sizeof(__u32) ||
5859 (desc->size_offset > 0 && info_len < desc->size_offset))
5860 include_array = false;
5862 if (!include_array) {
5863 arrays &= ~(1UL << i); /* clear the bit */
5867 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
5868 size = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
5870 data_len += count * size;
5873 /* step 3: allocate continuous memory */
5874 data_len = roundup(data_len, sizeof(__u64));
5875 info_linear = malloc(sizeof(struct bpf_prog_info_linear) + data_len);
5877 return ERR_PTR(-ENOMEM);
5879 /* step 4: fill data to info_linear->info */
5880 info_linear->arrays = arrays;
5881 memset(&info_linear->info, 0, sizeof(info));
5882 ptr = info_linear->data;
5884 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
5885 struct bpf_prog_info_array_desc *desc;
5888 if ((arrays & (1UL << i)) == 0)
5891 desc = bpf_prog_info_array_desc + i;
5892 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
5893 size = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
5894 bpf_prog_info_set_offset_u32(&info_linear->info,
5895 desc->count_offset, count);
5896 bpf_prog_info_set_offset_u32(&info_linear->info,
5897 desc->size_offset, size);
5898 bpf_prog_info_set_offset_u64(&info_linear->info,
5901 ptr += count * size;
5904 /* step 5: call syscall again to get required arrays */
5905 err = bpf_obj_get_info_by_fd(fd, &info_linear->info, &info_len);
5907 pr_debug("can't get prog info: %s", strerror(errno));
5909 return ERR_PTR(-EFAULT);
5912 /* step 6: verify the data */
5913 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
5914 struct bpf_prog_info_array_desc *desc;
5917 if ((arrays & (1UL << i)) == 0)
5920 desc = bpf_prog_info_array_desc + i;
5921 v1 = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
5922 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
5923 desc->count_offset);
5925 pr_warning("%s: mismatch in element count\n", __func__);
5927 v1 = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
5928 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
5931 pr_warning("%s: mismatch in rec size\n", __func__);
5934 /* step 7: update info_len and data_len */
5935 info_linear->info_len = sizeof(struct bpf_prog_info);
5936 info_linear->data_len = data_len;
5941 void bpf_program__bpil_addr_to_offs(struct bpf_prog_info_linear *info_linear)
5945 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
5946 struct bpf_prog_info_array_desc *desc;
5949 if ((info_linear->arrays & (1UL << i)) == 0)
5952 desc = bpf_prog_info_array_desc + i;
5953 addr = bpf_prog_info_read_offset_u64(&info_linear->info,
5954 desc->array_offset);
5955 offs = addr - ptr_to_u64(info_linear->data);
5956 bpf_prog_info_set_offset_u64(&info_linear->info,
5957 desc->array_offset, offs);
5961 void bpf_program__bpil_offs_to_addr(struct bpf_prog_info_linear *info_linear)
5965 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
5966 struct bpf_prog_info_array_desc *desc;
5969 if ((info_linear->arrays & (1UL << i)) == 0)
5972 desc = bpf_prog_info_array_desc + i;
5973 offs = bpf_prog_info_read_offset_u64(&info_linear->info,
5974 desc->array_offset);
5975 addr = offs + ptr_to_u64(info_linear->data);
5976 bpf_prog_info_set_offset_u64(&info_linear->info,
5977 desc->array_offset, addr);
5981 int libbpf_num_possible_cpus(void)
5983 static const char *fcpu = "/sys/devices/system/cpu/possible";
5984 int len = 0, n = 0, il = 0, ir = 0;
5985 unsigned int start = 0, end = 0;
5992 tmp_cpus = READ_ONCE(cpus);
5996 fd = open(fcpu, O_RDONLY);
5999 pr_warning("Failed to open file %s: %s\n",
6000 fcpu, strerror(error));
6003 len = read(fd, buf, sizeof(buf));
6006 error = len ? errno : EINVAL;
6007 pr_warning("Failed to read # of possible cpus from %s: %s\n",
6008 fcpu, strerror(error));
6011 if (len == sizeof(buf)) {
6012 pr_warning("File %s size overflow\n", fcpu);
6017 for (ir = 0, tmp_cpus = 0; ir <= len; ir++) {
6018 /* Each sub string separated by ',' has format \d+-\d+ or \d+ */
6019 if (buf[ir] == ',' || buf[ir] == '\0') {
6021 n = sscanf(&buf[il], "%u-%u", &start, &end);
6023 pr_warning("Failed to get # CPUs from %s\n",
6026 } else if (n == 1) {
6029 tmp_cpus += end - start + 1;
6033 if (tmp_cpus <= 0) {
6034 pr_warning("Invalid #CPUs %d from %s\n", tmp_cpus, fcpu);
6038 WRITE_ONCE(cpus, tmp_cpus);