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.
27 #include <asm/unistd.h>
28 #include <linux/err.h>
29 #include <linux/kernel.h>
30 #include <linux/bpf.h>
31 #include <linux/btf.h>
32 #include <linux/filter.h>
33 #include <linux/list.h>
34 #include <linux/limits.h>
35 #include <linux/perf_event.h>
36 #include <linux/ring_buffer.h>
37 #include <linux/version.h>
38 #include <sys/epoll.h>
39 #include <sys/ioctl.h>
42 #include <sys/types.h>
44 #include <sys/utsname.h>
45 #include <sys/resource.h>
46 #include <tools/libc_compat.h>
54 #include "str_error.h"
55 #include "libbpf_internal.h"
63 #define BPF_FS_MAGIC 0xcafe4a11
66 /* vsprintf() in __base_pr() uses nonliteral format string. It may break
67 * compilation if user enables corresponding warning. Disable it explicitly.
69 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
71 #define __printf(a, b) __attribute__((format(printf, a, b)))
73 static int __base_pr(enum libbpf_print_level level, const char *format,
76 if (level == LIBBPF_DEBUG)
79 return vfprintf(stderr, format, args);
82 static libbpf_print_fn_t __libbpf_pr = __base_pr;
84 libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn)
86 libbpf_print_fn_t old_print_fn = __libbpf_pr;
93 void libbpf_print(enum libbpf_print_level level, const char *format, ...)
100 va_start(args, format);
101 __libbpf_pr(level, format, args);
105 static void pr_perm_msg(int err)
110 if (err != -EPERM || geteuid() != 0)
113 err = getrlimit(RLIMIT_MEMLOCK, &limit);
117 if (limit.rlim_cur == RLIM_INFINITY)
120 if (limit.rlim_cur < 1024)
121 snprintf(buf, sizeof(buf), "%zu bytes", (size_t)limit.rlim_cur);
122 else if (limit.rlim_cur < 1024*1024)
123 snprintf(buf, sizeof(buf), "%.1f KiB", (double)limit.rlim_cur / 1024);
125 snprintf(buf, sizeof(buf), "%.1f MiB", (double)limit.rlim_cur / (1024*1024));
127 pr_warn("permission error while running as root; try raising 'ulimit -l'? current value: %s\n",
131 #define STRERR_BUFSIZE 128
133 /* Copied from tools/perf/util/util.h */
135 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
139 # define zclose(fd) ({ \
142 ___err = close((fd)); \
147 #ifdef HAVE_LIBELF_MMAP_SUPPORT
148 # define LIBBPF_ELF_C_READ_MMAP ELF_C_READ_MMAP
150 # define LIBBPF_ELF_C_READ_MMAP ELF_C_READ
153 static inline __u64 ptr_to_u64(const void *ptr)
155 return (__u64) (unsigned long) ptr;
158 struct bpf_capabilities {
159 /* v4.14: kernel support for program & map names. */
161 /* v5.2: kernel support for global data sections. */
163 /* BTF_KIND_FUNC and BTF_KIND_FUNC_PROTO support */
165 /* BTF_KIND_VAR and BTF_KIND_DATASEC support */
167 /* BPF_F_MMAPABLE is supported for arrays */
179 enum reloc_type type;
186 * bpf_prog should be a better name but it has been used in
190 /* Index in elf obj file, for relocation use. */
195 /* section_name with / replaced by _; makes recursive pinning
196 * in bpf_object__pin_programs easier
199 struct bpf_insn *insns;
200 size_t insns_cnt, main_prog_cnt;
201 enum bpf_prog_type type;
203 struct reloc_desc *reloc_desc;
211 bpf_program_prep_t preprocessor;
213 struct bpf_object *obj;
215 bpf_program_clear_priv_t clear_priv;
217 enum bpf_attach_type expected_attach_type;
219 __u32 attach_prog_fd;
221 __u32 func_info_rec_size;
224 struct bpf_capabilities *caps;
227 __u32 line_info_rec_size;
232 #define DATA_SEC ".data"
233 #define BSS_SEC ".bss"
234 #define RODATA_SEC ".rodata"
235 #define KCONFIG_SEC ".kconfig"
237 enum libbpf_map_type {
245 static const char * const libbpf_type_to_btf_name[] = {
246 [LIBBPF_MAP_DATA] = DATA_SEC,
247 [LIBBPF_MAP_BSS] = BSS_SEC,
248 [LIBBPF_MAP_RODATA] = RODATA_SEC,
249 [LIBBPF_MAP_KCONFIG] = KCONFIG_SEC,
259 struct bpf_map_def def;
260 __u32 btf_key_type_id;
261 __u32 btf_value_type_id;
263 bpf_map_clear_priv_t clear_priv;
264 enum libbpf_map_type libbpf_type;
284 enum extern_type type;
293 static LIST_HEAD(bpf_objects_list);
296 char name[BPF_OBJ_NAME_LEN];
300 struct bpf_program *programs;
302 struct bpf_map *maps;
307 struct extern_desc *externs;
312 bool has_pseudo_calls;
313 bool relaxed_core_relocs;
316 * Information when doing elf related work. Only valid if fd
344 * All loaded bpf_object is linked in a list, which is
345 * hidden to caller. bpf_objects__<func> handlers deal with
348 struct list_head list;
351 struct btf_ext *btf_ext;
354 bpf_object_clear_priv_t clear_priv;
356 struct bpf_capabilities caps;
360 #define obj_elf_valid(o) ((o)->efile.elf)
362 void bpf_program__unload(struct bpf_program *prog)
370 * If the object is opened but the program was never loaded,
371 * it is possible that prog->instances.nr == -1.
373 if (prog->instances.nr > 0) {
374 for (i = 0; i < prog->instances.nr; i++)
375 zclose(prog->instances.fds[i]);
376 } else if (prog->instances.nr != -1) {
377 pr_warn("Internal error: instances.nr is %d\n",
381 prog->instances.nr = -1;
382 zfree(&prog->instances.fds);
384 zfree(&prog->func_info);
385 zfree(&prog->line_info);
388 static void bpf_program__exit(struct bpf_program *prog)
393 if (prog->clear_priv)
394 prog->clear_priv(prog, prog->priv);
397 prog->clear_priv = NULL;
399 bpf_program__unload(prog);
401 zfree(&prog->section_name);
402 zfree(&prog->pin_name);
404 zfree(&prog->reloc_desc);
411 static char *__bpf_program__pin_name(struct bpf_program *prog)
415 name = p = strdup(prog->section_name);
416 while ((p = strchr(p, '/')))
423 bpf_program__init(void *data, size_t size, char *section_name, int idx,
424 struct bpf_program *prog)
426 const size_t bpf_insn_sz = sizeof(struct bpf_insn);
428 if (size == 0 || size % bpf_insn_sz) {
429 pr_warn("corrupted section '%s', size: %zu\n",
434 memset(prog, 0, sizeof(*prog));
436 prog->section_name = strdup(section_name);
437 if (!prog->section_name) {
438 pr_warn("failed to alloc name for prog under section(%d) %s\n",
443 prog->pin_name = __bpf_program__pin_name(prog);
444 if (!prog->pin_name) {
445 pr_warn("failed to alloc pin name for prog under section(%d) %s\n",
450 prog->insns = malloc(size);
452 pr_warn("failed to alloc insns for prog under section %s\n",
456 prog->insns_cnt = size / bpf_insn_sz;
457 memcpy(prog->insns, data, size);
459 prog->instances.fds = NULL;
460 prog->instances.nr = -1;
461 prog->type = BPF_PROG_TYPE_UNSPEC;
465 bpf_program__exit(prog);
470 bpf_object__add_program(struct bpf_object *obj, void *data, size_t size,
471 char *section_name, int idx)
473 struct bpf_program prog, *progs;
476 err = bpf_program__init(data, size, section_name, idx, &prog);
480 prog.caps = &obj->caps;
481 progs = obj->programs;
482 nr_progs = obj->nr_programs;
484 progs = reallocarray(progs, nr_progs + 1, sizeof(progs[0]));
487 * In this case the original obj->programs
488 * is still valid, so don't need special treat for
489 * bpf_close_object().
491 pr_warn("failed to alloc a new program under section '%s'\n",
493 bpf_program__exit(&prog);
497 pr_debug("found program %s\n", prog.section_name);
498 obj->programs = progs;
499 obj->nr_programs = nr_progs + 1;
501 progs[nr_progs] = prog;
506 bpf_object__init_prog_names(struct bpf_object *obj)
508 Elf_Data *symbols = obj->efile.symbols;
509 struct bpf_program *prog;
512 for (pi = 0; pi < obj->nr_programs; pi++) {
513 const char *name = NULL;
515 prog = &obj->programs[pi];
517 for (si = 0; si < symbols->d_size / sizeof(GElf_Sym) && !name;
521 if (!gelf_getsym(symbols, si, &sym))
523 if (sym.st_shndx != prog->idx)
525 if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL)
528 name = elf_strptr(obj->efile.elf,
529 obj->efile.strtabidx,
532 pr_warn("failed to get sym name string for prog %s\n",
534 return -LIBBPF_ERRNO__LIBELF;
538 if (!name && prog->idx == obj->efile.text_shndx)
542 pr_warn("failed to find sym for prog %s\n",
547 prog->name = strdup(name);
549 pr_warn("failed to allocate memory for prog sym %s\n",
558 static __u32 get_kernel_version(void)
560 __u32 major, minor, patch;
564 if (sscanf(info.release, "%u.%u.%u", &major, &minor, &patch) != 3)
566 return KERNEL_VERSION(major, minor, patch);
569 static struct bpf_object *bpf_object__new(const char *path,
572 const char *obj_name)
574 struct bpf_object *obj;
577 obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
579 pr_warn("alloc memory failed for %s\n", path);
580 return ERR_PTR(-ENOMEM);
583 strcpy(obj->path, path);
585 strncpy(obj->name, obj_name, sizeof(obj->name) - 1);
586 obj->name[sizeof(obj->name) - 1] = 0;
588 /* Using basename() GNU version which doesn't modify arg. */
589 strncpy(obj->name, basename((void *)path),
590 sizeof(obj->name) - 1);
591 end = strchr(obj->name, '.');
598 * Caller of this function should also call
599 * bpf_object__elf_finish() after data collection to return
600 * obj_buf to user. If not, we should duplicate the buffer to
601 * avoid user freeing them before elf finish.
603 obj->efile.obj_buf = obj_buf;
604 obj->efile.obj_buf_sz = obj_buf_sz;
605 obj->efile.maps_shndx = -1;
606 obj->efile.btf_maps_shndx = -1;
607 obj->efile.data_shndx = -1;
608 obj->efile.rodata_shndx = -1;
609 obj->efile.bss_shndx = -1;
610 obj->kconfig_map_idx = -1;
612 obj->kern_version = get_kernel_version();
615 INIT_LIST_HEAD(&obj->list);
616 list_add(&obj->list, &bpf_objects_list);
620 static void bpf_object__elf_finish(struct bpf_object *obj)
622 if (!obj_elf_valid(obj))
625 if (obj->efile.elf) {
626 elf_end(obj->efile.elf);
627 obj->efile.elf = NULL;
629 obj->efile.symbols = NULL;
630 obj->efile.data = NULL;
631 obj->efile.rodata = NULL;
632 obj->efile.bss = NULL;
634 zfree(&obj->efile.reloc_sects);
635 obj->efile.nr_reloc_sects = 0;
636 zclose(obj->efile.fd);
637 obj->efile.obj_buf = NULL;
638 obj->efile.obj_buf_sz = 0;
641 static int bpf_object__elf_init(struct bpf_object *obj)
646 if (obj_elf_valid(obj)) {
647 pr_warn("elf init: internal error\n");
648 return -LIBBPF_ERRNO__LIBELF;
651 if (obj->efile.obj_buf_sz > 0) {
653 * obj_buf should have been validated by
654 * bpf_object__open_buffer().
656 obj->efile.elf = elf_memory((char *)obj->efile.obj_buf,
657 obj->efile.obj_buf_sz);
659 obj->efile.fd = open(obj->path, O_RDONLY);
660 if (obj->efile.fd < 0) {
661 char errmsg[STRERR_BUFSIZE], *cp;
664 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
665 pr_warn("failed to open %s: %s\n", obj->path, cp);
669 obj->efile.elf = elf_begin(obj->efile.fd,
670 LIBBPF_ELF_C_READ_MMAP, NULL);
673 if (!obj->efile.elf) {
674 pr_warn("failed to open %s as ELF file\n", obj->path);
675 err = -LIBBPF_ERRNO__LIBELF;
679 if (!gelf_getehdr(obj->efile.elf, &obj->efile.ehdr)) {
680 pr_warn("failed to get EHDR from %s\n", obj->path);
681 err = -LIBBPF_ERRNO__FORMAT;
684 ep = &obj->efile.ehdr;
686 /* Old LLVM set e_machine to EM_NONE */
687 if (ep->e_type != ET_REL ||
688 (ep->e_machine && ep->e_machine != EM_BPF)) {
689 pr_warn("%s is not an eBPF object file\n", obj->path);
690 err = -LIBBPF_ERRNO__FORMAT;
696 bpf_object__elf_finish(obj);
700 static int bpf_object__check_endianness(struct bpf_object *obj)
702 #if __BYTE_ORDER == __LITTLE_ENDIAN
703 if (obj->efile.ehdr.e_ident[EI_DATA] == ELFDATA2LSB)
705 #elif __BYTE_ORDER == __BIG_ENDIAN
706 if (obj->efile.ehdr.e_ident[EI_DATA] == ELFDATA2MSB)
709 # error "Unrecognized __BYTE_ORDER__"
711 pr_warn("endianness mismatch.\n");
712 return -LIBBPF_ERRNO__ENDIAN;
716 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
718 memcpy(obj->license, data, min(size, sizeof(obj->license) - 1));
719 pr_debug("license of %s is %s\n", obj->path, obj->license);
724 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
728 if (size != sizeof(kver)) {
729 pr_warn("invalid kver section in %s\n", obj->path);
730 return -LIBBPF_ERRNO__FORMAT;
732 memcpy(&kver, data, sizeof(kver));
733 obj->kern_version = kver;
734 pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
738 static int compare_bpf_map(const void *_a, const void *_b)
740 const struct bpf_map *a = _a;
741 const struct bpf_map *b = _b;
743 if (a->sec_idx != b->sec_idx)
744 return a->sec_idx - b->sec_idx;
745 return a->sec_offset - b->sec_offset;
748 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
750 if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
751 type == BPF_MAP_TYPE_HASH_OF_MAPS)
756 static int bpf_object_search_section_size(const struct bpf_object *obj,
757 const char *name, size_t *d_size)
759 const GElf_Ehdr *ep = &obj->efile.ehdr;
760 Elf *elf = obj->efile.elf;
764 while ((scn = elf_nextscn(elf, scn)) != NULL) {
765 const char *sec_name;
770 if (gelf_getshdr(scn, &sh) != &sh) {
771 pr_warn("failed to get section(%d) header from %s\n",
776 sec_name = elf_strptr(elf, ep->e_shstrndx, sh.sh_name);
778 pr_warn("failed to get section(%d) name from %s\n",
783 if (strcmp(name, sec_name))
786 data = elf_getdata(scn, 0);
788 pr_warn("failed to get section(%d) data from %s(%s)\n",
789 idx, name, obj->path);
793 *d_size = data->d_size;
800 int bpf_object__section_size(const struct bpf_object *obj, const char *name,
809 } else if (!strcmp(name, DATA_SEC)) {
811 *size = obj->efile.data->d_size;
812 } else if (!strcmp(name, BSS_SEC)) {
814 *size = obj->efile.bss->d_size;
815 } else if (!strcmp(name, RODATA_SEC)) {
816 if (obj->efile.rodata)
817 *size = obj->efile.rodata->d_size;
819 ret = bpf_object_search_section_size(obj, name, &d_size);
824 return *size ? 0 : ret;
827 int bpf_object__variable_offset(const struct bpf_object *obj, const char *name,
830 Elf_Data *symbols = obj->efile.symbols;
837 for (si = 0; si < symbols->d_size / sizeof(GElf_Sym); si++) {
840 if (!gelf_getsym(symbols, si, &sym))
842 if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL ||
843 GELF_ST_TYPE(sym.st_info) != STT_OBJECT)
846 sname = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
849 pr_warn("failed to get sym name string for var %s\n",
853 if (strcmp(name, sname) == 0) {
862 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
864 struct bpf_map *new_maps;
868 if (obj->nr_maps < obj->maps_cap)
869 return &obj->maps[obj->nr_maps++];
871 new_cap = max((size_t)4, obj->maps_cap * 3 / 2);
872 new_maps = realloc(obj->maps, new_cap * sizeof(*obj->maps));
874 pr_warn("alloc maps for object failed\n");
875 return ERR_PTR(-ENOMEM);
878 obj->maps_cap = new_cap;
879 obj->maps = new_maps;
881 /* zero out new maps */
882 memset(obj->maps + obj->nr_maps, 0,
883 (obj->maps_cap - obj->nr_maps) * sizeof(*obj->maps));
885 * fill all fd with -1 so won't close incorrect fd (fd=0 is stdin)
886 * when failure (zclose won't close negative fd)).
888 for (i = obj->nr_maps; i < obj->maps_cap; i++) {
889 obj->maps[i].fd = -1;
890 obj->maps[i].inner_map_fd = -1;
893 return &obj->maps[obj->nr_maps++];
896 static size_t bpf_map_mmap_sz(const struct bpf_map *map)
898 long page_sz = sysconf(_SC_PAGE_SIZE);
901 map_sz = roundup(map->def.value_size, 8) * map->def.max_entries;
902 map_sz = roundup(map_sz, page_sz);
906 static char *internal_map_name(struct bpf_object *obj,
907 enum libbpf_map_type type)
909 char map_name[BPF_OBJ_NAME_LEN];
910 const char *sfx = libbpf_type_to_btf_name[type];
911 int sfx_len = max((size_t)7, strlen(sfx));
912 int pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1,
915 snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
916 sfx_len, libbpf_type_to_btf_name[type]);
918 return strdup(map_name);
922 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
923 int sec_idx, void *data, size_t data_sz)
925 struct bpf_map_def *def;
929 map = bpf_object__add_map(obj);
933 map->libbpf_type = type;
934 map->sec_idx = sec_idx;
936 map->name = internal_map_name(obj, type);
938 pr_warn("failed to alloc map name\n");
943 def->type = BPF_MAP_TYPE_ARRAY;
944 def->key_size = sizeof(int);
945 def->value_size = data_sz;
946 def->max_entries = 1;
947 def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
948 ? BPF_F_RDONLY_PROG : 0;
949 def->map_flags |= BPF_F_MMAPABLE;
951 pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
952 map->name, map->sec_idx, map->sec_offset, def->map_flags);
954 map->mmaped = mmap(NULL, bpf_map_mmap_sz(map), PROT_READ | PROT_WRITE,
955 MAP_SHARED | MAP_ANONYMOUS, -1, 0);
956 if (map->mmaped == MAP_FAILED) {
959 pr_warn("failed to alloc map '%s' content buffer: %d\n",
966 memcpy(map->mmaped, data, data_sz);
968 pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
972 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
977 * Populate obj->maps with libbpf internal maps.
979 if (obj->efile.data_shndx >= 0) {
980 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
981 obj->efile.data_shndx,
982 obj->efile.data->d_buf,
983 obj->efile.data->d_size);
987 if (obj->efile.rodata_shndx >= 0) {
988 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
989 obj->efile.rodata_shndx,
990 obj->efile.rodata->d_buf,
991 obj->efile.rodata->d_size);
995 if (obj->efile.bss_shndx >= 0) {
996 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
997 obj->efile.bss_shndx,
999 obj->efile.bss->d_size);
1007 static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
1012 for (i = 0; i < obj->nr_extern; i++) {
1013 if (strcmp(obj->externs[i].name, name) == 0)
1014 return &obj->externs[i];
1019 static int set_ext_value_tri(struct extern_desc *ext, void *ext_val,
1022 switch (ext->type) {
1025 pr_warn("extern %s=%c should be tristate or char\n",
1029 *(bool *)ext_val = value == 'y' ? true : false;
1033 *(enum libbpf_tristate *)ext_val = TRI_YES;
1034 else if (value == 'm')
1035 *(enum libbpf_tristate *)ext_val = TRI_MODULE;
1036 else /* value == 'n' */
1037 *(enum libbpf_tristate *)ext_val = TRI_NO;
1040 *(char *)ext_val = value;
1046 pr_warn("extern %s=%c should be bool, tristate, or char\n",
1054 static int set_ext_value_str(struct extern_desc *ext, char *ext_val,
1059 if (ext->type != EXT_CHAR_ARR) {
1060 pr_warn("extern %s=%s should char array\n", ext->name, value);
1064 len = strlen(value);
1065 if (value[len - 1] != '"') {
1066 pr_warn("extern '%s': invalid string config '%s'\n",
1073 if (len >= ext->sz) {
1074 pr_warn("extern '%s': long string config %s of (%zu bytes) truncated to %d bytes\n",
1075 ext->name, value, len, ext->sz - 1);
1078 memcpy(ext_val, value + 1, len);
1079 ext_val[len] = '\0';
1084 static int parse_u64(const char *value, __u64 *res)
1090 *res = strtoull(value, &value_end, 0);
1093 pr_warn("failed to parse '%s' as integer: %d\n", value, err);
1097 pr_warn("failed to parse '%s' as integer completely\n", value);
1103 static bool is_ext_value_in_range(const struct extern_desc *ext, __u64 v)
1105 int bit_sz = ext->sz * 8;
1110 /* Validate that value stored in u64 fits in integer of `ext->sz`
1111 * bytes size without any loss of information. If the target integer
1112 * is signed, we rely on the following limits of integer type of
1113 * Y bits and subsequent transformation:
1115 * -2^(Y-1) <= X <= 2^(Y-1) - 1
1116 * 0 <= X + 2^(Y-1) <= 2^Y - 1
1117 * 0 <= X + 2^(Y-1) < 2^Y
1119 * For unsigned target integer, check that all the (64 - Y) bits are
1123 return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
1125 return (v >> bit_sz) == 0;
1128 static int set_ext_value_num(struct extern_desc *ext, void *ext_val,
1131 if (ext->type != EXT_INT && ext->type != EXT_CHAR) {
1132 pr_warn("extern %s=%llu should be integer\n",
1133 ext->name, (unsigned long long)value);
1136 if (!is_ext_value_in_range(ext, value)) {
1137 pr_warn("extern %s=%llu value doesn't fit in %d bytes\n",
1138 ext->name, (unsigned long long)value, ext->sz);
1142 case 1: *(__u8 *)ext_val = value; break;
1143 case 2: *(__u16 *)ext_val = value; break;
1144 case 4: *(__u32 *)ext_val = value; break;
1145 case 8: *(__u64 *)ext_val = value; break;
1153 static int bpf_object__process_kconfig_line(struct bpf_object *obj,
1154 char *buf, void *data)
1156 struct extern_desc *ext;
1162 if (strncmp(buf, "CONFIG_", 7))
1165 sep = strchr(buf, '=');
1167 pr_warn("failed to parse '%s': no separator\n", buf);
1171 /* Trim ending '\n' */
1173 if (buf[len - 1] == '\n')
1174 buf[len - 1] = '\0';
1175 /* Split on '=' and ensure that a value is present. */
1179 pr_warn("failed to parse '%s': no value\n", buf);
1183 ext = find_extern_by_name(obj, buf);
1184 if (!ext || ext->is_set)
1187 ext_val = data + ext->data_off;
1191 case 'y': case 'n': case 'm':
1192 err = set_ext_value_tri(ext, ext_val, *value);
1195 err = set_ext_value_str(ext, ext_val, value);
1198 /* assume integer */
1199 err = parse_u64(value, &num);
1201 pr_warn("extern %s=%s should be integer\n",
1205 err = set_ext_value_num(ext, ext_val, num);
1210 pr_debug("extern %s=%s\n", ext->name, value);
1214 static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
1222 len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
1225 else if (len >= PATH_MAX)
1226 return -ENAMETOOLONG;
1228 /* gzopen also accepts uncompressed files. */
1229 file = gzopen(buf, "r");
1231 file = gzopen("/proc/config.gz", "r");
1234 pr_warn("failed to open system Kconfig\n");
1238 while (gzgets(file, buf, sizeof(buf))) {
1239 err = bpf_object__process_kconfig_line(obj, buf, data);
1241 pr_warn("error parsing system Kconfig line '%s': %d\n",
1252 static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
1253 const char *config, void *data)
1259 file = fmemopen((void *)config, strlen(config), "r");
1262 pr_warn("failed to open in-memory Kconfig: %d\n", err);
1266 while (fgets(buf, sizeof(buf), file)) {
1267 err = bpf_object__process_kconfig_line(obj, buf, data);
1269 pr_warn("error parsing in-memory Kconfig line '%s': %d\n",
1279 static int bpf_object__init_kconfig_map(struct bpf_object *obj)
1281 struct extern_desc *last_ext;
1285 if (obj->nr_extern == 0)
1288 last_ext = &obj->externs[obj->nr_extern - 1];
1289 map_sz = last_ext->data_off + last_ext->sz;
1291 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
1292 obj->efile.symbols_shndx,
1297 obj->kconfig_map_idx = obj->nr_maps - 1;
1302 static int bpf_object__init_user_maps(struct bpf_object *obj, bool strict)
1304 Elf_Data *symbols = obj->efile.symbols;
1305 int i, map_def_sz = 0, nr_maps = 0, nr_syms;
1306 Elf_Data *data = NULL;
1309 if (obj->efile.maps_shndx < 0)
1315 scn = elf_getscn(obj->efile.elf, obj->efile.maps_shndx);
1317 data = elf_getdata(scn, NULL);
1318 if (!scn || !data) {
1319 pr_warn("failed to get Elf_Data from map section %d\n",
1320 obj->efile.maps_shndx);
1325 * Count number of maps. Each map has a name.
1326 * Array of maps is not supported: only the first element is
1329 * TODO: Detect array of map and report error.
1331 nr_syms = symbols->d_size / sizeof(GElf_Sym);
1332 for (i = 0; i < nr_syms; i++) {
1335 if (!gelf_getsym(symbols, i, &sym))
1337 if (sym.st_shndx != obj->efile.maps_shndx)
1341 /* Assume equally sized map definitions */
1342 pr_debug("maps in %s: %d maps in %zd bytes\n",
1343 obj->path, nr_maps, data->d_size);
1345 if (!data->d_size || nr_maps == 0 || (data->d_size % nr_maps) != 0) {
1346 pr_warn("unable to determine map definition size section %s, %d maps in %zd bytes\n",
1347 obj->path, nr_maps, data->d_size);
1350 map_def_sz = data->d_size / nr_maps;
1352 /* Fill obj->maps using data in "maps" section. */
1353 for (i = 0; i < nr_syms; i++) {
1355 const char *map_name;
1356 struct bpf_map_def *def;
1357 struct bpf_map *map;
1359 if (!gelf_getsym(symbols, i, &sym))
1361 if (sym.st_shndx != obj->efile.maps_shndx)
1364 map = bpf_object__add_map(obj);
1366 return PTR_ERR(map);
1368 map_name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
1371 pr_warn("failed to get map #%d name sym string for obj %s\n",
1373 return -LIBBPF_ERRNO__FORMAT;
1376 map->libbpf_type = LIBBPF_MAP_UNSPEC;
1377 map->sec_idx = sym.st_shndx;
1378 map->sec_offset = sym.st_value;
1379 pr_debug("map '%s' (legacy): at sec_idx %d, offset %zu.\n",
1380 map_name, map->sec_idx, map->sec_offset);
1381 if (sym.st_value + map_def_sz > data->d_size) {
1382 pr_warn("corrupted maps section in %s: last map \"%s\" too small\n",
1383 obj->path, map_name);
1387 map->name = strdup(map_name);
1389 pr_warn("failed to alloc map name\n");
1392 pr_debug("map %d is \"%s\"\n", i, map->name);
1393 def = (struct bpf_map_def *)(data->d_buf + sym.st_value);
1395 * If the definition of the map in the object file fits in
1396 * bpf_map_def, copy it. Any extra fields in our version
1397 * of bpf_map_def will default to zero as a result of the
1400 if (map_def_sz <= sizeof(struct bpf_map_def)) {
1401 memcpy(&map->def, def, map_def_sz);
1404 * Here the map structure being read is bigger than what
1405 * we expect, truncate if the excess bits are all zero.
1406 * If they are not zero, reject this map as
1411 for (b = ((char *)def) + sizeof(struct bpf_map_def);
1412 b < ((char *)def) + map_def_sz; b++) {
1414 pr_warn("maps section in %s: \"%s\" has unrecognized, non-zero options\n",
1415 obj->path, map_name);
1420 memcpy(&map->def, def, sizeof(struct bpf_map_def));
1426 static const struct btf_type *
1427 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
1429 const struct btf_type *t = btf__type_by_id(btf, id);
1434 while (btf_is_mod(t) || btf_is_typedef(t)) {
1437 t = btf__type_by_id(btf, t->type);
1444 * Fetch integer attribute of BTF map definition. Such attributes are
1445 * represented using a pointer to an array, in which dimensionality of array
1446 * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
1447 * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
1448 * type definition, while using only sizeof(void *) space in ELF data section.
1450 static bool get_map_field_int(const char *map_name, const struct btf *btf,
1451 const struct btf_type *def,
1452 const struct btf_member *m, __u32 *res)
1454 const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
1455 const char *name = btf__name_by_offset(btf, m->name_off);
1456 const struct btf_array *arr_info;
1457 const struct btf_type *arr_t;
1459 if (!btf_is_ptr(t)) {
1460 pr_warn("map '%s': attr '%s': expected PTR, got %u.\n",
1461 map_name, name, btf_kind(t));
1465 arr_t = btf__type_by_id(btf, t->type);
1467 pr_warn("map '%s': attr '%s': type [%u] not found.\n",
1468 map_name, name, t->type);
1471 if (!btf_is_array(arr_t)) {
1472 pr_warn("map '%s': attr '%s': expected ARRAY, got %u.\n",
1473 map_name, name, btf_kind(arr_t));
1476 arr_info = btf_array(arr_t);
1477 *res = arr_info->nelems;
1481 static int build_map_pin_path(struct bpf_map *map, const char *path)
1487 path = "/sys/fs/bpf";
1489 len = snprintf(buf, PATH_MAX, "%s/%s", path, bpf_map__name(map));
1492 else if (len >= PATH_MAX)
1493 return -ENAMETOOLONG;
1495 err = bpf_map__set_pin_path(map, buf);
1502 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
1503 const struct btf_type *sec,
1504 int var_idx, int sec_idx,
1505 const Elf_Data *data, bool strict,
1506 const char *pin_root_path)
1508 const struct btf_type *var, *def, *t;
1509 const struct btf_var_secinfo *vi;
1510 const struct btf_var *var_extra;
1511 const struct btf_member *m;
1512 const char *map_name;
1513 struct bpf_map *map;
1516 vi = btf_var_secinfos(sec) + var_idx;
1517 var = btf__type_by_id(obj->btf, vi->type);
1518 var_extra = btf_var(var);
1519 map_name = btf__name_by_offset(obj->btf, var->name_off);
1520 vlen = btf_vlen(var);
1522 if (map_name == NULL || map_name[0] == '\0') {
1523 pr_warn("map #%d: empty name.\n", var_idx);
1526 if ((__u64)vi->offset + vi->size > data->d_size) {
1527 pr_warn("map '%s' BTF data is corrupted.\n", map_name);
1530 if (!btf_is_var(var)) {
1531 pr_warn("map '%s': unexpected var kind %u.\n",
1532 map_name, btf_kind(var));
1535 if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED &&
1536 var_extra->linkage != BTF_VAR_STATIC) {
1537 pr_warn("map '%s': unsupported var linkage %u.\n",
1538 map_name, var_extra->linkage);
1542 def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
1543 if (!btf_is_struct(def)) {
1544 pr_warn("map '%s': unexpected def kind %u.\n",
1545 map_name, btf_kind(var));
1548 if (def->size > vi->size) {
1549 pr_warn("map '%s': invalid def size.\n", map_name);
1553 map = bpf_object__add_map(obj);
1555 return PTR_ERR(map);
1556 map->name = strdup(map_name);
1558 pr_warn("map '%s': failed to alloc map name.\n", map_name);
1561 map->libbpf_type = LIBBPF_MAP_UNSPEC;
1562 map->def.type = BPF_MAP_TYPE_UNSPEC;
1563 map->sec_idx = sec_idx;
1564 map->sec_offset = vi->offset;
1565 pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
1566 map_name, map->sec_idx, map->sec_offset);
1568 vlen = btf_vlen(def);
1569 m = btf_members(def);
1570 for (i = 0; i < vlen; i++, m++) {
1571 const char *name = btf__name_by_offset(obj->btf, m->name_off);
1574 pr_warn("map '%s': invalid field #%d.\n", map_name, i);
1577 if (strcmp(name, "type") == 0) {
1578 if (!get_map_field_int(map_name, obj->btf, def, m,
1581 pr_debug("map '%s': found type = %u.\n",
1582 map_name, map->def.type);
1583 } else if (strcmp(name, "max_entries") == 0) {
1584 if (!get_map_field_int(map_name, obj->btf, def, m,
1585 &map->def.max_entries))
1587 pr_debug("map '%s': found max_entries = %u.\n",
1588 map_name, map->def.max_entries);
1589 } else if (strcmp(name, "map_flags") == 0) {
1590 if (!get_map_field_int(map_name, obj->btf, def, m,
1591 &map->def.map_flags))
1593 pr_debug("map '%s': found map_flags = %u.\n",
1594 map_name, map->def.map_flags);
1595 } else if (strcmp(name, "key_size") == 0) {
1598 if (!get_map_field_int(map_name, obj->btf, def, m,
1601 pr_debug("map '%s': found key_size = %u.\n",
1603 if (map->def.key_size && map->def.key_size != sz) {
1604 pr_warn("map '%s': conflicting key size %u != %u.\n",
1605 map_name, map->def.key_size, sz);
1608 map->def.key_size = sz;
1609 } else if (strcmp(name, "key") == 0) {
1612 t = btf__type_by_id(obj->btf, m->type);
1614 pr_warn("map '%s': key type [%d] not found.\n",
1618 if (!btf_is_ptr(t)) {
1619 pr_warn("map '%s': key spec is not PTR: %u.\n",
1620 map_name, btf_kind(t));
1623 sz = btf__resolve_size(obj->btf, t->type);
1625 pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
1626 map_name, t->type, (ssize_t)sz);
1629 pr_debug("map '%s': found key [%u], sz = %zd.\n",
1630 map_name, t->type, (ssize_t)sz);
1631 if (map->def.key_size && map->def.key_size != sz) {
1632 pr_warn("map '%s': conflicting key size %u != %zd.\n",
1633 map_name, map->def.key_size, (ssize_t)sz);
1636 map->def.key_size = sz;
1637 map->btf_key_type_id = t->type;
1638 } else if (strcmp(name, "value_size") == 0) {
1641 if (!get_map_field_int(map_name, obj->btf, def, m,
1644 pr_debug("map '%s': found value_size = %u.\n",
1646 if (map->def.value_size && map->def.value_size != sz) {
1647 pr_warn("map '%s': conflicting value size %u != %u.\n",
1648 map_name, map->def.value_size, sz);
1651 map->def.value_size = sz;
1652 } else if (strcmp(name, "value") == 0) {
1655 t = btf__type_by_id(obj->btf, m->type);
1657 pr_warn("map '%s': value type [%d] not found.\n",
1661 if (!btf_is_ptr(t)) {
1662 pr_warn("map '%s': value spec is not PTR: %u.\n",
1663 map_name, btf_kind(t));
1666 sz = btf__resolve_size(obj->btf, t->type);
1668 pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
1669 map_name, t->type, (ssize_t)sz);
1672 pr_debug("map '%s': found value [%u], sz = %zd.\n",
1673 map_name, t->type, (ssize_t)sz);
1674 if (map->def.value_size && map->def.value_size != sz) {
1675 pr_warn("map '%s': conflicting value size %u != %zd.\n",
1676 map_name, map->def.value_size, (ssize_t)sz);
1679 map->def.value_size = sz;
1680 map->btf_value_type_id = t->type;
1681 } else if (strcmp(name, "pinning") == 0) {
1685 if (!get_map_field_int(map_name, obj->btf, def, m,
1688 pr_debug("map '%s': found pinning = %u.\n",
1691 if (val != LIBBPF_PIN_NONE &&
1692 val != LIBBPF_PIN_BY_NAME) {
1693 pr_warn("map '%s': invalid pinning value %u.\n",
1697 if (val == LIBBPF_PIN_BY_NAME) {
1698 err = build_map_pin_path(map, pin_root_path);
1700 pr_warn("map '%s': couldn't build pin path.\n",
1707 pr_warn("map '%s': unknown field '%s'.\n",
1711 pr_debug("map '%s': ignoring unknown field '%s'.\n",
1716 if (map->def.type == BPF_MAP_TYPE_UNSPEC) {
1717 pr_warn("map '%s': map type isn't specified.\n", map_name);
1724 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
1725 const char *pin_root_path)
1727 const struct btf_type *sec = NULL;
1728 int nr_types, i, vlen, err;
1729 const struct btf_type *t;
1734 if (obj->efile.btf_maps_shndx < 0)
1737 scn = elf_getscn(obj->efile.elf, obj->efile.btf_maps_shndx);
1739 data = elf_getdata(scn, NULL);
1740 if (!scn || !data) {
1741 pr_warn("failed to get Elf_Data from map section %d (%s)\n",
1742 obj->efile.maps_shndx, MAPS_ELF_SEC);
1746 nr_types = btf__get_nr_types(obj->btf);
1747 for (i = 1; i <= nr_types; i++) {
1748 t = btf__type_by_id(obj->btf, i);
1749 if (!btf_is_datasec(t))
1751 name = btf__name_by_offset(obj->btf, t->name_off);
1752 if (strcmp(name, MAPS_ELF_SEC) == 0) {
1759 pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
1763 vlen = btf_vlen(sec);
1764 for (i = 0; i < vlen; i++) {
1765 err = bpf_object__init_user_btf_map(obj, sec, i,
1766 obj->efile.btf_maps_shndx,
1776 static int bpf_object__init_maps(struct bpf_object *obj,
1777 const struct bpf_object_open_opts *opts)
1779 const char *pin_root_path;
1783 strict = !OPTS_GET(opts, relaxed_maps, false);
1784 pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
1786 err = bpf_object__init_user_maps(obj, strict);
1787 err = err ?: bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
1788 err = err ?: bpf_object__init_global_data_maps(obj);
1789 err = err ?: bpf_object__init_kconfig_map(obj);
1794 qsort(obj->maps, obj->nr_maps, sizeof(obj->maps[0]),
1800 static bool section_have_execinstr(struct bpf_object *obj, int idx)
1805 scn = elf_getscn(obj->efile.elf, idx);
1809 if (gelf_getshdr(scn, &sh) != &sh)
1812 if (sh.sh_flags & SHF_EXECINSTR)
1818 static void bpf_object__sanitize_btf(struct bpf_object *obj)
1820 bool has_datasec = obj->caps.btf_datasec;
1821 bool has_func = obj->caps.btf_func;
1822 struct btf *btf = obj->btf;
1826 if (!obj->btf || (has_func && has_datasec))
1829 for (i = 1; i <= btf__get_nr_types(btf); i++) {
1830 t = (struct btf_type *)btf__type_by_id(btf, i);
1832 if (!has_datasec && btf_is_var(t)) {
1833 /* replace VAR with INT */
1834 t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
1836 * using size = 1 is the safest choice, 4 will be too
1837 * big and cause kernel BTF validation failure if
1838 * original variable took less than 4 bytes
1841 *(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
1842 } else if (!has_datasec && btf_is_datasec(t)) {
1843 /* replace DATASEC with STRUCT */
1844 const struct btf_var_secinfo *v = btf_var_secinfos(t);
1845 struct btf_member *m = btf_members(t);
1846 struct btf_type *vt;
1849 name = (char *)btf__name_by_offset(btf, t->name_off);
1857 t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
1858 for (j = 0; j < vlen; j++, v++, m++) {
1859 /* order of field assignments is important */
1860 m->offset = v->offset * 8;
1862 /* preserve variable name as member name */
1863 vt = (void *)btf__type_by_id(btf, v->type);
1864 m->name_off = vt->name_off;
1866 } else if (!has_func && btf_is_func_proto(t)) {
1867 /* replace FUNC_PROTO with ENUM */
1869 t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
1870 t->size = sizeof(__u32); /* kernel enforced */
1871 } else if (!has_func && btf_is_func(t)) {
1872 /* replace FUNC with TYPEDEF */
1873 t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
1878 static void bpf_object__sanitize_btf_ext(struct bpf_object *obj)
1883 if (!obj->caps.btf_func) {
1884 btf_ext__free(obj->btf_ext);
1885 obj->btf_ext = NULL;
1889 static bool bpf_object__is_btf_mandatory(const struct bpf_object *obj)
1891 return obj->efile.btf_maps_shndx >= 0 ||
1895 static int bpf_object__init_btf(struct bpf_object *obj,
1897 Elf_Data *btf_ext_data)
1899 bool btf_required = bpf_object__is_btf_mandatory(obj);
1903 obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
1904 if (IS_ERR(obj->btf)) {
1905 pr_warn("Error loading ELF section %s: %d.\n",
1912 pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
1913 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
1916 obj->btf_ext = btf_ext__new(btf_ext_data->d_buf,
1917 btf_ext_data->d_size);
1918 if (IS_ERR(obj->btf_ext)) {
1919 pr_warn("Error loading ELF section %s: %ld. Ignored and continue.\n",
1920 BTF_EXT_ELF_SEC, PTR_ERR(obj->btf_ext));
1921 obj->btf_ext = NULL;
1926 if (err || IS_ERR(obj->btf)) {
1928 err = err ? : PTR_ERR(obj->btf);
1931 if (!IS_ERR_OR_NULL(obj->btf))
1932 btf__free(obj->btf);
1935 if (btf_required && !obj->btf) {
1936 pr_warn("BTF is required, but is missing or corrupted.\n");
1937 return err == 0 ? -ENOENT : err;
1942 static int bpf_object__finalize_btf(struct bpf_object *obj)
1949 err = btf__finalize_data(obj, obj->btf);
1953 pr_warn("Error finalizing %s: %d.\n", BTF_ELF_SEC, err);
1954 btf__free(obj->btf);
1956 btf_ext__free(obj->btf_ext);
1957 obj->btf_ext = NULL;
1959 if (bpf_object__is_btf_mandatory(obj)) {
1960 pr_warn("BTF is required, but is missing or corrupted.\n");
1966 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
1973 bpf_object__sanitize_btf(obj);
1974 bpf_object__sanitize_btf_ext(obj);
1976 err = btf__load(obj->btf);
1978 pr_warn("Error loading %s into kernel: %d.\n",
1980 btf__free(obj->btf);
1982 /* btf_ext can't exist without btf, so free it as well */
1984 btf_ext__free(obj->btf_ext);
1985 obj->btf_ext = NULL;
1988 if (bpf_object__is_btf_mandatory(obj))
1994 static int bpf_object__elf_collect(struct bpf_object *obj)
1996 Elf *elf = obj->efile.elf;
1997 GElf_Ehdr *ep = &obj->efile.ehdr;
1998 Elf_Data *btf_ext_data = NULL;
1999 Elf_Data *btf_data = NULL;
2000 Elf_Scn *scn = NULL;
2001 int idx = 0, err = 0;
2003 /* Elf is corrupted/truncated, avoid calling elf_strptr. */
2004 if (!elf_rawdata(elf_getscn(elf, ep->e_shstrndx), NULL)) {
2005 pr_warn("failed to get e_shstrndx from %s\n", obj->path);
2006 return -LIBBPF_ERRNO__FORMAT;
2009 while ((scn = elf_nextscn(elf, scn)) != NULL) {
2015 if (gelf_getshdr(scn, &sh) != &sh) {
2016 pr_warn("failed to get section(%d) header from %s\n",
2018 return -LIBBPF_ERRNO__FORMAT;
2021 name = elf_strptr(elf, ep->e_shstrndx, sh.sh_name);
2023 pr_warn("failed to get section(%d) name from %s\n",
2025 return -LIBBPF_ERRNO__FORMAT;
2028 data = elf_getdata(scn, 0);
2030 pr_warn("failed to get section(%d) data from %s(%s)\n",
2031 idx, name, obj->path);
2032 return -LIBBPF_ERRNO__FORMAT;
2034 pr_debug("section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
2035 idx, name, (unsigned long)data->d_size,
2036 (int)sh.sh_link, (unsigned long)sh.sh_flags,
2039 if (strcmp(name, "license") == 0) {
2040 err = bpf_object__init_license(obj,
2045 } else if (strcmp(name, "version") == 0) {
2046 err = bpf_object__init_kversion(obj,
2051 } else if (strcmp(name, "maps") == 0) {
2052 obj->efile.maps_shndx = idx;
2053 } else if (strcmp(name, MAPS_ELF_SEC) == 0) {
2054 obj->efile.btf_maps_shndx = idx;
2055 } else if (strcmp(name, BTF_ELF_SEC) == 0) {
2057 } else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
2058 btf_ext_data = data;
2059 } else if (sh.sh_type == SHT_SYMTAB) {
2060 if (obj->efile.symbols) {
2061 pr_warn("bpf: multiple SYMTAB in %s\n",
2063 return -LIBBPF_ERRNO__FORMAT;
2065 obj->efile.symbols = data;
2066 obj->efile.symbols_shndx = idx;
2067 obj->efile.strtabidx = sh.sh_link;
2068 } else if (sh.sh_type == SHT_PROGBITS && data->d_size > 0) {
2069 if (sh.sh_flags & SHF_EXECINSTR) {
2070 if (strcmp(name, ".text") == 0)
2071 obj->efile.text_shndx = idx;
2072 err = bpf_object__add_program(obj, data->d_buf,
2076 char errmsg[STRERR_BUFSIZE];
2079 cp = libbpf_strerror_r(-err, errmsg,
2081 pr_warn("failed to alloc program %s (%s): %s",
2082 name, obj->path, cp);
2085 } else if (strcmp(name, DATA_SEC) == 0) {
2086 obj->efile.data = data;
2087 obj->efile.data_shndx = idx;
2088 } else if (strcmp(name, RODATA_SEC) == 0) {
2089 obj->efile.rodata = data;
2090 obj->efile.rodata_shndx = idx;
2092 pr_debug("skip section(%d) %s\n", idx, name);
2094 } else if (sh.sh_type == SHT_REL) {
2095 int nr_sects = obj->efile.nr_reloc_sects;
2096 void *sects = obj->efile.reloc_sects;
2097 int sec = sh.sh_info; /* points to other section */
2099 /* Only do relo for section with exec instructions */
2100 if (!section_have_execinstr(obj, sec)) {
2101 pr_debug("skip relo %s(%d) for section(%d)\n",
2106 sects = reallocarray(sects, nr_sects + 1,
2107 sizeof(*obj->efile.reloc_sects));
2109 pr_warn("reloc_sects realloc failed\n");
2113 obj->efile.reloc_sects = sects;
2114 obj->efile.nr_reloc_sects++;
2116 obj->efile.reloc_sects[nr_sects].shdr = sh;
2117 obj->efile.reloc_sects[nr_sects].data = data;
2118 } else if (sh.sh_type == SHT_NOBITS &&
2119 strcmp(name, BSS_SEC) == 0) {
2120 obj->efile.bss = data;
2121 obj->efile.bss_shndx = idx;
2123 pr_debug("skip section(%d) %s\n", idx, name);
2127 if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
2128 pr_warn("Corrupted ELF file: index of strtab invalid\n");
2129 return -LIBBPF_ERRNO__FORMAT;
2131 return bpf_object__init_btf(obj, btf_data, btf_ext_data);
2134 static bool sym_is_extern(const GElf_Sym *sym)
2136 int bind = GELF_ST_BIND(sym->st_info);
2137 /* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
2138 return sym->st_shndx == SHN_UNDEF &&
2139 (bind == STB_GLOBAL || bind == STB_WEAK) &&
2140 GELF_ST_TYPE(sym->st_info) == STT_NOTYPE;
2143 static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
2145 const struct btf_type *t;
2146 const char *var_name;
2152 n = btf__get_nr_types(btf);
2153 for (i = 1; i <= n; i++) {
2154 t = btf__type_by_id(btf, i);
2159 var_name = btf__name_by_offset(btf, t->name_off);
2160 if (strcmp(var_name, ext_name))
2163 if (btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
2172 static enum extern_type find_extern_type(const struct btf *btf, int id,
2175 const struct btf_type *t;
2178 t = skip_mods_and_typedefs(btf, id, NULL);
2179 name = btf__name_by_offset(btf, t->name_off);
2183 switch (btf_kind(t)) {
2184 case BTF_KIND_INT: {
2185 int enc = btf_int_encoding(t);
2187 if (enc & BTF_INT_BOOL)
2188 return t->size == 1 ? EXT_BOOL : EXT_UNKNOWN;
2190 *is_signed = enc & BTF_INT_SIGNED;
2193 if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
2200 if (strcmp(name, "libbpf_tristate"))
2202 return EXT_TRISTATE;
2203 case BTF_KIND_ARRAY:
2204 if (btf_array(t)->nelems == 0)
2206 if (find_extern_type(btf, btf_array(t)->type, NULL) != EXT_CHAR)
2208 return EXT_CHAR_ARR;
2214 static int cmp_externs(const void *_a, const void *_b)
2216 const struct extern_desc *a = _a;
2217 const struct extern_desc *b = _b;
2219 /* descending order by alignment requirements */
2220 if (a->align != b->align)
2221 return a->align > b->align ? -1 : 1;
2222 /* ascending order by size, within same alignment class */
2224 return a->sz < b->sz ? -1 : 1;
2225 /* resolve ties by name */
2226 return strcmp(a->name, b->name);
2229 static int bpf_object__collect_externs(struct bpf_object *obj)
2231 const struct btf_type *t;
2232 struct extern_desc *ext;
2233 int i, n, off, btf_id;
2234 struct btf_type *sec;
2235 const char *ext_name;
2239 if (!obj->efile.symbols)
2242 scn = elf_getscn(obj->efile.elf, obj->efile.symbols_shndx);
2244 return -LIBBPF_ERRNO__FORMAT;
2245 if (gelf_getshdr(scn, &sh) != &sh)
2246 return -LIBBPF_ERRNO__FORMAT;
2247 n = sh.sh_size / sh.sh_entsize;
2249 pr_debug("looking for externs among %d symbols...\n", n);
2250 for (i = 0; i < n; i++) {
2253 if (!gelf_getsym(obj->efile.symbols, i, &sym))
2254 return -LIBBPF_ERRNO__FORMAT;
2255 if (!sym_is_extern(&sym))
2257 ext_name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
2259 if (!ext_name || !ext_name[0])
2263 ext = reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
2267 ext = &ext[obj->nr_extern];
2268 memset(ext, 0, sizeof(*ext));
2271 ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
2272 if (ext->btf_id <= 0) {
2273 pr_warn("failed to find BTF for extern '%s': %d\n",
2274 ext_name, ext->btf_id);
2277 t = btf__type_by_id(obj->btf, ext->btf_id);
2278 ext->name = btf__name_by_offset(obj->btf, t->name_off);
2280 ext->is_weak = GELF_ST_BIND(sym.st_info) == STB_WEAK;
2281 ext->sz = btf__resolve_size(obj->btf, t->type);
2283 pr_warn("failed to resolve size of extern '%s': %d\n",
2287 ext->align = btf__align_of(obj->btf, t->type);
2288 if (ext->align <= 0) {
2289 pr_warn("failed to determine alignment of extern '%s': %d\n",
2290 ext_name, ext->align);
2293 ext->type = find_extern_type(obj->btf, t->type,
2295 if (ext->type == EXT_UNKNOWN) {
2296 pr_warn("extern '%s' type is unsupported\n", ext_name);
2300 pr_debug("collected %d externs total\n", obj->nr_extern);
2302 if (!obj->nr_extern)
2305 /* sort externs by (alignment, size, name) and calculate their offsets
2307 qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
2309 for (i = 0; i < obj->nr_extern; i++) {
2310 ext = &obj->externs[i];
2311 ext->data_off = roundup(off, ext->align);
2312 off = ext->data_off + ext->sz;
2313 pr_debug("extern #%d: symbol %d, off %u, name %s\n",
2314 i, ext->sym_idx, ext->data_off, ext->name);
2317 btf_id = btf__find_by_name(obj->btf, KCONFIG_SEC);
2319 pr_warn("no BTF info found for '%s' datasec\n", KCONFIG_SEC);
2323 sec = (struct btf_type *)btf__type_by_id(obj->btf, btf_id);
2326 for (i = 0; i < n; i++) {
2327 struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
2329 t = btf__type_by_id(obj->btf, vs->type);
2330 ext_name = btf__name_by_offset(obj->btf, t->name_off);
2331 ext = find_extern_by_name(obj, ext_name);
2333 pr_warn("failed to find extern definition for BTF var '%s'\n",
2337 vs->offset = ext->data_off;
2338 btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
2344 static struct bpf_program *
2345 bpf_object__find_prog_by_idx(struct bpf_object *obj, int idx)
2347 struct bpf_program *prog;
2350 for (i = 0; i < obj->nr_programs; i++) {
2351 prog = &obj->programs[i];
2352 if (prog->idx == idx)
2358 struct bpf_program *
2359 bpf_object__find_program_by_title(const struct bpf_object *obj,
2362 struct bpf_program *pos;
2364 bpf_object__for_each_program(pos, obj) {
2365 if (pos->section_name && !strcmp(pos->section_name, title))
2371 struct bpf_program *
2372 bpf_object__find_program_by_name(const struct bpf_object *obj,
2375 struct bpf_program *prog;
2377 bpf_object__for_each_program(prog, obj) {
2378 if (!strcmp(prog->name, name))
2384 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
2387 return shndx == obj->efile.data_shndx ||
2388 shndx == obj->efile.bss_shndx ||
2389 shndx == obj->efile.rodata_shndx;
2392 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
2395 return shndx == obj->efile.maps_shndx ||
2396 shndx == obj->efile.btf_maps_shndx;
2399 static enum libbpf_map_type
2400 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
2402 if (shndx == obj->efile.data_shndx)
2403 return LIBBPF_MAP_DATA;
2404 else if (shndx == obj->efile.bss_shndx)
2405 return LIBBPF_MAP_BSS;
2406 else if (shndx == obj->efile.rodata_shndx)
2407 return LIBBPF_MAP_RODATA;
2408 else if (shndx == obj->efile.symbols_shndx)
2409 return LIBBPF_MAP_KCONFIG;
2411 return LIBBPF_MAP_UNSPEC;
2414 static int bpf_program__record_reloc(struct bpf_program *prog,
2415 struct reloc_desc *reloc_desc,
2416 __u32 insn_idx, const char *name,
2417 const GElf_Sym *sym, const GElf_Rel *rel)
2419 struct bpf_insn *insn = &prog->insns[insn_idx];
2420 size_t map_idx, nr_maps = prog->obj->nr_maps;
2421 struct bpf_object *obj = prog->obj;
2422 __u32 shdr_idx = sym->st_shndx;
2423 enum libbpf_map_type type;
2424 struct bpf_map *map;
2426 /* sub-program call relocation */
2427 if (insn->code == (BPF_JMP | BPF_CALL)) {
2428 if (insn->src_reg != BPF_PSEUDO_CALL) {
2429 pr_warn("incorrect bpf_call opcode\n");
2430 return -LIBBPF_ERRNO__RELOC;
2432 /* text_shndx can be 0, if no default "main" program exists */
2433 if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
2434 pr_warn("bad call relo against section %u\n", shdr_idx);
2435 return -LIBBPF_ERRNO__RELOC;
2437 if (sym->st_value % 8) {
2438 pr_warn("bad call relo offset: %zu\n",
2439 (size_t)sym->st_value);
2440 return -LIBBPF_ERRNO__RELOC;
2442 reloc_desc->type = RELO_CALL;
2443 reloc_desc->insn_idx = insn_idx;
2444 reloc_desc->sym_off = sym->st_value;
2445 obj->has_pseudo_calls = true;
2449 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) {
2450 pr_warn("invalid relo for insns[%d].code 0x%x\n",
2451 insn_idx, insn->code);
2452 return -LIBBPF_ERRNO__RELOC;
2455 if (sym_is_extern(sym)) {
2456 int sym_idx = GELF_R_SYM(rel->r_info);
2457 int i, n = obj->nr_extern;
2458 struct extern_desc *ext;
2460 for (i = 0; i < n; i++) {
2461 ext = &obj->externs[i];
2462 if (ext->sym_idx == sym_idx)
2466 pr_warn("extern relo failed to find extern for sym %d\n",
2468 return -LIBBPF_ERRNO__RELOC;
2470 pr_debug("found extern #%d '%s' (sym %d, off %u) for insn %u\n",
2471 i, ext->name, ext->sym_idx, ext->data_off, insn_idx);
2472 reloc_desc->type = RELO_EXTERN;
2473 reloc_desc->insn_idx = insn_idx;
2474 reloc_desc->sym_off = ext->data_off;
2478 if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
2479 pr_warn("invalid relo for \'%s\' in special section 0x%x; forgot to initialize global var?..\n",
2481 return -LIBBPF_ERRNO__RELOC;
2484 type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
2486 /* generic map reference relocation */
2487 if (type == LIBBPF_MAP_UNSPEC) {
2488 if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
2489 pr_warn("bad map relo against section %u\n",
2491 return -LIBBPF_ERRNO__RELOC;
2493 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
2494 map = &obj->maps[map_idx];
2495 if (map->libbpf_type != type ||
2496 map->sec_idx != sym->st_shndx ||
2497 map->sec_offset != sym->st_value)
2499 pr_debug("found map %zd (%s, sec %d, off %zu) for insn %u\n",
2500 map_idx, map->name, map->sec_idx,
2501 map->sec_offset, insn_idx);
2504 if (map_idx >= nr_maps) {
2505 pr_warn("map relo failed to find map for sec %u, off %zu\n",
2506 shdr_idx, (size_t)sym->st_value);
2507 return -LIBBPF_ERRNO__RELOC;
2509 reloc_desc->type = RELO_LD64;
2510 reloc_desc->insn_idx = insn_idx;
2511 reloc_desc->map_idx = map_idx;
2512 reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
2516 /* global data map relocation */
2517 if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
2518 pr_warn("bad data relo against section %u\n", shdr_idx);
2519 return -LIBBPF_ERRNO__RELOC;
2521 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
2522 map = &obj->maps[map_idx];
2523 if (map->libbpf_type != type)
2525 pr_debug("found data map %zd (%s, sec %d, off %zu) for insn %u\n",
2526 map_idx, map->name, map->sec_idx, map->sec_offset,
2530 if (map_idx >= nr_maps) {
2531 pr_warn("data relo failed to find map for sec %u\n",
2533 return -LIBBPF_ERRNO__RELOC;
2536 reloc_desc->type = RELO_DATA;
2537 reloc_desc->insn_idx = insn_idx;
2538 reloc_desc->map_idx = map_idx;
2539 reloc_desc->sym_off = sym->st_value;
2544 bpf_program__collect_reloc(struct bpf_program *prog, GElf_Shdr *shdr,
2545 Elf_Data *data, struct bpf_object *obj)
2547 Elf_Data *symbols = obj->efile.symbols;
2550 pr_debug("collecting relocating info for: '%s'\n", prog->section_name);
2551 nrels = shdr->sh_size / shdr->sh_entsize;
2553 prog->reloc_desc = malloc(sizeof(*prog->reloc_desc) * nrels);
2554 if (!prog->reloc_desc) {
2555 pr_warn("failed to alloc memory in relocation\n");
2558 prog->nr_reloc = nrels;
2560 for (i = 0; i < nrels; i++) {
2566 if (!gelf_getrel(data, i, &rel)) {
2567 pr_warn("relocation: failed to get %d reloc\n", i);
2568 return -LIBBPF_ERRNO__FORMAT;
2570 if (!gelf_getsym(symbols, GELF_R_SYM(rel.r_info), &sym)) {
2571 pr_warn("relocation: symbol %"PRIx64" not found\n",
2572 GELF_R_SYM(rel.r_info));
2573 return -LIBBPF_ERRNO__FORMAT;
2575 if (rel.r_offset % sizeof(struct bpf_insn))
2576 return -LIBBPF_ERRNO__FORMAT;
2578 insn_idx = rel.r_offset / sizeof(struct bpf_insn);
2579 name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
2580 sym.st_name) ? : "<?>";
2582 pr_debug("relo for shdr %u, symb %zu, value %zu, type %d, bind %d, name %d (\'%s\'), insn %u\n",
2583 (__u32)sym.st_shndx, (size_t)GELF_R_SYM(rel.r_info),
2584 (size_t)sym.st_value, GELF_ST_TYPE(sym.st_info),
2585 GELF_ST_BIND(sym.st_info), sym.st_name, name,
2588 err = bpf_program__record_reloc(prog, &prog->reloc_desc[i],
2589 insn_idx, name, &sym, &rel);
2596 static int bpf_map_find_btf_info(struct bpf_object *obj, struct bpf_map *map)
2598 struct bpf_map_def *def = &map->def;
2599 __u32 key_type_id = 0, value_type_id = 0;
2602 /* if it's BTF-defined map, we don't need to search for type IDs */
2603 if (map->sec_idx == obj->efile.btf_maps_shndx)
2606 if (!bpf_map__is_internal(map)) {
2607 ret = btf__get_map_kv_tids(obj->btf, map->name, def->key_size,
2608 def->value_size, &key_type_id,
2612 * LLVM annotates global data differently in BTF, that is,
2613 * only as '.data', '.bss' or '.rodata'.
2615 ret = btf__find_by_name(obj->btf,
2616 libbpf_type_to_btf_name[map->libbpf_type]);
2621 map->btf_key_type_id = key_type_id;
2622 map->btf_value_type_id = bpf_map__is_internal(map) ?
2623 ret : value_type_id;
2627 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
2629 struct bpf_map_info info = {};
2630 __u32 len = sizeof(info);
2634 err = bpf_obj_get_info_by_fd(fd, &info, &len);
2638 new_name = strdup(info.name);
2642 new_fd = open("/", O_RDONLY | O_CLOEXEC);
2645 goto err_free_new_name;
2648 new_fd = dup3(fd, new_fd, O_CLOEXEC);
2651 goto err_close_new_fd;
2654 err = zclose(map->fd);
2657 goto err_close_new_fd;
2662 map->name = new_name;
2663 map->def.type = info.type;
2664 map->def.key_size = info.key_size;
2665 map->def.value_size = info.value_size;
2666 map->def.max_entries = info.max_entries;
2667 map->def.map_flags = info.map_flags;
2668 map->btf_key_type_id = info.btf_key_type_id;
2669 map->btf_value_type_id = info.btf_value_type_id;
2681 int bpf_map__resize(struct bpf_map *map, __u32 max_entries)
2683 if (!map || !max_entries)
2686 /* If map already created, its attributes can't be changed. */
2690 map->def.max_entries = max_entries;
2696 bpf_object__probe_name(struct bpf_object *obj)
2698 struct bpf_load_program_attr attr;
2699 char *cp, errmsg[STRERR_BUFSIZE];
2700 struct bpf_insn insns[] = {
2701 BPF_MOV64_IMM(BPF_REG_0, 0),
2706 /* make sure basic loading works */
2708 memset(&attr, 0, sizeof(attr));
2709 attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
2711 attr.insns_cnt = ARRAY_SIZE(insns);
2712 attr.license = "GPL";
2714 ret = bpf_load_program_xattr(&attr, NULL, 0);
2716 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
2717 pr_warn("Error in %s():%s(%d). Couldn't load basic 'r0 = 0' BPF program.\n",
2718 __func__, cp, errno);
2723 /* now try the same program, but with the name */
2726 ret = bpf_load_program_xattr(&attr, NULL, 0);
2736 bpf_object__probe_global_data(struct bpf_object *obj)
2738 struct bpf_load_program_attr prg_attr;
2739 struct bpf_create_map_attr map_attr;
2740 char *cp, errmsg[STRERR_BUFSIZE];
2741 struct bpf_insn insns[] = {
2742 BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16),
2743 BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42),
2744 BPF_MOV64_IMM(BPF_REG_0, 0),
2749 memset(&map_attr, 0, sizeof(map_attr));
2750 map_attr.map_type = BPF_MAP_TYPE_ARRAY;
2751 map_attr.key_size = sizeof(int);
2752 map_attr.value_size = 32;
2753 map_attr.max_entries = 1;
2755 map = bpf_create_map_xattr(&map_attr);
2757 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
2758 pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
2759 __func__, cp, errno);
2765 memset(&prg_attr, 0, sizeof(prg_attr));
2766 prg_attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
2767 prg_attr.insns = insns;
2768 prg_attr.insns_cnt = ARRAY_SIZE(insns);
2769 prg_attr.license = "GPL";
2771 ret = bpf_load_program_xattr(&prg_attr, NULL, 0);
2773 obj->caps.global_data = 1;
2781 static int bpf_object__probe_btf_func(struct bpf_object *obj)
2783 static const char strs[] = "\0int\0x\0a";
2784 /* void x(int a) {} */
2787 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
2788 /* FUNC_PROTO */ /* [2] */
2789 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
2790 BTF_PARAM_ENC(7, 1),
2791 /* FUNC x */ /* [3] */
2792 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0), 2),
2796 btf_fd = libbpf__load_raw_btf((char *)types, sizeof(types),
2797 strs, sizeof(strs));
2799 obj->caps.btf_func = 1;
2807 static int bpf_object__probe_btf_datasec(struct bpf_object *obj)
2809 static const char strs[] = "\0x\0.data";
2813 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
2814 /* VAR x */ /* [2] */
2815 BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
2817 /* DATASEC val */ /* [3] */
2818 BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC, 0, 1), 4),
2819 BTF_VAR_SECINFO_ENC(2, 0, 4),
2823 btf_fd = libbpf__load_raw_btf((char *)types, sizeof(types),
2824 strs, sizeof(strs));
2826 obj->caps.btf_datasec = 1;
2834 static int bpf_object__probe_array_mmap(struct bpf_object *obj)
2836 struct bpf_create_map_attr attr = {
2837 .map_type = BPF_MAP_TYPE_ARRAY,
2838 .map_flags = BPF_F_MMAPABLE,
2839 .key_size = sizeof(int),
2840 .value_size = sizeof(int),
2845 fd = bpf_create_map_xattr(&attr);
2847 obj->caps.array_mmap = 1;
2856 bpf_object__probe_caps(struct bpf_object *obj)
2858 int (*probe_fn[])(struct bpf_object *obj) = {
2859 bpf_object__probe_name,
2860 bpf_object__probe_global_data,
2861 bpf_object__probe_btf_func,
2862 bpf_object__probe_btf_datasec,
2863 bpf_object__probe_array_mmap,
2867 for (i = 0; i < ARRAY_SIZE(probe_fn); i++) {
2868 ret = probe_fn[i](obj);
2870 pr_debug("Probe #%d failed with %d.\n", i, ret);
2876 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
2878 struct bpf_map_info map_info = {};
2879 char msg[STRERR_BUFSIZE];
2882 map_info_len = sizeof(map_info);
2884 if (bpf_obj_get_info_by_fd(map_fd, &map_info, &map_info_len)) {
2885 pr_warn("failed to get map info for map FD %d: %s\n",
2886 map_fd, libbpf_strerror_r(errno, msg, sizeof(msg)));
2890 return (map_info.type == map->def.type &&
2891 map_info.key_size == map->def.key_size &&
2892 map_info.value_size == map->def.value_size &&
2893 map_info.max_entries == map->def.max_entries &&
2894 map_info.map_flags == map->def.map_flags);
2898 bpf_object__reuse_map(struct bpf_map *map)
2900 char *cp, errmsg[STRERR_BUFSIZE];
2903 pin_fd = bpf_obj_get(map->pin_path);
2906 if (err == -ENOENT) {
2907 pr_debug("found no pinned map to reuse at '%s'\n",
2912 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
2913 pr_warn("couldn't retrieve pinned map '%s': %s\n",
2918 if (!map_is_reuse_compat(map, pin_fd)) {
2919 pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
2925 err = bpf_map__reuse_fd(map, pin_fd);
2931 pr_debug("reused pinned map at '%s'\n", map->pin_path);
2937 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
2939 enum libbpf_map_type map_type = map->libbpf_type;
2940 char *cp, errmsg[STRERR_BUFSIZE];
2943 /* kernel already zero-initializes .bss map. */
2944 if (map_type == LIBBPF_MAP_BSS)
2947 err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
2950 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
2951 pr_warn("Error setting initial map(%s) contents: %s\n",
2956 /* Freeze .rodata and .kconfig map as read-only from syscall side. */
2957 if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
2958 err = bpf_map_freeze(map->fd);
2961 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
2962 pr_warn("Error freezing map(%s) as read-only: %s\n",
2971 bpf_object__create_maps(struct bpf_object *obj)
2973 struct bpf_create_map_attr create_attr = {};
2978 for (i = 0; i < obj->nr_maps; i++) {
2979 struct bpf_map *map = &obj->maps[i];
2980 struct bpf_map_def *def = &map->def;
2981 char *cp, errmsg[STRERR_BUFSIZE];
2982 int *pfd = &map->fd;
2984 if (map->pin_path) {
2985 err = bpf_object__reuse_map(map);
2987 pr_warn("error reusing pinned map %s\n",
2994 pr_debug("skip map create (preset) %s: fd=%d\n",
2995 map->name, map->fd);
3000 create_attr.name = map->name;
3001 create_attr.map_ifindex = map->map_ifindex;
3002 create_attr.map_type = def->type;
3003 create_attr.map_flags = def->map_flags;
3004 create_attr.key_size = def->key_size;
3005 create_attr.value_size = def->value_size;
3006 if (def->type == BPF_MAP_TYPE_PERF_EVENT_ARRAY &&
3007 !def->max_entries) {
3009 nr_cpus = libbpf_num_possible_cpus();
3011 pr_warn("failed to determine number of system CPUs: %d\n",
3016 pr_debug("map '%s': setting size to %d\n",
3017 map->name, nr_cpus);
3018 create_attr.max_entries = nr_cpus;
3020 create_attr.max_entries = def->max_entries;
3022 create_attr.btf_fd = 0;
3023 create_attr.btf_key_type_id = 0;
3024 create_attr.btf_value_type_id = 0;
3025 if (bpf_map_type__is_map_in_map(def->type) &&
3026 map->inner_map_fd >= 0)
3027 create_attr.inner_map_fd = map->inner_map_fd;
3029 if (obj->btf && !bpf_map_find_btf_info(obj, map)) {
3030 create_attr.btf_fd = btf__fd(obj->btf);
3031 create_attr.btf_key_type_id = map->btf_key_type_id;
3032 create_attr.btf_value_type_id = map->btf_value_type_id;
3035 *pfd = bpf_create_map_xattr(&create_attr);
3036 if (*pfd < 0 && (create_attr.btf_key_type_id ||
3037 create_attr.btf_value_type_id)) {
3039 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
3040 pr_warn("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
3041 map->name, cp, err);
3042 create_attr.btf_fd = 0;
3043 create_attr.btf_key_type_id = 0;
3044 create_attr.btf_value_type_id = 0;
3045 map->btf_key_type_id = 0;
3046 map->btf_value_type_id = 0;
3047 *pfd = bpf_create_map_xattr(&create_attr);
3055 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
3056 pr_warn("failed to create map (name: '%s'): %s(%d)\n",
3057 map->name, cp, err);
3059 for (j = 0; j < i; j++)
3060 zclose(obj->maps[j].fd);
3064 if (bpf_map__is_internal(map)) {
3065 err = bpf_object__populate_internal_map(obj, map);
3072 if (map->pin_path && !map->pinned) {
3073 err = bpf_map__pin(map, NULL);
3075 pr_warn("failed to auto-pin map name '%s' at '%s'\n",
3076 map->name, map->pin_path);
3081 pr_debug("created map %s: fd=%d\n", map->name, *pfd);
3088 check_btf_ext_reloc_err(struct bpf_program *prog, int err,
3089 void *btf_prog_info, const char *info_name)
3091 if (err != -ENOENT) {
3092 pr_warn("Error in loading %s for sec %s.\n",
3093 info_name, prog->section_name);
3097 /* err == -ENOENT (i.e. prog->section_name not found in btf_ext) */
3099 if (btf_prog_info) {
3101 * Some info has already been found but has problem
3102 * in the last btf_ext reloc. Must have to error out.
3104 pr_warn("Error in relocating %s for sec %s.\n",
3105 info_name, prog->section_name);
3109 /* Have problem loading the very first info. Ignore the rest. */
3110 pr_warn("Cannot find %s for main program sec %s. Ignore all %s.\n",
3111 info_name, prog->section_name, info_name);
3116 bpf_program_reloc_btf_ext(struct bpf_program *prog, struct bpf_object *obj,
3117 const char *section_name, __u32 insn_offset)
3121 if (!insn_offset || prog->func_info) {
3123 * !insn_offset => main program
3125 * For sub prog, the main program's func_info has to
3126 * be loaded first (i.e. prog->func_info != NULL)
3128 err = btf_ext__reloc_func_info(obj->btf, obj->btf_ext,
3129 section_name, insn_offset,
3131 &prog->func_info_cnt);
3133 return check_btf_ext_reloc_err(prog, err,
3137 prog->func_info_rec_size = btf_ext__func_info_rec_size(obj->btf_ext);
3140 if (!insn_offset || prog->line_info) {
3141 err = btf_ext__reloc_line_info(obj->btf, obj->btf_ext,
3142 section_name, insn_offset,
3144 &prog->line_info_cnt);
3146 return check_btf_ext_reloc_err(prog, err,
3150 prog->line_info_rec_size = btf_ext__line_info_rec_size(obj->btf_ext);
3156 #define BPF_CORE_SPEC_MAX_LEN 64
3158 /* represents BPF CO-RE field or array element accessor */
3159 struct bpf_core_accessor {
3160 __u32 type_id; /* struct/union type or array element type */
3161 __u32 idx; /* field index or array index */
3162 const char *name; /* field name or NULL for array accessor */
3165 struct bpf_core_spec {
3166 const struct btf *btf;
3167 /* high-level spec: named fields and array indices only */
3168 struct bpf_core_accessor spec[BPF_CORE_SPEC_MAX_LEN];
3169 /* high-level spec length */
3171 /* raw, low-level spec: 1-to-1 with accessor spec string */
3172 int raw_spec[BPF_CORE_SPEC_MAX_LEN];
3173 /* raw spec length */
3175 /* field bit offset represented by spec */
3179 static bool str_is_empty(const char *s)
3184 static bool is_flex_arr(const struct btf *btf,
3185 const struct bpf_core_accessor *acc,
3186 const struct btf_array *arr)
3188 const struct btf_type *t;
3190 /* not a flexible array, if not inside a struct or has non-zero size */
3191 if (!acc->name || arr->nelems > 0)
3194 /* has to be the last member of enclosing struct */
3195 t = btf__type_by_id(btf, acc->type_id);
3196 return acc->idx == btf_vlen(t) - 1;
3200 * Turn bpf_field_reloc into a low- and high-level spec representation,
3201 * validating correctness along the way, as well as calculating resulting
3202 * field bit offset, specified by accessor string. Low-level spec captures
3203 * every single level of nestedness, including traversing anonymous
3204 * struct/union members. High-level one only captures semantically meaningful
3205 * "turning points": named fields and array indicies.
3206 * E.g., for this case:
3209 * int __unimportant;
3217 * struct sample *s = ...;
3219 * int x = &s->a[3]; // access string = '0:1:2:3'
3221 * Low-level spec has 1:1 mapping with each element of access string (it's
3222 * just a parsed access string representation): [0, 1, 2, 3].
3224 * High-level spec will capture only 3 points:
3225 * - intial zero-index access by pointer (&s->... is the same as &s[0]...);
3226 * - field 'a' access (corresponds to '2' in low-level spec);
3227 * - array element #3 access (corresponds to '3' in low-level spec).
3230 static int bpf_core_spec_parse(const struct btf *btf,
3232 const char *spec_str,
3233 struct bpf_core_spec *spec)
3235 int access_idx, parsed_len, i;
3236 struct bpf_core_accessor *acc;
3237 const struct btf_type *t;
3242 if (str_is_empty(spec_str) || *spec_str == ':')
3245 memset(spec, 0, sizeof(*spec));
3248 /* parse spec_str="0:1:2:3:4" into array raw_spec=[0, 1, 2, 3, 4] */
3250 if (*spec_str == ':')
3252 if (sscanf(spec_str, "%d%n", &access_idx, &parsed_len) != 1)
3254 if (spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
3256 spec_str += parsed_len;
3257 spec->raw_spec[spec->raw_len++] = access_idx;
3260 if (spec->raw_len == 0)
3263 /* first spec value is always reloc type array index */
3264 t = skip_mods_and_typedefs(btf, type_id, &id);
3268 access_idx = spec->raw_spec[0];
3269 spec->spec[0].type_id = id;
3270 spec->spec[0].idx = access_idx;
3273 sz = btf__resolve_size(btf, id);
3276 spec->bit_offset = access_idx * sz * 8;
3278 for (i = 1; i < spec->raw_len; i++) {
3279 t = skip_mods_and_typedefs(btf, id, &id);
3283 access_idx = spec->raw_spec[i];
3284 acc = &spec->spec[spec->len];
3286 if (btf_is_composite(t)) {
3287 const struct btf_member *m;
3290 if (access_idx >= btf_vlen(t))
3293 bit_offset = btf_member_bit_offset(t, access_idx);
3294 spec->bit_offset += bit_offset;
3296 m = btf_members(t) + access_idx;
3298 name = btf__name_by_offset(btf, m->name_off);
3299 if (str_is_empty(name))
3303 acc->idx = access_idx;
3309 } else if (btf_is_array(t)) {
3310 const struct btf_array *a = btf_array(t);
3313 t = skip_mods_and_typedefs(btf, a->type, &id);
3317 flex = is_flex_arr(btf, acc - 1, a);
3318 if (!flex && access_idx >= a->nelems)
3321 spec->spec[spec->len].type_id = id;
3322 spec->spec[spec->len].idx = access_idx;
3325 sz = btf__resolve_size(btf, id);
3328 spec->bit_offset += access_idx * sz * 8;
3330 pr_warn("relo for [%u] %s (at idx %d) captures type [%d] of unexpected kind %d\n",
3331 type_id, spec_str, i, id, btf_kind(t));
3339 static bool bpf_core_is_flavor_sep(const char *s)
3341 /* check X___Y name pattern, where X and Y are not underscores */
3342 return s[0] != '_' && /* X */
3343 s[1] == '_' && s[2] == '_' && s[3] == '_' && /* ___ */
3344 s[4] != '_'; /* Y */
3347 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
3348 * before last triple underscore. Struct name part after last triple
3349 * underscore is ignored by BPF CO-RE relocation during relocation matching.
3351 static size_t bpf_core_essential_name_len(const char *name)
3353 size_t n = strlen(name);
3356 for (i = n - 5; i >= 0; i--) {
3357 if (bpf_core_is_flavor_sep(name + i))
3363 /* dynamically sized list of type IDs */
3369 static void bpf_core_free_cands(struct ids_vec *cand_ids)
3371 free(cand_ids->data);
3375 static struct ids_vec *bpf_core_find_cands(const struct btf *local_btf,
3376 __u32 local_type_id,
3377 const struct btf *targ_btf)
3379 size_t local_essent_len, targ_essent_len;
3380 const char *local_name, *targ_name;
3381 const struct btf_type *t;
3382 struct ids_vec *cand_ids;
3386 t = btf__type_by_id(local_btf, local_type_id);
3388 return ERR_PTR(-EINVAL);
3390 local_name = btf__name_by_offset(local_btf, t->name_off);
3391 if (str_is_empty(local_name))
3392 return ERR_PTR(-EINVAL);
3393 local_essent_len = bpf_core_essential_name_len(local_name);
3395 cand_ids = calloc(1, sizeof(*cand_ids));
3397 return ERR_PTR(-ENOMEM);
3399 n = btf__get_nr_types(targ_btf);
3400 for (i = 1; i <= n; i++) {
3401 t = btf__type_by_id(targ_btf, i);
3402 targ_name = btf__name_by_offset(targ_btf, t->name_off);
3403 if (str_is_empty(targ_name))
3406 targ_essent_len = bpf_core_essential_name_len(targ_name);
3407 if (targ_essent_len != local_essent_len)
3410 if (strncmp(local_name, targ_name, local_essent_len) == 0) {
3411 pr_debug("[%d] %s: found candidate [%d] %s\n",
3412 local_type_id, local_name, i, targ_name);
3413 new_ids = realloc(cand_ids->data, cand_ids->len + 1);
3418 cand_ids->data = new_ids;
3419 cand_ids->data[cand_ids->len++] = i;
3424 bpf_core_free_cands(cand_ids);
3425 return ERR_PTR(err);
3428 /* Check two types for compatibility, skipping const/volatile/restrict and
3429 * typedefs, to ensure we are relocating compatible entities:
3430 * - any two STRUCTs/UNIONs are compatible and can be mixed;
3431 * - any two FWDs are compatible, if their names match (modulo flavor suffix);
3432 * - any two PTRs are always compatible;
3433 * - for ENUMs, names should be the same (ignoring flavor suffix) or at
3434 * least one of enums should be anonymous;
3435 * - for ENUMs, check sizes, names are ignored;
3436 * - for INT, size and signedness are ignored;
3437 * - for ARRAY, dimensionality is ignored, element types are checked for
3438 * compatibility recursively;
3439 * - everything else shouldn't be ever a target of relocation.
3440 * These rules are not set in stone and probably will be adjusted as we get
3441 * more experience with using BPF CO-RE relocations.
3443 static int bpf_core_fields_are_compat(const struct btf *local_btf,
3445 const struct btf *targ_btf,
3448 const struct btf_type *local_type, *targ_type;
3451 local_type = skip_mods_and_typedefs(local_btf, local_id, &local_id);
3452 targ_type = skip_mods_and_typedefs(targ_btf, targ_id, &targ_id);
3453 if (!local_type || !targ_type)
3456 if (btf_is_composite(local_type) && btf_is_composite(targ_type))
3458 if (btf_kind(local_type) != btf_kind(targ_type))
3461 switch (btf_kind(local_type)) {
3465 case BTF_KIND_ENUM: {
3466 const char *local_name, *targ_name;
3467 size_t local_len, targ_len;
3469 local_name = btf__name_by_offset(local_btf,
3470 local_type->name_off);
3471 targ_name = btf__name_by_offset(targ_btf, targ_type->name_off);
3472 local_len = bpf_core_essential_name_len(local_name);
3473 targ_len = bpf_core_essential_name_len(targ_name);
3474 /* one of them is anonymous or both w/ same flavor-less names */
3475 return local_len == 0 || targ_len == 0 ||
3476 (local_len == targ_len &&
3477 strncmp(local_name, targ_name, local_len) == 0);
3480 /* just reject deprecated bitfield-like integers; all other
3481 * integers are by default compatible between each other
3483 return btf_int_offset(local_type) == 0 &&
3484 btf_int_offset(targ_type) == 0;
3485 case BTF_KIND_ARRAY:
3486 local_id = btf_array(local_type)->type;
3487 targ_id = btf_array(targ_type)->type;
3490 pr_warn("unexpected kind %d relocated, local [%d], target [%d]\n",
3491 btf_kind(local_type), local_id, targ_id);
3497 * Given single high-level named field accessor in local type, find
3498 * corresponding high-level accessor for a target type. Along the way,
3499 * maintain low-level spec for target as well. Also keep updating target
3502 * Searching is performed through recursive exhaustive enumeration of all
3503 * fields of a struct/union. If there are any anonymous (embedded)
3504 * structs/unions, they are recursively searched as well. If field with
3505 * desired name is found, check compatibility between local and target types,
3506 * before returning result.
3508 * 1 is returned, if field is found.
3509 * 0 is returned if no compatible field is found.
3510 * <0 is returned on error.
3512 static int bpf_core_match_member(const struct btf *local_btf,
3513 const struct bpf_core_accessor *local_acc,
3514 const struct btf *targ_btf,
3516 struct bpf_core_spec *spec,
3517 __u32 *next_targ_id)
3519 const struct btf_type *local_type, *targ_type;
3520 const struct btf_member *local_member, *m;
3521 const char *local_name, *targ_name;
3525 targ_type = skip_mods_and_typedefs(targ_btf, targ_id, &targ_id);
3528 if (!btf_is_composite(targ_type))
3531 local_id = local_acc->type_id;
3532 local_type = btf__type_by_id(local_btf, local_id);
3533 local_member = btf_members(local_type) + local_acc->idx;
3534 local_name = btf__name_by_offset(local_btf, local_member->name_off);
3536 n = btf_vlen(targ_type);
3537 m = btf_members(targ_type);
3538 for (i = 0; i < n; i++, m++) {
3541 bit_offset = btf_member_bit_offset(targ_type, i);
3543 /* too deep struct/union/array nesting */
3544 if (spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
3547 /* speculate this member will be the good one */
3548 spec->bit_offset += bit_offset;
3549 spec->raw_spec[spec->raw_len++] = i;
3551 targ_name = btf__name_by_offset(targ_btf, m->name_off);
3552 if (str_is_empty(targ_name)) {
3553 /* embedded struct/union, we need to go deeper */
3554 found = bpf_core_match_member(local_btf, local_acc,
3556 spec, next_targ_id);
3557 if (found) /* either found or error */
3559 } else if (strcmp(local_name, targ_name) == 0) {
3560 /* matching named field */
3561 struct bpf_core_accessor *targ_acc;
3563 targ_acc = &spec->spec[spec->len++];
3564 targ_acc->type_id = targ_id;
3566 targ_acc->name = targ_name;
3568 *next_targ_id = m->type;
3569 found = bpf_core_fields_are_compat(local_btf,
3573 spec->len--; /* pop accessor */
3576 /* member turned out not to be what we looked for */
3577 spec->bit_offset -= bit_offset;
3585 * Try to match local spec to a target type and, if successful, produce full
3586 * target spec (high-level, low-level + bit offset).
3588 static int bpf_core_spec_match(struct bpf_core_spec *local_spec,
3589 const struct btf *targ_btf, __u32 targ_id,
3590 struct bpf_core_spec *targ_spec)
3592 const struct btf_type *targ_type;
3593 const struct bpf_core_accessor *local_acc;
3594 struct bpf_core_accessor *targ_acc;
3597 memset(targ_spec, 0, sizeof(*targ_spec));
3598 targ_spec->btf = targ_btf;
3600 local_acc = &local_spec->spec[0];
3601 targ_acc = &targ_spec->spec[0];
3603 for (i = 0; i < local_spec->len; i++, local_acc++, targ_acc++) {
3604 targ_type = skip_mods_and_typedefs(targ_spec->btf, targ_id,
3609 if (local_acc->name) {
3610 matched = bpf_core_match_member(local_spec->btf,
3613 targ_spec, &targ_id);
3617 /* for i=0, targ_id is already treated as array element
3618 * type (because it's the original struct), for others
3619 * we should find array element type first
3622 const struct btf_array *a;
3625 if (!btf_is_array(targ_type))
3628 a = btf_array(targ_type);
3629 flex = is_flex_arr(targ_btf, targ_acc - 1, a);
3630 if (!flex && local_acc->idx >= a->nelems)
3632 if (!skip_mods_and_typedefs(targ_btf, a->type,
3637 /* too deep struct/union/array nesting */
3638 if (targ_spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
3641 targ_acc->type_id = targ_id;
3642 targ_acc->idx = local_acc->idx;
3643 targ_acc->name = NULL;
3645 targ_spec->raw_spec[targ_spec->raw_len] = targ_acc->idx;
3646 targ_spec->raw_len++;
3648 sz = btf__resolve_size(targ_btf, targ_id);
3651 targ_spec->bit_offset += local_acc->idx * sz * 8;
3658 static int bpf_core_calc_field_relo(const struct bpf_program *prog,
3659 const struct bpf_field_reloc *relo,
3660 const struct bpf_core_spec *spec,
3661 __u32 *val, bool *validate)
3663 const struct bpf_core_accessor *acc = &spec->spec[spec->len - 1];
3664 const struct btf_type *t = btf__type_by_id(spec->btf, acc->type_id);
3665 __u32 byte_off, byte_sz, bit_off, bit_sz;
3666 const struct btf_member *m;
3667 const struct btf_type *mt;
3671 /* a[n] accessor needs special handling */
3673 if (relo->kind == BPF_FIELD_BYTE_OFFSET) {
3674 *val = spec->bit_offset / 8;
3675 } else if (relo->kind == BPF_FIELD_BYTE_SIZE) {
3676 sz = btf__resolve_size(spec->btf, acc->type_id);
3681 pr_warn("prog '%s': relo %d at insn #%d can't be applied to array access\n",
3682 bpf_program__title(prog, false),
3683 relo->kind, relo->insn_off / 8);
3691 m = btf_members(t) + acc->idx;
3692 mt = skip_mods_and_typedefs(spec->btf, m->type, NULL);
3693 bit_off = spec->bit_offset;
3694 bit_sz = btf_member_bitfield_size(t, acc->idx);
3696 bitfield = bit_sz > 0;
3699 byte_off = bit_off / 8 / byte_sz * byte_sz;
3700 /* figure out smallest int size necessary for bitfield load */
3701 while (bit_off + bit_sz - byte_off * 8 > byte_sz * 8) {
3703 /* bitfield can't be read with 64-bit read */
3704 pr_warn("prog '%s': relo %d at insn #%d can't be satisfied for bitfield\n",
3705 bpf_program__title(prog, false),
3706 relo->kind, relo->insn_off / 8);
3710 byte_off = bit_off / 8 / byte_sz * byte_sz;
3713 sz = btf__resolve_size(spec->btf, m->type);
3717 byte_off = spec->bit_offset / 8;
3718 bit_sz = byte_sz * 8;
3721 /* for bitfields, all the relocatable aspects are ambiguous and we
3722 * might disagree with compiler, so turn off validation of expected
3723 * value, except for signedness
3726 *validate = !bitfield;
3728 switch (relo->kind) {
3729 case BPF_FIELD_BYTE_OFFSET:
3732 case BPF_FIELD_BYTE_SIZE:
3735 case BPF_FIELD_SIGNED:
3736 /* enums will be assumed unsigned */
3737 *val = btf_is_enum(mt) ||
3738 (btf_int_encoding(mt) & BTF_INT_SIGNED);
3740 *validate = true; /* signedness is never ambiguous */
3742 case BPF_FIELD_LSHIFT_U64:
3743 #if __BYTE_ORDER == __LITTLE_ENDIAN
3744 *val = 64 - (bit_off + bit_sz - byte_off * 8);
3746 *val = (8 - byte_sz) * 8 + (bit_off - byte_off * 8);
3749 case BPF_FIELD_RSHIFT_U64:
3752 *validate = true; /* right shift is never ambiguous */
3754 case BPF_FIELD_EXISTS:
3756 pr_warn("prog '%s': unknown relo %d at insn #%d\n",
3757 bpf_program__title(prog, false),
3758 relo->kind, relo->insn_off / 8);
3766 * Patch relocatable BPF instruction.
3768 * Patched value is determined by relocation kind and target specification.
3769 * For field existence relocation target spec will be NULL if field is not
3771 * Expected insn->imm value is determined using relocation kind and local
3772 * spec, and is checked before patching instruction. If actual insn->imm value
3773 * is wrong, bail out with error.
3775 * Currently three kinds of BPF instructions are supported:
3776 * 1. rX = <imm> (assignment with immediate operand);
3777 * 2. rX += <imm> (arithmetic operations with immediate operand);
3779 static int bpf_core_reloc_insn(struct bpf_program *prog,
3780 const struct bpf_field_reloc *relo,
3781 const struct bpf_core_spec *local_spec,
3782 const struct bpf_core_spec *targ_spec)
3784 bool failed = false, validate = true;
3785 __u32 orig_val, new_val;
3786 struct bpf_insn *insn;
3790 if (relo->insn_off % sizeof(struct bpf_insn))
3792 insn_idx = relo->insn_off / sizeof(struct bpf_insn);
3794 if (relo->kind == BPF_FIELD_EXISTS) {
3795 orig_val = 1; /* can't generate EXISTS relo w/o local field */
3796 new_val = targ_spec ? 1 : 0;
3797 } else if (!targ_spec) {
3799 new_val = (__u32)-1;
3801 err = bpf_core_calc_field_relo(prog, relo, local_spec,
3802 &orig_val, &validate);
3805 err = bpf_core_calc_field_relo(prog, relo, targ_spec,
3811 insn = &prog->insns[insn_idx];
3812 class = BPF_CLASS(insn->code);
3817 if (BPF_SRC(insn->code) != BPF_K)
3819 if (!failed && validate && insn->imm != orig_val) {
3820 pr_warn("prog '%s': unexpected insn #%d (ALU/ALU64) value: got %u, exp %u -> %u\n",
3821 bpf_program__title(prog, false), insn_idx,
3822 insn->imm, orig_val, new_val);
3825 orig_val = insn->imm;
3826 insn->imm = new_val;
3827 pr_debug("prog '%s': patched insn #%d (ALU/ALU64)%s imm %u -> %u\n",
3828 bpf_program__title(prog, false), insn_idx,
3829 failed ? " w/ failed reloc" : "", orig_val, new_val);
3834 if (!failed && validate && insn->off != orig_val) {
3835 pr_warn("prog '%s': unexpected insn #%d (LD/LDX/ST/STX) value: got %u, exp %u -> %u\n",
3836 bpf_program__title(prog, false), insn_idx,
3837 insn->off, orig_val, new_val);
3840 if (new_val > SHRT_MAX) {
3841 pr_warn("prog '%s': insn #%d (LD/LDX/ST/STX) value too big: %u\n",
3842 bpf_program__title(prog, false), insn_idx,
3846 orig_val = insn->off;
3847 insn->off = new_val;
3848 pr_debug("prog '%s': patched insn #%d (LD/LDX/ST/STX)%s off %u -> %u\n",
3849 bpf_program__title(prog, false), insn_idx,
3850 failed ? " w/ failed reloc" : "", orig_val, new_val);
3853 pr_warn("prog '%s': trying to relocate unrecognized insn #%d, code:%x, src:%x, dst:%x, off:%x, imm:%x\n",
3854 bpf_program__title(prog, false),
3855 insn_idx, insn->code, insn->src_reg, insn->dst_reg,
3856 insn->off, insn->imm);
3863 static struct btf *btf_load_raw(const char *path)
3871 if (stat(path, &st))
3872 return ERR_PTR(-errno);
3874 data = malloc(st.st_size);
3876 return ERR_PTR(-ENOMEM);
3878 f = fopen(path, "rb");
3880 btf = ERR_PTR(-errno);
3884 read_cnt = fread(data, 1, st.st_size, f);
3886 if (read_cnt < st.st_size) {
3887 btf = ERR_PTR(-EBADF);
3891 btf = btf__new(data, read_cnt);
3899 * Probe few well-known locations for vmlinux kernel image and try to load BTF
3900 * data out of it to use for target BTF.
3902 static struct btf *bpf_core_find_kernel_btf(void)
3905 const char *path_fmt;
3908 /* try canonical vmlinux BTF through sysfs first */
3909 { "/sys/kernel/btf/vmlinux", true /* raw BTF */ },
3910 /* fall back to trying to find vmlinux ELF on disk otherwise */
3911 { "/boot/vmlinux-%1$s" },
3912 { "/lib/modules/%1$s/vmlinux-%1$s" },
3913 { "/lib/modules/%1$s/build/vmlinux" },
3914 { "/usr/lib/modules/%1$s/kernel/vmlinux" },
3915 { "/usr/lib/debug/boot/vmlinux-%1$s" },
3916 { "/usr/lib/debug/boot/vmlinux-%1$s.debug" },
3917 { "/usr/lib/debug/lib/modules/%1$s/vmlinux" },
3919 char path[PATH_MAX + 1];
3926 for (i = 0; i < ARRAY_SIZE(locations); i++) {
3927 snprintf(path, PATH_MAX, locations[i].path_fmt, buf.release);
3929 if (access(path, R_OK))
3932 if (locations[i].raw_btf)
3933 btf = btf_load_raw(path);
3935 btf = btf__parse_elf(path, NULL);
3937 pr_debug("loading kernel BTF '%s': %ld\n",
3938 path, IS_ERR(btf) ? PTR_ERR(btf) : 0);
3945 pr_warn("failed to find valid kernel BTF\n");
3946 return ERR_PTR(-ESRCH);
3949 /* Output spec definition in the format:
3950 * [<type-id>] (<type-name>) + <raw-spec> => <offset>@<spec>,
3951 * where <spec> is a C-syntax view of recorded field access, e.g.: x.a[3].b
3953 static void bpf_core_dump_spec(int level, const struct bpf_core_spec *spec)
3955 const struct btf_type *t;
3960 type_id = spec->spec[0].type_id;
3961 t = btf__type_by_id(spec->btf, type_id);
3962 s = btf__name_by_offset(spec->btf, t->name_off);
3963 libbpf_print(level, "[%u] %s + ", type_id, s);
3965 for (i = 0; i < spec->raw_len; i++)
3966 libbpf_print(level, "%d%s", spec->raw_spec[i],
3967 i == spec->raw_len - 1 ? " => " : ":");
3969 libbpf_print(level, "%u.%u @ &x",
3970 spec->bit_offset / 8, spec->bit_offset % 8);
3972 for (i = 0; i < spec->len; i++) {
3973 if (spec->spec[i].name)
3974 libbpf_print(level, ".%s", spec->spec[i].name);
3976 libbpf_print(level, "[%u]", spec->spec[i].idx);
3981 static size_t bpf_core_hash_fn(const void *key, void *ctx)
3986 static bool bpf_core_equal_fn(const void *k1, const void *k2, void *ctx)
3991 static void *u32_as_hash_key(__u32 x)
3993 return (void *)(uintptr_t)x;
3997 * CO-RE relocate single instruction.
3999 * The outline and important points of the algorithm:
4000 * 1. For given local type, find corresponding candidate target types.
4001 * Candidate type is a type with the same "essential" name, ignoring
4002 * everything after last triple underscore (___). E.g., `sample`,
4003 * `sample___flavor_one`, `sample___flavor_another_one`, are all candidates
4004 * for each other. Names with triple underscore are referred to as
4005 * "flavors" and are useful, among other things, to allow to
4006 * specify/support incompatible variations of the same kernel struct, which
4007 * might differ between different kernel versions and/or build
4010 * N.B. Struct "flavors" could be generated by bpftool's BTF-to-C
4011 * converter, when deduplicated BTF of a kernel still contains more than
4012 * one different types with the same name. In that case, ___2, ___3, etc
4013 * are appended starting from second name conflict. But start flavors are
4014 * also useful to be defined "locally", in BPF program, to extract same
4015 * data from incompatible changes between different kernel
4016 * versions/configurations. For instance, to handle field renames between
4017 * kernel versions, one can use two flavors of the struct name with the
4018 * same common name and use conditional relocations to extract that field,
4019 * depending on target kernel version.
4020 * 2. For each candidate type, try to match local specification to this
4021 * candidate target type. Matching involves finding corresponding
4022 * high-level spec accessors, meaning that all named fields should match,
4023 * as well as all array accesses should be within the actual bounds. Also,
4024 * types should be compatible (see bpf_core_fields_are_compat for details).
4025 * 3. It is supported and expected that there might be multiple flavors
4026 * matching the spec. As long as all the specs resolve to the same set of
4027 * offsets across all candidates, there is no error. If there is any
4028 * ambiguity, CO-RE relocation will fail. This is necessary to accomodate
4029 * imprefection of BTF deduplication, which can cause slight duplication of
4030 * the same BTF type, if some directly or indirectly referenced (by
4031 * pointer) type gets resolved to different actual types in different
4032 * object files. If such situation occurs, deduplicated BTF will end up
4033 * with two (or more) structurally identical types, which differ only in
4034 * types they refer to through pointer. This should be OK in most cases and
4036 * 4. Candidate types search is performed by linearly scanning through all
4037 * types in target BTF. It is anticipated that this is overall more
4038 * efficient memory-wise and not significantly worse (if not better)
4039 * CPU-wise compared to prebuilding a map from all local type names to
4040 * a list of candidate type names. It's also sped up by caching resolved
4041 * list of matching candidates per each local "root" type ID, that has at
4042 * least one bpf_field_reloc associated with it. This list is shared
4043 * between multiple relocations for the same type ID and is updated as some
4044 * of the candidates are pruned due to structural incompatibility.
4046 static int bpf_core_reloc_field(struct bpf_program *prog,
4047 const struct bpf_field_reloc *relo,
4049 const struct btf *local_btf,
4050 const struct btf *targ_btf,
4051 struct hashmap *cand_cache)
4053 const char *prog_name = bpf_program__title(prog, false);
4054 struct bpf_core_spec local_spec, cand_spec, targ_spec;
4055 const void *type_key = u32_as_hash_key(relo->type_id);
4056 const struct btf_type *local_type, *cand_type;
4057 const char *local_name, *cand_name;
4058 struct ids_vec *cand_ids;
4059 __u32 local_id, cand_id;
4060 const char *spec_str;
4063 local_id = relo->type_id;
4064 local_type = btf__type_by_id(local_btf, local_id);
4068 local_name = btf__name_by_offset(local_btf, local_type->name_off);
4069 if (str_is_empty(local_name))
4072 spec_str = btf__name_by_offset(local_btf, relo->access_str_off);
4073 if (str_is_empty(spec_str))
4076 err = bpf_core_spec_parse(local_btf, local_id, spec_str, &local_spec);
4078 pr_warn("prog '%s': relo #%d: parsing [%d] %s + %s failed: %d\n",
4079 prog_name, relo_idx, local_id, local_name, spec_str,
4084 pr_debug("prog '%s': relo #%d: kind %d, spec is ", prog_name, relo_idx,
4086 bpf_core_dump_spec(LIBBPF_DEBUG, &local_spec);
4087 libbpf_print(LIBBPF_DEBUG, "\n");
4089 if (!hashmap__find(cand_cache, type_key, (void **)&cand_ids)) {
4090 cand_ids = bpf_core_find_cands(local_btf, local_id, targ_btf);
4091 if (IS_ERR(cand_ids)) {
4092 pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s: %ld",
4093 prog_name, relo_idx, local_id, local_name,
4095 return PTR_ERR(cand_ids);
4097 err = hashmap__set(cand_cache, type_key, cand_ids, NULL, NULL);
4099 bpf_core_free_cands(cand_ids);
4104 for (i = 0, j = 0; i < cand_ids->len; i++) {
4105 cand_id = cand_ids->data[i];
4106 cand_type = btf__type_by_id(targ_btf, cand_id);
4107 cand_name = btf__name_by_offset(targ_btf, cand_type->name_off);
4109 err = bpf_core_spec_match(&local_spec, targ_btf,
4110 cand_id, &cand_spec);
4111 pr_debug("prog '%s': relo #%d: matching candidate #%d %s against spec ",
4112 prog_name, relo_idx, i, cand_name);
4113 bpf_core_dump_spec(LIBBPF_DEBUG, &cand_spec);
4114 libbpf_print(LIBBPF_DEBUG, ": %d\n", err);
4116 pr_warn("prog '%s': relo #%d: matching error: %d\n",
4117 prog_name, relo_idx, err);
4124 targ_spec = cand_spec;
4125 } else if (cand_spec.bit_offset != targ_spec.bit_offset) {
4126 /* if there are many candidates, they should all
4127 * resolve to the same bit offset
4129 pr_warn("prog '%s': relo #%d: offset ambiguity: %u != %u\n",
4130 prog_name, relo_idx, cand_spec.bit_offset,
4131 targ_spec.bit_offset);
4135 cand_ids->data[j++] = cand_spec.spec[0].type_id;
4139 * For BPF_FIELD_EXISTS relo or when relaxed CO-RE reloc mode is
4140 * requested, it's expected that we might not find any candidates.
4141 * In this case, if field wasn't found in any candidate, the list of
4142 * candidates shouldn't change at all, we'll just handle relocating
4143 * appropriately, depending on relo's kind.
4148 if (j == 0 && !prog->obj->relaxed_core_relocs &&
4149 relo->kind != BPF_FIELD_EXISTS) {
4150 pr_warn("prog '%s': relo #%d: no matching targets found for [%d] %s + %s\n",
4151 prog_name, relo_idx, local_id, local_name, spec_str);
4155 /* bpf_core_reloc_insn should know how to handle missing targ_spec */
4156 err = bpf_core_reloc_insn(prog, relo, &local_spec,
4157 j ? &targ_spec : NULL);
4159 pr_warn("prog '%s': relo #%d: failed to patch insn at offset %d: %d\n",
4160 prog_name, relo_idx, relo->insn_off, err);
4168 bpf_core_reloc_fields(struct bpf_object *obj, const char *targ_btf_path)
4170 const struct btf_ext_info_sec *sec;
4171 const struct bpf_field_reloc *rec;
4172 const struct btf_ext_info *seg;
4173 struct hashmap_entry *entry;
4174 struct hashmap *cand_cache = NULL;
4175 struct bpf_program *prog;
4176 struct btf *targ_btf;
4177 const char *sec_name;
4181 targ_btf = btf__parse_elf(targ_btf_path, NULL);
4183 targ_btf = bpf_core_find_kernel_btf();
4184 if (IS_ERR(targ_btf)) {
4185 pr_warn("failed to get target BTF: %ld\n", PTR_ERR(targ_btf));
4186 return PTR_ERR(targ_btf);
4189 cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
4190 if (IS_ERR(cand_cache)) {
4191 err = PTR_ERR(cand_cache);
4195 seg = &obj->btf_ext->field_reloc_info;
4196 for_each_btf_ext_sec(seg, sec) {
4197 sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
4198 if (str_is_empty(sec_name)) {
4202 prog = bpf_object__find_program_by_title(obj, sec_name);
4204 pr_warn("failed to find program '%s' for CO-RE offset relocation\n",
4210 pr_debug("prog '%s': performing %d CO-RE offset relocs\n",
4211 sec_name, sec->num_info);
4213 for_each_btf_ext_rec(seg, sec, i, rec) {
4214 err = bpf_core_reloc_field(prog, rec, i, obj->btf,
4215 targ_btf, cand_cache);
4217 pr_warn("prog '%s': relo #%d: failed to relocate: %d\n",
4225 btf__free(targ_btf);
4226 if (!IS_ERR_OR_NULL(cand_cache)) {
4227 hashmap__for_each_entry(cand_cache, entry, i) {
4228 bpf_core_free_cands(entry->value);
4230 hashmap__free(cand_cache);
4236 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
4240 if (obj->btf_ext->field_reloc_info.len)
4241 err = bpf_core_reloc_fields(obj, targ_btf_path);
4247 bpf_program__reloc_text(struct bpf_program *prog, struct bpf_object *obj,
4248 struct reloc_desc *relo)
4250 struct bpf_insn *insn, *new_insn;
4251 struct bpf_program *text;
4255 if (prog->idx == obj->efile.text_shndx) {
4256 pr_warn("relo in .text insn %d into off %d (insn #%d)\n",
4257 relo->insn_idx, relo->sym_off, relo->sym_off / 8);
4258 return -LIBBPF_ERRNO__RELOC;
4261 if (prog->main_prog_cnt == 0) {
4262 text = bpf_object__find_prog_by_idx(obj, obj->efile.text_shndx);
4264 pr_warn("no .text section found yet relo into text exist\n");
4265 return -LIBBPF_ERRNO__RELOC;
4267 new_cnt = prog->insns_cnt + text->insns_cnt;
4268 new_insn = reallocarray(prog->insns, new_cnt, sizeof(*insn));
4270 pr_warn("oom in prog realloc\n");
4273 prog->insns = new_insn;
4276 err = bpf_program_reloc_btf_ext(prog, obj,
4283 memcpy(new_insn + prog->insns_cnt, text->insns,
4284 text->insns_cnt * sizeof(*insn));
4285 prog->main_prog_cnt = prog->insns_cnt;
4286 prog->insns_cnt = new_cnt;
4287 pr_debug("added %zd insn from %s to prog %s\n",
4288 text->insns_cnt, text->section_name,
4289 prog->section_name);
4291 insn = &prog->insns[relo->insn_idx];
4292 insn->imm += relo->sym_off / 8 + prog->main_prog_cnt - relo->insn_idx;
4297 bpf_program__relocate(struct bpf_program *prog, struct bpf_object *obj)
4305 err = bpf_program_reloc_btf_ext(prog, obj,
4306 prog->section_name, 0);
4311 if (!prog->reloc_desc)
4314 for (i = 0; i < prog->nr_reloc; i++) {
4315 struct reloc_desc *relo = &prog->reloc_desc[i];
4316 struct bpf_insn *insn = &prog->insns[relo->insn_idx];
4318 if (relo->insn_idx + 1 >= (int)prog->insns_cnt) {
4319 pr_warn("relocation out of range: '%s'\n",
4320 prog->section_name);
4321 return -LIBBPF_ERRNO__RELOC;
4324 switch (relo->type) {
4326 insn[0].src_reg = BPF_PSEUDO_MAP_FD;
4327 insn[0].imm = obj->maps[relo->map_idx].fd;
4330 insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
4331 insn[1].imm = insn[0].imm + relo->sym_off;
4332 insn[0].imm = obj->maps[relo->map_idx].fd;
4335 insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
4336 insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
4337 insn[1].imm = relo->sym_off;
4340 err = bpf_program__reloc_text(prog, obj, relo);
4345 pr_warn("relo #%d: bad relo type %d\n", i, relo->type);
4350 zfree(&prog->reloc_desc);
4356 bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
4358 struct bpf_program *prog;
4363 err = bpf_object__relocate_core(obj, targ_btf_path);
4365 pr_warn("failed to perform CO-RE relocations: %d\n",
4370 for (i = 0; i < obj->nr_programs; i++) {
4371 prog = &obj->programs[i];
4373 err = bpf_program__relocate(prog, obj);
4375 pr_warn("failed to relocate '%s'\n", prog->section_name);
4382 static int bpf_object__collect_reloc(struct bpf_object *obj)
4386 if (!obj_elf_valid(obj)) {
4387 pr_warn("Internal error: elf object is closed\n");
4388 return -LIBBPF_ERRNO__INTERNAL;
4391 for (i = 0; i < obj->efile.nr_reloc_sects; i++) {
4392 GElf_Shdr *shdr = &obj->efile.reloc_sects[i].shdr;
4393 Elf_Data *data = obj->efile.reloc_sects[i].data;
4394 int idx = shdr->sh_info;
4395 struct bpf_program *prog;
4397 if (shdr->sh_type != SHT_REL) {
4398 pr_warn("internal error at %d\n", __LINE__);
4399 return -LIBBPF_ERRNO__INTERNAL;
4402 prog = bpf_object__find_prog_by_idx(obj, idx);
4404 pr_warn("relocation failed: no section(%d)\n", idx);
4405 return -LIBBPF_ERRNO__RELOC;
4408 err = bpf_program__collect_reloc(prog, shdr, data, obj);
4416 load_program(struct bpf_program *prog, struct bpf_insn *insns, int insns_cnt,
4417 char *license, __u32 kern_version, int *pfd)
4419 struct bpf_load_program_attr load_attr;
4420 char *cp, errmsg[STRERR_BUFSIZE];
4421 int log_buf_size = BPF_LOG_BUF_SIZE;
4425 if (!insns || !insns_cnt)
4428 memset(&load_attr, 0, sizeof(struct bpf_load_program_attr));
4429 load_attr.prog_type = prog->type;
4430 load_attr.expected_attach_type = prog->expected_attach_type;
4431 if (prog->caps->name)
4432 load_attr.name = prog->name;
4433 load_attr.insns = insns;
4434 load_attr.insns_cnt = insns_cnt;
4435 load_attr.license = license;
4436 if (prog->type == BPF_PROG_TYPE_TRACING) {
4437 load_attr.attach_prog_fd = prog->attach_prog_fd;
4438 load_attr.attach_btf_id = prog->attach_btf_id;
4440 load_attr.kern_version = kern_version;
4441 load_attr.prog_ifindex = prog->prog_ifindex;
4443 /* if .BTF.ext was loaded, kernel supports associated BTF for prog */
4444 if (prog->obj->btf_ext)
4445 btf_fd = bpf_object__btf_fd(prog->obj);
4448 load_attr.prog_btf_fd = btf_fd >= 0 ? btf_fd : 0;
4449 load_attr.func_info = prog->func_info;
4450 load_attr.func_info_rec_size = prog->func_info_rec_size;
4451 load_attr.func_info_cnt = prog->func_info_cnt;
4452 load_attr.line_info = prog->line_info;
4453 load_attr.line_info_rec_size = prog->line_info_rec_size;
4454 load_attr.line_info_cnt = prog->line_info_cnt;
4455 load_attr.log_level = prog->log_level;
4456 load_attr.prog_flags = prog->prog_flags;
4459 log_buf = malloc(log_buf_size);
4461 pr_warn("Alloc log buffer for bpf loader error, continue without log\n");
4463 ret = bpf_load_program_xattr(&load_attr, log_buf, log_buf_size);
4466 if (load_attr.log_level)
4467 pr_debug("verifier log:\n%s", log_buf);
4473 if (errno == ENOSPC) {
4479 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
4480 pr_warn("load bpf program failed: %s\n", cp);
4483 if (log_buf && log_buf[0] != '\0') {
4484 ret = -LIBBPF_ERRNO__VERIFY;
4485 pr_warn("-- BEGIN DUMP LOG ---\n");
4486 pr_warn("\n%s\n", log_buf);
4487 pr_warn("-- END LOG --\n");
4488 } else if (load_attr.insns_cnt >= BPF_MAXINSNS) {
4489 pr_warn("Program too large (%zu insns), at most %d insns\n",
4490 load_attr.insns_cnt, BPF_MAXINSNS);
4491 ret = -LIBBPF_ERRNO__PROG2BIG;
4492 } else if (load_attr.prog_type != BPF_PROG_TYPE_KPROBE) {
4493 /* Wrong program type? */
4496 load_attr.prog_type = BPF_PROG_TYPE_KPROBE;
4497 load_attr.expected_attach_type = 0;
4498 fd = bpf_load_program_xattr(&load_attr, NULL, 0);
4501 ret = -LIBBPF_ERRNO__PROGTYPE;
4511 static int libbpf_find_attach_btf_id(const char *name,
4512 enum bpf_attach_type attach_type,
4513 __u32 attach_prog_fd);
4515 int bpf_program__load(struct bpf_program *prog, char *license, __u32 kern_ver)
4517 int err = 0, fd, i, btf_id;
4519 if (prog->type == BPF_PROG_TYPE_TRACING) {
4520 btf_id = libbpf_find_attach_btf_id(prog->section_name,
4521 prog->expected_attach_type,
4522 prog->attach_prog_fd);
4525 prog->attach_btf_id = btf_id;
4528 if (prog->instances.nr < 0 || !prog->instances.fds) {
4529 if (prog->preprocessor) {
4530 pr_warn("Internal error: can't load program '%s'\n",
4531 prog->section_name);
4532 return -LIBBPF_ERRNO__INTERNAL;
4535 prog->instances.fds = malloc(sizeof(int));
4536 if (!prog->instances.fds) {
4537 pr_warn("Not enough memory for BPF fds\n");
4540 prog->instances.nr = 1;
4541 prog->instances.fds[0] = -1;
4544 if (!prog->preprocessor) {
4545 if (prog->instances.nr != 1) {
4546 pr_warn("Program '%s' is inconsistent: nr(%d) != 1\n",
4547 prog->section_name, prog->instances.nr);
4549 err = load_program(prog, prog->insns, prog->insns_cnt,
4550 license, kern_ver, &fd);
4552 prog->instances.fds[0] = fd;
4556 for (i = 0; i < prog->instances.nr; i++) {
4557 struct bpf_prog_prep_result result;
4558 bpf_program_prep_t preprocessor = prog->preprocessor;
4560 memset(&result, 0, sizeof(result));
4561 err = preprocessor(prog, i, prog->insns,
4562 prog->insns_cnt, &result);
4564 pr_warn("Preprocessing the %dth instance of program '%s' failed\n",
4565 i, prog->section_name);
4569 if (!result.new_insn_ptr || !result.new_insn_cnt) {
4570 pr_debug("Skip loading the %dth instance of program '%s'\n",
4571 i, prog->section_name);
4572 prog->instances.fds[i] = -1;
4578 err = load_program(prog, result.new_insn_ptr,
4579 result.new_insn_cnt, license, kern_ver, &fd);
4581 pr_warn("Loading the %dth instance of program '%s' failed\n",
4582 i, prog->section_name);
4588 prog->instances.fds[i] = fd;
4592 pr_warn("failed to load program '%s'\n", prog->section_name);
4593 zfree(&prog->insns);
4594 prog->insns_cnt = 0;
4598 static bool bpf_program__is_function_storage(const struct bpf_program *prog,
4599 const struct bpf_object *obj)
4601 return prog->idx == obj->efile.text_shndx && obj->has_pseudo_calls;
4605 bpf_object__load_progs(struct bpf_object *obj, int log_level)
4610 for (i = 0; i < obj->nr_programs; i++) {
4611 if (bpf_program__is_function_storage(&obj->programs[i], obj))
4613 obj->programs[i].log_level |= log_level;
4614 err = bpf_program__load(&obj->programs[i],
4623 static struct bpf_object *
4624 __bpf_object__open(const char *path, const void *obj_buf, size_t obj_buf_sz,
4625 const struct bpf_object_open_opts *opts)
4627 const char *obj_name, *kconfig;
4628 struct bpf_program *prog;
4629 struct bpf_object *obj;
4633 if (elf_version(EV_CURRENT) == EV_NONE) {
4634 pr_warn("failed to init libelf for %s\n",
4635 path ? : "(mem buf)");
4636 return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
4639 if (!OPTS_VALID(opts, bpf_object_open_opts))
4640 return ERR_PTR(-EINVAL);
4642 obj_name = OPTS_GET(opts, object_name, NULL);
4645 snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
4646 (unsigned long)obj_buf,
4647 (unsigned long)obj_buf_sz);
4648 obj_name = tmp_name;
4651 pr_debug("loading object '%s' from buffer\n", obj_name);
4654 obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
4658 obj->relaxed_core_relocs = OPTS_GET(opts, relaxed_core_relocs, false);
4659 kconfig = OPTS_GET(opts, kconfig, NULL);
4661 obj->kconfig = strdup(kconfig);
4663 return ERR_PTR(-ENOMEM);
4666 err = bpf_object__elf_init(obj);
4667 err = err ? : bpf_object__check_endianness(obj);
4668 err = err ? : bpf_object__elf_collect(obj);
4669 err = err ? : bpf_object__collect_externs(obj);
4670 err = err ? : bpf_object__finalize_btf(obj);
4671 err = err ? : bpf_object__init_maps(obj, opts);
4672 err = err ? : bpf_object__init_prog_names(obj);
4673 err = err ? : bpf_object__collect_reloc(obj);
4676 bpf_object__elf_finish(obj);
4678 bpf_object__for_each_program(prog, obj) {
4679 enum bpf_prog_type prog_type;
4680 enum bpf_attach_type attach_type;
4682 err = libbpf_prog_type_by_name(prog->section_name, &prog_type,
4685 /* couldn't guess, but user might manually specify */
4690 bpf_program__set_type(prog, prog_type);
4691 bpf_program__set_expected_attach_type(prog, attach_type);
4692 if (prog_type == BPF_PROG_TYPE_TRACING)
4693 prog->attach_prog_fd = OPTS_GET(opts, attach_prog_fd, 0);
4698 bpf_object__close(obj);
4699 return ERR_PTR(err);
4702 static struct bpf_object *
4703 __bpf_object__open_xattr(struct bpf_object_open_attr *attr, int flags)
4705 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts,
4706 .relaxed_maps = flags & MAPS_RELAX_COMPAT,
4709 /* param validation */
4713 pr_debug("loading %s\n", attr->file);
4714 return __bpf_object__open(attr->file, NULL, 0, &opts);
4717 struct bpf_object *bpf_object__open_xattr(struct bpf_object_open_attr *attr)
4719 return __bpf_object__open_xattr(attr, 0);
4722 struct bpf_object *bpf_object__open(const char *path)
4724 struct bpf_object_open_attr attr = {
4726 .prog_type = BPF_PROG_TYPE_UNSPEC,
4729 return bpf_object__open_xattr(&attr);
4733 bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
4736 return ERR_PTR(-EINVAL);
4738 pr_debug("loading %s\n", path);
4740 return __bpf_object__open(path, NULL, 0, opts);
4744 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
4745 const struct bpf_object_open_opts *opts)
4747 if (!obj_buf || obj_buf_sz == 0)
4748 return ERR_PTR(-EINVAL);
4750 return __bpf_object__open(NULL, obj_buf, obj_buf_sz, opts);
4754 bpf_object__open_buffer(const void *obj_buf, size_t obj_buf_sz,
4757 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts,
4758 .object_name = name,
4759 /* wrong default, but backwards-compatible */
4760 .relaxed_maps = true,
4763 /* returning NULL is wrong, but backwards-compatible */
4764 if (!obj_buf || obj_buf_sz == 0)
4767 return bpf_object__open_mem(obj_buf, obj_buf_sz, &opts);
4770 int bpf_object__unload(struct bpf_object *obj)
4777 for (i = 0; i < obj->nr_maps; i++)
4778 zclose(obj->maps[i].fd);
4780 for (i = 0; i < obj->nr_programs; i++)
4781 bpf_program__unload(&obj->programs[i]);
4786 static int bpf_object__sanitize_maps(struct bpf_object *obj)
4790 bpf_object__for_each_map(m, obj) {
4791 if (!bpf_map__is_internal(m))
4793 if (!obj->caps.global_data) {
4794 pr_warn("kernel doesn't support global data\n");
4797 if (!obj->caps.array_mmap)
4798 m->def.map_flags ^= BPF_F_MMAPABLE;
4804 static int bpf_object__resolve_externs(struct bpf_object *obj,
4805 const char *extra_kconfig)
4807 bool need_config = false;
4808 struct extern_desc *ext;
4812 if (obj->nr_extern == 0)
4815 data = obj->maps[obj->kconfig_map_idx].mmaped;
4817 for (i = 0; i < obj->nr_extern; i++) {
4818 ext = &obj->externs[i];
4820 if (strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
4821 void *ext_val = data + ext->data_off;
4822 __u32 kver = get_kernel_version();
4825 pr_warn("failed to get kernel version\n");
4828 err = set_ext_value_num(ext, ext_val, kver);
4831 pr_debug("extern %s=0x%x\n", ext->name, kver);
4832 } else if (strncmp(ext->name, "CONFIG_", 7) == 0) {
4835 pr_warn("unrecognized extern '%s'\n", ext->name);
4839 if (need_config && extra_kconfig) {
4840 err = bpf_object__read_kconfig_mem(obj, extra_kconfig, data);
4843 need_config = false;
4844 for (i = 0; i < obj->nr_extern; i++) {
4845 ext = &obj->externs[i];
4853 err = bpf_object__read_kconfig_file(obj, data);
4857 for (i = 0; i < obj->nr_extern; i++) {
4858 ext = &obj->externs[i];
4860 if (!ext->is_set && !ext->is_weak) {
4861 pr_warn("extern %s (strong) not resolved\n", ext->name);
4863 } else if (!ext->is_set) {
4864 pr_debug("extern %s (weak) not resolved, defaulting to zero\n",
4872 int bpf_object__load_xattr(struct bpf_object_load_attr *attr)
4874 struct bpf_object *obj;
4884 pr_warn("object should not be loaded twice\n");
4890 err = bpf_object__probe_caps(obj);
4891 err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
4892 err = err ? : bpf_object__sanitize_and_load_btf(obj);
4893 err = err ? : bpf_object__sanitize_maps(obj);
4894 err = err ? : bpf_object__create_maps(obj);
4895 err = err ? : bpf_object__relocate(obj, attr->target_btf_path);
4896 err = err ? : bpf_object__load_progs(obj, attr->log_level);
4902 /* unpin any maps that were auto-pinned during load */
4903 for (i = 0; i < obj->nr_maps; i++)
4904 if (obj->maps[i].pinned && !obj->maps[i].reused)
4905 bpf_map__unpin(&obj->maps[i], NULL);
4907 bpf_object__unload(obj);
4908 pr_warn("failed to load object '%s'\n", obj->path);
4912 int bpf_object__load(struct bpf_object *obj)
4914 struct bpf_object_load_attr attr = {
4918 return bpf_object__load_xattr(&attr);
4921 static int make_parent_dir(const char *path)
4923 char *cp, errmsg[STRERR_BUFSIZE];
4927 dname = strdup(path);
4931 dir = dirname(dname);
4932 if (mkdir(dir, 0700) && errno != EEXIST)
4937 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
4938 pr_warn("failed to mkdir %s: %s\n", path, cp);
4943 static int check_path(const char *path)
4945 char *cp, errmsg[STRERR_BUFSIZE];
4946 struct statfs st_fs;
4953 dname = strdup(path);
4957 dir = dirname(dname);
4958 if (statfs(dir, &st_fs)) {
4959 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
4960 pr_warn("failed to statfs %s: %s\n", dir, cp);
4965 if (!err && st_fs.f_type != BPF_FS_MAGIC) {
4966 pr_warn("specified path %s is not on BPF FS\n", path);
4973 int bpf_program__pin_instance(struct bpf_program *prog, const char *path,
4976 char *cp, errmsg[STRERR_BUFSIZE];
4979 err = make_parent_dir(path);
4983 err = check_path(path);
4988 pr_warn("invalid program pointer\n");
4992 if (instance < 0 || instance >= prog->instances.nr) {
4993 pr_warn("invalid prog instance %d of prog %s (max %d)\n",
4994 instance, prog->section_name, prog->instances.nr);
4998 if (bpf_obj_pin(prog->instances.fds[instance], path)) {
4999 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
5000 pr_warn("failed to pin program: %s\n", cp);
5003 pr_debug("pinned program '%s'\n", path);
5008 int bpf_program__unpin_instance(struct bpf_program *prog, const char *path,
5013 err = check_path(path);
5018 pr_warn("invalid program pointer\n");
5022 if (instance < 0 || instance >= prog->instances.nr) {
5023 pr_warn("invalid prog instance %d of prog %s (max %d)\n",
5024 instance, prog->section_name, prog->instances.nr);
5031 pr_debug("unpinned program '%s'\n", path);
5036 int bpf_program__pin(struct bpf_program *prog, const char *path)
5040 err = make_parent_dir(path);
5044 err = check_path(path);
5049 pr_warn("invalid program pointer\n");
5053 if (prog->instances.nr <= 0) {
5054 pr_warn("no instances of prog %s to pin\n",
5055 prog->section_name);
5059 if (prog->instances.nr == 1) {
5060 /* don't create subdirs when pinning single instance */
5061 return bpf_program__pin_instance(prog, path, 0);
5064 for (i = 0; i < prog->instances.nr; i++) {
5068 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
5072 } else if (len >= PATH_MAX) {
5073 err = -ENAMETOOLONG;
5077 err = bpf_program__pin_instance(prog, buf, i);
5085 for (i = i - 1; i >= 0; i--) {
5089 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
5092 else if (len >= PATH_MAX)
5095 bpf_program__unpin_instance(prog, buf, i);
5103 int bpf_program__unpin(struct bpf_program *prog, const char *path)
5107 err = check_path(path);
5112 pr_warn("invalid program pointer\n");
5116 if (prog->instances.nr <= 0) {
5117 pr_warn("no instances of prog %s to pin\n",
5118 prog->section_name);
5122 if (prog->instances.nr == 1) {
5123 /* don't create subdirs when pinning single instance */
5124 return bpf_program__unpin_instance(prog, path, 0);
5127 for (i = 0; i < prog->instances.nr; i++) {
5131 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
5134 else if (len >= PATH_MAX)
5135 return -ENAMETOOLONG;
5137 err = bpf_program__unpin_instance(prog, buf, i);
5149 int bpf_map__pin(struct bpf_map *map, const char *path)
5151 char *cp, errmsg[STRERR_BUFSIZE];
5155 pr_warn("invalid map pointer\n");
5159 if (map->pin_path) {
5160 if (path && strcmp(path, map->pin_path)) {
5161 pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
5162 bpf_map__name(map), map->pin_path, path);
5164 } else if (map->pinned) {
5165 pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
5166 bpf_map__name(map), map->pin_path);
5171 pr_warn("missing a path to pin map '%s' at\n",
5172 bpf_map__name(map));
5174 } else if (map->pinned) {
5175 pr_warn("map '%s' already pinned\n", bpf_map__name(map));
5179 map->pin_path = strdup(path);
5180 if (!map->pin_path) {
5186 err = make_parent_dir(map->pin_path);
5190 err = check_path(map->pin_path);
5194 if (bpf_obj_pin(map->fd, map->pin_path)) {
5200 pr_debug("pinned map '%s'\n", map->pin_path);
5205 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
5206 pr_warn("failed to pin map: %s\n", cp);
5210 int bpf_map__unpin(struct bpf_map *map, const char *path)
5215 pr_warn("invalid map pointer\n");
5219 if (map->pin_path) {
5220 if (path && strcmp(path, map->pin_path)) {
5221 pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
5222 bpf_map__name(map), map->pin_path, path);
5225 path = map->pin_path;
5227 pr_warn("no path to unpin map '%s' from\n",
5228 bpf_map__name(map));
5232 err = check_path(path);
5240 map->pinned = false;
5241 pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
5246 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
5256 free(map->pin_path);
5257 map->pin_path = new;
5261 const char *bpf_map__get_pin_path(const struct bpf_map *map)
5263 return map->pin_path;
5266 bool bpf_map__is_pinned(const struct bpf_map *map)
5271 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
5273 struct bpf_map *map;
5280 pr_warn("object not yet loaded; load it first\n");
5284 bpf_object__for_each_map(map, obj) {
5285 char *pin_path = NULL;
5291 len = snprintf(buf, PATH_MAX, "%s/%s", path,
5292 bpf_map__name(map));
5295 goto err_unpin_maps;
5296 } else if (len >= PATH_MAX) {
5297 err = -ENAMETOOLONG;
5298 goto err_unpin_maps;
5301 } else if (!map->pin_path) {
5305 err = bpf_map__pin(map, pin_path);
5307 goto err_unpin_maps;
5313 while ((map = bpf_map__prev(map, obj))) {
5317 bpf_map__unpin(map, NULL);
5323 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
5325 struct bpf_map *map;
5331 bpf_object__for_each_map(map, obj) {
5332 char *pin_path = NULL;
5338 len = snprintf(buf, PATH_MAX, "%s/%s", path,
5339 bpf_map__name(map));
5342 else if (len >= PATH_MAX)
5343 return -ENAMETOOLONG;
5345 } else if (!map->pin_path) {
5349 err = bpf_map__unpin(map, pin_path);
5357 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
5359 struct bpf_program *prog;
5366 pr_warn("object not yet loaded; load it first\n");
5370 bpf_object__for_each_program(prog, obj) {
5374 len = snprintf(buf, PATH_MAX, "%s/%s", path,
5378 goto err_unpin_programs;
5379 } else if (len >= PATH_MAX) {
5380 err = -ENAMETOOLONG;
5381 goto err_unpin_programs;
5384 err = bpf_program__pin(prog, buf);
5386 goto err_unpin_programs;
5392 while ((prog = bpf_program__prev(prog, obj))) {
5396 len = snprintf(buf, PATH_MAX, "%s/%s", path,
5400 else if (len >= PATH_MAX)
5403 bpf_program__unpin(prog, buf);
5409 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
5411 struct bpf_program *prog;
5417 bpf_object__for_each_program(prog, obj) {
5421 len = snprintf(buf, PATH_MAX, "%s/%s", path,
5425 else if (len >= PATH_MAX)
5426 return -ENAMETOOLONG;
5428 err = bpf_program__unpin(prog, buf);
5436 int bpf_object__pin(struct bpf_object *obj, const char *path)
5440 err = bpf_object__pin_maps(obj, path);
5444 err = bpf_object__pin_programs(obj, path);
5446 bpf_object__unpin_maps(obj, path);
5453 void bpf_object__close(struct bpf_object *obj)
5460 if (obj->clear_priv)
5461 obj->clear_priv(obj, obj->priv);
5463 bpf_object__elf_finish(obj);
5464 bpf_object__unload(obj);
5465 btf__free(obj->btf);
5466 btf_ext__free(obj->btf_ext);
5468 for (i = 0; i < obj->nr_maps; i++) {
5469 struct bpf_map *map = &obj->maps[i];
5471 if (map->clear_priv)
5472 map->clear_priv(map, map->priv);
5474 map->clear_priv = NULL;
5477 munmap(map->mmaped, bpf_map_mmap_sz(map));
5482 zfree(&map->pin_path);
5485 zfree(&obj->kconfig);
5486 zfree(&obj->externs);
5492 if (obj->programs && obj->nr_programs) {
5493 for (i = 0; i < obj->nr_programs; i++)
5494 bpf_program__exit(&obj->programs[i]);
5496 zfree(&obj->programs);
5498 list_del(&obj->list);
5503 bpf_object__next(struct bpf_object *prev)
5505 struct bpf_object *next;
5508 next = list_first_entry(&bpf_objects_list,
5512 next = list_next_entry(prev, list);
5514 /* Empty list is noticed here so don't need checking on entry. */
5515 if (&next->list == &bpf_objects_list)
5521 const char *bpf_object__name(const struct bpf_object *obj)
5523 return obj ? obj->name : ERR_PTR(-EINVAL);
5526 unsigned int bpf_object__kversion(const struct bpf_object *obj)
5528 return obj ? obj->kern_version : 0;
5531 struct btf *bpf_object__btf(const struct bpf_object *obj)
5533 return obj ? obj->btf : NULL;
5536 int bpf_object__btf_fd(const struct bpf_object *obj)
5538 return obj->btf ? btf__fd(obj->btf) : -1;
5541 int bpf_object__set_priv(struct bpf_object *obj, void *priv,
5542 bpf_object_clear_priv_t clear_priv)
5544 if (obj->priv && obj->clear_priv)
5545 obj->clear_priv(obj, obj->priv);
5548 obj->clear_priv = clear_priv;
5552 void *bpf_object__priv(const struct bpf_object *obj)
5554 return obj ? obj->priv : ERR_PTR(-EINVAL);
5557 static struct bpf_program *
5558 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
5561 size_t nr_programs = obj->nr_programs;
5568 /* Iter from the beginning */
5569 return forward ? &obj->programs[0] :
5570 &obj->programs[nr_programs - 1];
5572 if (p->obj != obj) {
5573 pr_warn("error: program handler doesn't match object\n");
5577 idx = (p - obj->programs) + (forward ? 1 : -1);
5578 if (idx >= obj->nr_programs || idx < 0)
5580 return &obj->programs[idx];
5583 struct bpf_program *
5584 bpf_program__next(struct bpf_program *prev, const struct bpf_object *obj)
5586 struct bpf_program *prog = prev;
5589 prog = __bpf_program__iter(prog, obj, true);
5590 } while (prog && bpf_program__is_function_storage(prog, obj));
5595 struct bpf_program *
5596 bpf_program__prev(struct bpf_program *next, const struct bpf_object *obj)
5598 struct bpf_program *prog = next;
5601 prog = __bpf_program__iter(prog, obj, false);
5602 } while (prog && bpf_program__is_function_storage(prog, obj));
5607 int bpf_program__set_priv(struct bpf_program *prog, void *priv,
5608 bpf_program_clear_priv_t clear_priv)
5610 if (prog->priv && prog->clear_priv)
5611 prog->clear_priv(prog, prog->priv);
5614 prog->clear_priv = clear_priv;
5618 void *bpf_program__priv(const struct bpf_program *prog)
5620 return prog ? prog->priv : ERR_PTR(-EINVAL);
5623 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
5625 prog->prog_ifindex = ifindex;
5628 const char *bpf_program__name(const struct bpf_program *prog)
5633 const char *bpf_program__title(const struct bpf_program *prog, bool needs_copy)
5637 title = prog->section_name;
5639 title = strdup(title);
5641 pr_warn("failed to strdup program title\n");
5642 return ERR_PTR(-ENOMEM);
5649 int bpf_program__fd(const struct bpf_program *prog)
5651 return bpf_program__nth_fd(prog, 0);
5654 size_t bpf_program__size(const struct bpf_program *prog)
5656 return prog->insns_cnt * sizeof(struct bpf_insn);
5659 int bpf_program__set_prep(struct bpf_program *prog, int nr_instances,
5660 bpf_program_prep_t prep)
5664 if (nr_instances <= 0 || !prep)
5667 if (prog->instances.nr > 0 || prog->instances.fds) {
5668 pr_warn("Can't set pre-processor after loading\n");
5672 instances_fds = malloc(sizeof(int) * nr_instances);
5673 if (!instances_fds) {
5674 pr_warn("alloc memory failed for fds\n");
5678 /* fill all fd with -1 */
5679 memset(instances_fds, -1, sizeof(int) * nr_instances);
5681 prog->instances.nr = nr_instances;
5682 prog->instances.fds = instances_fds;
5683 prog->preprocessor = prep;
5687 int bpf_program__nth_fd(const struct bpf_program *prog, int n)
5694 if (n >= prog->instances.nr || n < 0) {
5695 pr_warn("Can't get the %dth fd from program %s: only %d instances\n",
5696 n, prog->section_name, prog->instances.nr);
5700 fd = prog->instances.fds[n];
5702 pr_warn("%dth instance of program '%s' is invalid\n",
5703 n, prog->section_name);
5710 enum bpf_prog_type bpf_program__get_type(struct bpf_program *prog)
5715 void bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
5720 static bool bpf_program__is_type(const struct bpf_program *prog,
5721 enum bpf_prog_type type)
5723 return prog ? (prog->type == type) : false;
5726 #define BPF_PROG_TYPE_FNS(NAME, TYPE) \
5727 int bpf_program__set_##NAME(struct bpf_program *prog) \
5731 bpf_program__set_type(prog, TYPE); \
5735 bool bpf_program__is_##NAME(const struct bpf_program *prog) \
5737 return bpf_program__is_type(prog, TYPE); \
5740 BPF_PROG_TYPE_FNS(socket_filter, BPF_PROG_TYPE_SOCKET_FILTER);
5741 BPF_PROG_TYPE_FNS(kprobe, BPF_PROG_TYPE_KPROBE);
5742 BPF_PROG_TYPE_FNS(sched_cls, BPF_PROG_TYPE_SCHED_CLS);
5743 BPF_PROG_TYPE_FNS(sched_act, BPF_PROG_TYPE_SCHED_ACT);
5744 BPF_PROG_TYPE_FNS(tracepoint, BPF_PROG_TYPE_TRACEPOINT);
5745 BPF_PROG_TYPE_FNS(raw_tracepoint, BPF_PROG_TYPE_RAW_TRACEPOINT);
5746 BPF_PROG_TYPE_FNS(xdp, BPF_PROG_TYPE_XDP);
5747 BPF_PROG_TYPE_FNS(perf_event, BPF_PROG_TYPE_PERF_EVENT);
5748 BPF_PROG_TYPE_FNS(tracing, BPF_PROG_TYPE_TRACING);
5750 enum bpf_attach_type
5751 bpf_program__get_expected_attach_type(struct bpf_program *prog)
5753 return prog->expected_attach_type;
5756 void bpf_program__set_expected_attach_type(struct bpf_program *prog,
5757 enum bpf_attach_type type)
5759 prog->expected_attach_type = type;
5762 #define BPF_PROG_SEC_IMPL(string, ptype, eatype, is_attachable, btf, atype) \
5763 { string, sizeof(string) - 1, ptype, eatype, is_attachable, btf, atype }
5765 /* Programs that can NOT be attached. */
5766 #define BPF_PROG_SEC(string, ptype) BPF_PROG_SEC_IMPL(string, ptype, 0, 0, 0, 0)
5768 /* Programs that can be attached. */
5769 #define BPF_APROG_SEC(string, ptype, atype) \
5770 BPF_PROG_SEC_IMPL(string, ptype, 0, 1, 0, atype)
5772 /* Programs that must specify expected attach type at load time. */
5773 #define BPF_EAPROG_SEC(string, ptype, eatype) \
5774 BPF_PROG_SEC_IMPL(string, ptype, eatype, 1, 0, eatype)
5776 /* Programs that use BTF to identify attach point */
5777 #define BPF_PROG_BTF(string, ptype, eatype) \
5778 BPF_PROG_SEC_IMPL(string, ptype, eatype, 0, 1, 0)
5780 /* Programs that can be attached but attach type can't be identified by section
5781 * name. Kept for backward compatibility.
5783 #define BPF_APROG_COMPAT(string, ptype) BPF_PROG_SEC(string, ptype)
5785 #define SEC_DEF(sec_pfx, ptype, ...) { \
5787 .len = sizeof(sec_pfx) - 1, \
5788 .prog_type = BPF_PROG_TYPE_##ptype, \
5794 typedef struct bpf_link *(*attach_fn_t)(const struct bpf_sec_def *sec,
5795 struct bpf_program *prog);
5797 static struct bpf_link *attach_kprobe(const struct bpf_sec_def *sec,
5798 struct bpf_program *prog);
5799 static struct bpf_link *attach_tp(const struct bpf_sec_def *sec,
5800 struct bpf_program *prog);
5801 static struct bpf_link *attach_raw_tp(const struct bpf_sec_def *sec,
5802 struct bpf_program *prog);
5803 static struct bpf_link *attach_trace(const struct bpf_sec_def *sec,
5804 struct bpf_program *prog);
5806 struct bpf_sec_def {
5809 enum bpf_prog_type prog_type;
5810 enum bpf_attach_type expected_attach_type;
5813 enum bpf_attach_type attach_type;
5814 attach_fn_t attach_fn;
5817 static const struct bpf_sec_def section_defs[] = {
5818 BPF_PROG_SEC("socket", BPF_PROG_TYPE_SOCKET_FILTER),
5819 BPF_PROG_SEC("sk_reuseport", BPF_PROG_TYPE_SK_REUSEPORT),
5820 SEC_DEF("kprobe/", KPROBE,
5821 .attach_fn = attach_kprobe),
5822 BPF_PROG_SEC("uprobe/", BPF_PROG_TYPE_KPROBE),
5823 SEC_DEF("kretprobe/", KPROBE,
5824 .attach_fn = attach_kprobe),
5825 BPF_PROG_SEC("uretprobe/", BPF_PROG_TYPE_KPROBE),
5826 BPF_PROG_SEC("classifier", BPF_PROG_TYPE_SCHED_CLS),
5827 BPF_PROG_SEC("action", BPF_PROG_TYPE_SCHED_ACT),
5828 SEC_DEF("tracepoint/", TRACEPOINT,
5829 .attach_fn = attach_tp),
5830 SEC_DEF("tp/", TRACEPOINT,
5831 .attach_fn = attach_tp),
5832 SEC_DEF("raw_tracepoint/", RAW_TRACEPOINT,
5833 .attach_fn = attach_raw_tp),
5834 SEC_DEF("raw_tp/", RAW_TRACEPOINT,
5835 .attach_fn = attach_raw_tp),
5836 SEC_DEF("tp_btf/", TRACING,
5837 .expected_attach_type = BPF_TRACE_RAW_TP,
5838 .is_attach_btf = true,
5839 .attach_fn = attach_trace),
5840 SEC_DEF("fentry/", TRACING,
5841 .expected_attach_type = BPF_TRACE_FENTRY,
5842 .is_attach_btf = true,
5843 .attach_fn = attach_trace),
5844 SEC_DEF("fexit/", TRACING,
5845 .expected_attach_type = BPF_TRACE_FEXIT,
5846 .is_attach_btf = true,
5847 .attach_fn = attach_trace),
5848 BPF_PROG_SEC("xdp", BPF_PROG_TYPE_XDP),
5849 BPF_PROG_SEC("perf_event", BPF_PROG_TYPE_PERF_EVENT),
5850 BPF_PROG_SEC("lwt_in", BPF_PROG_TYPE_LWT_IN),
5851 BPF_PROG_SEC("lwt_out", BPF_PROG_TYPE_LWT_OUT),
5852 BPF_PROG_SEC("lwt_xmit", BPF_PROG_TYPE_LWT_XMIT),
5853 BPF_PROG_SEC("lwt_seg6local", BPF_PROG_TYPE_LWT_SEG6LOCAL),
5854 BPF_APROG_SEC("cgroup_skb/ingress", BPF_PROG_TYPE_CGROUP_SKB,
5855 BPF_CGROUP_INET_INGRESS),
5856 BPF_APROG_SEC("cgroup_skb/egress", BPF_PROG_TYPE_CGROUP_SKB,
5857 BPF_CGROUP_INET_EGRESS),
5858 BPF_APROG_COMPAT("cgroup/skb", BPF_PROG_TYPE_CGROUP_SKB),
5859 BPF_APROG_SEC("cgroup/sock", BPF_PROG_TYPE_CGROUP_SOCK,
5860 BPF_CGROUP_INET_SOCK_CREATE),
5861 BPF_EAPROG_SEC("cgroup/post_bind4", BPF_PROG_TYPE_CGROUP_SOCK,
5862 BPF_CGROUP_INET4_POST_BIND),
5863 BPF_EAPROG_SEC("cgroup/post_bind6", BPF_PROG_TYPE_CGROUP_SOCK,
5864 BPF_CGROUP_INET6_POST_BIND),
5865 BPF_APROG_SEC("cgroup/dev", BPF_PROG_TYPE_CGROUP_DEVICE,
5867 BPF_APROG_SEC("sockops", BPF_PROG_TYPE_SOCK_OPS,
5868 BPF_CGROUP_SOCK_OPS),
5869 BPF_APROG_SEC("sk_skb/stream_parser", BPF_PROG_TYPE_SK_SKB,
5870 BPF_SK_SKB_STREAM_PARSER),
5871 BPF_APROG_SEC("sk_skb/stream_verdict", BPF_PROG_TYPE_SK_SKB,
5872 BPF_SK_SKB_STREAM_VERDICT),
5873 BPF_APROG_COMPAT("sk_skb", BPF_PROG_TYPE_SK_SKB),
5874 BPF_APROG_SEC("sk_msg", BPF_PROG_TYPE_SK_MSG,
5875 BPF_SK_MSG_VERDICT),
5876 BPF_APROG_SEC("lirc_mode2", BPF_PROG_TYPE_LIRC_MODE2,
5878 BPF_APROG_SEC("flow_dissector", BPF_PROG_TYPE_FLOW_DISSECTOR,
5879 BPF_FLOW_DISSECTOR),
5880 BPF_EAPROG_SEC("cgroup/bind4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
5881 BPF_CGROUP_INET4_BIND),
5882 BPF_EAPROG_SEC("cgroup/bind6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
5883 BPF_CGROUP_INET6_BIND),
5884 BPF_EAPROG_SEC("cgroup/connect4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
5885 BPF_CGROUP_INET4_CONNECT),
5886 BPF_EAPROG_SEC("cgroup/connect6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
5887 BPF_CGROUP_INET6_CONNECT),
5888 BPF_EAPROG_SEC("cgroup/sendmsg4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
5889 BPF_CGROUP_UDP4_SENDMSG),
5890 BPF_EAPROG_SEC("cgroup/sendmsg6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
5891 BPF_CGROUP_UDP6_SENDMSG),
5892 BPF_EAPROG_SEC("cgroup/recvmsg4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
5893 BPF_CGROUP_UDP4_RECVMSG),
5894 BPF_EAPROG_SEC("cgroup/recvmsg6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
5895 BPF_CGROUP_UDP6_RECVMSG),
5896 BPF_EAPROG_SEC("cgroup/sysctl", BPF_PROG_TYPE_CGROUP_SYSCTL,
5898 BPF_EAPROG_SEC("cgroup/getsockopt", BPF_PROG_TYPE_CGROUP_SOCKOPT,
5899 BPF_CGROUP_GETSOCKOPT),
5900 BPF_EAPROG_SEC("cgroup/setsockopt", BPF_PROG_TYPE_CGROUP_SOCKOPT,
5901 BPF_CGROUP_SETSOCKOPT),
5904 #undef BPF_PROG_SEC_IMPL
5906 #undef BPF_APROG_SEC
5907 #undef BPF_EAPROG_SEC
5908 #undef BPF_APROG_COMPAT
5911 #define MAX_TYPE_NAME_SIZE 32
5913 static const struct bpf_sec_def *find_sec_def(const char *sec_name)
5915 int i, n = ARRAY_SIZE(section_defs);
5917 for (i = 0; i < n; i++) {
5918 if (strncmp(sec_name,
5919 section_defs[i].sec, section_defs[i].len))
5921 return §ion_defs[i];
5926 static char *libbpf_get_type_names(bool attach_type)
5928 int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
5936 /* Forge string buf with all available names */
5937 for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
5938 if (attach_type && !section_defs[i].is_attachable)
5941 if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
5946 strcat(buf, section_defs[i].sec);
5952 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
5953 enum bpf_attach_type *expected_attach_type)
5955 const struct bpf_sec_def *sec_def;
5961 sec_def = find_sec_def(name);
5963 *prog_type = sec_def->prog_type;
5964 *expected_attach_type = sec_def->expected_attach_type;
5968 pr_debug("failed to guess program type from ELF section '%s'\n", name);
5969 type_names = libbpf_get_type_names(false);
5970 if (type_names != NULL) {
5971 pr_debug("supported section(type) names are:%s\n", type_names);
5978 #define BTF_PREFIX "btf_trace_"
5979 int libbpf_find_vmlinux_btf_id(const char *name,
5980 enum bpf_attach_type attach_type)
5982 struct btf *btf = bpf_core_find_kernel_btf();
5983 char raw_tp_btf[128] = BTF_PREFIX;
5984 char *dst = raw_tp_btf + sizeof(BTF_PREFIX) - 1;
5985 const char *btf_name;
5990 pr_warn("vmlinux BTF is not found\n");
5994 if (attach_type == BPF_TRACE_RAW_TP) {
5995 /* prepend "btf_trace_" prefix per kernel convention */
5996 strncat(dst, name, sizeof(raw_tp_btf) - sizeof(BTF_PREFIX));
5997 btf_name = raw_tp_btf;
5998 kind = BTF_KIND_TYPEDEF;
6001 kind = BTF_KIND_FUNC;
6003 err = btf__find_by_name_kind(btf, btf_name, kind);
6008 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd)
6010 struct bpf_prog_info_linear *info_linear;
6011 struct bpf_prog_info *info;
6012 struct btf *btf = NULL;
6015 info_linear = bpf_program__get_prog_info_linear(attach_prog_fd, 0);
6016 if (IS_ERR_OR_NULL(info_linear)) {
6017 pr_warn("failed get_prog_info_linear for FD %d\n",
6021 info = &info_linear->info;
6022 if (!info->btf_id) {
6023 pr_warn("The target program doesn't have BTF\n");
6026 if (btf__get_from_id(info->btf_id, &btf)) {
6027 pr_warn("Failed to get BTF of the program\n");
6030 err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
6033 pr_warn("%s is not found in prog's BTF\n", name);
6041 static int libbpf_find_attach_btf_id(const char *name,
6042 enum bpf_attach_type attach_type,
6043 __u32 attach_prog_fd)
6050 for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
6051 if (!section_defs[i].is_attach_btf)
6053 if (strncmp(name, section_defs[i].sec, section_defs[i].len))
6056 err = libbpf_find_prog_btf_id(name + section_defs[i].len,
6059 err = libbpf_find_vmlinux_btf_id(name + section_defs[i].len,
6062 pr_warn("%s is not found in vmlinux BTF\n", name);
6065 pr_warn("failed to identify btf_id based on ELF section name '%s'\n", name);
6069 int libbpf_attach_type_by_name(const char *name,
6070 enum bpf_attach_type *attach_type)
6078 for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
6079 if (strncmp(name, section_defs[i].sec, section_defs[i].len))
6081 if (!section_defs[i].is_attachable)
6083 *attach_type = section_defs[i].attach_type;
6086 pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
6087 type_names = libbpf_get_type_names(true);
6088 if (type_names != NULL) {
6089 pr_debug("attachable section(type) names are:%s\n", type_names);
6096 int bpf_map__fd(const struct bpf_map *map)
6098 return map ? map->fd : -EINVAL;
6101 const struct bpf_map_def *bpf_map__def(const struct bpf_map *map)
6103 return map ? &map->def : ERR_PTR(-EINVAL);
6106 const char *bpf_map__name(const struct bpf_map *map)
6108 return map ? map->name : NULL;
6111 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
6113 return map ? map->btf_key_type_id : 0;
6116 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
6118 return map ? map->btf_value_type_id : 0;
6121 int bpf_map__set_priv(struct bpf_map *map, void *priv,
6122 bpf_map_clear_priv_t clear_priv)
6128 if (map->clear_priv)
6129 map->clear_priv(map, map->priv);
6133 map->clear_priv = clear_priv;
6137 void *bpf_map__priv(const struct bpf_map *map)
6139 return map ? map->priv : ERR_PTR(-EINVAL);
6142 bool bpf_map__is_offload_neutral(const struct bpf_map *map)
6144 return map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY;
6147 bool bpf_map__is_internal(const struct bpf_map *map)
6149 return map->libbpf_type != LIBBPF_MAP_UNSPEC;
6152 void bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
6154 map->map_ifindex = ifindex;
6157 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
6159 if (!bpf_map_type__is_map_in_map(map->def.type)) {
6160 pr_warn("error: unsupported map type\n");
6163 if (map->inner_map_fd != -1) {
6164 pr_warn("error: inner_map_fd already specified\n");
6167 map->inner_map_fd = fd;
6171 static struct bpf_map *
6172 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
6175 struct bpf_map *s, *e;
6177 if (!obj || !obj->maps)
6181 e = obj->maps + obj->nr_maps;
6183 if ((m < s) || (m >= e)) {
6184 pr_warn("error in %s: map handler doesn't belong to object\n",
6189 idx = (m - obj->maps) + i;
6190 if (idx >= obj->nr_maps || idx < 0)
6192 return &obj->maps[idx];
6196 bpf_map__next(const struct bpf_map *prev, const struct bpf_object *obj)
6201 return __bpf_map__iter(prev, obj, 1);
6205 bpf_map__prev(const struct bpf_map *next, const struct bpf_object *obj)
6210 return obj->maps + obj->nr_maps - 1;
6213 return __bpf_map__iter(next, obj, -1);
6217 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
6219 struct bpf_map *pos;
6221 bpf_object__for_each_map(pos, obj) {
6222 if (pos->name && !strcmp(pos->name, name))
6229 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
6231 return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
6235 bpf_object__find_map_by_offset(struct bpf_object *obj, size_t offset)
6237 return ERR_PTR(-ENOTSUP);
6240 long libbpf_get_error(const void *ptr)
6242 return PTR_ERR_OR_ZERO(ptr);
6245 int bpf_prog_load(const char *file, enum bpf_prog_type type,
6246 struct bpf_object **pobj, int *prog_fd)
6248 struct bpf_prog_load_attr attr;
6250 memset(&attr, 0, sizeof(struct bpf_prog_load_attr));
6252 attr.prog_type = type;
6253 attr.expected_attach_type = 0;
6255 return bpf_prog_load_xattr(&attr, pobj, prog_fd);
6258 int bpf_prog_load_xattr(const struct bpf_prog_load_attr *attr,
6259 struct bpf_object **pobj, int *prog_fd)
6261 struct bpf_object_open_attr open_attr = {};
6262 struct bpf_program *prog, *first_prog = NULL;
6263 struct bpf_object *obj;
6264 struct bpf_map *map;
6272 open_attr.file = attr->file;
6273 open_attr.prog_type = attr->prog_type;
6275 obj = bpf_object__open_xattr(&open_attr);
6276 if (IS_ERR_OR_NULL(obj))
6279 bpf_object__for_each_program(prog, obj) {
6280 enum bpf_attach_type attach_type = attr->expected_attach_type;
6282 * to preserve backwards compatibility, bpf_prog_load treats
6283 * attr->prog_type, if specified, as an override to whatever
6284 * bpf_object__open guessed
6286 if (attr->prog_type != BPF_PROG_TYPE_UNSPEC) {
6287 bpf_program__set_type(prog, attr->prog_type);
6288 bpf_program__set_expected_attach_type(prog,
6291 if (bpf_program__get_type(prog) == BPF_PROG_TYPE_UNSPEC) {
6293 * we haven't guessed from section name and user
6294 * didn't provide a fallback type, too bad...
6296 bpf_object__close(obj);
6300 prog->prog_ifindex = attr->ifindex;
6301 prog->log_level = attr->log_level;
6302 prog->prog_flags = attr->prog_flags;
6307 bpf_object__for_each_map(map, obj) {
6308 if (!bpf_map__is_offload_neutral(map))
6309 map->map_ifindex = attr->ifindex;
6313 pr_warn("object file doesn't contain bpf program\n");
6314 bpf_object__close(obj);
6318 err = bpf_object__load(obj);
6320 bpf_object__close(obj);
6325 *prog_fd = bpf_program__fd(first_prog);
6330 int (*detach)(struct bpf_link *link);
6331 int (*destroy)(struct bpf_link *link);
6335 /* Release "ownership" of underlying BPF resource (typically, BPF program
6336 * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
6337 * link, when destructed through bpf_link__destroy() call won't attempt to
6338 * detach/unregisted that BPF resource. This is useful in situations where,
6339 * say, attached BPF program has to outlive userspace program that attached it
6340 * in the system. Depending on type of BPF program, though, there might be
6341 * additional steps (like pinning BPF program in BPF FS) necessary to ensure
6342 * exit of userspace program doesn't trigger automatic detachment and clean up
6343 * inside the kernel.
6345 void bpf_link__disconnect(struct bpf_link *link)
6347 link->disconnected = true;
6350 int bpf_link__destroy(struct bpf_link *link)
6357 if (!link->disconnected && link->detach)
6358 err = link->detach(link);
6360 link->destroy(link);
6366 struct bpf_link_fd {
6367 struct bpf_link link; /* has to be at the top of struct */
6368 int fd; /* hook FD */
6371 static int bpf_link__detach_perf_event(struct bpf_link *link)
6373 struct bpf_link_fd *l = (void *)link;
6376 err = ioctl(l->fd, PERF_EVENT_IOC_DISABLE, 0);
6384 struct bpf_link *bpf_program__attach_perf_event(struct bpf_program *prog,
6387 char errmsg[STRERR_BUFSIZE];
6388 struct bpf_link_fd *link;
6392 pr_warn("program '%s': invalid perf event FD %d\n",
6393 bpf_program__title(prog, false), pfd);
6394 return ERR_PTR(-EINVAL);
6396 prog_fd = bpf_program__fd(prog);
6398 pr_warn("program '%s': can't attach BPF program w/o FD (did you load it?)\n",
6399 bpf_program__title(prog, false));
6400 return ERR_PTR(-EINVAL);
6403 link = calloc(1, sizeof(*link));
6405 return ERR_PTR(-ENOMEM);
6406 link->link.detach = &bpf_link__detach_perf_event;
6409 if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
6412 pr_warn("program '%s': failed to attach to pfd %d: %s\n",
6413 bpf_program__title(prog, false), pfd,
6414 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
6415 return ERR_PTR(err);
6417 if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
6420 pr_warn("program '%s': failed to enable pfd %d: %s\n",
6421 bpf_program__title(prog, false), pfd,
6422 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
6423 return ERR_PTR(err);
6425 return (struct bpf_link *)link;
6429 * this function is expected to parse integer in the range of [0, 2^31-1] from
6430 * given file using scanf format string fmt. If actual parsed value is
6431 * negative, the result might be indistinguishable from error
6433 static int parse_uint_from_file(const char *file, const char *fmt)
6435 char buf[STRERR_BUFSIZE];
6439 f = fopen(file, "r");
6442 pr_debug("failed to open '%s': %s\n", file,
6443 libbpf_strerror_r(err, buf, sizeof(buf)));
6446 err = fscanf(f, fmt, &ret);
6448 err = err == EOF ? -EIO : -errno;
6449 pr_debug("failed to parse '%s': %s\n", file,
6450 libbpf_strerror_r(err, buf, sizeof(buf)));
6458 static int determine_kprobe_perf_type(void)
6460 const char *file = "/sys/bus/event_source/devices/kprobe/type";
6462 return parse_uint_from_file(file, "%d\n");
6465 static int determine_uprobe_perf_type(void)
6467 const char *file = "/sys/bus/event_source/devices/uprobe/type";
6469 return parse_uint_from_file(file, "%d\n");
6472 static int determine_kprobe_retprobe_bit(void)
6474 const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
6476 return parse_uint_from_file(file, "config:%d\n");
6479 static int determine_uprobe_retprobe_bit(void)
6481 const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
6483 return parse_uint_from_file(file, "config:%d\n");
6486 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
6487 uint64_t offset, int pid)
6489 struct perf_event_attr attr = {};
6490 char errmsg[STRERR_BUFSIZE];
6493 type = uprobe ? determine_uprobe_perf_type()
6494 : determine_kprobe_perf_type();
6496 pr_warn("failed to determine %s perf type: %s\n",
6497 uprobe ? "uprobe" : "kprobe",
6498 libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
6502 int bit = uprobe ? determine_uprobe_retprobe_bit()
6503 : determine_kprobe_retprobe_bit();
6506 pr_warn("failed to determine %s retprobe bit: %s\n",
6507 uprobe ? "uprobe" : "kprobe",
6508 libbpf_strerror_r(bit, errmsg, sizeof(errmsg)));
6511 attr.config |= 1 << bit;
6513 attr.size = sizeof(attr);
6515 attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
6516 attr.config2 = offset; /* kprobe_addr or probe_offset */
6518 /* pid filter is meaningful only for uprobes */
6519 pfd = syscall(__NR_perf_event_open, &attr,
6520 pid < 0 ? -1 : pid /* pid */,
6521 pid == -1 ? 0 : -1 /* cpu */,
6522 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
6525 pr_warn("%s perf_event_open() failed: %s\n",
6526 uprobe ? "uprobe" : "kprobe",
6527 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
6533 struct bpf_link *bpf_program__attach_kprobe(struct bpf_program *prog,
6535 const char *func_name)
6537 char errmsg[STRERR_BUFSIZE];
6538 struct bpf_link *link;
6541 pfd = perf_event_open_probe(false /* uprobe */, retprobe, func_name,
6542 0 /* offset */, -1 /* pid */);
6544 pr_warn("program '%s': failed to create %s '%s' perf event: %s\n",
6545 bpf_program__title(prog, false),
6546 retprobe ? "kretprobe" : "kprobe", func_name,
6547 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
6548 return ERR_PTR(pfd);
6550 link = bpf_program__attach_perf_event(prog, pfd);
6553 err = PTR_ERR(link);
6554 pr_warn("program '%s': failed to attach to %s '%s': %s\n",
6555 bpf_program__title(prog, false),
6556 retprobe ? "kretprobe" : "kprobe", func_name,
6557 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
6563 static struct bpf_link *attach_kprobe(const struct bpf_sec_def *sec,
6564 struct bpf_program *prog)
6566 const char *func_name;
6569 func_name = bpf_program__title(prog, false) + sec->len;
6570 retprobe = strcmp(sec->sec, "kretprobe/") == 0;
6572 return bpf_program__attach_kprobe(prog, retprobe, func_name);
6575 struct bpf_link *bpf_program__attach_uprobe(struct bpf_program *prog,
6576 bool retprobe, pid_t pid,
6577 const char *binary_path,
6580 char errmsg[STRERR_BUFSIZE];
6581 struct bpf_link *link;
6584 pfd = perf_event_open_probe(true /* uprobe */, retprobe,
6585 binary_path, func_offset, pid);
6587 pr_warn("program '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
6588 bpf_program__title(prog, false),
6589 retprobe ? "uretprobe" : "uprobe",
6590 binary_path, func_offset,
6591 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
6592 return ERR_PTR(pfd);
6594 link = bpf_program__attach_perf_event(prog, pfd);
6597 err = PTR_ERR(link);
6598 pr_warn("program '%s': failed to attach to %s '%s:0x%zx': %s\n",
6599 bpf_program__title(prog, false),
6600 retprobe ? "uretprobe" : "uprobe",
6601 binary_path, func_offset,
6602 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
6608 static int determine_tracepoint_id(const char *tp_category,
6609 const char *tp_name)
6611 char file[PATH_MAX];
6614 ret = snprintf(file, sizeof(file),
6615 "/sys/kernel/debug/tracing/events/%s/%s/id",
6616 tp_category, tp_name);
6619 if (ret >= sizeof(file)) {
6620 pr_debug("tracepoint %s/%s path is too long\n",
6621 tp_category, tp_name);
6624 return parse_uint_from_file(file, "%d\n");
6627 static int perf_event_open_tracepoint(const char *tp_category,
6628 const char *tp_name)
6630 struct perf_event_attr attr = {};
6631 char errmsg[STRERR_BUFSIZE];
6632 int tp_id, pfd, err;
6634 tp_id = determine_tracepoint_id(tp_category, tp_name);
6636 pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
6637 tp_category, tp_name,
6638 libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
6642 attr.type = PERF_TYPE_TRACEPOINT;
6643 attr.size = sizeof(attr);
6644 attr.config = tp_id;
6646 pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
6647 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
6650 pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
6651 tp_category, tp_name,
6652 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
6658 struct bpf_link *bpf_program__attach_tracepoint(struct bpf_program *prog,
6659 const char *tp_category,
6660 const char *tp_name)
6662 char errmsg[STRERR_BUFSIZE];
6663 struct bpf_link *link;
6666 pfd = perf_event_open_tracepoint(tp_category, tp_name);
6668 pr_warn("program '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
6669 bpf_program__title(prog, false),
6670 tp_category, tp_name,
6671 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
6672 return ERR_PTR(pfd);
6674 link = bpf_program__attach_perf_event(prog, pfd);
6677 err = PTR_ERR(link);
6678 pr_warn("program '%s': failed to attach to tracepoint '%s/%s': %s\n",
6679 bpf_program__title(prog, false),
6680 tp_category, tp_name,
6681 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
6687 static struct bpf_link *attach_tp(const struct bpf_sec_def *sec,
6688 struct bpf_program *prog)
6690 char *sec_name, *tp_cat, *tp_name;
6691 struct bpf_link *link;
6693 sec_name = strdup(bpf_program__title(prog, false));
6695 return ERR_PTR(-ENOMEM);
6697 /* extract "tp/<category>/<name>" */
6698 tp_cat = sec_name + sec->len;
6699 tp_name = strchr(tp_cat, '/');
6701 link = ERR_PTR(-EINVAL);
6707 link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
6713 static int bpf_link__detach_fd(struct bpf_link *link)
6715 struct bpf_link_fd *l = (void *)link;
6717 return close(l->fd);
6720 struct bpf_link *bpf_program__attach_raw_tracepoint(struct bpf_program *prog,
6721 const char *tp_name)
6723 char errmsg[STRERR_BUFSIZE];
6724 struct bpf_link_fd *link;
6727 prog_fd = bpf_program__fd(prog);
6729 pr_warn("program '%s': can't attach before loaded\n",
6730 bpf_program__title(prog, false));
6731 return ERR_PTR(-EINVAL);
6734 link = calloc(1, sizeof(*link));
6736 return ERR_PTR(-ENOMEM);
6737 link->link.detach = &bpf_link__detach_fd;
6739 pfd = bpf_raw_tracepoint_open(tp_name, prog_fd);
6743 pr_warn("program '%s': failed to attach to raw tracepoint '%s': %s\n",
6744 bpf_program__title(prog, false), tp_name,
6745 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
6746 return ERR_PTR(pfd);
6749 return (struct bpf_link *)link;
6752 static struct bpf_link *attach_raw_tp(const struct bpf_sec_def *sec,
6753 struct bpf_program *prog)
6755 const char *tp_name = bpf_program__title(prog, false) + sec->len;
6757 return bpf_program__attach_raw_tracepoint(prog, tp_name);
6760 struct bpf_link *bpf_program__attach_trace(struct bpf_program *prog)
6762 char errmsg[STRERR_BUFSIZE];
6763 struct bpf_link_fd *link;
6766 prog_fd = bpf_program__fd(prog);
6768 pr_warn("program '%s': can't attach before loaded\n",
6769 bpf_program__title(prog, false));
6770 return ERR_PTR(-EINVAL);
6773 link = calloc(1, sizeof(*link));
6775 return ERR_PTR(-ENOMEM);
6776 link->link.detach = &bpf_link__detach_fd;
6778 pfd = bpf_raw_tracepoint_open(NULL, prog_fd);
6782 pr_warn("program '%s': failed to attach to trace: %s\n",
6783 bpf_program__title(prog, false),
6784 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
6785 return ERR_PTR(pfd);
6788 return (struct bpf_link *)link;
6791 static struct bpf_link *attach_trace(const struct bpf_sec_def *sec,
6792 struct bpf_program *prog)
6794 return bpf_program__attach_trace(prog);
6797 struct bpf_link *bpf_program__attach(struct bpf_program *prog)
6799 const struct bpf_sec_def *sec_def;
6801 sec_def = find_sec_def(bpf_program__title(prog, false));
6802 if (!sec_def || !sec_def->attach_fn)
6803 return ERR_PTR(-ESRCH);
6805 return sec_def->attach_fn(sec_def, prog);
6808 enum bpf_perf_event_ret
6809 bpf_perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
6810 void **copy_mem, size_t *copy_size,
6811 bpf_perf_event_print_t fn, void *private_data)
6813 struct perf_event_mmap_page *header = mmap_mem;
6814 __u64 data_head = ring_buffer_read_head(header);
6815 __u64 data_tail = header->data_tail;
6816 void *base = ((__u8 *)header) + page_size;
6817 int ret = LIBBPF_PERF_EVENT_CONT;
6818 struct perf_event_header *ehdr;
6821 while (data_head != data_tail) {
6822 ehdr = base + (data_tail & (mmap_size - 1));
6823 ehdr_size = ehdr->size;
6825 if (((void *)ehdr) + ehdr_size > base + mmap_size) {
6826 void *copy_start = ehdr;
6827 size_t len_first = base + mmap_size - copy_start;
6828 size_t len_secnd = ehdr_size - len_first;
6830 if (*copy_size < ehdr_size) {
6832 *copy_mem = malloc(ehdr_size);
6835 ret = LIBBPF_PERF_EVENT_ERROR;
6838 *copy_size = ehdr_size;
6841 memcpy(*copy_mem, copy_start, len_first);
6842 memcpy(*copy_mem + len_first, base, len_secnd);
6846 ret = fn(ehdr, private_data);
6847 data_tail += ehdr_size;
6848 if (ret != LIBBPF_PERF_EVENT_CONT)
6852 ring_buffer_write_tail(header, data_tail);
6858 struct perf_buffer_params {
6859 struct perf_event_attr *attr;
6860 /* if event_cb is specified, it takes precendence */
6861 perf_buffer_event_fn event_cb;
6862 /* sample_cb and lost_cb are higher-level common-case callbacks */
6863 perf_buffer_sample_fn sample_cb;
6864 perf_buffer_lost_fn lost_cb;
6871 struct perf_cpu_buf {
6872 struct perf_buffer *pb;
6873 void *base; /* mmap()'ed memory */
6874 void *buf; /* for reconstructing segmented data */
6881 struct perf_buffer {
6882 perf_buffer_event_fn event_cb;
6883 perf_buffer_sample_fn sample_cb;
6884 perf_buffer_lost_fn lost_cb;
6885 void *ctx; /* passed into callbacks */
6889 struct perf_cpu_buf **cpu_bufs;
6890 struct epoll_event *events;
6891 int cpu_cnt; /* number of allocated CPU buffers */
6892 int epoll_fd; /* perf event FD */
6893 int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
6896 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
6897 struct perf_cpu_buf *cpu_buf)
6901 if (cpu_buf->base &&
6902 munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
6903 pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
6904 if (cpu_buf->fd >= 0) {
6905 ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
6912 void perf_buffer__free(struct perf_buffer *pb)
6919 for (i = 0; i < pb->cpu_cnt && pb->cpu_bufs[i]; i++) {
6920 struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
6922 bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
6923 perf_buffer__free_cpu_buf(pb, cpu_buf);
6927 if (pb->epoll_fd >= 0)
6928 close(pb->epoll_fd);
6933 static struct perf_cpu_buf *
6934 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
6935 int cpu, int map_key)
6937 struct perf_cpu_buf *cpu_buf;
6938 char msg[STRERR_BUFSIZE];
6941 cpu_buf = calloc(1, sizeof(*cpu_buf));
6943 return ERR_PTR(-ENOMEM);
6947 cpu_buf->map_key = map_key;
6949 cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
6950 -1, PERF_FLAG_FD_CLOEXEC);
6951 if (cpu_buf->fd < 0) {
6953 pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
6954 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
6958 cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
6959 PROT_READ | PROT_WRITE, MAP_SHARED,
6961 if (cpu_buf->base == MAP_FAILED) {
6962 cpu_buf->base = NULL;
6964 pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
6965 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
6969 if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
6971 pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
6972 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
6979 perf_buffer__free_cpu_buf(pb, cpu_buf);
6980 return (struct perf_cpu_buf *)ERR_PTR(err);
6983 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
6984 struct perf_buffer_params *p);
6986 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
6987 const struct perf_buffer_opts *opts)
6989 struct perf_buffer_params p = {};
6990 struct perf_event_attr attr = { 0, };
6992 attr.config = PERF_COUNT_SW_BPF_OUTPUT,
6993 attr.type = PERF_TYPE_SOFTWARE;
6994 attr.sample_type = PERF_SAMPLE_RAW;
6995 attr.sample_period = 1;
6996 attr.wakeup_events = 1;
6999 p.sample_cb = opts ? opts->sample_cb : NULL;
7000 p.lost_cb = opts ? opts->lost_cb : NULL;
7001 p.ctx = opts ? opts->ctx : NULL;
7003 return __perf_buffer__new(map_fd, page_cnt, &p);
7006 struct perf_buffer *
7007 perf_buffer__new_raw(int map_fd, size_t page_cnt,
7008 const struct perf_buffer_raw_opts *opts)
7010 struct perf_buffer_params p = {};
7012 p.attr = opts->attr;
7013 p.event_cb = opts->event_cb;
7015 p.cpu_cnt = opts->cpu_cnt;
7016 p.cpus = opts->cpus;
7017 p.map_keys = opts->map_keys;
7019 return __perf_buffer__new(map_fd, page_cnt, &p);
7022 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
7023 struct perf_buffer_params *p)
7025 const char *online_cpus_file = "/sys/devices/system/cpu/online";
7026 struct bpf_map_info map = {};
7027 char msg[STRERR_BUFSIZE];
7028 struct perf_buffer *pb;
7029 bool *online = NULL;
7033 if (page_cnt & (page_cnt - 1)) {
7034 pr_warn("page count should be power of two, but is %zu\n",
7036 return ERR_PTR(-EINVAL);
7039 map_info_len = sizeof(map);
7040 err = bpf_obj_get_info_by_fd(map_fd, &map, &map_info_len);
7043 pr_warn("failed to get map info for map FD %d: %s\n",
7044 map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
7045 return ERR_PTR(err);
7048 if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
7049 pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
7051 return ERR_PTR(-EINVAL);
7054 pb = calloc(1, sizeof(*pb));
7056 return ERR_PTR(-ENOMEM);
7058 pb->event_cb = p->event_cb;
7059 pb->sample_cb = p->sample_cb;
7060 pb->lost_cb = p->lost_cb;
7063 pb->page_size = getpagesize();
7064 pb->mmap_size = pb->page_size * page_cnt;
7065 pb->map_fd = map_fd;
7067 pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
7068 if (pb->epoll_fd < 0) {
7070 pr_warn("failed to create epoll instance: %s\n",
7071 libbpf_strerror_r(err, msg, sizeof(msg)));
7075 if (p->cpu_cnt > 0) {
7076 pb->cpu_cnt = p->cpu_cnt;
7078 pb->cpu_cnt = libbpf_num_possible_cpus();
7079 if (pb->cpu_cnt < 0) {
7083 if (map.max_entries < pb->cpu_cnt)
7084 pb->cpu_cnt = map.max_entries;
7087 pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
7090 pr_warn("failed to allocate events: out of memory\n");
7093 pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
7094 if (!pb->cpu_bufs) {
7096 pr_warn("failed to allocate buffers: out of memory\n");
7100 err = parse_cpu_mask_file(online_cpus_file, &online, &n);
7102 pr_warn("failed to get online CPU mask: %d\n", err);
7106 for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
7107 struct perf_cpu_buf *cpu_buf;
7110 cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
7111 map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
7113 /* in case user didn't explicitly requested particular CPUs to
7114 * be attached to, skip offline/not present CPUs
7116 if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
7119 cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
7120 if (IS_ERR(cpu_buf)) {
7121 err = PTR_ERR(cpu_buf);
7125 pb->cpu_bufs[j] = cpu_buf;
7127 err = bpf_map_update_elem(pb->map_fd, &map_key,
7131 pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
7132 cpu, map_key, cpu_buf->fd,
7133 libbpf_strerror_r(err, msg, sizeof(msg)));
7137 pb->events[j].events = EPOLLIN;
7138 pb->events[j].data.ptr = cpu_buf;
7139 if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
7140 &pb->events[j]) < 0) {
7142 pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
7144 libbpf_strerror_r(err, msg, sizeof(msg)));
7157 perf_buffer__free(pb);
7158 return ERR_PTR(err);
7161 struct perf_sample_raw {
7162 struct perf_event_header header;
7167 struct perf_sample_lost {
7168 struct perf_event_header header;
7174 static enum bpf_perf_event_ret
7175 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
7177 struct perf_cpu_buf *cpu_buf = ctx;
7178 struct perf_buffer *pb = cpu_buf->pb;
7181 /* user wants full control over parsing perf event */
7183 return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
7186 case PERF_RECORD_SAMPLE: {
7187 struct perf_sample_raw *s = data;
7190 pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
7193 case PERF_RECORD_LOST: {
7194 struct perf_sample_lost *s = data;
7197 pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
7201 pr_warn("unknown perf sample type %d\n", e->type);
7202 return LIBBPF_PERF_EVENT_ERROR;
7204 return LIBBPF_PERF_EVENT_CONT;
7207 static int perf_buffer__process_records(struct perf_buffer *pb,
7208 struct perf_cpu_buf *cpu_buf)
7210 enum bpf_perf_event_ret ret;
7212 ret = bpf_perf_event_read_simple(cpu_buf->base, pb->mmap_size,
7213 pb->page_size, &cpu_buf->buf,
7215 perf_buffer__process_record, cpu_buf);
7216 if (ret != LIBBPF_PERF_EVENT_CONT)
7221 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
7225 cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
7226 for (i = 0; i < cnt; i++) {
7227 struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
7229 err = perf_buffer__process_records(pb, cpu_buf);
7231 pr_warn("error while processing records: %d\n", err);
7235 return cnt < 0 ? -errno : cnt;
7238 struct bpf_prog_info_array_desc {
7239 int array_offset; /* e.g. offset of jited_prog_insns */
7240 int count_offset; /* e.g. offset of jited_prog_len */
7241 int size_offset; /* > 0: offset of rec size,
7242 * < 0: fix size of -size_offset
7246 static struct bpf_prog_info_array_desc bpf_prog_info_array_desc[] = {
7247 [BPF_PROG_INFO_JITED_INSNS] = {
7248 offsetof(struct bpf_prog_info, jited_prog_insns),
7249 offsetof(struct bpf_prog_info, jited_prog_len),
7252 [BPF_PROG_INFO_XLATED_INSNS] = {
7253 offsetof(struct bpf_prog_info, xlated_prog_insns),
7254 offsetof(struct bpf_prog_info, xlated_prog_len),
7257 [BPF_PROG_INFO_MAP_IDS] = {
7258 offsetof(struct bpf_prog_info, map_ids),
7259 offsetof(struct bpf_prog_info, nr_map_ids),
7260 -(int)sizeof(__u32),
7262 [BPF_PROG_INFO_JITED_KSYMS] = {
7263 offsetof(struct bpf_prog_info, jited_ksyms),
7264 offsetof(struct bpf_prog_info, nr_jited_ksyms),
7265 -(int)sizeof(__u64),
7267 [BPF_PROG_INFO_JITED_FUNC_LENS] = {
7268 offsetof(struct bpf_prog_info, jited_func_lens),
7269 offsetof(struct bpf_prog_info, nr_jited_func_lens),
7270 -(int)sizeof(__u32),
7272 [BPF_PROG_INFO_FUNC_INFO] = {
7273 offsetof(struct bpf_prog_info, func_info),
7274 offsetof(struct bpf_prog_info, nr_func_info),
7275 offsetof(struct bpf_prog_info, func_info_rec_size),
7277 [BPF_PROG_INFO_LINE_INFO] = {
7278 offsetof(struct bpf_prog_info, line_info),
7279 offsetof(struct bpf_prog_info, nr_line_info),
7280 offsetof(struct bpf_prog_info, line_info_rec_size),
7282 [BPF_PROG_INFO_JITED_LINE_INFO] = {
7283 offsetof(struct bpf_prog_info, jited_line_info),
7284 offsetof(struct bpf_prog_info, nr_jited_line_info),
7285 offsetof(struct bpf_prog_info, jited_line_info_rec_size),
7287 [BPF_PROG_INFO_PROG_TAGS] = {
7288 offsetof(struct bpf_prog_info, prog_tags),
7289 offsetof(struct bpf_prog_info, nr_prog_tags),
7290 -(int)sizeof(__u8) * BPF_TAG_SIZE,
7295 static __u32 bpf_prog_info_read_offset_u32(struct bpf_prog_info *info,
7298 __u32 *array = (__u32 *)info;
7301 return array[offset / sizeof(__u32)];
7302 return -(int)offset;
7305 static __u64 bpf_prog_info_read_offset_u64(struct bpf_prog_info *info,
7308 __u64 *array = (__u64 *)info;
7311 return array[offset / sizeof(__u64)];
7312 return -(int)offset;
7315 static void bpf_prog_info_set_offset_u32(struct bpf_prog_info *info, int offset,
7318 __u32 *array = (__u32 *)info;
7321 array[offset / sizeof(__u32)] = val;
7324 static void bpf_prog_info_set_offset_u64(struct bpf_prog_info *info, int offset,
7327 __u64 *array = (__u64 *)info;
7330 array[offset / sizeof(__u64)] = val;
7333 struct bpf_prog_info_linear *
7334 bpf_program__get_prog_info_linear(int fd, __u64 arrays)
7336 struct bpf_prog_info_linear *info_linear;
7337 struct bpf_prog_info info = {};
7338 __u32 info_len = sizeof(info);
7343 if (arrays >> BPF_PROG_INFO_LAST_ARRAY)
7344 return ERR_PTR(-EINVAL);
7346 /* step 1: get array dimensions */
7347 err = bpf_obj_get_info_by_fd(fd, &info, &info_len);
7349 pr_debug("can't get prog info: %s", strerror(errno));
7350 return ERR_PTR(-EFAULT);
7353 /* step 2: calculate total size of all arrays */
7354 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
7355 bool include_array = (arrays & (1UL << i)) > 0;
7356 struct bpf_prog_info_array_desc *desc;
7359 desc = bpf_prog_info_array_desc + i;
7361 /* kernel is too old to support this field */
7362 if (info_len < desc->array_offset + sizeof(__u32) ||
7363 info_len < desc->count_offset + sizeof(__u32) ||
7364 (desc->size_offset > 0 && info_len < desc->size_offset))
7365 include_array = false;
7367 if (!include_array) {
7368 arrays &= ~(1UL << i); /* clear the bit */
7372 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
7373 size = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
7375 data_len += count * size;
7378 /* step 3: allocate continuous memory */
7379 data_len = roundup(data_len, sizeof(__u64));
7380 info_linear = malloc(sizeof(struct bpf_prog_info_linear) + data_len);
7382 return ERR_PTR(-ENOMEM);
7384 /* step 4: fill data to info_linear->info */
7385 info_linear->arrays = arrays;
7386 memset(&info_linear->info, 0, sizeof(info));
7387 ptr = info_linear->data;
7389 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
7390 struct bpf_prog_info_array_desc *desc;
7393 if ((arrays & (1UL << i)) == 0)
7396 desc = bpf_prog_info_array_desc + i;
7397 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
7398 size = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
7399 bpf_prog_info_set_offset_u32(&info_linear->info,
7400 desc->count_offset, count);
7401 bpf_prog_info_set_offset_u32(&info_linear->info,
7402 desc->size_offset, size);
7403 bpf_prog_info_set_offset_u64(&info_linear->info,
7406 ptr += count * size;
7409 /* step 5: call syscall again to get required arrays */
7410 err = bpf_obj_get_info_by_fd(fd, &info_linear->info, &info_len);
7412 pr_debug("can't get prog info: %s", strerror(errno));
7414 return ERR_PTR(-EFAULT);
7417 /* step 6: verify the data */
7418 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
7419 struct bpf_prog_info_array_desc *desc;
7422 if ((arrays & (1UL << i)) == 0)
7425 desc = bpf_prog_info_array_desc + i;
7426 v1 = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
7427 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
7428 desc->count_offset);
7430 pr_warn("%s: mismatch in element count\n", __func__);
7432 v1 = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
7433 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
7436 pr_warn("%s: mismatch in rec size\n", __func__);
7439 /* step 7: update info_len and data_len */
7440 info_linear->info_len = sizeof(struct bpf_prog_info);
7441 info_linear->data_len = data_len;
7446 void bpf_program__bpil_addr_to_offs(struct bpf_prog_info_linear *info_linear)
7450 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
7451 struct bpf_prog_info_array_desc *desc;
7454 if ((info_linear->arrays & (1UL << i)) == 0)
7457 desc = bpf_prog_info_array_desc + i;
7458 addr = bpf_prog_info_read_offset_u64(&info_linear->info,
7459 desc->array_offset);
7460 offs = addr - ptr_to_u64(info_linear->data);
7461 bpf_prog_info_set_offset_u64(&info_linear->info,
7462 desc->array_offset, offs);
7466 void bpf_program__bpil_offs_to_addr(struct bpf_prog_info_linear *info_linear)
7470 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
7471 struct bpf_prog_info_array_desc *desc;
7474 if ((info_linear->arrays & (1UL << i)) == 0)
7477 desc = bpf_prog_info_array_desc + i;
7478 offs = bpf_prog_info_read_offset_u64(&info_linear->info,
7479 desc->array_offset);
7480 addr = offs + ptr_to_u64(info_linear->data);
7481 bpf_prog_info_set_offset_u64(&info_linear->info,
7482 desc->array_offset, addr);
7486 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
7488 int err = 0, n, len, start, end = -1;
7494 /* Each sub string separated by ',' has format \d+-\d+ or \d+ */
7496 if (*s == ',' || *s == '\n') {
7500 n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
7501 if (n <= 0 || n > 2) {
7502 pr_warn("Failed to get CPU range %s: %d\n", s, n);
7505 } else if (n == 1) {
7508 if (start < 0 || start > end) {
7509 pr_warn("Invalid CPU range [%d,%d] in %s\n",
7514 tmp = realloc(*mask, end + 1);
7520 memset(tmp + *mask_sz, 0, start - *mask_sz);
7521 memset(tmp + start, 1, end - start + 1);
7526 pr_warn("Empty CPU range\n");
7536 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
7538 int fd, err = 0, len;
7541 fd = open(fcpu, O_RDONLY);
7544 pr_warn("Failed to open cpu mask file %s: %d\n", fcpu, err);
7547 len = read(fd, buf, sizeof(buf));
7550 err = len ? -errno : -EINVAL;
7551 pr_warn("Failed to read cpu mask from %s: %d\n", fcpu, err);
7554 if (len >= sizeof(buf)) {
7555 pr_warn("CPU mask is too big in file %s\n", fcpu);
7560 return parse_cpu_mask_str(buf, mask, mask_sz);
7563 int libbpf_num_possible_cpus(void)
7565 static const char *fcpu = "/sys/devices/system/cpu/possible";
7567 int err, n, i, tmp_cpus;
7570 tmp_cpus = READ_ONCE(cpus);
7574 err = parse_cpu_mask_file(fcpu, &mask, &n);
7579 for (i = 0; i < n; i++) {
7585 WRITE_ONCE(cpus, tmp_cpus);
7589 int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
7590 const struct bpf_object_open_opts *opts)
7592 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, skel_opts,
7593 .object_name = s->name,
7595 struct bpf_object *obj;
7598 /* Attempt to preserve opts->object_name, unless overriden by user
7599 * explicitly. Overwriting object name for skeletons is discouraged,
7600 * as it breaks global data maps, because they contain object name
7601 * prefix as their own map name prefix. When skeleton is generated,
7602 * bpftool is making an assumption that this name will stay the same.
7605 memcpy(&skel_opts, opts, sizeof(*opts));
7606 if (!opts->object_name)
7607 skel_opts.object_name = s->name;
7610 obj = bpf_object__open_mem(s->data, s->data_sz, &skel_opts);
7612 pr_warn("failed to initialize skeleton BPF object '%s': %ld\n",
7613 s->name, PTR_ERR(obj));
7614 return PTR_ERR(obj);
7619 for (i = 0; i < s->map_cnt; i++) {
7620 struct bpf_map **map = s->maps[i].map;
7621 const char *name = s->maps[i].name;
7622 void **mmaped = s->maps[i].mmaped;
7624 *map = bpf_object__find_map_by_name(obj, name);
7626 pr_warn("failed to find skeleton map '%s'\n", name);
7630 /* externs shouldn't be pre-setup from user code */
7631 if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
7632 *mmaped = (*map)->mmaped;
7635 for (i = 0; i < s->prog_cnt; i++) {
7636 struct bpf_program **prog = s->progs[i].prog;
7637 const char *name = s->progs[i].name;
7639 *prog = bpf_object__find_program_by_name(obj, name);
7641 pr_warn("failed to find skeleton program '%s'\n", name);
7649 int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
7653 err = bpf_object__load(*s->obj);
7655 pr_warn("failed to load BPF skeleton '%s': %d\n", s->name, err);
7659 for (i = 0; i < s->map_cnt; i++) {
7660 struct bpf_map *map = *s->maps[i].map;
7661 size_t mmap_sz = bpf_map_mmap_sz(map);
7662 int prot, map_fd = bpf_map__fd(map);
7663 void **mmaped = s->maps[i].mmaped;
7668 if (!(map->def.map_flags & BPF_F_MMAPABLE)) {
7673 if (map->def.map_flags & BPF_F_RDONLY_PROG)
7676 prot = PROT_READ | PROT_WRITE;
7678 /* Remap anonymous mmap()-ed "map initialization image" as
7679 * a BPF map-backed mmap()-ed memory, but preserving the same
7680 * memory address. This will cause kernel to change process'
7681 * page table to point to a different piece of kernel memory,
7682 * but from userspace point of view memory address (and its
7683 * contents, being identical at this point) will stay the
7684 * same. This mapping will be released by bpf_object__close()
7685 * as per normal clean up procedure, so we don't need to worry
7686 * about it from skeleton's clean up perspective.
7688 *mmaped = mmap(map->mmaped, mmap_sz, prot,
7689 MAP_SHARED | MAP_FIXED, map_fd, 0);
7690 if (*mmaped == MAP_FAILED) {
7693 pr_warn("failed to re-mmap() map '%s': %d\n",
7694 bpf_map__name(map), err);
7702 int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
7706 for (i = 0; i < s->prog_cnt; i++) {
7707 struct bpf_program *prog = *s->progs[i].prog;
7708 struct bpf_link **link = s->progs[i].link;
7709 const struct bpf_sec_def *sec_def;
7710 const char *sec_name = bpf_program__title(prog, false);
7712 sec_def = find_sec_def(sec_name);
7713 if (!sec_def || !sec_def->attach_fn)
7716 *link = sec_def->attach_fn(sec_def, prog);
7717 if (IS_ERR(*link)) {
7718 pr_warn("failed to auto-attach program '%s': %ld\n",
7719 bpf_program__name(prog), PTR_ERR(*link));
7720 return PTR_ERR(*link);
7727 void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
7731 for (i = 0; i < s->prog_cnt; i++) {
7732 struct bpf_link **link = s->progs[i].link;
7734 if (!IS_ERR_OR_NULL(*link))
7735 bpf_link__destroy(*link);
7740 void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
7743 bpf_object__detach_skeleton(s);
7745 bpf_object__close(*s->obj);