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);
660 static int compare_bpf_map(const void *_a, const void *_b)
662 const struct bpf_map *a = _a;
663 const struct bpf_map *b = _b;
665 if (a->sec_idx != b->sec_idx)
666 return a->sec_idx - b->sec_idx;
667 return a->sec_offset - b->sec_offset;
670 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
672 if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
673 type == BPF_MAP_TYPE_HASH_OF_MAPS)
678 static int bpf_object_search_section_size(const struct bpf_object *obj,
679 const char *name, size_t *d_size)
681 const GElf_Ehdr *ep = &obj->efile.ehdr;
682 Elf *elf = obj->efile.elf;
686 while ((scn = elf_nextscn(elf, scn)) != NULL) {
687 const char *sec_name;
692 if (gelf_getshdr(scn, &sh) != &sh) {
693 pr_warning("failed to get section(%d) header from %s\n",
698 sec_name = elf_strptr(elf, ep->e_shstrndx, sh.sh_name);
700 pr_warning("failed to get section(%d) name from %s\n",
705 if (strcmp(name, sec_name))
708 data = elf_getdata(scn, 0);
710 pr_warning("failed to get section(%d) data from %s(%s)\n",
711 idx, name, obj->path);
715 *d_size = data->d_size;
722 int bpf_object__section_size(const struct bpf_object *obj, const char *name,
731 } else if (!strcmp(name, ".data")) {
733 *size = obj->efile.data->d_size;
734 } else if (!strcmp(name, ".bss")) {
736 *size = obj->efile.bss->d_size;
737 } else if (!strcmp(name, ".rodata")) {
738 if (obj->efile.rodata)
739 *size = obj->efile.rodata->d_size;
741 ret = bpf_object_search_section_size(obj, name, &d_size);
746 return *size ? 0 : ret;
749 int bpf_object__variable_offset(const struct bpf_object *obj, const char *name,
752 Elf_Data *symbols = obj->efile.symbols;
759 for (si = 0; si < symbols->d_size / sizeof(GElf_Sym); si++) {
762 if (!gelf_getsym(symbols, si, &sym))
764 if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL ||
765 GELF_ST_TYPE(sym.st_info) != STT_OBJECT)
768 sname = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
771 pr_warning("failed to get sym name string for var %s\n",
775 if (strcmp(name, sname) == 0) {
784 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
786 struct bpf_map *new_maps;
790 if (obj->nr_maps < obj->maps_cap)
791 return &obj->maps[obj->nr_maps++];
793 new_cap = max((size_t)4, obj->maps_cap * 3 / 2);
794 new_maps = realloc(obj->maps, new_cap * sizeof(*obj->maps));
796 pr_warning("alloc maps for object failed\n");
797 return ERR_PTR(-ENOMEM);
800 obj->maps_cap = new_cap;
801 obj->maps = new_maps;
803 /* zero out new maps */
804 memset(obj->maps + obj->nr_maps, 0,
805 (obj->maps_cap - obj->nr_maps) * sizeof(*obj->maps));
807 * fill all fd with -1 so won't close incorrect fd (fd=0 is stdin)
808 * when failure (zclose won't close negative fd)).
810 for (i = obj->nr_maps; i < obj->maps_cap; i++) {
811 obj->maps[i].fd = -1;
812 obj->maps[i].inner_map_fd = -1;
815 return &obj->maps[obj->nr_maps++];
819 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
820 int sec_idx, Elf_Data *data, void **data_buff)
822 char map_name[BPF_OBJ_NAME_LEN];
823 struct bpf_map_def *def;
826 map = bpf_object__add_map(obj);
830 map->libbpf_type = type;
831 map->sec_idx = sec_idx;
833 snprintf(map_name, sizeof(map_name), "%.8s%.7s", obj->name,
834 libbpf_type_to_btf_name[type]);
835 map->name = strdup(map_name);
837 pr_warning("failed to alloc map name\n");
840 pr_debug("map '%s' (global data): at sec_idx %d, offset %zu.\n",
841 map_name, map->sec_idx, map->sec_offset);
844 def->type = BPF_MAP_TYPE_ARRAY;
845 def->key_size = sizeof(int);
846 def->value_size = data->d_size;
847 def->max_entries = 1;
848 def->map_flags = type == LIBBPF_MAP_RODATA ? BPF_F_RDONLY_PROG : 0;
850 *data_buff = malloc(data->d_size);
853 pr_warning("failed to alloc map content buffer\n");
856 memcpy(*data_buff, data->d_buf, data->d_size);
859 pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
863 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
867 if (!obj->caps.global_data)
870 * Populate obj->maps with libbpf internal maps.
872 if (obj->efile.data_shndx >= 0) {
873 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
874 obj->efile.data_shndx,
876 &obj->sections.data);
880 if (obj->efile.rodata_shndx >= 0) {
881 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
882 obj->efile.rodata_shndx,
884 &obj->sections.rodata);
888 if (obj->efile.bss_shndx >= 0) {
889 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
890 obj->efile.bss_shndx,
891 obj->efile.bss, NULL);
898 static int bpf_object__init_user_maps(struct bpf_object *obj, bool strict)
900 Elf_Data *symbols = obj->efile.symbols;
901 int i, map_def_sz = 0, nr_maps = 0, nr_syms;
902 Elf_Data *data = NULL;
905 if (obj->efile.maps_shndx < 0)
911 scn = elf_getscn(obj->efile.elf, obj->efile.maps_shndx);
913 data = elf_getdata(scn, NULL);
915 pr_warning("failed to get Elf_Data from map section %d\n",
916 obj->efile.maps_shndx);
921 * Count number of maps. Each map has a name.
922 * Array of maps is not supported: only the first element is
925 * TODO: Detect array of map and report error.
927 nr_syms = symbols->d_size / sizeof(GElf_Sym);
928 for (i = 0; i < nr_syms; i++) {
931 if (!gelf_getsym(symbols, i, &sym))
933 if (sym.st_shndx != obj->efile.maps_shndx)
937 /* Assume equally sized map definitions */
938 pr_debug("maps in %s: %d maps in %zd bytes\n",
939 obj->path, nr_maps, data->d_size);
941 map_def_sz = data->d_size / nr_maps;
942 if (!data->d_size || (data->d_size % nr_maps) != 0) {
943 pr_warning("unable to determine map definition size "
944 "section %s, %d maps in %zd bytes\n",
945 obj->path, nr_maps, data->d_size);
949 /* Fill obj->maps using data in "maps" section. */
950 for (i = 0; i < nr_syms; i++) {
952 const char *map_name;
953 struct bpf_map_def *def;
956 if (!gelf_getsym(symbols, i, &sym))
958 if (sym.st_shndx != obj->efile.maps_shndx)
961 map = bpf_object__add_map(obj);
965 map_name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
968 pr_warning("failed to get map #%d name sym string for obj %s\n",
970 return -LIBBPF_ERRNO__FORMAT;
973 map->libbpf_type = LIBBPF_MAP_UNSPEC;
974 map->sec_idx = sym.st_shndx;
975 map->sec_offset = sym.st_value;
976 pr_debug("map '%s' (legacy): at sec_idx %d, offset %zu.\n",
977 map_name, map->sec_idx, map->sec_offset);
978 if (sym.st_value + map_def_sz > data->d_size) {
979 pr_warning("corrupted maps section in %s: last map \"%s\" too small\n",
980 obj->path, map_name);
984 map->name = strdup(map_name);
986 pr_warning("failed to alloc map name\n");
989 pr_debug("map %d is \"%s\"\n", i, map->name);
990 def = (struct bpf_map_def *)(data->d_buf + sym.st_value);
992 * If the definition of the map in the object file fits in
993 * bpf_map_def, copy it. Any extra fields in our version
994 * of bpf_map_def will default to zero as a result of the
997 if (map_def_sz <= sizeof(struct bpf_map_def)) {
998 memcpy(&map->def, def, map_def_sz);
1001 * Here the map structure being read is bigger than what
1002 * we expect, truncate if the excess bits are all zero.
1003 * If they are not zero, reject this map as
1007 for (b = ((char *)def) + sizeof(struct bpf_map_def);
1008 b < ((char *)def) + map_def_sz; b++) {
1010 pr_warning("maps section in %s: \"%s\" "
1011 "has unrecognized, non-zero "
1013 obj->path, map_name);
1018 memcpy(&map->def, def, sizeof(struct bpf_map_def));
1024 static const struct btf_type *
1025 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
1027 const struct btf_type *t = btf__type_by_id(btf, id);
1032 while (btf_is_mod(t) || btf_is_typedef(t)) {
1035 t = btf__type_by_id(btf, t->type);
1042 * Fetch integer attribute of BTF map definition. Such attributes are
1043 * represented using a pointer to an array, in which dimensionality of array
1044 * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
1045 * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
1046 * type definition, while using only sizeof(void *) space in ELF data section.
1048 static bool get_map_field_int(const char *map_name, const struct btf *btf,
1049 const struct btf_type *def,
1050 const struct btf_member *m, __u32 *res) {
1051 const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
1052 const char *name = btf__name_by_offset(btf, m->name_off);
1053 const struct btf_array *arr_info;
1054 const struct btf_type *arr_t;
1056 if (!btf_is_ptr(t)) {
1057 pr_warning("map '%s': attr '%s': expected PTR, got %u.\n",
1058 map_name, name, btf_kind(t));
1062 arr_t = btf__type_by_id(btf, t->type);
1064 pr_warning("map '%s': attr '%s': type [%u] not found.\n",
1065 map_name, name, t->type);
1068 if (!btf_is_array(arr_t)) {
1069 pr_warning("map '%s': attr '%s': expected ARRAY, got %u.\n",
1070 map_name, name, btf_kind(arr_t));
1073 arr_info = btf_array(arr_t);
1074 *res = arr_info->nelems;
1078 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
1079 const struct btf_type *sec,
1080 int var_idx, int sec_idx,
1081 const Elf_Data *data, bool strict)
1083 const struct btf_type *var, *def, *t;
1084 const struct btf_var_secinfo *vi;
1085 const struct btf_var *var_extra;
1086 const struct btf_member *m;
1087 const char *map_name;
1088 struct bpf_map *map;
1091 vi = btf_var_secinfos(sec) + var_idx;
1092 var = btf__type_by_id(obj->btf, vi->type);
1093 var_extra = btf_var(var);
1094 map_name = btf__name_by_offset(obj->btf, var->name_off);
1095 vlen = btf_vlen(var);
1097 if (map_name == NULL || map_name[0] == '\0') {
1098 pr_warning("map #%d: empty name.\n", var_idx);
1101 if ((__u64)vi->offset + vi->size > data->d_size) {
1102 pr_warning("map '%s' BTF data is corrupted.\n", map_name);
1105 if (!btf_is_var(var)) {
1106 pr_warning("map '%s': unexpected var kind %u.\n",
1107 map_name, btf_kind(var));
1110 if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED &&
1111 var_extra->linkage != BTF_VAR_STATIC) {
1112 pr_warning("map '%s': unsupported var linkage %u.\n",
1113 map_name, var_extra->linkage);
1117 def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
1118 if (!btf_is_struct(def)) {
1119 pr_warning("map '%s': unexpected def kind %u.\n",
1120 map_name, btf_kind(var));
1123 if (def->size > vi->size) {
1124 pr_warning("map '%s': invalid def size.\n", map_name);
1128 map = bpf_object__add_map(obj);
1130 return PTR_ERR(map);
1131 map->name = strdup(map_name);
1133 pr_warning("map '%s': failed to alloc map name.\n", map_name);
1136 map->libbpf_type = LIBBPF_MAP_UNSPEC;
1137 map->def.type = BPF_MAP_TYPE_UNSPEC;
1138 map->sec_idx = sec_idx;
1139 map->sec_offset = vi->offset;
1140 pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
1141 map_name, map->sec_idx, map->sec_offset);
1143 vlen = btf_vlen(def);
1144 m = btf_members(def);
1145 for (i = 0; i < vlen; i++, m++) {
1146 const char *name = btf__name_by_offset(obj->btf, m->name_off);
1149 pr_warning("map '%s': invalid field #%d.\n",
1153 if (strcmp(name, "type") == 0) {
1154 if (!get_map_field_int(map_name, obj->btf, def, m,
1157 pr_debug("map '%s': found type = %u.\n",
1158 map_name, map->def.type);
1159 } else if (strcmp(name, "max_entries") == 0) {
1160 if (!get_map_field_int(map_name, obj->btf, def, m,
1161 &map->def.max_entries))
1163 pr_debug("map '%s': found max_entries = %u.\n",
1164 map_name, map->def.max_entries);
1165 } else if (strcmp(name, "map_flags") == 0) {
1166 if (!get_map_field_int(map_name, obj->btf, def, m,
1167 &map->def.map_flags))
1169 pr_debug("map '%s': found map_flags = %u.\n",
1170 map_name, map->def.map_flags);
1171 } else if (strcmp(name, "key_size") == 0) {
1174 if (!get_map_field_int(map_name, obj->btf, def, m,
1177 pr_debug("map '%s': found key_size = %u.\n",
1179 if (map->def.key_size && map->def.key_size != sz) {
1180 pr_warning("map '%s': conflicting key size %u != %u.\n",
1181 map_name, map->def.key_size, sz);
1184 map->def.key_size = sz;
1185 } else if (strcmp(name, "key") == 0) {
1188 t = btf__type_by_id(obj->btf, m->type);
1190 pr_warning("map '%s': key type [%d] not found.\n",
1194 if (!btf_is_ptr(t)) {
1195 pr_warning("map '%s': key spec is not PTR: %u.\n",
1196 map_name, btf_kind(t));
1199 sz = btf__resolve_size(obj->btf, t->type);
1201 pr_warning("map '%s': can't determine key size for type [%u]: %lld.\n",
1202 map_name, t->type, sz);
1205 pr_debug("map '%s': found key [%u], sz = %lld.\n",
1206 map_name, t->type, sz);
1207 if (map->def.key_size && map->def.key_size != sz) {
1208 pr_warning("map '%s': conflicting key size %u != %lld.\n",
1209 map_name, map->def.key_size, sz);
1212 map->def.key_size = sz;
1213 map->btf_key_type_id = t->type;
1214 } else if (strcmp(name, "value_size") == 0) {
1217 if (!get_map_field_int(map_name, obj->btf, def, m,
1220 pr_debug("map '%s': found value_size = %u.\n",
1222 if (map->def.value_size && map->def.value_size != sz) {
1223 pr_warning("map '%s': conflicting value size %u != %u.\n",
1224 map_name, map->def.value_size, sz);
1227 map->def.value_size = sz;
1228 } else if (strcmp(name, "value") == 0) {
1231 t = btf__type_by_id(obj->btf, m->type);
1233 pr_warning("map '%s': value type [%d] not found.\n",
1237 if (!btf_is_ptr(t)) {
1238 pr_warning("map '%s': value spec is not PTR: %u.\n",
1239 map_name, btf_kind(t));
1242 sz = btf__resolve_size(obj->btf, t->type);
1244 pr_warning("map '%s': can't determine value size for type [%u]: %lld.\n",
1245 map_name, t->type, sz);
1248 pr_debug("map '%s': found value [%u], sz = %lld.\n",
1249 map_name, t->type, sz);
1250 if (map->def.value_size && map->def.value_size != sz) {
1251 pr_warning("map '%s': conflicting value size %u != %lld.\n",
1252 map_name, map->def.value_size, sz);
1255 map->def.value_size = sz;
1256 map->btf_value_type_id = t->type;
1259 pr_warning("map '%s': unknown field '%s'.\n",
1263 pr_debug("map '%s': ignoring unknown field '%s'.\n",
1268 if (map->def.type == BPF_MAP_TYPE_UNSPEC) {
1269 pr_warning("map '%s': map type isn't specified.\n", map_name);
1276 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict)
1278 const struct btf_type *sec = NULL;
1279 int nr_types, i, vlen, err;
1280 const struct btf_type *t;
1285 if (obj->efile.btf_maps_shndx < 0)
1288 scn = elf_getscn(obj->efile.elf, obj->efile.btf_maps_shndx);
1290 data = elf_getdata(scn, NULL);
1291 if (!scn || !data) {
1292 pr_warning("failed to get Elf_Data from map section %d (%s)\n",
1293 obj->efile.maps_shndx, MAPS_ELF_SEC);
1297 nr_types = btf__get_nr_types(obj->btf);
1298 for (i = 1; i <= nr_types; i++) {
1299 t = btf__type_by_id(obj->btf, i);
1300 if (!btf_is_datasec(t))
1302 name = btf__name_by_offset(obj->btf, t->name_off);
1303 if (strcmp(name, MAPS_ELF_SEC) == 0) {
1310 pr_warning("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
1314 vlen = btf_vlen(sec);
1315 for (i = 0; i < vlen; i++) {
1316 err = bpf_object__init_user_btf_map(obj, sec, i,
1317 obj->efile.btf_maps_shndx,
1326 static int bpf_object__init_maps(struct bpf_object *obj, bool relaxed_maps)
1328 bool strict = !relaxed_maps;
1331 err = bpf_object__init_user_maps(obj, strict);
1335 err = bpf_object__init_user_btf_maps(obj, strict);
1339 err = bpf_object__init_global_data_maps(obj);
1344 qsort(obj->maps, obj->nr_maps, sizeof(obj->maps[0]),
1350 static bool section_have_execinstr(struct bpf_object *obj, int idx)
1355 scn = elf_getscn(obj->efile.elf, idx);
1359 if (gelf_getshdr(scn, &sh) != &sh)
1362 if (sh.sh_flags & SHF_EXECINSTR)
1368 static void bpf_object__sanitize_btf(struct bpf_object *obj)
1370 bool has_datasec = obj->caps.btf_datasec;
1371 bool has_func = obj->caps.btf_func;
1372 struct btf *btf = obj->btf;
1376 if (!obj->btf || (has_func && has_datasec))
1379 for (i = 1; i <= btf__get_nr_types(btf); i++) {
1380 t = (struct btf_type *)btf__type_by_id(btf, i);
1382 if (!has_datasec && btf_is_var(t)) {
1383 /* replace VAR with INT */
1384 t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
1386 * using size = 1 is the safest choice, 4 will be too
1387 * big and cause kernel BTF validation failure if
1388 * original variable took less than 4 bytes
1391 *(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
1392 } else if (!has_datasec && btf_is_datasec(t)) {
1393 /* replace DATASEC with STRUCT */
1394 const struct btf_var_secinfo *v = btf_var_secinfos(t);
1395 struct btf_member *m = btf_members(t);
1396 struct btf_type *vt;
1399 name = (char *)btf__name_by_offset(btf, t->name_off);
1407 t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
1408 for (j = 0; j < vlen; j++, v++, m++) {
1409 /* order of field assignments is important */
1410 m->offset = v->offset * 8;
1412 /* preserve variable name as member name */
1413 vt = (void *)btf__type_by_id(btf, v->type);
1414 m->name_off = vt->name_off;
1416 } else if (!has_func && btf_is_func_proto(t)) {
1417 /* replace FUNC_PROTO with ENUM */
1419 t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
1420 t->size = sizeof(__u32); /* kernel enforced */
1421 } else if (!has_func && btf_is_func(t)) {
1422 /* replace FUNC with TYPEDEF */
1423 t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
1428 static void bpf_object__sanitize_btf_ext(struct bpf_object *obj)
1433 if (!obj->caps.btf_func) {
1434 btf_ext__free(obj->btf_ext);
1435 obj->btf_ext = NULL;
1439 static bool bpf_object__is_btf_mandatory(const struct bpf_object *obj)
1441 return obj->efile.btf_maps_shndx >= 0;
1444 static int bpf_object__init_btf(struct bpf_object *obj,
1446 Elf_Data *btf_ext_data)
1448 bool btf_required = bpf_object__is_btf_mandatory(obj);
1452 obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
1453 if (IS_ERR(obj->btf)) {
1454 pr_warning("Error loading ELF section %s: %d.\n",
1458 err = btf__finalize_data(obj, obj->btf);
1460 pr_warning("Error finalizing %s: %d.\n",
1467 pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
1468 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
1471 obj->btf_ext = btf_ext__new(btf_ext_data->d_buf,
1472 btf_ext_data->d_size);
1473 if (IS_ERR(obj->btf_ext)) {
1474 pr_warning("Error loading ELF section %s: %ld. Ignored and continue.\n",
1475 BTF_EXT_ELF_SEC, PTR_ERR(obj->btf_ext));
1476 obj->btf_ext = NULL;
1481 if (err || IS_ERR(obj->btf)) {
1483 err = err ? : PTR_ERR(obj->btf);
1486 if (!IS_ERR_OR_NULL(obj->btf))
1487 btf__free(obj->btf);
1490 if (btf_required && !obj->btf) {
1491 pr_warning("BTF is required, but is missing or corrupted.\n");
1492 return err == 0 ? -ENOENT : err;
1497 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
1504 bpf_object__sanitize_btf(obj);
1505 bpf_object__sanitize_btf_ext(obj);
1507 err = btf__load(obj->btf);
1509 pr_warning("Error loading %s into kernel: %d.\n",
1511 btf__free(obj->btf);
1513 /* btf_ext can't exist without btf, so free it as well */
1515 btf_ext__free(obj->btf_ext);
1516 obj->btf_ext = NULL;
1519 if (bpf_object__is_btf_mandatory(obj))
1525 static int bpf_object__elf_collect(struct bpf_object *obj, bool relaxed_maps)
1527 Elf *elf = obj->efile.elf;
1528 GElf_Ehdr *ep = &obj->efile.ehdr;
1529 Elf_Data *btf_ext_data = NULL;
1530 Elf_Data *btf_data = NULL;
1531 Elf_Scn *scn = NULL;
1532 int idx = 0, err = 0;
1534 /* Elf is corrupted/truncated, avoid calling elf_strptr. */
1535 if (!elf_rawdata(elf_getscn(elf, ep->e_shstrndx), NULL)) {
1536 pr_warning("failed to get e_shstrndx from %s\n", obj->path);
1537 return -LIBBPF_ERRNO__FORMAT;
1540 while ((scn = elf_nextscn(elf, scn)) != NULL) {
1546 if (gelf_getshdr(scn, &sh) != &sh) {
1547 pr_warning("failed to get section(%d) header from %s\n",
1549 return -LIBBPF_ERRNO__FORMAT;
1552 name = elf_strptr(elf, ep->e_shstrndx, sh.sh_name);
1554 pr_warning("failed to get section(%d) name from %s\n",
1556 return -LIBBPF_ERRNO__FORMAT;
1559 data = elf_getdata(scn, 0);
1561 pr_warning("failed to get section(%d) data from %s(%s)\n",
1562 idx, name, obj->path);
1563 return -LIBBPF_ERRNO__FORMAT;
1565 pr_debug("section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
1566 idx, name, (unsigned long)data->d_size,
1567 (int)sh.sh_link, (unsigned long)sh.sh_flags,
1570 if (strcmp(name, "license") == 0) {
1571 err = bpf_object__init_license(obj,
1576 } else if (strcmp(name, "version") == 0) {
1577 /* skip, we don't need it anymore */
1578 } else if (strcmp(name, "maps") == 0) {
1579 obj->efile.maps_shndx = idx;
1580 } else if (strcmp(name, MAPS_ELF_SEC) == 0) {
1581 obj->efile.btf_maps_shndx = idx;
1582 } else if (strcmp(name, BTF_ELF_SEC) == 0) {
1584 } else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
1585 btf_ext_data = data;
1586 } else if (sh.sh_type == SHT_SYMTAB) {
1587 if (obj->efile.symbols) {
1588 pr_warning("bpf: multiple SYMTAB in %s\n",
1590 return -LIBBPF_ERRNO__FORMAT;
1592 obj->efile.symbols = data;
1593 obj->efile.strtabidx = sh.sh_link;
1594 } else if (sh.sh_type == SHT_PROGBITS && data->d_size > 0) {
1595 if (sh.sh_flags & SHF_EXECINSTR) {
1596 if (strcmp(name, ".text") == 0)
1597 obj->efile.text_shndx = idx;
1598 err = bpf_object__add_program(obj, data->d_buf,
1599 data->d_size, name, idx);
1601 char errmsg[STRERR_BUFSIZE];
1602 char *cp = libbpf_strerror_r(-err, errmsg,
1605 pr_warning("failed to alloc program %s (%s): %s",
1606 name, obj->path, cp);
1609 } else if (strcmp(name, ".data") == 0) {
1610 obj->efile.data = data;
1611 obj->efile.data_shndx = idx;
1612 } else if (strcmp(name, ".rodata") == 0) {
1613 obj->efile.rodata = data;
1614 obj->efile.rodata_shndx = idx;
1616 pr_debug("skip section(%d) %s\n", idx, name);
1618 } else if (sh.sh_type == SHT_REL) {
1619 int nr_reloc = obj->efile.nr_reloc;
1620 void *reloc = obj->efile.reloc;
1621 int sec = sh.sh_info; /* points to other section */
1623 /* Only do relo for section with exec instructions */
1624 if (!section_have_execinstr(obj, sec)) {
1625 pr_debug("skip relo %s(%d) for section(%d)\n",
1630 reloc = reallocarray(reloc, nr_reloc + 1,
1631 sizeof(*obj->efile.reloc));
1633 pr_warning("realloc failed\n");
1637 obj->efile.reloc = reloc;
1638 obj->efile.nr_reloc++;
1640 obj->efile.reloc[nr_reloc].shdr = sh;
1641 obj->efile.reloc[nr_reloc].data = data;
1642 } else if (sh.sh_type == SHT_NOBITS && strcmp(name, ".bss") == 0) {
1643 obj->efile.bss = data;
1644 obj->efile.bss_shndx = idx;
1646 pr_debug("skip section(%d) %s\n", idx, name);
1650 if (!obj->efile.strtabidx || obj->efile.strtabidx >= idx) {
1651 pr_warning("Corrupted ELF file: index of strtab invalid\n");
1652 return -LIBBPF_ERRNO__FORMAT;
1654 err = bpf_object__init_btf(obj, btf_data, btf_ext_data);
1656 err = bpf_object__init_maps(obj, relaxed_maps);
1658 err = bpf_object__sanitize_and_load_btf(obj);
1660 err = bpf_object__init_prog_names(obj);
1664 static struct bpf_program *
1665 bpf_object__find_prog_by_idx(struct bpf_object *obj, int idx)
1667 struct bpf_program *prog;
1670 for (i = 0; i < obj->nr_programs; i++) {
1671 prog = &obj->programs[i];
1672 if (prog->idx == idx)
1678 struct bpf_program *
1679 bpf_object__find_program_by_title(const struct bpf_object *obj,
1682 struct bpf_program *pos;
1684 bpf_object__for_each_program(pos, obj) {
1685 if (pos->section_name && !strcmp(pos->section_name, title))
1691 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
1694 return shndx == obj->efile.data_shndx ||
1695 shndx == obj->efile.bss_shndx ||
1696 shndx == obj->efile.rodata_shndx;
1699 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
1702 return shndx == obj->efile.maps_shndx ||
1703 shndx == obj->efile.btf_maps_shndx;
1706 static bool bpf_object__relo_in_known_section(const struct bpf_object *obj,
1709 return shndx == obj->efile.text_shndx ||
1710 bpf_object__shndx_is_maps(obj, shndx) ||
1711 bpf_object__shndx_is_data(obj, shndx);
1714 static enum libbpf_map_type
1715 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
1717 if (shndx == obj->efile.data_shndx)
1718 return LIBBPF_MAP_DATA;
1719 else if (shndx == obj->efile.bss_shndx)
1720 return LIBBPF_MAP_BSS;
1721 else if (shndx == obj->efile.rodata_shndx)
1722 return LIBBPF_MAP_RODATA;
1724 return LIBBPF_MAP_UNSPEC;
1728 bpf_program__collect_reloc(struct bpf_program *prog, GElf_Shdr *shdr,
1729 Elf_Data *data, struct bpf_object *obj)
1731 Elf_Data *symbols = obj->efile.symbols;
1732 struct bpf_map *maps = obj->maps;
1733 size_t nr_maps = obj->nr_maps;
1736 pr_debug("collecting relocating info for: '%s'\n", prog->section_name);
1737 nrels = shdr->sh_size / shdr->sh_entsize;
1739 prog->reloc_desc = malloc(sizeof(*prog->reloc_desc) * nrels);
1740 if (!prog->reloc_desc) {
1741 pr_warning("failed to alloc memory in relocation\n");
1744 prog->nr_reloc = nrels;
1746 for (i = 0; i < nrels; i++) {
1747 struct bpf_insn *insns = prog->insns;
1748 enum libbpf_map_type type;
1749 unsigned int insn_idx;
1750 unsigned int shdr_idx;
1756 if (!gelf_getrel(data, i, &rel)) {
1757 pr_warning("relocation: failed to get %d reloc\n", i);
1758 return -LIBBPF_ERRNO__FORMAT;
1761 if (!gelf_getsym(symbols, GELF_R_SYM(rel.r_info), &sym)) {
1762 pr_warning("relocation: symbol %"PRIx64" not found\n",
1763 GELF_R_SYM(rel.r_info));
1764 return -LIBBPF_ERRNO__FORMAT;
1767 name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
1768 sym.st_name) ? : "<?>";
1770 pr_debug("relo for %lld value %lld name %d (\'%s\')\n",
1771 (long long) (rel.r_info >> 32),
1772 (long long) sym.st_value, sym.st_name, name);
1774 shdr_idx = sym.st_shndx;
1775 insn_idx = rel.r_offset / sizeof(struct bpf_insn);
1776 pr_debug("relocation: insn_idx=%u, shdr_idx=%u\n",
1777 insn_idx, shdr_idx);
1779 if (shdr_idx >= SHN_LORESERVE) {
1780 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",
1781 name, shdr_idx, insn_idx,
1782 insns[insn_idx].code);
1783 return -LIBBPF_ERRNO__RELOC;
1785 if (!bpf_object__relo_in_known_section(obj, shdr_idx)) {
1786 pr_warning("Program '%s' contains unrecognized relo data pointing to section %u\n",
1787 prog->section_name, shdr_idx);
1788 return -LIBBPF_ERRNO__RELOC;
1791 if (insns[insn_idx].code == (BPF_JMP | BPF_CALL)) {
1792 if (insns[insn_idx].src_reg != BPF_PSEUDO_CALL) {
1793 pr_warning("incorrect bpf_call opcode\n");
1794 return -LIBBPF_ERRNO__RELOC;
1796 prog->reloc_desc[i].type = RELO_CALL;
1797 prog->reloc_desc[i].insn_idx = insn_idx;
1798 prog->reloc_desc[i].text_off = sym.st_value;
1799 obj->has_pseudo_calls = true;
1803 if (insns[insn_idx].code != (BPF_LD | BPF_IMM | BPF_DW)) {
1804 pr_warning("bpf: relocation: invalid relo for insns[%d].code 0x%x\n",
1805 insn_idx, insns[insn_idx].code);
1806 return -LIBBPF_ERRNO__RELOC;
1809 if (bpf_object__shndx_is_maps(obj, shdr_idx) ||
1810 bpf_object__shndx_is_data(obj, shdr_idx)) {
1811 type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
1812 if (type != LIBBPF_MAP_UNSPEC) {
1813 if (GELF_ST_BIND(sym.st_info) == STB_GLOBAL) {
1814 pr_warning("bpf: relocation: not yet supported relo for non-static global \'%s\' variable found in insns[%d].code 0x%x\n",
1815 name, insn_idx, insns[insn_idx].code);
1816 return -LIBBPF_ERRNO__RELOC;
1818 if (!obj->caps.global_data) {
1819 pr_warning("bpf: relocation: kernel does not support global \'%s\' variable access in insns[%d]\n",
1821 return -LIBBPF_ERRNO__RELOC;
1825 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
1826 if (maps[map_idx].libbpf_type != type)
1828 if (type != LIBBPF_MAP_UNSPEC ||
1829 (maps[map_idx].sec_idx == sym.st_shndx &&
1830 maps[map_idx].sec_offset == sym.st_value)) {
1831 pr_debug("relocation: found map %zd (%s, sec_idx %d, offset %zu) for insn %u\n",
1832 map_idx, maps[map_idx].name,
1833 maps[map_idx].sec_idx,
1834 maps[map_idx].sec_offset,
1840 if (map_idx >= nr_maps) {
1841 pr_warning("bpf relocation: map_idx %d larger than %d\n",
1842 (int)map_idx, (int)nr_maps - 1);
1843 return -LIBBPF_ERRNO__RELOC;
1846 prog->reloc_desc[i].type = type != LIBBPF_MAP_UNSPEC ?
1847 RELO_DATA : RELO_LD64;
1848 prog->reloc_desc[i].insn_idx = insn_idx;
1849 prog->reloc_desc[i].map_idx = map_idx;
1855 static int bpf_map_find_btf_info(struct bpf_object *obj, struct bpf_map *map)
1857 struct bpf_map_def *def = &map->def;
1858 __u32 key_type_id = 0, value_type_id = 0;
1861 /* if it's BTF-defined map, we don't need to search for type IDs */
1862 if (map->sec_idx == obj->efile.btf_maps_shndx)
1865 if (!bpf_map__is_internal(map)) {
1866 ret = btf__get_map_kv_tids(obj->btf, map->name, def->key_size,
1867 def->value_size, &key_type_id,
1871 * LLVM annotates global data differently in BTF, that is,
1872 * only as '.data', '.bss' or '.rodata'.
1874 ret = btf__find_by_name(obj->btf,
1875 libbpf_type_to_btf_name[map->libbpf_type]);
1880 map->btf_key_type_id = key_type_id;
1881 map->btf_value_type_id = bpf_map__is_internal(map) ?
1882 ret : value_type_id;
1886 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
1888 struct bpf_map_info info = {};
1889 __u32 len = sizeof(info);
1893 err = bpf_obj_get_info_by_fd(fd, &info, &len);
1897 new_name = strdup(info.name);
1901 new_fd = open("/", O_RDONLY | O_CLOEXEC);
1903 goto err_free_new_name;
1905 new_fd = dup3(fd, new_fd, O_CLOEXEC);
1907 goto err_close_new_fd;
1909 err = zclose(map->fd);
1911 goto err_close_new_fd;
1915 map->name = new_name;
1916 map->def.type = info.type;
1917 map->def.key_size = info.key_size;
1918 map->def.value_size = info.value_size;
1919 map->def.max_entries = info.max_entries;
1920 map->def.map_flags = info.map_flags;
1921 map->btf_key_type_id = info.btf_key_type_id;
1922 map->btf_value_type_id = info.btf_value_type_id;
1933 int bpf_map__resize(struct bpf_map *map, __u32 max_entries)
1935 if (!map || !max_entries)
1938 /* If map already created, its attributes can't be changed. */
1942 map->def.max_entries = max_entries;
1948 bpf_object__probe_name(struct bpf_object *obj)
1950 struct bpf_load_program_attr attr;
1951 char *cp, errmsg[STRERR_BUFSIZE];
1952 struct bpf_insn insns[] = {
1953 BPF_MOV64_IMM(BPF_REG_0, 0),
1958 /* make sure basic loading works */
1960 memset(&attr, 0, sizeof(attr));
1961 attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
1963 attr.insns_cnt = ARRAY_SIZE(insns);
1964 attr.license = "GPL";
1966 ret = bpf_load_program_xattr(&attr, NULL, 0);
1968 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
1969 pr_warning("Error in %s():%s(%d). Couldn't load basic 'r0 = 0' BPF program.\n",
1970 __func__, cp, errno);
1975 /* now try the same program, but with the name */
1978 ret = bpf_load_program_xattr(&attr, NULL, 0);
1988 bpf_object__probe_global_data(struct bpf_object *obj)
1990 struct bpf_load_program_attr prg_attr;
1991 struct bpf_create_map_attr map_attr;
1992 char *cp, errmsg[STRERR_BUFSIZE];
1993 struct bpf_insn insns[] = {
1994 BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16),
1995 BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42),
1996 BPF_MOV64_IMM(BPF_REG_0, 0),
2001 memset(&map_attr, 0, sizeof(map_attr));
2002 map_attr.map_type = BPF_MAP_TYPE_ARRAY;
2003 map_attr.key_size = sizeof(int);
2004 map_attr.value_size = 32;
2005 map_attr.max_entries = 1;
2007 map = bpf_create_map_xattr(&map_attr);
2009 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
2010 pr_warning("Error in %s():%s(%d). Couldn't create simple array map.\n",
2011 __func__, cp, errno);
2017 memset(&prg_attr, 0, sizeof(prg_attr));
2018 prg_attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
2019 prg_attr.insns = insns;
2020 prg_attr.insns_cnt = ARRAY_SIZE(insns);
2021 prg_attr.license = "GPL";
2023 ret = bpf_load_program_xattr(&prg_attr, NULL, 0);
2025 obj->caps.global_data = 1;
2033 static int bpf_object__probe_btf_func(struct bpf_object *obj)
2035 const char strs[] = "\0int\0x\0a";
2036 /* void x(int a) {} */
2039 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
2040 /* FUNC_PROTO */ /* [2] */
2041 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
2042 BTF_PARAM_ENC(7, 1),
2043 /* FUNC x */ /* [3] */
2044 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0), 2),
2048 btf_fd = libbpf__load_raw_btf((char *)types, sizeof(types),
2049 strs, sizeof(strs));
2051 obj->caps.btf_func = 1;
2059 static int bpf_object__probe_btf_datasec(struct bpf_object *obj)
2061 const char strs[] = "\0x\0.data";
2065 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
2066 /* VAR x */ /* [2] */
2067 BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
2069 /* DATASEC val */ /* [3] */
2070 BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC, 0, 1), 4),
2071 BTF_VAR_SECINFO_ENC(2, 0, 4),
2075 btf_fd = libbpf__load_raw_btf((char *)types, sizeof(types),
2076 strs, sizeof(strs));
2078 obj->caps.btf_datasec = 1;
2087 bpf_object__probe_caps(struct bpf_object *obj)
2089 int (*probe_fn[])(struct bpf_object *obj) = {
2090 bpf_object__probe_name,
2091 bpf_object__probe_global_data,
2092 bpf_object__probe_btf_func,
2093 bpf_object__probe_btf_datasec,
2097 for (i = 0; i < ARRAY_SIZE(probe_fn); i++) {
2098 ret = probe_fn[i](obj);
2100 pr_debug("Probe #%d failed with %d.\n", i, ret);
2107 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
2109 char *cp, errmsg[STRERR_BUFSIZE];
2113 /* Nothing to do here since kernel already zero-initializes .bss map. */
2114 if (map->libbpf_type == LIBBPF_MAP_BSS)
2117 data = map->libbpf_type == LIBBPF_MAP_DATA ?
2118 obj->sections.data : obj->sections.rodata;
2120 err = bpf_map_update_elem(map->fd, &zero, data, 0);
2121 /* Freeze .rodata map as read-only from syscall side. */
2122 if (!err && map->libbpf_type == LIBBPF_MAP_RODATA) {
2123 err = bpf_map_freeze(map->fd);
2125 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
2126 pr_warning("Error freezing map(%s) as read-only: %s\n",
2135 bpf_object__create_maps(struct bpf_object *obj)
2137 struct bpf_create_map_attr create_attr = {};
2142 for (i = 0; i < obj->nr_maps; i++) {
2143 struct bpf_map *map = &obj->maps[i];
2144 struct bpf_map_def *def = &map->def;
2145 char *cp, errmsg[STRERR_BUFSIZE];
2146 int *pfd = &map->fd;
2149 pr_debug("skip map create (preset) %s: fd=%d\n",
2150 map->name, map->fd);
2155 create_attr.name = map->name;
2156 create_attr.map_ifindex = map->map_ifindex;
2157 create_attr.map_type = def->type;
2158 create_attr.map_flags = def->map_flags;
2159 create_attr.key_size = def->key_size;
2160 create_attr.value_size = def->value_size;
2161 if (def->type == BPF_MAP_TYPE_PERF_EVENT_ARRAY &&
2162 !def->max_entries) {
2164 nr_cpus = libbpf_num_possible_cpus();
2166 pr_warning("failed to determine number of system CPUs: %d\n",
2171 pr_debug("map '%s': setting size to %d\n",
2172 map->name, nr_cpus);
2173 create_attr.max_entries = nr_cpus;
2175 create_attr.max_entries = def->max_entries;
2177 create_attr.btf_fd = 0;
2178 create_attr.btf_key_type_id = 0;
2179 create_attr.btf_value_type_id = 0;
2180 if (bpf_map_type__is_map_in_map(def->type) &&
2181 map->inner_map_fd >= 0)
2182 create_attr.inner_map_fd = map->inner_map_fd;
2184 if (obj->btf && !bpf_map_find_btf_info(obj, map)) {
2185 create_attr.btf_fd = btf__fd(obj->btf);
2186 create_attr.btf_key_type_id = map->btf_key_type_id;
2187 create_attr.btf_value_type_id = map->btf_value_type_id;
2190 *pfd = bpf_create_map_xattr(&create_attr);
2191 if (*pfd < 0 && (create_attr.btf_key_type_id ||
2192 create_attr.btf_value_type_id)) {
2194 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
2195 pr_warning("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
2196 map->name, cp, err);
2197 create_attr.btf_fd = 0;
2198 create_attr.btf_key_type_id = 0;
2199 create_attr.btf_value_type_id = 0;
2200 map->btf_key_type_id = 0;
2201 map->btf_value_type_id = 0;
2202 *pfd = bpf_create_map_xattr(&create_attr);
2210 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
2211 pr_warning("failed to create map (name: '%s'): %s(%d)\n",
2212 map->name, cp, err);
2213 for (j = 0; j < i; j++)
2214 zclose(obj->maps[j].fd);
2218 if (bpf_map__is_internal(map)) {
2219 err = bpf_object__populate_internal_map(obj, map);
2226 pr_debug("created map %s: fd=%d\n", map->name, *pfd);
2233 check_btf_ext_reloc_err(struct bpf_program *prog, int err,
2234 void *btf_prog_info, const char *info_name)
2236 if (err != -ENOENT) {
2237 pr_warning("Error in loading %s for sec %s.\n",
2238 info_name, prog->section_name);
2242 /* err == -ENOENT (i.e. prog->section_name not found in btf_ext) */
2244 if (btf_prog_info) {
2246 * Some info has already been found but has problem
2247 * in the last btf_ext reloc. Must have to error out.
2249 pr_warning("Error in relocating %s for sec %s.\n",
2250 info_name, prog->section_name);
2254 /* Have problem loading the very first info. Ignore the rest. */
2255 pr_warning("Cannot find %s for main program sec %s. Ignore all %s.\n",
2256 info_name, prog->section_name, info_name);
2261 bpf_program_reloc_btf_ext(struct bpf_program *prog, struct bpf_object *obj,
2262 const char *section_name, __u32 insn_offset)
2266 if (!insn_offset || prog->func_info) {
2268 * !insn_offset => main program
2270 * For sub prog, the main program's func_info has to
2271 * be loaded first (i.e. prog->func_info != NULL)
2273 err = btf_ext__reloc_func_info(obj->btf, obj->btf_ext,
2274 section_name, insn_offset,
2276 &prog->func_info_cnt);
2278 return check_btf_ext_reloc_err(prog, err,
2282 prog->func_info_rec_size = btf_ext__func_info_rec_size(obj->btf_ext);
2285 if (!insn_offset || prog->line_info) {
2286 err = btf_ext__reloc_line_info(obj->btf, obj->btf_ext,
2287 section_name, insn_offset,
2289 &prog->line_info_cnt);
2291 return check_btf_ext_reloc_err(prog, err,
2295 prog->line_info_rec_size = btf_ext__line_info_rec_size(obj->btf_ext);
2301 #define BPF_CORE_SPEC_MAX_LEN 64
2303 /* represents BPF CO-RE field or array element accessor */
2304 struct bpf_core_accessor {
2305 __u32 type_id; /* struct/union type or array element type */
2306 __u32 idx; /* field index or array index */
2307 const char *name; /* field name or NULL for array accessor */
2310 struct bpf_core_spec {
2311 const struct btf *btf;
2312 /* high-level spec: named fields and array indices only */
2313 struct bpf_core_accessor spec[BPF_CORE_SPEC_MAX_LEN];
2314 /* high-level spec length */
2316 /* raw, low-level spec: 1-to-1 with accessor spec string */
2317 int raw_spec[BPF_CORE_SPEC_MAX_LEN];
2318 /* raw spec length */
2320 /* field byte offset represented by spec */
2324 static bool str_is_empty(const char *s)
2330 * Turn bpf_field_reloc into a low- and high-level spec representation,
2331 * validating correctness along the way, as well as calculating resulting
2332 * field offset (in bytes), specified by accessor string. Low-level spec
2333 * captures every single level of nestedness, including traversing anonymous
2334 * struct/union members. High-level one only captures semantically meaningful
2335 * "turning points": named fields and array indicies.
2336 * E.g., for this case:
2339 * int __unimportant;
2347 * struct sample *s = ...;
2349 * int x = &s->a[3]; // access string = '0:1:2:3'
2351 * Low-level spec has 1:1 mapping with each element of access string (it's
2352 * just a parsed access string representation): [0, 1, 2, 3].
2354 * High-level spec will capture only 3 points:
2355 * - intial zero-index access by pointer (&s->... is the same as &s[0]...);
2356 * - field 'a' access (corresponds to '2' in low-level spec);
2357 * - array element #3 access (corresponds to '3' in low-level spec).
2360 static int bpf_core_spec_parse(const struct btf *btf,
2362 const char *spec_str,
2363 struct bpf_core_spec *spec)
2365 int access_idx, parsed_len, i;
2366 const struct btf_type *t;
2371 if (str_is_empty(spec_str) || *spec_str == ':')
2374 memset(spec, 0, sizeof(*spec));
2377 /* parse spec_str="0:1:2:3:4" into array raw_spec=[0, 1, 2, 3, 4] */
2379 if (*spec_str == ':')
2381 if (sscanf(spec_str, "%d%n", &access_idx, &parsed_len) != 1)
2383 if (spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
2385 spec_str += parsed_len;
2386 spec->raw_spec[spec->raw_len++] = access_idx;
2389 if (spec->raw_len == 0)
2392 /* first spec value is always reloc type array index */
2393 t = skip_mods_and_typedefs(btf, type_id, &id);
2397 access_idx = spec->raw_spec[0];
2398 spec->spec[0].type_id = id;
2399 spec->spec[0].idx = access_idx;
2402 sz = btf__resolve_size(btf, id);
2405 spec->offset = access_idx * sz;
2407 for (i = 1; i < spec->raw_len; i++) {
2408 t = skip_mods_and_typedefs(btf, id, &id);
2412 access_idx = spec->raw_spec[i];
2414 if (btf_is_composite(t)) {
2415 const struct btf_member *m;
2418 if (access_idx >= btf_vlen(t))
2420 if (btf_member_bitfield_size(t, access_idx))
2423 offset = btf_member_bit_offset(t, access_idx);
2426 spec->offset += offset / 8;
2428 m = btf_members(t) + access_idx;
2430 name = btf__name_by_offset(btf, m->name_off);
2431 if (str_is_empty(name))
2434 spec->spec[spec->len].type_id = id;
2435 spec->spec[spec->len].idx = access_idx;
2436 spec->spec[spec->len].name = name;
2441 } else if (btf_is_array(t)) {
2442 const struct btf_array *a = btf_array(t);
2444 t = skip_mods_and_typedefs(btf, a->type, &id);
2445 if (!t || access_idx >= a->nelems)
2448 spec->spec[spec->len].type_id = id;
2449 spec->spec[spec->len].idx = access_idx;
2452 sz = btf__resolve_size(btf, id);
2455 spec->offset += access_idx * sz;
2457 pr_warning("relo for [%u] %s (at idx %d) captures type [%d] of unexpected kind %d\n",
2458 type_id, spec_str, i, id, btf_kind(t));
2466 static bool bpf_core_is_flavor_sep(const char *s)
2468 /* check X___Y name pattern, where X and Y are not underscores */
2469 return s[0] != '_' && /* X */
2470 s[1] == '_' && s[2] == '_' && s[3] == '_' && /* ___ */
2471 s[4] != '_'; /* Y */
2474 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
2475 * before last triple underscore. Struct name part after last triple
2476 * underscore is ignored by BPF CO-RE relocation during relocation matching.
2478 static size_t bpf_core_essential_name_len(const char *name)
2480 size_t n = strlen(name);
2483 for (i = n - 5; i >= 0; i--) {
2484 if (bpf_core_is_flavor_sep(name + i))
2490 /* dynamically sized list of type IDs */
2496 static void bpf_core_free_cands(struct ids_vec *cand_ids)
2498 free(cand_ids->data);
2502 static struct ids_vec *bpf_core_find_cands(const struct btf *local_btf,
2503 __u32 local_type_id,
2504 const struct btf *targ_btf)
2506 size_t local_essent_len, targ_essent_len;
2507 const char *local_name, *targ_name;
2508 const struct btf_type *t;
2509 struct ids_vec *cand_ids;
2513 t = btf__type_by_id(local_btf, local_type_id);
2515 return ERR_PTR(-EINVAL);
2517 local_name = btf__name_by_offset(local_btf, t->name_off);
2518 if (str_is_empty(local_name))
2519 return ERR_PTR(-EINVAL);
2520 local_essent_len = bpf_core_essential_name_len(local_name);
2522 cand_ids = calloc(1, sizeof(*cand_ids));
2524 return ERR_PTR(-ENOMEM);
2526 n = btf__get_nr_types(targ_btf);
2527 for (i = 1; i <= n; i++) {
2528 t = btf__type_by_id(targ_btf, i);
2529 targ_name = btf__name_by_offset(targ_btf, t->name_off);
2530 if (str_is_empty(targ_name))
2533 targ_essent_len = bpf_core_essential_name_len(targ_name);
2534 if (targ_essent_len != local_essent_len)
2537 if (strncmp(local_name, targ_name, local_essent_len) == 0) {
2538 pr_debug("[%d] %s: found candidate [%d] %s\n",
2539 local_type_id, local_name, i, targ_name);
2540 new_ids = realloc(cand_ids->data, cand_ids->len + 1);
2545 cand_ids->data = new_ids;
2546 cand_ids->data[cand_ids->len++] = i;
2551 bpf_core_free_cands(cand_ids);
2552 return ERR_PTR(err);
2555 /* Check two types for compatibility, skipping const/volatile/restrict and
2556 * typedefs, to ensure we are relocating offset to the compatible entities:
2557 * - any two STRUCTs/UNIONs are compatible and can be mixed;
2558 * - any two FWDs are compatible;
2559 * - any two PTRs are always compatible;
2560 * - for ENUMs, check sizes, names are ignored;
2561 * - for INT, size and bitness should match, signedness is ignored;
2562 * - for ARRAY, dimensionality is ignored, element types are checked for
2563 * compatibility recursively;
2564 * - everything else shouldn't be ever a target of relocation.
2565 * These rules are not set in stone and probably will be adjusted as we get
2566 * more experience with using BPF CO-RE relocations.
2568 static int bpf_core_fields_are_compat(const struct btf *local_btf,
2570 const struct btf *targ_btf,
2573 const struct btf_type *local_type, *targ_type;
2576 local_type = skip_mods_and_typedefs(local_btf, local_id, &local_id);
2577 targ_type = skip_mods_and_typedefs(targ_btf, targ_id, &targ_id);
2578 if (!local_type || !targ_type)
2581 if (btf_is_composite(local_type) && btf_is_composite(targ_type))
2583 if (btf_kind(local_type) != btf_kind(targ_type))
2586 switch (btf_kind(local_type)) {
2591 return local_type->size == targ_type->size;
2593 return btf_int_offset(local_type) == 0 &&
2594 btf_int_offset(targ_type) == 0 &&
2595 local_type->size == targ_type->size &&
2596 btf_int_bits(local_type) == btf_int_bits(targ_type);
2597 case BTF_KIND_ARRAY:
2598 local_id = btf_array(local_type)->type;
2599 targ_id = btf_array(targ_type)->type;
2602 pr_warning("unexpected kind %d relocated, local [%d], target [%d]\n",
2603 btf_kind(local_type), local_id, targ_id);
2609 * Given single high-level named field accessor in local type, find
2610 * corresponding high-level accessor for a target type. Along the way,
2611 * maintain low-level spec for target as well. Also keep updating target
2614 * Searching is performed through recursive exhaustive enumeration of all
2615 * fields of a struct/union. If there are any anonymous (embedded)
2616 * structs/unions, they are recursively searched as well. If field with
2617 * desired name is found, check compatibility between local and target types,
2618 * before returning result.
2620 * 1 is returned, if field is found.
2621 * 0 is returned if no compatible field is found.
2622 * <0 is returned on error.
2624 static int bpf_core_match_member(const struct btf *local_btf,
2625 const struct bpf_core_accessor *local_acc,
2626 const struct btf *targ_btf,
2628 struct bpf_core_spec *spec,
2629 __u32 *next_targ_id)
2631 const struct btf_type *local_type, *targ_type;
2632 const struct btf_member *local_member, *m;
2633 const char *local_name, *targ_name;
2637 targ_type = skip_mods_and_typedefs(targ_btf, targ_id, &targ_id);
2640 if (!btf_is_composite(targ_type))
2643 local_id = local_acc->type_id;
2644 local_type = btf__type_by_id(local_btf, local_id);
2645 local_member = btf_members(local_type) + local_acc->idx;
2646 local_name = btf__name_by_offset(local_btf, local_member->name_off);
2648 n = btf_vlen(targ_type);
2649 m = btf_members(targ_type);
2650 for (i = 0; i < n; i++, m++) {
2653 /* bitfield relocations not supported */
2654 if (btf_member_bitfield_size(targ_type, i))
2656 offset = btf_member_bit_offset(targ_type, i);
2660 /* too deep struct/union/array nesting */
2661 if (spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
2664 /* speculate this member will be the good one */
2665 spec->offset += offset / 8;
2666 spec->raw_spec[spec->raw_len++] = i;
2668 targ_name = btf__name_by_offset(targ_btf, m->name_off);
2669 if (str_is_empty(targ_name)) {
2670 /* embedded struct/union, we need to go deeper */
2671 found = bpf_core_match_member(local_btf, local_acc,
2673 spec, next_targ_id);
2674 if (found) /* either found or error */
2676 } else if (strcmp(local_name, targ_name) == 0) {
2677 /* matching named field */
2678 struct bpf_core_accessor *targ_acc;
2680 targ_acc = &spec->spec[spec->len++];
2681 targ_acc->type_id = targ_id;
2683 targ_acc->name = targ_name;
2685 *next_targ_id = m->type;
2686 found = bpf_core_fields_are_compat(local_btf,
2690 spec->len--; /* pop accessor */
2693 /* member turned out not to be what we looked for */
2694 spec->offset -= offset / 8;
2702 * Try to match local spec to a target type and, if successful, produce full
2703 * target spec (high-level, low-level + offset).
2705 static int bpf_core_spec_match(struct bpf_core_spec *local_spec,
2706 const struct btf *targ_btf, __u32 targ_id,
2707 struct bpf_core_spec *targ_spec)
2709 const struct btf_type *targ_type;
2710 const struct bpf_core_accessor *local_acc;
2711 struct bpf_core_accessor *targ_acc;
2714 memset(targ_spec, 0, sizeof(*targ_spec));
2715 targ_spec->btf = targ_btf;
2717 local_acc = &local_spec->spec[0];
2718 targ_acc = &targ_spec->spec[0];
2720 for (i = 0; i < local_spec->len; i++, local_acc++, targ_acc++) {
2721 targ_type = skip_mods_and_typedefs(targ_spec->btf, targ_id,
2726 if (local_acc->name) {
2727 matched = bpf_core_match_member(local_spec->btf,
2730 targ_spec, &targ_id);
2734 /* for i=0, targ_id is already treated as array element
2735 * type (because it's the original struct), for others
2736 * we should find array element type first
2739 const struct btf_array *a;
2741 if (!btf_is_array(targ_type))
2744 a = btf_array(targ_type);
2745 if (local_acc->idx >= a->nelems)
2747 if (!skip_mods_and_typedefs(targ_btf, a->type,
2752 /* too deep struct/union/array nesting */
2753 if (targ_spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
2756 targ_acc->type_id = targ_id;
2757 targ_acc->idx = local_acc->idx;
2758 targ_acc->name = NULL;
2760 targ_spec->raw_spec[targ_spec->raw_len] = targ_acc->idx;
2761 targ_spec->raw_len++;
2763 sz = btf__resolve_size(targ_btf, targ_id);
2766 targ_spec->offset += local_acc->idx * sz;
2774 * Patch relocatable BPF instruction.
2776 * Patched value is determined by relocation kind and target specification.
2777 * For field existence relocation target spec will be NULL if field is not
2779 * Expected insn->imm value is determined using relocation kind and local
2780 * spec, and is checked before patching instruction. If actual insn->imm value
2781 * is wrong, bail out with error.
2783 * Currently three kinds of BPF instructions are supported:
2784 * 1. rX = <imm> (assignment with immediate operand);
2785 * 2. rX += <imm> (arithmetic operations with immediate operand);
2787 static int bpf_core_reloc_insn(struct bpf_program *prog,
2788 const struct bpf_field_reloc *relo,
2789 const struct bpf_core_spec *local_spec,
2790 const struct bpf_core_spec *targ_spec)
2792 __u32 orig_val, new_val;
2793 struct bpf_insn *insn;
2797 if (relo->insn_off % sizeof(struct bpf_insn))
2799 insn_idx = relo->insn_off / sizeof(struct bpf_insn);
2801 switch (relo->kind) {
2802 case BPF_FIELD_BYTE_OFFSET:
2803 orig_val = local_spec->offset;
2805 new_val = targ_spec->offset;
2807 pr_warning("prog '%s': patching insn #%d w/ failed reloc, imm %d -> %d\n",
2808 bpf_program__title(prog, false), insn_idx,
2810 new_val = (__u32)-1;
2813 case BPF_FIELD_EXISTS:
2814 orig_val = 1; /* can't generate EXISTS relo w/o local field */
2815 new_val = targ_spec ? 1 : 0;
2818 pr_warning("prog '%s': unknown relo %d at insn #%d'\n",
2819 bpf_program__title(prog, false),
2820 relo->kind, insn_idx);
2824 insn = &prog->insns[insn_idx];
2825 class = BPF_CLASS(insn->code);
2827 if (class == BPF_ALU || class == BPF_ALU64) {
2828 if (BPF_SRC(insn->code) != BPF_K)
2830 if (insn->imm != orig_val)
2832 insn->imm = new_val;
2833 pr_debug("prog '%s': patched insn #%d (ALU/ALU64) imm %d -> %d\n",
2834 bpf_program__title(prog, false),
2835 insn_idx, orig_val, new_val);
2837 pr_warning("prog '%s': trying to relocate unrecognized insn #%d, code:%x, src:%x, dst:%x, off:%x, imm:%x\n",
2838 bpf_program__title(prog, false),
2839 insn_idx, insn->code, insn->src_reg, insn->dst_reg,
2840 insn->off, insn->imm);
2847 static struct btf *btf_load_raw(const char *path)
2855 if (stat(path, &st))
2856 return ERR_PTR(-errno);
2858 data = malloc(st.st_size);
2860 return ERR_PTR(-ENOMEM);
2862 f = fopen(path, "rb");
2864 btf = ERR_PTR(-errno);
2868 read_cnt = fread(data, 1, st.st_size, f);
2870 if (read_cnt < st.st_size) {
2871 btf = ERR_PTR(-EBADF);
2875 btf = btf__new(data, read_cnt);
2883 * Probe few well-known locations for vmlinux kernel image and try to load BTF
2884 * data out of it to use for target BTF.
2886 static struct btf *bpf_core_find_kernel_btf(void)
2889 const char *path_fmt;
2892 /* try canonical vmlinux BTF through sysfs first */
2893 { "/sys/kernel/btf/vmlinux", true /* raw BTF */ },
2894 /* fall back to trying to find vmlinux ELF on disk otherwise */
2895 { "/boot/vmlinux-%1$s" },
2896 { "/lib/modules/%1$s/vmlinux-%1$s" },
2897 { "/lib/modules/%1$s/build/vmlinux" },
2898 { "/usr/lib/modules/%1$s/kernel/vmlinux" },
2899 { "/usr/lib/debug/boot/vmlinux-%1$s" },
2900 { "/usr/lib/debug/boot/vmlinux-%1$s.debug" },
2901 { "/usr/lib/debug/lib/modules/%1$s/vmlinux" },
2903 char path[PATH_MAX + 1];
2910 for (i = 0; i < ARRAY_SIZE(locations); i++) {
2911 snprintf(path, PATH_MAX, locations[i].path_fmt, buf.release);
2913 if (access(path, R_OK))
2916 if (locations[i].raw_btf)
2917 btf = btf_load_raw(path);
2919 btf = btf__parse_elf(path, NULL);
2921 pr_debug("loading kernel BTF '%s': %ld\n",
2922 path, IS_ERR(btf) ? PTR_ERR(btf) : 0);
2929 pr_warning("failed to find valid kernel BTF\n");
2930 return ERR_PTR(-ESRCH);
2933 /* Output spec definition in the format:
2934 * [<type-id>] (<type-name>) + <raw-spec> => <offset>@<spec>,
2935 * where <spec> is a C-syntax view of recorded field access, e.g.: x.a[3].b
2937 static void bpf_core_dump_spec(int level, const struct bpf_core_spec *spec)
2939 const struct btf_type *t;
2944 type_id = spec->spec[0].type_id;
2945 t = btf__type_by_id(spec->btf, type_id);
2946 s = btf__name_by_offset(spec->btf, t->name_off);
2947 libbpf_print(level, "[%u] %s + ", type_id, s);
2949 for (i = 0; i < spec->raw_len; i++)
2950 libbpf_print(level, "%d%s", spec->raw_spec[i],
2951 i == spec->raw_len - 1 ? " => " : ":");
2953 libbpf_print(level, "%u @ &x", spec->offset);
2955 for (i = 0; i < spec->len; i++) {
2956 if (spec->spec[i].name)
2957 libbpf_print(level, ".%s", spec->spec[i].name);
2959 libbpf_print(level, "[%u]", spec->spec[i].idx);
2964 static size_t bpf_core_hash_fn(const void *key, void *ctx)
2969 static bool bpf_core_equal_fn(const void *k1, const void *k2, void *ctx)
2974 static void *u32_as_hash_key(__u32 x)
2976 return (void *)(uintptr_t)x;
2980 * CO-RE relocate single instruction.
2982 * The outline and important points of the algorithm:
2983 * 1. For given local type, find corresponding candidate target types.
2984 * Candidate type is a type with the same "essential" name, ignoring
2985 * everything after last triple underscore (___). E.g., `sample`,
2986 * `sample___flavor_one`, `sample___flavor_another_one`, are all candidates
2987 * for each other. Names with triple underscore are referred to as
2988 * "flavors" and are useful, among other things, to allow to
2989 * specify/support incompatible variations of the same kernel struct, which
2990 * might differ between different kernel versions and/or build
2993 * N.B. Struct "flavors" could be generated by bpftool's BTF-to-C
2994 * converter, when deduplicated BTF of a kernel still contains more than
2995 * one different types with the same name. In that case, ___2, ___3, etc
2996 * are appended starting from second name conflict. But start flavors are
2997 * also useful to be defined "locally", in BPF program, to extract same
2998 * data from incompatible changes between different kernel
2999 * versions/configurations. For instance, to handle field renames between
3000 * kernel versions, one can use two flavors of the struct name with the
3001 * same common name and use conditional relocations to extract that field,
3002 * depending on target kernel version.
3003 * 2. For each candidate type, try to match local specification to this
3004 * candidate target type. Matching involves finding corresponding
3005 * high-level spec accessors, meaning that all named fields should match,
3006 * as well as all array accesses should be within the actual bounds. Also,
3007 * types should be compatible (see bpf_core_fields_are_compat for details).
3008 * 3. It is supported and expected that there might be multiple flavors
3009 * matching the spec. As long as all the specs resolve to the same set of
3010 * offsets across all candidates, there is no error. If there is any
3011 * ambiguity, CO-RE relocation will fail. This is necessary to accomodate
3012 * imprefection of BTF deduplication, which can cause slight duplication of
3013 * the same BTF type, if some directly or indirectly referenced (by
3014 * pointer) type gets resolved to different actual types in different
3015 * object files. If such situation occurs, deduplicated BTF will end up
3016 * with two (or more) structurally identical types, which differ only in
3017 * types they refer to through pointer. This should be OK in most cases and
3019 * 4. Candidate types search is performed by linearly scanning through all
3020 * types in target BTF. It is anticipated that this is overall more
3021 * efficient memory-wise and not significantly worse (if not better)
3022 * CPU-wise compared to prebuilding a map from all local type names to
3023 * a list of candidate type names. It's also sped up by caching resolved
3024 * list of matching candidates per each local "root" type ID, that has at
3025 * least one bpf_field_reloc associated with it. This list is shared
3026 * between multiple relocations for the same type ID and is updated as some
3027 * of the candidates are pruned due to structural incompatibility.
3029 static int bpf_core_reloc_field(struct bpf_program *prog,
3030 const struct bpf_field_reloc *relo,
3032 const struct btf *local_btf,
3033 const struct btf *targ_btf,
3034 struct hashmap *cand_cache)
3036 const char *prog_name = bpf_program__title(prog, false);
3037 struct bpf_core_spec local_spec, cand_spec, targ_spec;
3038 const void *type_key = u32_as_hash_key(relo->type_id);
3039 const struct btf_type *local_type, *cand_type;
3040 const char *local_name, *cand_name;
3041 struct ids_vec *cand_ids;
3042 __u32 local_id, cand_id;
3043 const char *spec_str;
3046 local_id = relo->type_id;
3047 local_type = btf__type_by_id(local_btf, local_id);
3051 local_name = btf__name_by_offset(local_btf, local_type->name_off);
3052 if (str_is_empty(local_name))
3055 spec_str = btf__name_by_offset(local_btf, relo->access_str_off);
3056 if (str_is_empty(spec_str))
3059 err = bpf_core_spec_parse(local_btf, local_id, spec_str, &local_spec);
3061 pr_warning("prog '%s': relo #%d: parsing [%d] %s + %s failed: %d\n",
3062 prog_name, relo_idx, local_id, local_name, spec_str,
3067 pr_debug("prog '%s': relo #%d: spec is ", prog_name, relo_idx);
3068 bpf_core_dump_spec(LIBBPF_DEBUG, &local_spec);
3069 libbpf_print(LIBBPF_DEBUG, "\n");
3071 if (!hashmap__find(cand_cache, type_key, (void **)&cand_ids)) {
3072 cand_ids = bpf_core_find_cands(local_btf, local_id, targ_btf);
3073 if (IS_ERR(cand_ids)) {
3074 pr_warning("prog '%s': relo #%d: target candidate search failed for [%d] %s: %ld",
3075 prog_name, relo_idx, local_id, local_name,
3077 return PTR_ERR(cand_ids);
3079 err = hashmap__set(cand_cache, type_key, cand_ids, NULL, NULL);
3081 bpf_core_free_cands(cand_ids);
3086 for (i = 0, j = 0; i < cand_ids->len; i++) {
3087 cand_id = cand_ids->data[i];
3088 cand_type = btf__type_by_id(targ_btf, cand_id);
3089 cand_name = btf__name_by_offset(targ_btf, cand_type->name_off);
3091 err = bpf_core_spec_match(&local_spec, targ_btf,
3092 cand_id, &cand_spec);
3093 pr_debug("prog '%s': relo #%d: matching candidate #%d %s against spec ",
3094 prog_name, relo_idx, i, cand_name);
3095 bpf_core_dump_spec(LIBBPF_DEBUG, &cand_spec);
3096 libbpf_print(LIBBPF_DEBUG, ": %d\n", err);
3098 pr_warning("prog '%s': relo #%d: matching error: %d\n",
3099 prog_name, relo_idx, err);
3106 targ_spec = cand_spec;
3107 } else if (cand_spec.offset != targ_spec.offset) {
3108 /* if there are many candidates, they should all
3109 * resolve to the same offset
3111 pr_warning("prog '%s': relo #%d: offset ambiguity: %u != %u\n",
3112 prog_name, relo_idx, cand_spec.offset,
3117 cand_ids->data[j++] = cand_spec.spec[0].type_id;
3121 * For BPF_FIELD_EXISTS relo or when relaxed CO-RE reloc mode is
3122 * requested, it's expected that we might not find any candidates.
3123 * In this case, if field wasn't found in any candidate, the list of
3124 * candidates shouldn't change at all, we'll just handle relocating
3125 * appropriately, depending on relo's kind.
3130 if (j == 0 && !prog->obj->relaxed_core_relocs &&
3131 relo->kind != BPF_FIELD_EXISTS) {
3132 pr_warning("prog '%s': relo #%d: no matching targets found for [%d] %s + %s\n",
3133 prog_name, relo_idx, local_id, local_name, spec_str);
3137 /* bpf_core_reloc_insn should know how to handle missing targ_spec */
3138 err = bpf_core_reloc_insn(prog, relo, &local_spec,
3139 j ? &targ_spec : NULL);
3141 pr_warning("prog '%s': relo #%d: failed to patch insn at offset %d: %d\n",
3142 prog_name, relo_idx, relo->insn_off, err);
3150 bpf_core_reloc_fields(struct bpf_object *obj, const char *targ_btf_path)
3152 const struct btf_ext_info_sec *sec;
3153 const struct bpf_field_reloc *rec;
3154 const struct btf_ext_info *seg;
3155 struct hashmap_entry *entry;
3156 struct hashmap *cand_cache = NULL;
3157 struct bpf_program *prog;
3158 struct btf *targ_btf;
3159 const char *sec_name;
3163 targ_btf = btf__parse_elf(targ_btf_path, NULL);
3165 targ_btf = bpf_core_find_kernel_btf();
3166 if (IS_ERR(targ_btf)) {
3167 pr_warning("failed to get target BTF: %ld\n",
3169 return PTR_ERR(targ_btf);
3172 cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
3173 if (IS_ERR(cand_cache)) {
3174 err = PTR_ERR(cand_cache);
3178 seg = &obj->btf_ext->field_reloc_info;
3179 for_each_btf_ext_sec(seg, sec) {
3180 sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
3181 if (str_is_empty(sec_name)) {
3185 prog = bpf_object__find_program_by_title(obj, sec_name);
3187 pr_warning("failed to find program '%s' for CO-RE offset relocation\n",
3193 pr_debug("prog '%s': performing %d CO-RE offset relocs\n",
3194 sec_name, sec->num_info);
3196 for_each_btf_ext_rec(seg, sec, i, rec) {
3197 err = bpf_core_reloc_field(prog, rec, i, obj->btf,
3198 targ_btf, cand_cache);
3200 pr_warning("prog '%s': relo #%d: failed to relocate: %d\n",
3208 btf__free(targ_btf);
3209 if (!IS_ERR_OR_NULL(cand_cache)) {
3210 hashmap__for_each_entry(cand_cache, entry, i) {
3211 bpf_core_free_cands(entry->value);
3213 hashmap__free(cand_cache);
3219 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
3223 if (obj->btf_ext->field_reloc_info.len)
3224 err = bpf_core_reloc_fields(obj, targ_btf_path);
3230 bpf_program__reloc_text(struct bpf_program *prog, struct bpf_object *obj,
3231 struct reloc_desc *relo)
3233 struct bpf_insn *insn, *new_insn;
3234 struct bpf_program *text;
3238 if (relo->type != RELO_CALL)
3239 return -LIBBPF_ERRNO__RELOC;
3241 if (prog->idx == obj->efile.text_shndx) {
3242 pr_warning("relo in .text insn %d into off %d\n",
3243 relo->insn_idx, relo->text_off);
3244 return -LIBBPF_ERRNO__RELOC;
3247 if (prog->main_prog_cnt == 0) {
3248 text = bpf_object__find_prog_by_idx(obj, obj->efile.text_shndx);
3250 pr_warning("no .text section found yet relo into text exist\n");
3251 return -LIBBPF_ERRNO__RELOC;
3253 new_cnt = prog->insns_cnt + text->insns_cnt;
3254 new_insn = reallocarray(prog->insns, new_cnt, sizeof(*insn));
3256 pr_warning("oom in prog realloc\n");
3261 err = bpf_program_reloc_btf_ext(prog, obj,
3268 memcpy(new_insn + prog->insns_cnt, text->insns,
3269 text->insns_cnt * sizeof(*insn));
3270 prog->insns = new_insn;
3271 prog->main_prog_cnt = prog->insns_cnt;
3272 prog->insns_cnt = new_cnt;
3273 pr_debug("added %zd insn from %s to prog %s\n",
3274 text->insns_cnt, text->section_name,
3275 prog->section_name);
3277 insn = &prog->insns[relo->insn_idx];
3278 insn->imm += prog->main_prog_cnt - relo->insn_idx;
3283 bpf_program__relocate(struct bpf_program *prog, struct bpf_object *obj)
3291 err = bpf_program_reloc_btf_ext(prog, obj,
3292 prog->section_name, 0);
3297 if (!prog->reloc_desc)
3300 for (i = 0; i < prog->nr_reloc; i++) {
3301 if (prog->reloc_desc[i].type == RELO_LD64 ||
3302 prog->reloc_desc[i].type == RELO_DATA) {
3303 bool relo_data = prog->reloc_desc[i].type == RELO_DATA;
3304 struct bpf_insn *insns = prog->insns;
3305 int insn_idx, map_idx;
3307 insn_idx = prog->reloc_desc[i].insn_idx;
3308 map_idx = prog->reloc_desc[i].map_idx;
3310 if (insn_idx + 1 >= (int)prog->insns_cnt) {
3311 pr_warning("relocation out of range: '%s'\n",
3312 prog->section_name);
3313 return -LIBBPF_ERRNO__RELOC;
3317 insns[insn_idx].src_reg = BPF_PSEUDO_MAP_FD;
3319 insns[insn_idx].src_reg = BPF_PSEUDO_MAP_VALUE;
3320 insns[insn_idx + 1].imm = insns[insn_idx].imm;
3322 insns[insn_idx].imm = obj->maps[map_idx].fd;
3323 } else if (prog->reloc_desc[i].type == RELO_CALL) {
3324 err = bpf_program__reloc_text(prog, obj,
3325 &prog->reloc_desc[i]);
3331 zfree(&prog->reloc_desc);
3337 bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
3339 struct bpf_program *prog;
3344 err = bpf_object__relocate_core(obj, targ_btf_path);
3346 pr_warning("failed to perform CO-RE relocations: %d\n",
3351 for (i = 0; i < obj->nr_programs; i++) {
3352 prog = &obj->programs[i];
3354 err = bpf_program__relocate(prog, obj);
3356 pr_warning("failed to relocate '%s'\n",
3357 prog->section_name);
3364 static int bpf_object__collect_reloc(struct bpf_object *obj)
3368 if (!obj_elf_valid(obj)) {
3369 pr_warning("Internal error: elf object is closed\n");
3370 return -LIBBPF_ERRNO__INTERNAL;
3373 for (i = 0; i < obj->efile.nr_reloc; i++) {
3374 GElf_Shdr *shdr = &obj->efile.reloc[i].shdr;
3375 Elf_Data *data = obj->efile.reloc[i].data;
3376 int idx = shdr->sh_info;
3377 struct bpf_program *prog;
3379 if (shdr->sh_type != SHT_REL) {
3380 pr_warning("internal error at %d\n", __LINE__);
3381 return -LIBBPF_ERRNO__INTERNAL;
3384 prog = bpf_object__find_prog_by_idx(obj, idx);
3386 pr_warning("relocation failed: no section(%d)\n", idx);
3387 return -LIBBPF_ERRNO__RELOC;
3390 err = bpf_program__collect_reloc(prog, shdr, data, obj);
3398 load_program(struct bpf_program *prog, struct bpf_insn *insns, int insns_cnt,
3399 char *license, __u32 kern_version, int *pfd)
3401 struct bpf_load_program_attr load_attr;
3402 char *cp, errmsg[STRERR_BUFSIZE];
3403 int log_buf_size = BPF_LOG_BUF_SIZE;
3407 if (!insns || !insns_cnt)
3410 memset(&load_attr, 0, sizeof(struct bpf_load_program_attr));
3411 load_attr.prog_type = prog->type;
3412 load_attr.expected_attach_type = prog->expected_attach_type;
3413 if (prog->caps->name)
3414 load_attr.name = prog->name;
3415 load_attr.insns = insns;
3416 load_attr.insns_cnt = insns_cnt;
3417 load_attr.license = license;
3418 load_attr.kern_version = kern_version;
3419 load_attr.prog_ifindex = prog->prog_ifindex;
3420 /* if .BTF.ext was loaded, kernel supports associated BTF for prog */
3421 if (prog->obj->btf_ext)
3422 btf_fd = bpf_object__btf_fd(prog->obj);
3425 load_attr.prog_btf_fd = btf_fd >= 0 ? btf_fd : 0;
3426 load_attr.func_info = prog->func_info;
3427 load_attr.func_info_rec_size = prog->func_info_rec_size;
3428 load_attr.func_info_cnt = prog->func_info_cnt;
3429 load_attr.line_info = prog->line_info;
3430 load_attr.line_info_rec_size = prog->line_info_rec_size;
3431 load_attr.line_info_cnt = prog->line_info_cnt;
3432 load_attr.log_level = prog->log_level;
3433 load_attr.prog_flags = prog->prog_flags;
3436 log_buf = malloc(log_buf_size);
3438 pr_warning("Alloc log buffer for bpf loader error, continue without log\n");
3440 ret = bpf_load_program_xattr(&load_attr, log_buf, log_buf_size);
3443 if (load_attr.log_level)
3444 pr_debug("verifier log:\n%s", log_buf);
3450 if (errno == ENOSPC) {
3455 ret = -LIBBPF_ERRNO__LOAD;
3456 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
3457 pr_warning("load bpf program failed: %s\n", cp);
3459 if (log_buf && log_buf[0] != '\0') {
3460 ret = -LIBBPF_ERRNO__VERIFY;
3461 pr_warning("-- BEGIN DUMP LOG ---\n");
3462 pr_warning("\n%s\n", log_buf);
3463 pr_warning("-- END LOG --\n");
3464 } else if (load_attr.insns_cnt >= BPF_MAXINSNS) {
3465 pr_warning("Program too large (%zu insns), at most %d insns\n",
3466 load_attr.insns_cnt, BPF_MAXINSNS);
3467 ret = -LIBBPF_ERRNO__PROG2BIG;
3469 /* Wrong program type? */
3470 if (load_attr.prog_type != BPF_PROG_TYPE_KPROBE) {
3473 load_attr.prog_type = BPF_PROG_TYPE_KPROBE;
3474 load_attr.expected_attach_type = 0;
3475 fd = bpf_load_program_xattr(&load_attr, NULL, 0);
3478 ret = -LIBBPF_ERRNO__PROGTYPE;
3484 ret = -LIBBPF_ERRNO__KVER;
3493 bpf_program__load(struct bpf_program *prog,
3494 char *license, __u32 kern_version)
3498 if (prog->instances.nr < 0 || !prog->instances.fds) {
3499 if (prog->preprocessor) {
3500 pr_warning("Internal error: can't load program '%s'\n",
3501 prog->section_name);
3502 return -LIBBPF_ERRNO__INTERNAL;
3505 prog->instances.fds = malloc(sizeof(int));
3506 if (!prog->instances.fds) {
3507 pr_warning("Not enough memory for BPF fds\n");
3510 prog->instances.nr = 1;
3511 prog->instances.fds[0] = -1;
3514 if (!prog->preprocessor) {
3515 if (prog->instances.nr != 1) {
3516 pr_warning("Program '%s' is inconsistent: nr(%d) != 1\n",
3517 prog->section_name, prog->instances.nr);
3519 err = load_program(prog, prog->insns, prog->insns_cnt,
3520 license, kern_version, &fd);
3522 prog->instances.fds[0] = fd;
3526 for (i = 0; i < prog->instances.nr; i++) {
3527 struct bpf_prog_prep_result result;
3528 bpf_program_prep_t preprocessor = prog->preprocessor;
3530 memset(&result, 0, sizeof(result));
3531 err = preprocessor(prog, i, prog->insns,
3532 prog->insns_cnt, &result);
3534 pr_warning("Preprocessing the %dth instance of program '%s' failed\n",
3535 i, prog->section_name);
3539 if (!result.new_insn_ptr || !result.new_insn_cnt) {
3540 pr_debug("Skip loading the %dth instance of program '%s'\n",
3541 i, prog->section_name);
3542 prog->instances.fds[i] = -1;
3548 err = load_program(prog, result.new_insn_ptr,
3549 result.new_insn_cnt,
3550 license, kern_version, &fd);
3553 pr_warning("Loading the %dth instance of program '%s' failed\n",
3554 i, prog->section_name);
3560 prog->instances.fds[i] = fd;
3564 pr_warning("failed to load program '%s'\n",
3565 prog->section_name);
3566 zfree(&prog->insns);
3567 prog->insns_cnt = 0;
3571 static bool bpf_program__is_function_storage(const struct bpf_program *prog,
3572 const struct bpf_object *obj)
3574 return prog->idx == obj->efile.text_shndx && obj->has_pseudo_calls;
3578 bpf_object__load_progs(struct bpf_object *obj, int log_level)
3583 for (i = 0; i < obj->nr_programs; i++) {
3584 if (bpf_program__is_function_storage(&obj->programs[i], obj))
3586 obj->programs[i].log_level |= log_level;
3587 err = bpf_program__load(&obj->programs[i],
3596 static struct bpf_object *
3597 __bpf_object__open(const char *path, const void *obj_buf, size_t obj_buf_sz,
3598 struct bpf_object_open_opts *opts)
3600 struct bpf_object *obj;
3601 const char *obj_name;
3606 if (elf_version(EV_CURRENT) == EV_NONE) {
3607 pr_warning("failed to init libelf for %s\n",
3608 path ? : "(mem buf)");
3609 return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
3612 if (!OPTS_VALID(opts, bpf_object_open_opts))
3613 return ERR_PTR(-EINVAL);
3615 obj_name = OPTS_GET(opts, object_name, path);
3618 snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
3619 (unsigned long)obj_buf,
3620 (unsigned long)obj_buf_sz);
3621 obj_name = tmp_name;
3624 pr_debug("loading object '%s' from buffer\n", obj_name);
3627 obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
3631 obj->relaxed_core_relocs = OPTS_GET(opts, relaxed_core_relocs, false);
3632 relaxed_maps = OPTS_GET(opts, relaxed_maps, false);
3634 CHECK_ERR(bpf_object__elf_init(obj), err, out);
3635 CHECK_ERR(bpf_object__check_endianness(obj), err, out);
3636 CHECK_ERR(bpf_object__probe_caps(obj), err, out);
3637 CHECK_ERR(bpf_object__elf_collect(obj, relaxed_maps), err, out);
3638 CHECK_ERR(bpf_object__collect_reloc(obj), err, out);
3640 bpf_object__elf_finish(obj);
3643 bpf_object__close(obj);
3644 return ERR_PTR(err);
3647 static struct bpf_object *
3648 __bpf_object__open_xattr(struct bpf_object_open_attr *attr, int flags)
3650 LIBBPF_OPTS(bpf_object_open_opts, opts,
3651 .relaxed_maps = flags & MAPS_RELAX_COMPAT,
3654 /* param validation */
3658 pr_debug("loading %s\n", attr->file);
3659 return __bpf_object__open(attr->file, NULL, 0, &opts);
3662 struct bpf_object *bpf_object__open_xattr(struct bpf_object_open_attr *attr)
3664 return __bpf_object__open_xattr(attr, 0);
3667 struct bpf_object *bpf_object__open(const char *path)
3669 struct bpf_object_open_attr attr = {
3671 .prog_type = BPF_PROG_TYPE_UNSPEC,
3674 return bpf_object__open_xattr(&attr);
3678 bpf_object__open_file(const char *path, struct bpf_object_open_opts *opts)
3681 return ERR_PTR(-EINVAL);
3683 pr_debug("loading %s\n", path);
3685 return __bpf_object__open(path, NULL, 0, opts);
3689 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
3690 struct bpf_object_open_opts *opts)
3692 if (!obj_buf || obj_buf_sz == 0)
3693 return ERR_PTR(-EINVAL);
3695 return __bpf_object__open(NULL, obj_buf, obj_buf_sz, opts);
3699 bpf_object__open_buffer(const void *obj_buf, size_t obj_buf_sz,
3702 LIBBPF_OPTS(bpf_object_open_opts, opts,
3703 .object_name = name,
3704 /* wrong default, but backwards-compatible */
3705 .relaxed_maps = true,
3708 /* returning NULL is wrong, but backwards-compatible */
3709 if (!obj_buf || obj_buf_sz == 0)
3712 return bpf_object__open_mem(obj_buf, obj_buf_sz, &opts);
3715 int bpf_object__unload(struct bpf_object *obj)
3722 for (i = 0; i < obj->nr_maps; i++)
3723 zclose(obj->maps[i].fd);
3725 for (i = 0; i < obj->nr_programs; i++)
3726 bpf_program__unload(&obj->programs[i]);
3731 int bpf_object__load_xattr(struct bpf_object_load_attr *attr)
3733 struct bpf_object *obj;
3743 pr_warning("object should not be loaded twice\n");
3749 CHECK_ERR(bpf_object__create_maps(obj), err, out);
3750 CHECK_ERR(bpf_object__relocate(obj, attr->target_btf_path), err, out);
3751 CHECK_ERR(bpf_object__load_progs(obj, attr->log_level), err, out);
3755 bpf_object__unload(obj);
3756 pr_warning("failed to load object '%s'\n", obj->path);
3760 int bpf_object__load(struct bpf_object *obj)
3762 struct bpf_object_load_attr attr = {
3766 return bpf_object__load_xattr(&attr);
3769 static int check_path(const char *path)
3771 char *cp, errmsg[STRERR_BUFSIZE];
3772 struct statfs st_fs;
3779 dname = strdup(path);
3783 dir = dirname(dname);
3784 if (statfs(dir, &st_fs)) {
3785 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
3786 pr_warning("failed to statfs %s: %s\n", dir, cp);
3791 if (!err && st_fs.f_type != BPF_FS_MAGIC) {
3792 pr_warning("specified path %s is not on BPF FS\n", path);
3799 int bpf_program__pin_instance(struct bpf_program *prog, const char *path,
3802 char *cp, errmsg[STRERR_BUFSIZE];
3805 err = check_path(path);
3810 pr_warning("invalid program pointer\n");
3814 if (instance < 0 || instance >= prog->instances.nr) {
3815 pr_warning("invalid prog instance %d of prog %s (max %d)\n",
3816 instance, prog->section_name, prog->instances.nr);
3820 if (bpf_obj_pin(prog->instances.fds[instance], path)) {
3821 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
3822 pr_warning("failed to pin program: %s\n", cp);
3825 pr_debug("pinned program '%s'\n", path);
3830 int bpf_program__unpin_instance(struct bpf_program *prog, const char *path,
3835 err = check_path(path);
3840 pr_warning("invalid program pointer\n");
3844 if (instance < 0 || instance >= prog->instances.nr) {
3845 pr_warning("invalid prog instance %d of prog %s (max %d)\n",
3846 instance, prog->section_name, prog->instances.nr);
3853 pr_debug("unpinned program '%s'\n", path);
3858 static int make_dir(const char *path)
3860 char *cp, errmsg[STRERR_BUFSIZE];
3863 if (mkdir(path, 0700) && errno != EEXIST)
3867 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
3868 pr_warning("failed to mkdir %s: %s\n", path, cp);
3873 int bpf_program__pin(struct bpf_program *prog, const char *path)
3877 err = check_path(path);
3882 pr_warning("invalid program pointer\n");
3886 if (prog->instances.nr <= 0) {
3887 pr_warning("no instances of prog %s to pin\n",
3888 prog->section_name);
3892 if (prog->instances.nr == 1) {
3893 /* don't create subdirs when pinning single instance */
3894 return bpf_program__pin_instance(prog, path, 0);
3897 err = make_dir(path);
3901 for (i = 0; i < prog->instances.nr; i++) {
3905 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
3909 } else if (len >= PATH_MAX) {
3910 err = -ENAMETOOLONG;
3914 err = bpf_program__pin_instance(prog, buf, i);
3922 for (i = i - 1; i >= 0; i--) {
3926 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
3929 else if (len >= PATH_MAX)
3932 bpf_program__unpin_instance(prog, buf, i);
3940 int bpf_program__unpin(struct bpf_program *prog, const char *path)
3944 err = check_path(path);
3949 pr_warning("invalid program pointer\n");
3953 if (prog->instances.nr <= 0) {
3954 pr_warning("no instances of prog %s to pin\n",
3955 prog->section_name);
3959 if (prog->instances.nr == 1) {
3960 /* don't create subdirs when pinning single instance */
3961 return bpf_program__unpin_instance(prog, path, 0);
3964 for (i = 0; i < prog->instances.nr; i++) {
3968 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
3971 else if (len >= PATH_MAX)
3972 return -ENAMETOOLONG;
3974 err = bpf_program__unpin_instance(prog, buf, i);
3986 int bpf_map__pin(struct bpf_map *map, const char *path)
3988 char *cp, errmsg[STRERR_BUFSIZE];
3991 err = check_path(path);
3996 pr_warning("invalid map pointer\n");
4000 if (bpf_obj_pin(map->fd, path)) {
4001 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
4002 pr_warning("failed to pin map: %s\n", cp);
4006 pr_debug("pinned map '%s'\n", path);
4011 int bpf_map__unpin(struct bpf_map *map, const char *path)
4015 err = check_path(path);
4020 pr_warning("invalid map pointer\n");
4027 pr_debug("unpinned map '%s'\n", path);
4032 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
4034 struct bpf_map *map;
4041 pr_warning("object not yet loaded; load it first\n");
4045 err = make_dir(path);
4049 bpf_object__for_each_map(map, obj) {
4053 len = snprintf(buf, PATH_MAX, "%s/%s", path,
4054 bpf_map__name(map));
4057 goto err_unpin_maps;
4058 } else if (len >= PATH_MAX) {
4059 err = -ENAMETOOLONG;
4060 goto err_unpin_maps;
4063 err = bpf_map__pin(map, buf);
4065 goto err_unpin_maps;
4071 while ((map = bpf_map__prev(map, obj))) {
4075 len = snprintf(buf, PATH_MAX, "%s/%s", path,
4076 bpf_map__name(map));
4079 else if (len >= PATH_MAX)
4082 bpf_map__unpin(map, buf);
4088 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
4090 struct bpf_map *map;
4096 bpf_object__for_each_map(map, obj) {
4100 len = snprintf(buf, PATH_MAX, "%s/%s", path,
4101 bpf_map__name(map));
4104 else if (len >= PATH_MAX)
4105 return -ENAMETOOLONG;
4107 err = bpf_map__unpin(map, buf);
4115 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
4117 struct bpf_program *prog;
4124 pr_warning("object not yet loaded; load it first\n");
4128 err = make_dir(path);
4132 bpf_object__for_each_program(prog, obj) {
4136 len = snprintf(buf, PATH_MAX, "%s/%s", path,
4140 goto err_unpin_programs;
4141 } else if (len >= PATH_MAX) {
4142 err = -ENAMETOOLONG;
4143 goto err_unpin_programs;
4146 err = bpf_program__pin(prog, buf);
4148 goto err_unpin_programs;
4154 while ((prog = bpf_program__prev(prog, obj))) {
4158 len = snprintf(buf, PATH_MAX, "%s/%s", path,
4162 else if (len >= PATH_MAX)
4165 bpf_program__unpin(prog, buf);
4171 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
4173 struct bpf_program *prog;
4179 bpf_object__for_each_program(prog, obj) {
4183 len = snprintf(buf, PATH_MAX, "%s/%s", path,
4187 else if (len >= PATH_MAX)
4188 return -ENAMETOOLONG;
4190 err = bpf_program__unpin(prog, buf);
4198 int bpf_object__pin(struct bpf_object *obj, const char *path)
4202 err = bpf_object__pin_maps(obj, path);
4206 err = bpf_object__pin_programs(obj, path);
4208 bpf_object__unpin_maps(obj, path);
4215 void bpf_object__close(struct bpf_object *obj)
4222 if (obj->clear_priv)
4223 obj->clear_priv(obj, obj->priv);
4225 bpf_object__elf_finish(obj);
4226 bpf_object__unload(obj);
4227 btf__free(obj->btf);
4228 btf_ext__free(obj->btf_ext);
4230 for (i = 0; i < obj->nr_maps; i++) {
4231 zfree(&obj->maps[i].name);
4232 if (obj->maps[i].clear_priv)
4233 obj->maps[i].clear_priv(&obj->maps[i],
4235 obj->maps[i].priv = NULL;
4236 obj->maps[i].clear_priv = NULL;
4239 zfree(&obj->sections.rodata);
4240 zfree(&obj->sections.data);
4244 if (obj->programs && obj->nr_programs) {
4245 for (i = 0; i < obj->nr_programs; i++)
4246 bpf_program__exit(&obj->programs[i]);
4248 zfree(&obj->programs);
4250 list_del(&obj->list);
4255 bpf_object__next(struct bpf_object *prev)
4257 struct bpf_object *next;
4260 next = list_first_entry(&bpf_objects_list,
4264 next = list_next_entry(prev, list);
4266 /* Empty list is noticed here so don't need checking on entry. */
4267 if (&next->list == &bpf_objects_list)
4273 const char *bpf_object__name(const struct bpf_object *obj)
4275 return obj ? obj->name : ERR_PTR(-EINVAL);
4278 unsigned int bpf_object__kversion(const struct bpf_object *obj)
4280 return obj ? obj->kern_version : 0;
4283 struct btf *bpf_object__btf(const struct bpf_object *obj)
4285 return obj ? obj->btf : NULL;
4288 int bpf_object__btf_fd(const struct bpf_object *obj)
4290 return obj->btf ? btf__fd(obj->btf) : -1;
4293 int bpf_object__set_priv(struct bpf_object *obj, void *priv,
4294 bpf_object_clear_priv_t clear_priv)
4296 if (obj->priv && obj->clear_priv)
4297 obj->clear_priv(obj, obj->priv);
4300 obj->clear_priv = clear_priv;
4304 void *bpf_object__priv(const struct bpf_object *obj)
4306 return obj ? obj->priv : ERR_PTR(-EINVAL);
4309 static struct bpf_program *
4310 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
4313 size_t nr_programs = obj->nr_programs;
4320 /* Iter from the beginning */
4321 return forward ? &obj->programs[0] :
4322 &obj->programs[nr_programs - 1];
4324 if (p->obj != obj) {
4325 pr_warning("error: program handler doesn't match object\n");
4329 idx = (p - obj->programs) + (forward ? 1 : -1);
4330 if (idx >= obj->nr_programs || idx < 0)
4332 return &obj->programs[idx];
4335 struct bpf_program *
4336 bpf_program__next(struct bpf_program *prev, const struct bpf_object *obj)
4338 struct bpf_program *prog = prev;
4341 prog = __bpf_program__iter(prog, obj, true);
4342 } while (prog && bpf_program__is_function_storage(prog, obj));
4347 struct bpf_program *
4348 bpf_program__prev(struct bpf_program *next, const struct bpf_object *obj)
4350 struct bpf_program *prog = next;
4353 prog = __bpf_program__iter(prog, obj, false);
4354 } while (prog && bpf_program__is_function_storage(prog, obj));
4359 int bpf_program__set_priv(struct bpf_program *prog, void *priv,
4360 bpf_program_clear_priv_t clear_priv)
4362 if (prog->priv && prog->clear_priv)
4363 prog->clear_priv(prog, prog->priv);
4366 prog->clear_priv = clear_priv;
4370 void *bpf_program__priv(const struct bpf_program *prog)
4372 return prog ? prog->priv : ERR_PTR(-EINVAL);
4375 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
4377 prog->prog_ifindex = ifindex;
4380 const char *bpf_program__title(const struct bpf_program *prog, bool needs_copy)
4384 title = prog->section_name;
4386 title = strdup(title);
4388 pr_warning("failed to strdup program title\n");
4389 return ERR_PTR(-ENOMEM);
4396 int bpf_program__fd(const struct bpf_program *prog)
4398 return bpf_program__nth_fd(prog, 0);
4401 int bpf_program__set_prep(struct bpf_program *prog, int nr_instances,
4402 bpf_program_prep_t prep)
4406 if (nr_instances <= 0 || !prep)
4409 if (prog->instances.nr > 0 || prog->instances.fds) {
4410 pr_warning("Can't set pre-processor after loading\n");
4414 instances_fds = malloc(sizeof(int) * nr_instances);
4415 if (!instances_fds) {
4416 pr_warning("alloc memory failed for fds\n");
4420 /* fill all fd with -1 */
4421 memset(instances_fds, -1, sizeof(int) * nr_instances);
4423 prog->instances.nr = nr_instances;
4424 prog->instances.fds = instances_fds;
4425 prog->preprocessor = prep;
4429 int bpf_program__nth_fd(const struct bpf_program *prog, int n)
4436 if (n >= prog->instances.nr || n < 0) {
4437 pr_warning("Can't get the %dth fd from program %s: only %d instances\n",
4438 n, prog->section_name, prog->instances.nr);
4442 fd = prog->instances.fds[n];
4444 pr_warning("%dth instance of program '%s' is invalid\n",
4445 n, prog->section_name);
4452 void bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
4457 static bool bpf_program__is_type(const struct bpf_program *prog,
4458 enum bpf_prog_type type)
4460 return prog ? (prog->type == type) : false;
4463 #define BPF_PROG_TYPE_FNS(NAME, TYPE) \
4464 int bpf_program__set_##NAME(struct bpf_program *prog) \
4468 bpf_program__set_type(prog, TYPE); \
4472 bool bpf_program__is_##NAME(const struct bpf_program *prog) \
4474 return bpf_program__is_type(prog, TYPE); \
4477 BPF_PROG_TYPE_FNS(socket_filter, BPF_PROG_TYPE_SOCKET_FILTER);
4478 BPF_PROG_TYPE_FNS(kprobe, BPF_PROG_TYPE_KPROBE);
4479 BPF_PROG_TYPE_FNS(sched_cls, BPF_PROG_TYPE_SCHED_CLS);
4480 BPF_PROG_TYPE_FNS(sched_act, BPF_PROG_TYPE_SCHED_ACT);
4481 BPF_PROG_TYPE_FNS(tracepoint, BPF_PROG_TYPE_TRACEPOINT);
4482 BPF_PROG_TYPE_FNS(raw_tracepoint, BPF_PROG_TYPE_RAW_TRACEPOINT);
4483 BPF_PROG_TYPE_FNS(xdp, BPF_PROG_TYPE_XDP);
4484 BPF_PROG_TYPE_FNS(perf_event, BPF_PROG_TYPE_PERF_EVENT);
4486 void bpf_program__set_expected_attach_type(struct bpf_program *prog,
4487 enum bpf_attach_type type)
4489 prog->expected_attach_type = type;
4492 #define BPF_PROG_SEC_IMPL(string, ptype, eatype, is_attachable, btf, atype) \
4493 { string, sizeof(string) - 1, ptype, eatype, is_attachable, btf, atype }
4495 /* Programs that can NOT be attached. */
4496 #define BPF_PROG_SEC(string, ptype) BPF_PROG_SEC_IMPL(string, ptype, 0, 0, 0, 0)
4498 /* Programs that can be attached. */
4499 #define BPF_APROG_SEC(string, ptype, atype) \
4500 BPF_PROG_SEC_IMPL(string, ptype, 0, 1, 0, atype)
4502 /* Programs that must specify expected attach type at load time. */
4503 #define BPF_EAPROG_SEC(string, ptype, eatype) \
4504 BPF_PROG_SEC_IMPL(string, ptype, eatype, 1, 0, eatype)
4506 /* Programs that use BTF to identify attach point */
4507 #define BPF_PROG_BTF(string, ptype) BPF_PROG_SEC_IMPL(string, ptype, 0, 0, 1, 0)
4509 /* Programs that can be attached but attach type can't be identified by section
4510 * name. Kept for backward compatibility.
4512 #define BPF_APROG_COMPAT(string, ptype) BPF_PROG_SEC(string, ptype)
4514 static const struct {
4517 enum bpf_prog_type prog_type;
4518 enum bpf_attach_type expected_attach_type;
4521 enum bpf_attach_type attach_type;
4522 } section_names[] = {
4523 BPF_PROG_SEC("socket", BPF_PROG_TYPE_SOCKET_FILTER),
4524 BPF_PROG_SEC("kprobe/", BPF_PROG_TYPE_KPROBE),
4525 BPF_PROG_SEC("kretprobe/", BPF_PROG_TYPE_KPROBE),
4526 BPF_PROG_SEC("classifier", BPF_PROG_TYPE_SCHED_CLS),
4527 BPF_PROG_SEC("action", BPF_PROG_TYPE_SCHED_ACT),
4528 BPF_PROG_SEC("tracepoint/", BPF_PROG_TYPE_TRACEPOINT),
4529 BPF_PROG_SEC("raw_tracepoint/", BPF_PROG_TYPE_RAW_TRACEPOINT),
4530 BPF_PROG_BTF("tp_btf/", BPF_PROG_TYPE_RAW_TRACEPOINT),
4531 BPF_PROG_SEC("xdp", BPF_PROG_TYPE_XDP),
4532 BPF_PROG_SEC("perf_event", BPF_PROG_TYPE_PERF_EVENT),
4533 BPF_PROG_SEC("lwt_in", BPF_PROG_TYPE_LWT_IN),
4534 BPF_PROG_SEC("lwt_out", BPF_PROG_TYPE_LWT_OUT),
4535 BPF_PROG_SEC("lwt_xmit", BPF_PROG_TYPE_LWT_XMIT),
4536 BPF_PROG_SEC("lwt_seg6local", BPF_PROG_TYPE_LWT_SEG6LOCAL),
4537 BPF_APROG_SEC("cgroup_skb/ingress", BPF_PROG_TYPE_CGROUP_SKB,
4538 BPF_CGROUP_INET_INGRESS),
4539 BPF_APROG_SEC("cgroup_skb/egress", BPF_PROG_TYPE_CGROUP_SKB,
4540 BPF_CGROUP_INET_EGRESS),
4541 BPF_APROG_COMPAT("cgroup/skb", BPF_PROG_TYPE_CGROUP_SKB),
4542 BPF_APROG_SEC("cgroup/sock", BPF_PROG_TYPE_CGROUP_SOCK,
4543 BPF_CGROUP_INET_SOCK_CREATE),
4544 BPF_EAPROG_SEC("cgroup/post_bind4", BPF_PROG_TYPE_CGROUP_SOCK,
4545 BPF_CGROUP_INET4_POST_BIND),
4546 BPF_EAPROG_SEC("cgroup/post_bind6", BPF_PROG_TYPE_CGROUP_SOCK,
4547 BPF_CGROUP_INET6_POST_BIND),
4548 BPF_APROG_SEC("cgroup/dev", BPF_PROG_TYPE_CGROUP_DEVICE,
4550 BPF_APROG_SEC("sockops", BPF_PROG_TYPE_SOCK_OPS,
4551 BPF_CGROUP_SOCK_OPS),
4552 BPF_APROG_SEC("sk_skb/stream_parser", BPF_PROG_TYPE_SK_SKB,
4553 BPF_SK_SKB_STREAM_PARSER),
4554 BPF_APROG_SEC("sk_skb/stream_verdict", BPF_PROG_TYPE_SK_SKB,
4555 BPF_SK_SKB_STREAM_VERDICT),
4556 BPF_APROG_COMPAT("sk_skb", BPF_PROG_TYPE_SK_SKB),
4557 BPF_APROG_SEC("sk_msg", BPF_PROG_TYPE_SK_MSG,
4558 BPF_SK_MSG_VERDICT),
4559 BPF_APROG_SEC("lirc_mode2", BPF_PROG_TYPE_LIRC_MODE2,
4561 BPF_APROG_SEC("flow_dissector", BPF_PROG_TYPE_FLOW_DISSECTOR,
4562 BPF_FLOW_DISSECTOR),
4563 BPF_EAPROG_SEC("cgroup/bind4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
4564 BPF_CGROUP_INET4_BIND),
4565 BPF_EAPROG_SEC("cgroup/bind6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
4566 BPF_CGROUP_INET6_BIND),
4567 BPF_EAPROG_SEC("cgroup/connect4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
4568 BPF_CGROUP_INET4_CONNECT),
4569 BPF_EAPROG_SEC("cgroup/connect6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
4570 BPF_CGROUP_INET6_CONNECT),
4571 BPF_EAPROG_SEC("cgroup/sendmsg4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
4572 BPF_CGROUP_UDP4_SENDMSG),
4573 BPF_EAPROG_SEC("cgroup/sendmsg6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
4574 BPF_CGROUP_UDP6_SENDMSG),
4575 BPF_EAPROG_SEC("cgroup/recvmsg4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
4576 BPF_CGROUP_UDP4_RECVMSG),
4577 BPF_EAPROG_SEC("cgroup/recvmsg6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
4578 BPF_CGROUP_UDP6_RECVMSG),
4579 BPF_EAPROG_SEC("cgroup/sysctl", BPF_PROG_TYPE_CGROUP_SYSCTL,
4581 BPF_EAPROG_SEC("cgroup/getsockopt", BPF_PROG_TYPE_CGROUP_SOCKOPT,
4582 BPF_CGROUP_GETSOCKOPT),
4583 BPF_EAPROG_SEC("cgroup/setsockopt", BPF_PROG_TYPE_CGROUP_SOCKOPT,
4584 BPF_CGROUP_SETSOCKOPT),
4587 #undef BPF_PROG_SEC_IMPL
4589 #undef BPF_APROG_SEC
4590 #undef BPF_EAPROG_SEC
4591 #undef BPF_APROG_COMPAT
4593 #define MAX_TYPE_NAME_SIZE 32
4595 static char *libbpf_get_type_names(bool attach_type)
4597 int i, len = ARRAY_SIZE(section_names) * MAX_TYPE_NAME_SIZE;
4605 /* Forge string buf with all available names */
4606 for (i = 0; i < ARRAY_SIZE(section_names); i++) {
4607 if (attach_type && !section_names[i].is_attachable)
4610 if (strlen(buf) + strlen(section_names[i].sec) + 2 > len) {
4615 strcat(buf, section_names[i].sec);
4621 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
4622 enum bpf_attach_type *expected_attach_type)
4630 for (i = 0; i < ARRAY_SIZE(section_names); i++) {
4631 if (strncmp(name, section_names[i].sec, section_names[i].len))
4633 *prog_type = section_names[i].prog_type;
4634 *expected_attach_type = section_names[i].expected_attach_type;
4635 if (section_names[i].is_attach_btf) {
4636 struct btf *btf = bpf_core_find_kernel_btf();
4637 char raw_tp_btf_name[128] = "btf_trace_";
4638 char *dst = raw_tp_btf_name + sizeof("btf_trace_") - 1;
4642 pr_warning("vmlinux BTF is not found\n");
4645 /* prepend "btf_trace_" prefix per kernel convention */
4646 strncat(dst, name + section_names[i].len,
4647 sizeof(raw_tp_btf_name) - (dst - raw_tp_btf_name));
4648 ret = btf__find_by_name(btf, raw_tp_btf_name);
4651 pr_warning("%s is not found in vmlinux BTF\n", dst);
4654 *expected_attach_type = ret;
4658 pr_warning("failed to guess program type based on ELF section name '%s'\n", name);
4659 type_names = libbpf_get_type_names(false);
4660 if (type_names != NULL) {
4661 pr_info("supported section(type) names are:%s\n", type_names);
4668 int libbpf_attach_type_by_name(const char *name,
4669 enum bpf_attach_type *attach_type)
4677 for (i = 0; i < ARRAY_SIZE(section_names); i++) {
4678 if (strncmp(name, section_names[i].sec, section_names[i].len))
4680 if (!section_names[i].is_attachable)
4682 *attach_type = section_names[i].attach_type;
4685 pr_warning("failed to guess attach type based on ELF section name '%s'\n", name);
4686 type_names = libbpf_get_type_names(true);
4687 if (type_names != NULL) {
4688 pr_info("attachable section(type) names are:%s\n", type_names);
4696 bpf_program__identify_section(struct bpf_program *prog,
4697 enum bpf_prog_type *prog_type,
4698 enum bpf_attach_type *expected_attach_type)
4700 return libbpf_prog_type_by_name(prog->section_name, prog_type,
4701 expected_attach_type);
4704 int bpf_map__fd(const struct bpf_map *map)
4706 return map ? map->fd : -EINVAL;
4709 const struct bpf_map_def *bpf_map__def(const struct bpf_map *map)
4711 return map ? &map->def : ERR_PTR(-EINVAL);
4714 const char *bpf_map__name(const struct bpf_map *map)
4716 return map ? map->name : NULL;
4719 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
4721 return map ? map->btf_key_type_id : 0;
4724 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
4726 return map ? map->btf_value_type_id : 0;
4729 int bpf_map__set_priv(struct bpf_map *map, void *priv,
4730 bpf_map_clear_priv_t clear_priv)
4736 if (map->clear_priv)
4737 map->clear_priv(map, map->priv);
4741 map->clear_priv = clear_priv;
4745 void *bpf_map__priv(const struct bpf_map *map)
4747 return map ? map->priv : ERR_PTR(-EINVAL);
4750 bool bpf_map__is_offload_neutral(const struct bpf_map *map)
4752 return map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY;
4755 bool bpf_map__is_internal(const struct bpf_map *map)
4757 return map->libbpf_type != LIBBPF_MAP_UNSPEC;
4760 void bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
4762 map->map_ifindex = ifindex;
4765 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
4767 if (!bpf_map_type__is_map_in_map(map->def.type)) {
4768 pr_warning("error: unsupported map type\n");
4771 if (map->inner_map_fd != -1) {
4772 pr_warning("error: inner_map_fd already specified\n");
4775 map->inner_map_fd = fd;
4779 static struct bpf_map *
4780 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
4783 struct bpf_map *s, *e;
4785 if (!obj || !obj->maps)
4789 e = obj->maps + obj->nr_maps;
4791 if ((m < s) || (m >= e)) {
4792 pr_warning("error in %s: map handler doesn't belong to object\n",
4797 idx = (m - obj->maps) + i;
4798 if (idx >= obj->nr_maps || idx < 0)
4800 return &obj->maps[idx];
4804 bpf_map__next(const struct bpf_map *prev, const struct bpf_object *obj)
4809 return __bpf_map__iter(prev, obj, 1);
4813 bpf_map__prev(const struct bpf_map *next, const struct bpf_object *obj)
4818 return obj->maps + obj->nr_maps - 1;
4821 return __bpf_map__iter(next, obj, -1);
4825 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
4827 struct bpf_map *pos;
4829 bpf_object__for_each_map(pos, obj) {
4830 if (pos->name && !strcmp(pos->name, name))
4837 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
4839 return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
4843 bpf_object__find_map_by_offset(struct bpf_object *obj, size_t offset)
4845 return ERR_PTR(-ENOTSUP);
4848 long libbpf_get_error(const void *ptr)
4850 return PTR_ERR_OR_ZERO(ptr);
4853 int bpf_prog_load(const char *file, enum bpf_prog_type type,
4854 struct bpf_object **pobj, int *prog_fd)
4856 struct bpf_prog_load_attr attr;
4858 memset(&attr, 0, sizeof(struct bpf_prog_load_attr));
4860 attr.prog_type = type;
4861 attr.expected_attach_type = 0;
4863 return bpf_prog_load_xattr(&attr, pobj, prog_fd);
4866 int bpf_prog_load_xattr(const struct bpf_prog_load_attr *attr,
4867 struct bpf_object **pobj, int *prog_fd)
4869 struct bpf_object_open_attr open_attr = {};
4870 struct bpf_program *prog, *first_prog = NULL;
4871 enum bpf_attach_type expected_attach_type;
4872 enum bpf_prog_type prog_type;
4873 struct bpf_object *obj;
4874 struct bpf_map *map;
4882 open_attr.file = attr->file;
4883 open_attr.prog_type = attr->prog_type;
4885 obj = bpf_object__open_xattr(&open_attr);
4886 if (IS_ERR_OR_NULL(obj))
4889 bpf_object__for_each_program(prog, obj) {
4891 * If type is not specified, try to guess it based on
4894 prog_type = attr->prog_type;
4895 prog->prog_ifindex = attr->ifindex;
4896 expected_attach_type = attr->expected_attach_type;
4897 if (prog_type == BPF_PROG_TYPE_UNSPEC) {
4898 err = bpf_program__identify_section(prog, &prog_type,
4899 &expected_attach_type);
4901 bpf_object__close(obj);
4906 bpf_program__set_type(prog, prog_type);
4907 bpf_program__set_expected_attach_type(prog,
4908 expected_attach_type);
4910 prog->log_level = attr->log_level;
4911 prog->prog_flags = attr->prog_flags;
4916 bpf_object__for_each_map(map, obj) {
4917 if (!bpf_map__is_offload_neutral(map))
4918 map->map_ifindex = attr->ifindex;
4922 pr_warning("object file doesn't contain bpf program\n");
4923 bpf_object__close(obj);
4927 err = bpf_object__load(obj);
4929 bpf_object__close(obj);
4934 *prog_fd = bpf_program__fd(first_prog);
4939 int (*destroy)(struct bpf_link *link);
4942 int bpf_link__destroy(struct bpf_link *link)
4949 err = link->destroy(link);
4955 struct bpf_link_fd {
4956 struct bpf_link link; /* has to be at the top of struct */
4957 int fd; /* hook FD */
4960 static int bpf_link__destroy_perf_event(struct bpf_link *link)
4962 struct bpf_link_fd *l = (void *)link;
4965 err = ioctl(l->fd, PERF_EVENT_IOC_DISABLE, 0);
4973 struct bpf_link *bpf_program__attach_perf_event(struct bpf_program *prog,
4976 char errmsg[STRERR_BUFSIZE];
4977 struct bpf_link_fd *link;
4981 pr_warning("program '%s': invalid perf event FD %d\n",
4982 bpf_program__title(prog, false), pfd);
4983 return ERR_PTR(-EINVAL);
4985 prog_fd = bpf_program__fd(prog);
4987 pr_warning("program '%s': can't attach BPF program w/o FD (did you load it?)\n",
4988 bpf_program__title(prog, false));
4989 return ERR_PTR(-EINVAL);
4992 link = malloc(sizeof(*link));
4994 return ERR_PTR(-ENOMEM);
4995 link->link.destroy = &bpf_link__destroy_perf_event;
4998 if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
5001 pr_warning("program '%s': failed to attach to pfd %d: %s\n",
5002 bpf_program__title(prog, false), pfd,
5003 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
5004 return ERR_PTR(err);
5006 if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
5009 pr_warning("program '%s': failed to enable pfd %d: %s\n",
5010 bpf_program__title(prog, false), pfd,
5011 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
5012 return ERR_PTR(err);
5014 return (struct bpf_link *)link;
5018 * this function is expected to parse integer in the range of [0, 2^31-1] from
5019 * given file using scanf format string fmt. If actual parsed value is
5020 * negative, the result might be indistinguishable from error
5022 static int parse_uint_from_file(const char *file, const char *fmt)
5024 char buf[STRERR_BUFSIZE];
5028 f = fopen(file, "r");
5031 pr_debug("failed to open '%s': %s\n", file,
5032 libbpf_strerror_r(err, buf, sizeof(buf)));
5035 err = fscanf(f, fmt, &ret);
5037 err = err == EOF ? -EIO : -errno;
5038 pr_debug("failed to parse '%s': %s\n", file,
5039 libbpf_strerror_r(err, buf, sizeof(buf)));
5047 static int determine_kprobe_perf_type(void)
5049 const char *file = "/sys/bus/event_source/devices/kprobe/type";
5051 return parse_uint_from_file(file, "%d\n");
5054 static int determine_uprobe_perf_type(void)
5056 const char *file = "/sys/bus/event_source/devices/uprobe/type";
5058 return parse_uint_from_file(file, "%d\n");
5061 static int determine_kprobe_retprobe_bit(void)
5063 const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
5065 return parse_uint_from_file(file, "config:%d\n");
5068 static int determine_uprobe_retprobe_bit(void)
5070 const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
5072 return parse_uint_from_file(file, "config:%d\n");
5075 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
5076 uint64_t offset, int pid)
5078 struct perf_event_attr attr = {};
5079 char errmsg[STRERR_BUFSIZE];
5082 type = uprobe ? determine_uprobe_perf_type()
5083 : determine_kprobe_perf_type();
5085 pr_warning("failed to determine %s perf type: %s\n",
5086 uprobe ? "uprobe" : "kprobe",
5087 libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
5091 int bit = uprobe ? determine_uprobe_retprobe_bit()
5092 : determine_kprobe_retprobe_bit();
5095 pr_warning("failed to determine %s retprobe bit: %s\n",
5096 uprobe ? "uprobe" : "kprobe",
5097 libbpf_strerror_r(bit, errmsg,
5101 attr.config |= 1 << bit;
5103 attr.size = sizeof(attr);
5105 attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
5106 attr.config2 = offset; /* kprobe_addr or probe_offset */
5108 /* pid filter is meaningful only for uprobes */
5109 pfd = syscall(__NR_perf_event_open, &attr,
5110 pid < 0 ? -1 : pid /* pid */,
5111 pid == -1 ? 0 : -1 /* cpu */,
5112 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
5115 pr_warning("%s perf_event_open() failed: %s\n",
5116 uprobe ? "uprobe" : "kprobe",
5117 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
5123 struct bpf_link *bpf_program__attach_kprobe(struct bpf_program *prog,
5125 const char *func_name)
5127 char errmsg[STRERR_BUFSIZE];
5128 struct bpf_link *link;
5131 pfd = perf_event_open_probe(false /* uprobe */, retprobe, func_name,
5132 0 /* offset */, -1 /* pid */);
5134 pr_warning("program '%s': failed to create %s '%s' perf event: %s\n",
5135 bpf_program__title(prog, false),
5136 retprobe ? "kretprobe" : "kprobe", func_name,
5137 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
5138 return ERR_PTR(pfd);
5140 link = bpf_program__attach_perf_event(prog, pfd);
5143 err = PTR_ERR(link);
5144 pr_warning("program '%s': failed to attach to %s '%s': %s\n",
5145 bpf_program__title(prog, false),
5146 retprobe ? "kretprobe" : "kprobe", func_name,
5147 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
5153 struct bpf_link *bpf_program__attach_uprobe(struct bpf_program *prog,
5154 bool retprobe, pid_t pid,
5155 const char *binary_path,
5158 char errmsg[STRERR_BUFSIZE];
5159 struct bpf_link *link;
5162 pfd = perf_event_open_probe(true /* uprobe */, retprobe,
5163 binary_path, func_offset, pid);
5165 pr_warning("program '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
5166 bpf_program__title(prog, false),
5167 retprobe ? "uretprobe" : "uprobe",
5168 binary_path, func_offset,
5169 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
5170 return ERR_PTR(pfd);
5172 link = bpf_program__attach_perf_event(prog, pfd);
5175 err = PTR_ERR(link);
5176 pr_warning("program '%s': failed to attach to %s '%s:0x%zx': %s\n",
5177 bpf_program__title(prog, false),
5178 retprobe ? "uretprobe" : "uprobe",
5179 binary_path, func_offset,
5180 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
5186 static int determine_tracepoint_id(const char *tp_category,
5187 const char *tp_name)
5189 char file[PATH_MAX];
5192 ret = snprintf(file, sizeof(file),
5193 "/sys/kernel/debug/tracing/events/%s/%s/id",
5194 tp_category, tp_name);
5197 if (ret >= sizeof(file)) {
5198 pr_debug("tracepoint %s/%s path is too long\n",
5199 tp_category, tp_name);
5202 return parse_uint_from_file(file, "%d\n");
5205 static int perf_event_open_tracepoint(const char *tp_category,
5206 const char *tp_name)
5208 struct perf_event_attr attr = {};
5209 char errmsg[STRERR_BUFSIZE];
5210 int tp_id, pfd, err;
5212 tp_id = determine_tracepoint_id(tp_category, tp_name);
5214 pr_warning("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
5215 tp_category, tp_name,
5216 libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
5220 attr.type = PERF_TYPE_TRACEPOINT;
5221 attr.size = sizeof(attr);
5222 attr.config = tp_id;
5224 pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
5225 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
5228 pr_warning("tracepoint '%s/%s' perf_event_open() failed: %s\n",
5229 tp_category, tp_name,
5230 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
5236 struct bpf_link *bpf_program__attach_tracepoint(struct bpf_program *prog,
5237 const char *tp_category,
5238 const char *tp_name)
5240 char errmsg[STRERR_BUFSIZE];
5241 struct bpf_link *link;
5244 pfd = perf_event_open_tracepoint(tp_category, tp_name);
5246 pr_warning("program '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
5247 bpf_program__title(prog, false),
5248 tp_category, tp_name,
5249 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
5250 return ERR_PTR(pfd);
5252 link = bpf_program__attach_perf_event(prog, pfd);
5255 err = PTR_ERR(link);
5256 pr_warning("program '%s': failed to attach to tracepoint '%s/%s': %s\n",
5257 bpf_program__title(prog, false),
5258 tp_category, tp_name,
5259 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
5265 static int bpf_link__destroy_fd(struct bpf_link *link)
5267 struct bpf_link_fd *l = (void *)link;
5269 return close(l->fd);
5272 struct bpf_link *bpf_program__attach_raw_tracepoint(struct bpf_program *prog,
5273 const char *tp_name)
5275 char errmsg[STRERR_BUFSIZE];
5276 struct bpf_link_fd *link;
5279 prog_fd = bpf_program__fd(prog);
5281 pr_warning("program '%s': can't attach before loaded\n",
5282 bpf_program__title(prog, false));
5283 return ERR_PTR(-EINVAL);
5286 link = malloc(sizeof(*link));
5288 return ERR_PTR(-ENOMEM);
5289 link->link.destroy = &bpf_link__destroy_fd;
5291 pfd = bpf_raw_tracepoint_open(tp_name, prog_fd);
5295 pr_warning("program '%s': failed to attach to raw tracepoint '%s': %s\n",
5296 bpf_program__title(prog, false), tp_name,
5297 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
5298 return ERR_PTR(pfd);
5301 return (struct bpf_link *)link;
5304 enum bpf_perf_event_ret
5305 bpf_perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
5306 void **copy_mem, size_t *copy_size,
5307 bpf_perf_event_print_t fn, void *private_data)
5309 struct perf_event_mmap_page *header = mmap_mem;
5310 __u64 data_head = ring_buffer_read_head(header);
5311 __u64 data_tail = header->data_tail;
5312 void *base = ((__u8 *)header) + page_size;
5313 int ret = LIBBPF_PERF_EVENT_CONT;
5314 struct perf_event_header *ehdr;
5317 while (data_head != data_tail) {
5318 ehdr = base + (data_tail & (mmap_size - 1));
5319 ehdr_size = ehdr->size;
5321 if (((void *)ehdr) + ehdr_size > base + mmap_size) {
5322 void *copy_start = ehdr;
5323 size_t len_first = base + mmap_size - copy_start;
5324 size_t len_secnd = ehdr_size - len_first;
5326 if (*copy_size < ehdr_size) {
5328 *copy_mem = malloc(ehdr_size);
5331 ret = LIBBPF_PERF_EVENT_ERROR;
5334 *copy_size = ehdr_size;
5337 memcpy(*copy_mem, copy_start, len_first);
5338 memcpy(*copy_mem + len_first, base, len_secnd);
5342 ret = fn(ehdr, private_data);
5343 data_tail += ehdr_size;
5344 if (ret != LIBBPF_PERF_EVENT_CONT)
5348 ring_buffer_write_tail(header, data_tail);
5354 struct perf_buffer_params {
5355 struct perf_event_attr *attr;
5356 /* if event_cb is specified, it takes precendence */
5357 perf_buffer_event_fn event_cb;
5358 /* sample_cb and lost_cb are higher-level common-case callbacks */
5359 perf_buffer_sample_fn sample_cb;
5360 perf_buffer_lost_fn lost_cb;
5367 struct perf_cpu_buf {
5368 struct perf_buffer *pb;
5369 void *base; /* mmap()'ed memory */
5370 void *buf; /* for reconstructing segmented data */
5377 struct perf_buffer {
5378 perf_buffer_event_fn event_cb;
5379 perf_buffer_sample_fn sample_cb;
5380 perf_buffer_lost_fn lost_cb;
5381 void *ctx; /* passed into callbacks */
5385 struct perf_cpu_buf **cpu_bufs;
5386 struct epoll_event *events;
5388 int epoll_fd; /* perf event FD */
5389 int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
5392 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
5393 struct perf_cpu_buf *cpu_buf)
5397 if (cpu_buf->base &&
5398 munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
5399 pr_warning("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
5400 if (cpu_buf->fd >= 0) {
5401 ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
5408 void perf_buffer__free(struct perf_buffer *pb)
5415 for (i = 0; i < pb->cpu_cnt && pb->cpu_bufs[i]; i++) {
5416 struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
5418 bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
5419 perf_buffer__free_cpu_buf(pb, cpu_buf);
5423 if (pb->epoll_fd >= 0)
5424 close(pb->epoll_fd);
5429 static struct perf_cpu_buf *
5430 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
5431 int cpu, int map_key)
5433 struct perf_cpu_buf *cpu_buf;
5434 char msg[STRERR_BUFSIZE];
5437 cpu_buf = calloc(1, sizeof(*cpu_buf));
5439 return ERR_PTR(-ENOMEM);
5443 cpu_buf->map_key = map_key;
5445 cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
5446 -1, PERF_FLAG_FD_CLOEXEC);
5447 if (cpu_buf->fd < 0) {
5449 pr_warning("failed to open perf buffer event on cpu #%d: %s\n",
5450 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
5454 cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
5455 PROT_READ | PROT_WRITE, MAP_SHARED,
5457 if (cpu_buf->base == MAP_FAILED) {
5458 cpu_buf->base = NULL;
5460 pr_warning("failed to mmap perf buffer on cpu #%d: %s\n",
5461 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
5465 if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
5467 pr_warning("failed to enable perf buffer event on cpu #%d: %s\n",
5468 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
5475 perf_buffer__free_cpu_buf(pb, cpu_buf);
5476 return (struct perf_cpu_buf *)ERR_PTR(err);
5479 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
5480 struct perf_buffer_params *p);
5482 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
5483 const struct perf_buffer_opts *opts)
5485 struct perf_buffer_params p = {};
5486 struct perf_event_attr attr = { 0, };
5488 attr.config = PERF_COUNT_SW_BPF_OUTPUT,
5489 attr.type = PERF_TYPE_SOFTWARE;
5490 attr.sample_type = PERF_SAMPLE_RAW;
5491 attr.sample_period = 1;
5492 attr.wakeup_events = 1;
5495 p.sample_cb = opts ? opts->sample_cb : NULL;
5496 p.lost_cb = opts ? opts->lost_cb : NULL;
5497 p.ctx = opts ? opts->ctx : NULL;
5499 return __perf_buffer__new(map_fd, page_cnt, &p);
5502 struct perf_buffer *
5503 perf_buffer__new_raw(int map_fd, size_t page_cnt,
5504 const struct perf_buffer_raw_opts *opts)
5506 struct perf_buffer_params p = {};
5508 p.attr = opts->attr;
5509 p.event_cb = opts->event_cb;
5511 p.cpu_cnt = opts->cpu_cnt;
5512 p.cpus = opts->cpus;
5513 p.map_keys = opts->map_keys;
5515 return __perf_buffer__new(map_fd, page_cnt, &p);
5518 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
5519 struct perf_buffer_params *p)
5521 struct bpf_map_info map = {};
5522 char msg[STRERR_BUFSIZE];
5523 struct perf_buffer *pb;
5527 if (page_cnt & (page_cnt - 1)) {
5528 pr_warning("page count should be power of two, but is %zu\n",
5530 return ERR_PTR(-EINVAL);
5533 map_info_len = sizeof(map);
5534 err = bpf_obj_get_info_by_fd(map_fd, &map, &map_info_len);
5537 pr_warning("failed to get map info for map FD %d: %s\n",
5538 map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
5539 return ERR_PTR(err);
5542 if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
5543 pr_warning("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
5545 return ERR_PTR(-EINVAL);
5548 pb = calloc(1, sizeof(*pb));
5550 return ERR_PTR(-ENOMEM);
5552 pb->event_cb = p->event_cb;
5553 pb->sample_cb = p->sample_cb;
5554 pb->lost_cb = p->lost_cb;
5557 pb->page_size = getpagesize();
5558 pb->mmap_size = pb->page_size * page_cnt;
5559 pb->map_fd = map_fd;
5561 pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
5562 if (pb->epoll_fd < 0) {
5564 pr_warning("failed to create epoll instance: %s\n",
5565 libbpf_strerror_r(err, msg, sizeof(msg)));
5569 if (p->cpu_cnt > 0) {
5570 pb->cpu_cnt = p->cpu_cnt;
5572 pb->cpu_cnt = libbpf_num_possible_cpus();
5573 if (pb->cpu_cnt < 0) {
5577 if (map.max_entries < pb->cpu_cnt)
5578 pb->cpu_cnt = map.max_entries;
5581 pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
5584 pr_warning("failed to allocate events: out of memory\n");
5587 pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
5588 if (!pb->cpu_bufs) {
5590 pr_warning("failed to allocate buffers: out of memory\n");
5594 for (i = 0; i < pb->cpu_cnt; i++) {
5595 struct perf_cpu_buf *cpu_buf;
5598 cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
5599 map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
5601 cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
5602 if (IS_ERR(cpu_buf)) {
5603 err = PTR_ERR(cpu_buf);
5607 pb->cpu_bufs[i] = cpu_buf;
5609 err = bpf_map_update_elem(pb->map_fd, &map_key,
5613 pr_warning("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
5614 cpu, map_key, cpu_buf->fd,
5615 libbpf_strerror_r(err, msg, sizeof(msg)));
5619 pb->events[i].events = EPOLLIN;
5620 pb->events[i].data.ptr = cpu_buf;
5621 if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
5622 &pb->events[i]) < 0) {
5624 pr_warning("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
5626 libbpf_strerror_r(err, msg, sizeof(msg)));
5635 perf_buffer__free(pb);
5636 return ERR_PTR(err);
5639 struct perf_sample_raw {
5640 struct perf_event_header header;
5645 struct perf_sample_lost {
5646 struct perf_event_header header;
5652 static enum bpf_perf_event_ret
5653 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
5655 struct perf_cpu_buf *cpu_buf = ctx;
5656 struct perf_buffer *pb = cpu_buf->pb;
5659 /* user wants full control over parsing perf event */
5661 return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
5664 case PERF_RECORD_SAMPLE: {
5665 struct perf_sample_raw *s = data;
5668 pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
5671 case PERF_RECORD_LOST: {
5672 struct perf_sample_lost *s = data;
5675 pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
5679 pr_warning("unknown perf sample type %d\n", e->type);
5680 return LIBBPF_PERF_EVENT_ERROR;
5682 return LIBBPF_PERF_EVENT_CONT;
5685 static int perf_buffer__process_records(struct perf_buffer *pb,
5686 struct perf_cpu_buf *cpu_buf)
5688 enum bpf_perf_event_ret ret;
5690 ret = bpf_perf_event_read_simple(cpu_buf->base, pb->mmap_size,
5691 pb->page_size, &cpu_buf->buf,
5693 perf_buffer__process_record, cpu_buf);
5694 if (ret != LIBBPF_PERF_EVENT_CONT)
5699 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
5703 cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
5704 for (i = 0; i < cnt; i++) {
5705 struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
5707 err = perf_buffer__process_records(pb, cpu_buf);
5709 pr_warning("error while processing records: %d\n", err);
5713 return cnt < 0 ? -errno : cnt;
5716 struct bpf_prog_info_array_desc {
5717 int array_offset; /* e.g. offset of jited_prog_insns */
5718 int count_offset; /* e.g. offset of jited_prog_len */
5719 int size_offset; /* > 0: offset of rec size,
5720 * < 0: fix size of -size_offset
5724 static struct bpf_prog_info_array_desc bpf_prog_info_array_desc[] = {
5725 [BPF_PROG_INFO_JITED_INSNS] = {
5726 offsetof(struct bpf_prog_info, jited_prog_insns),
5727 offsetof(struct bpf_prog_info, jited_prog_len),
5730 [BPF_PROG_INFO_XLATED_INSNS] = {
5731 offsetof(struct bpf_prog_info, xlated_prog_insns),
5732 offsetof(struct bpf_prog_info, xlated_prog_len),
5735 [BPF_PROG_INFO_MAP_IDS] = {
5736 offsetof(struct bpf_prog_info, map_ids),
5737 offsetof(struct bpf_prog_info, nr_map_ids),
5738 -(int)sizeof(__u32),
5740 [BPF_PROG_INFO_JITED_KSYMS] = {
5741 offsetof(struct bpf_prog_info, jited_ksyms),
5742 offsetof(struct bpf_prog_info, nr_jited_ksyms),
5743 -(int)sizeof(__u64),
5745 [BPF_PROG_INFO_JITED_FUNC_LENS] = {
5746 offsetof(struct bpf_prog_info, jited_func_lens),
5747 offsetof(struct bpf_prog_info, nr_jited_func_lens),
5748 -(int)sizeof(__u32),
5750 [BPF_PROG_INFO_FUNC_INFO] = {
5751 offsetof(struct bpf_prog_info, func_info),
5752 offsetof(struct bpf_prog_info, nr_func_info),
5753 offsetof(struct bpf_prog_info, func_info_rec_size),
5755 [BPF_PROG_INFO_LINE_INFO] = {
5756 offsetof(struct bpf_prog_info, line_info),
5757 offsetof(struct bpf_prog_info, nr_line_info),
5758 offsetof(struct bpf_prog_info, line_info_rec_size),
5760 [BPF_PROG_INFO_JITED_LINE_INFO] = {
5761 offsetof(struct bpf_prog_info, jited_line_info),
5762 offsetof(struct bpf_prog_info, nr_jited_line_info),
5763 offsetof(struct bpf_prog_info, jited_line_info_rec_size),
5765 [BPF_PROG_INFO_PROG_TAGS] = {
5766 offsetof(struct bpf_prog_info, prog_tags),
5767 offsetof(struct bpf_prog_info, nr_prog_tags),
5768 -(int)sizeof(__u8) * BPF_TAG_SIZE,
5773 static __u32 bpf_prog_info_read_offset_u32(struct bpf_prog_info *info, int offset)
5775 __u32 *array = (__u32 *)info;
5778 return array[offset / sizeof(__u32)];
5779 return -(int)offset;
5782 static __u64 bpf_prog_info_read_offset_u64(struct bpf_prog_info *info, int offset)
5784 __u64 *array = (__u64 *)info;
5787 return array[offset / sizeof(__u64)];
5788 return -(int)offset;
5791 static void bpf_prog_info_set_offset_u32(struct bpf_prog_info *info, int offset,
5794 __u32 *array = (__u32 *)info;
5797 array[offset / sizeof(__u32)] = val;
5800 static void bpf_prog_info_set_offset_u64(struct bpf_prog_info *info, int offset,
5803 __u64 *array = (__u64 *)info;
5806 array[offset / sizeof(__u64)] = val;
5809 struct bpf_prog_info_linear *
5810 bpf_program__get_prog_info_linear(int fd, __u64 arrays)
5812 struct bpf_prog_info_linear *info_linear;
5813 struct bpf_prog_info info = {};
5814 __u32 info_len = sizeof(info);
5819 if (arrays >> BPF_PROG_INFO_LAST_ARRAY)
5820 return ERR_PTR(-EINVAL);
5822 /* step 1: get array dimensions */
5823 err = bpf_obj_get_info_by_fd(fd, &info, &info_len);
5825 pr_debug("can't get prog info: %s", strerror(errno));
5826 return ERR_PTR(-EFAULT);
5829 /* step 2: calculate total size of all arrays */
5830 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
5831 bool include_array = (arrays & (1UL << i)) > 0;
5832 struct bpf_prog_info_array_desc *desc;
5835 desc = bpf_prog_info_array_desc + i;
5837 /* kernel is too old to support this field */
5838 if (info_len < desc->array_offset + sizeof(__u32) ||
5839 info_len < desc->count_offset + sizeof(__u32) ||
5840 (desc->size_offset > 0 && info_len < desc->size_offset))
5841 include_array = false;
5843 if (!include_array) {
5844 arrays &= ~(1UL << i); /* clear the bit */
5848 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
5849 size = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
5851 data_len += count * size;
5854 /* step 3: allocate continuous memory */
5855 data_len = roundup(data_len, sizeof(__u64));
5856 info_linear = malloc(sizeof(struct bpf_prog_info_linear) + data_len);
5858 return ERR_PTR(-ENOMEM);
5860 /* step 4: fill data to info_linear->info */
5861 info_linear->arrays = arrays;
5862 memset(&info_linear->info, 0, sizeof(info));
5863 ptr = info_linear->data;
5865 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
5866 struct bpf_prog_info_array_desc *desc;
5869 if ((arrays & (1UL << i)) == 0)
5872 desc = bpf_prog_info_array_desc + i;
5873 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
5874 size = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
5875 bpf_prog_info_set_offset_u32(&info_linear->info,
5876 desc->count_offset, count);
5877 bpf_prog_info_set_offset_u32(&info_linear->info,
5878 desc->size_offset, size);
5879 bpf_prog_info_set_offset_u64(&info_linear->info,
5882 ptr += count * size;
5885 /* step 5: call syscall again to get required arrays */
5886 err = bpf_obj_get_info_by_fd(fd, &info_linear->info, &info_len);
5888 pr_debug("can't get prog info: %s", strerror(errno));
5890 return ERR_PTR(-EFAULT);
5893 /* step 6: verify the data */
5894 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
5895 struct bpf_prog_info_array_desc *desc;
5898 if ((arrays & (1UL << i)) == 0)
5901 desc = bpf_prog_info_array_desc + i;
5902 v1 = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
5903 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
5904 desc->count_offset);
5906 pr_warning("%s: mismatch in element count\n", __func__);
5908 v1 = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
5909 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
5912 pr_warning("%s: mismatch in rec size\n", __func__);
5915 /* step 7: update info_len and data_len */
5916 info_linear->info_len = sizeof(struct bpf_prog_info);
5917 info_linear->data_len = data_len;
5922 void bpf_program__bpil_addr_to_offs(struct bpf_prog_info_linear *info_linear)
5926 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
5927 struct bpf_prog_info_array_desc *desc;
5930 if ((info_linear->arrays & (1UL << i)) == 0)
5933 desc = bpf_prog_info_array_desc + i;
5934 addr = bpf_prog_info_read_offset_u64(&info_linear->info,
5935 desc->array_offset);
5936 offs = addr - ptr_to_u64(info_linear->data);
5937 bpf_prog_info_set_offset_u64(&info_linear->info,
5938 desc->array_offset, offs);
5942 void bpf_program__bpil_offs_to_addr(struct bpf_prog_info_linear *info_linear)
5946 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
5947 struct bpf_prog_info_array_desc *desc;
5950 if ((info_linear->arrays & (1UL << i)) == 0)
5953 desc = bpf_prog_info_array_desc + i;
5954 offs = bpf_prog_info_read_offset_u64(&info_linear->info,
5955 desc->array_offset);
5956 addr = offs + ptr_to_u64(info_linear->data);
5957 bpf_prog_info_set_offset_u64(&info_linear->info,
5958 desc->array_offset, addr);
5962 int libbpf_num_possible_cpus(void)
5964 static const char *fcpu = "/sys/devices/system/cpu/possible";
5965 int len = 0, n = 0, il = 0, ir = 0;
5966 unsigned int start = 0, end = 0;
5973 tmp_cpus = READ_ONCE(cpus);
5977 fd = open(fcpu, O_RDONLY);
5980 pr_warning("Failed to open file %s: %s\n",
5981 fcpu, strerror(error));
5984 len = read(fd, buf, sizeof(buf));
5987 error = len ? errno : EINVAL;
5988 pr_warning("Failed to read # of possible cpus from %s: %s\n",
5989 fcpu, strerror(error));
5992 if (len == sizeof(buf)) {
5993 pr_warning("File %s size overflow\n", fcpu);
5998 for (ir = 0, tmp_cpus = 0; ir <= len; ir++) {
5999 /* Each sub string separated by ',' has format \d+-\d+ or \d+ */
6000 if (buf[ir] == ',' || buf[ir] == '\0') {
6002 n = sscanf(&buf[il], "%u-%u", &start, &end);
6004 pr_warning("Failed to get # CPUs from %s\n",
6007 } else if (n == 1) {
6010 tmp_cpus += end - start + 1;
6014 if (tmp_cpus <= 0) {
6015 pr_warning("Invalid #CPUs %d from %s\n", tmp_cpus, fcpu);
6019 WRITE_ONCE(cpus, tmp_cpus);