1 // SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
4 * Common eBPF ELF object loading operations.
6 * Copyright (C) 2013-2015 Alexei Starovoitov <ast@kernel.org>
7 * Copyright (C) 2015 Wang Nan <wangnan0@huawei.com>
8 * Copyright (C) 2015 Huawei Inc.
9 * Copyright (C) 2017 Nicira, Inc.
10 * Copyright (C) 2019 Isovalent, Inc.
26 #include <asm/unistd.h>
27 #include <linux/err.h>
28 #include <linux/kernel.h>
29 #include <linux/bpf.h>
30 #include <linux/btf.h>
31 #include <linux/filter.h>
32 #include <linux/list.h>
33 #include <linux/limits.h>
34 #include <linux/perf_event.h>
35 #include <linux/ring_buffer.h>
36 #include <linux/version.h>
37 #include <sys/epoll.h>
38 #include <sys/ioctl.h>
41 #include <sys/types.h>
43 #include <sys/utsname.h>
44 #include <sys/resource.h>
45 #include <tools/libc_compat.h>
53 #include "str_error.h"
54 #include "libbpf_internal.h"
62 #define BPF_FS_MAGIC 0xcafe4a11
65 /* vsprintf() in __base_pr() uses nonliteral format string. It may break
66 * compilation if user enables corresponding warning. Disable it explicitly.
68 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
70 #define __printf(a, b) __attribute__((format(printf, a, b)))
72 static int __base_pr(enum libbpf_print_level level, const char *format,
75 if (level == LIBBPF_DEBUG)
78 return vfprintf(stderr, format, args);
81 static libbpf_print_fn_t __libbpf_pr = __base_pr;
83 libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn)
85 libbpf_print_fn_t old_print_fn = __libbpf_pr;
92 void libbpf_print(enum libbpf_print_level level, const char *format, ...)
99 va_start(args, format);
100 __libbpf_pr(level, format, args);
104 static void pr_perm_msg(int err)
109 if (err != -EPERM || geteuid() != 0)
112 err = getrlimit(RLIMIT_MEMLOCK, &limit);
116 if (limit.rlim_cur == RLIM_INFINITY)
119 if (limit.rlim_cur < 1024)
120 snprintf(buf, sizeof(buf), "%lu bytes", limit.rlim_cur);
121 else if (limit.rlim_cur < 1024*1024)
122 snprintf(buf, sizeof(buf), "%.1f KiB", (double)limit.rlim_cur / 1024);
124 snprintf(buf, sizeof(buf), "%.1f MiB", (double)limit.rlim_cur / (1024*1024));
126 pr_warn("permission error while running as root; try raising 'ulimit -l'? current value: %s\n",
130 #define STRERR_BUFSIZE 128
132 /* Copied from tools/perf/util/util.h */
134 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
138 # define zclose(fd) ({ \
141 ___err = close((fd)); \
146 #ifdef HAVE_LIBELF_MMAP_SUPPORT
147 # define LIBBPF_ELF_C_READ_MMAP ELF_C_READ_MMAP
149 # define LIBBPF_ELF_C_READ_MMAP ELF_C_READ
152 static inline __u64 ptr_to_u64(const void *ptr)
154 return (__u64) (unsigned long) ptr;
157 struct bpf_capabilities {
158 /* v4.14: kernel support for program & map names. */
160 /* v5.2: kernel support for global data sections. */
162 /* BTF_KIND_FUNC and BTF_KIND_FUNC_PROTO support */
164 /* BTF_KIND_VAR and BTF_KIND_DATASEC support */
166 /* BPF_F_MMAPABLE is supported for arrays */
178 enum reloc_type type;
185 * bpf_prog should be a better name but it has been used in
189 /* Index in elf obj file, for relocation use. */
194 /* section_name with / replaced by _; makes recursive pinning
195 * in bpf_object__pin_programs easier
198 struct bpf_insn *insns;
199 size_t insns_cnt, main_prog_cnt;
200 enum bpf_prog_type type;
202 struct reloc_desc *reloc_desc;
210 bpf_program_prep_t preprocessor;
212 struct bpf_object *obj;
214 bpf_program_clear_priv_t clear_priv;
216 enum bpf_attach_type expected_attach_type;
218 __u32 attach_prog_fd;
220 __u32 func_info_rec_size;
223 struct bpf_capabilities *caps;
226 __u32 line_info_rec_size;
231 #define DATA_SEC ".data"
232 #define BSS_SEC ".bss"
233 #define RODATA_SEC ".rodata"
234 #define EXTERN_SEC ".extern"
236 enum libbpf_map_type {
244 static const char * const libbpf_type_to_btf_name[] = {
245 [LIBBPF_MAP_DATA] = DATA_SEC,
246 [LIBBPF_MAP_BSS] = BSS_SEC,
247 [LIBBPF_MAP_RODATA] = RODATA_SEC,
248 [LIBBPF_MAP_EXTERN] = EXTERN_SEC,
258 struct bpf_map_def def;
259 __u32 btf_key_type_id;
260 __u32 btf_value_type_id;
262 bpf_map_clear_priv_t clear_priv;
263 enum libbpf_map_type libbpf_type;
283 enum extern_type type;
292 static LIST_HEAD(bpf_objects_list);
295 char name[BPF_OBJ_NAME_LEN];
299 struct bpf_program *programs;
301 struct bpf_map *maps;
306 struct extern_desc *externs;
311 bool has_pseudo_calls;
312 bool relaxed_core_relocs;
315 * Information when doing elf related work. Only valid if fd
343 * All loaded bpf_object is linked in a list, which is
344 * hidden to caller. bpf_objects__<func> handlers deal with
347 struct list_head list;
350 struct btf_ext *btf_ext;
353 bpf_object_clear_priv_t clear_priv;
355 struct bpf_capabilities caps;
359 #define obj_elf_valid(o) ((o)->efile.elf)
361 void bpf_program__unload(struct bpf_program *prog)
369 * If the object is opened but the program was never loaded,
370 * it is possible that prog->instances.nr == -1.
372 if (prog->instances.nr > 0) {
373 for (i = 0; i < prog->instances.nr; i++)
374 zclose(prog->instances.fds[i]);
375 } else if (prog->instances.nr != -1) {
376 pr_warn("Internal error: instances.nr is %d\n",
380 prog->instances.nr = -1;
381 zfree(&prog->instances.fds);
383 zfree(&prog->func_info);
384 zfree(&prog->line_info);
387 static void bpf_program__exit(struct bpf_program *prog)
392 if (prog->clear_priv)
393 prog->clear_priv(prog, prog->priv);
396 prog->clear_priv = NULL;
398 bpf_program__unload(prog);
400 zfree(&prog->section_name);
401 zfree(&prog->pin_name);
403 zfree(&prog->reloc_desc);
410 static char *__bpf_program__pin_name(struct bpf_program *prog)
414 name = p = strdup(prog->section_name);
415 while ((p = strchr(p, '/')))
422 bpf_program__init(void *data, size_t size, char *section_name, int idx,
423 struct bpf_program *prog)
425 const size_t bpf_insn_sz = sizeof(struct bpf_insn);
427 if (size == 0 || size % bpf_insn_sz) {
428 pr_warn("corrupted section '%s', size: %zu\n",
433 memset(prog, 0, sizeof(*prog));
435 prog->section_name = strdup(section_name);
436 if (!prog->section_name) {
437 pr_warn("failed to alloc name for prog under section(%d) %s\n",
442 prog->pin_name = __bpf_program__pin_name(prog);
443 if (!prog->pin_name) {
444 pr_warn("failed to alloc pin name for prog under section(%d) %s\n",
449 prog->insns = malloc(size);
451 pr_warn("failed to alloc insns for prog under section %s\n",
455 prog->insns_cnt = size / bpf_insn_sz;
456 memcpy(prog->insns, data, size);
458 prog->instances.fds = NULL;
459 prog->instances.nr = -1;
460 prog->type = BPF_PROG_TYPE_UNSPEC;
464 bpf_program__exit(prog);
469 bpf_object__add_program(struct bpf_object *obj, void *data, size_t size,
470 char *section_name, int idx)
472 struct bpf_program prog, *progs;
475 err = bpf_program__init(data, size, section_name, idx, &prog);
479 prog.caps = &obj->caps;
480 progs = obj->programs;
481 nr_progs = obj->nr_programs;
483 progs = reallocarray(progs, nr_progs + 1, sizeof(progs[0]));
486 * In this case the original obj->programs
487 * is still valid, so don't need special treat for
488 * bpf_close_object().
490 pr_warn("failed to alloc a new program under section '%s'\n",
492 bpf_program__exit(&prog);
496 pr_debug("found program %s\n", prog.section_name);
497 obj->programs = progs;
498 obj->nr_programs = nr_progs + 1;
500 progs[nr_progs] = prog;
505 bpf_object__init_prog_names(struct bpf_object *obj)
507 Elf_Data *symbols = obj->efile.symbols;
508 struct bpf_program *prog;
511 for (pi = 0; pi < obj->nr_programs; pi++) {
512 const char *name = NULL;
514 prog = &obj->programs[pi];
516 for (si = 0; si < symbols->d_size / sizeof(GElf_Sym) && !name;
520 if (!gelf_getsym(symbols, si, &sym))
522 if (sym.st_shndx != prog->idx)
524 if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL)
527 name = elf_strptr(obj->efile.elf,
528 obj->efile.strtabidx,
531 pr_warn("failed to get sym name string for prog %s\n",
533 return -LIBBPF_ERRNO__LIBELF;
537 if (!name && prog->idx == obj->efile.text_shndx)
541 pr_warn("failed to find sym for prog %s\n",
546 prog->name = strdup(name);
548 pr_warn("failed to allocate memory for prog sym %s\n",
557 static __u32 get_kernel_version(void)
559 __u32 major, minor, patch;
563 if (sscanf(info.release, "%u.%u.%u", &major, &minor, &patch) != 3)
565 return KERNEL_VERSION(major, minor, patch);
568 static struct bpf_object *bpf_object__new(const char *path,
571 const char *obj_name)
573 struct bpf_object *obj;
576 obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
578 pr_warn("alloc memory failed for %s\n", path);
579 return ERR_PTR(-ENOMEM);
582 strcpy(obj->path, path);
584 strncpy(obj->name, obj_name, sizeof(obj->name) - 1);
585 obj->name[sizeof(obj->name) - 1] = 0;
587 /* Using basename() GNU version which doesn't modify arg. */
588 strncpy(obj->name, basename((void *)path),
589 sizeof(obj->name) - 1);
590 end = strchr(obj->name, '.');
597 * Caller of this function should also call
598 * bpf_object__elf_finish() after data collection to return
599 * obj_buf to user. If not, we should duplicate the buffer to
600 * avoid user freeing them before elf finish.
602 obj->efile.obj_buf = obj_buf;
603 obj->efile.obj_buf_sz = obj_buf_sz;
604 obj->efile.maps_shndx = -1;
605 obj->efile.btf_maps_shndx = -1;
606 obj->efile.data_shndx = -1;
607 obj->efile.rodata_shndx = -1;
608 obj->efile.bss_shndx = -1;
609 obj->extern_map_idx = -1;
611 obj->kern_version = get_kernel_version();
614 INIT_LIST_HEAD(&obj->list);
615 list_add(&obj->list, &bpf_objects_list);
619 static void bpf_object__elf_finish(struct bpf_object *obj)
621 if (!obj_elf_valid(obj))
624 if (obj->efile.elf) {
625 elf_end(obj->efile.elf);
626 obj->efile.elf = NULL;
628 obj->efile.symbols = NULL;
629 obj->efile.data = NULL;
630 obj->efile.rodata = NULL;
631 obj->efile.bss = NULL;
633 zfree(&obj->efile.reloc_sects);
634 obj->efile.nr_reloc_sects = 0;
635 zclose(obj->efile.fd);
636 obj->efile.obj_buf = NULL;
637 obj->efile.obj_buf_sz = 0;
640 static int bpf_object__elf_init(struct bpf_object *obj)
645 if (obj_elf_valid(obj)) {
646 pr_warn("elf init: internal error\n");
647 return -LIBBPF_ERRNO__LIBELF;
650 if (obj->efile.obj_buf_sz > 0) {
652 * obj_buf should have been validated by
653 * bpf_object__open_buffer().
655 obj->efile.elf = elf_memory((char *)obj->efile.obj_buf,
656 obj->efile.obj_buf_sz);
658 obj->efile.fd = open(obj->path, O_RDONLY);
659 if (obj->efile.fd < 0) {
660 char errmsg[STRERR_BUFSIZE], *cp;
663 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
664 pr_warn("failed to open %s: %s\n", obj->path, cp);
668 obj->efile.elf = elf_begin(obj->efile.fd,
669 LIBBPF_ELF_C_READ_MMAP, NULL);
672 if (!obj->efile.elf) {
673 pr_warn("failed to open %s as ELF file\n", obj->path);
674 err = -LIBBPF_ERRNO__LIBELF;
678 if (!gelf_getehdr(obj->efile.elf, &obj->efile.ehdr)) {
679 pr_warn("failed to get EHDR from %s\n", obj->path);
680 err = -LIBBPF_ERRNO__FORMAT;
683 ep = &obj->efile.ehdr;
685 /* Old LLVM set e_machine to EM_NONE */
686 if (ep->e_type != ET_REL ||
687 (ep->e_machine && ep->e_machine != EM_BPF)) {
688 pr_warn("%s is not an eBPF object file\n", obj->path);
689 err = -LIBBPF_ERRNO__FORMAT;
695 bpf_object__elf_finish(obj);
699 static int bpf_object__check_endianness(struct bpf_object *obj)
701 #if __BYTE_ORDER == __LITTLE_ENDIAN
702 if (obj->efile.ehdr.e_ident[EI_DATA] == ELFDATA2LSB)
704 #elif __BYTE_ORDER == __BIG_ENDIAN
705 if (obj->efile.ehdr.e_ident[EI_DATA] == ELFDATA2MSB)
708 # error "Unrecognized __BYTE_ORDER__"
710 pr_warn("endianness mismatch.\n");
711 return -LIBBPF_ERRNO__ENDIAN;
715 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
717 memcpy(obj->license, data, min(size, sizeof(obj->license) - 1));
718 pr_debug("license of %s is %s\n", obj->path, obj->license);
723 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
727 if (size != sizeof(kver)) {
728 pr_warn("invalid kver section in %s\n", obj->path);
729 return -LIBBPF_ERRNO__FORMAT;
731 memcpy(&kver, data, sizeof(kver));
732 obj->kern_version = kver;
733 pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
737 static int compare_bpf_map(const void *_a, const void *_b)
739 const struct bpf_map *a = _a;
740 const struct bpf_map *b = _b;
742 if (a->sec_idx != b->sec_idx)
743 return a->sec_idx - b->sec_idx;
744 return a->sec_offset - b->sec_offset;
747 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
749 if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
750 type == BPF_MAP_TYPE_HASH_OF_MAPS)
755 static int bpf_object_search_section_size(const struct bpf_object *obj,
756 const char *name, size_t *d_size)
758 const GElf_Ehdr *ep = &obj->efile.ehdr;
759 Elf *elf = obj->efile.elf;
763 while ((scn = elf_nextscn(elf, scn)) != NULL) {
764 const char *sec_name;
769 if (gelf_getshdr(scn, &sh) != &sh) {
770 pr_warn("failed to get section(%d) header from %s\n",
775 sec_name = elf_strptr(elf, ep->e_shstrndx, sh.sh_name);
777 pr_warn("failed to get section(%d) name from %s\n",
782 if (strcmp(name, sec_name))
785 data = elf_getdata(scn, 0);
787 pr_warn("failed to get section(%d) data from %s(%s)\n",
788 idx, name, obj->path);
792 *d_size = data->d_size;
799 int bpf_object__section_size(const struct bpf_object *obj, const char *name,
808 } else if (!strcmp(name, DATA_SEC)) {
810 *size = obj->efile.data->d_size;
811 } else if (!strcmp(name, BSS_SEC)) {
813 *size = obj->efile.bss->d_size;
814 } else if (!strcmp(name, RODATA_SEC)) {
815 if (obj->efile.rodata)
816 *size = obj->efile.rodata->d_size;
818 ret = bpf_object_search_section_size(obj, name, &d_size);
823 return *size ? 0 : ret;
826 int bpf_object__variable_offset(const struct bpf_object *obj, const char *name,
829 Elf_Data *symbols = obj->efile.symbols;
836 for (si = 0; si < symbols->d_size / sizeof(GElf_Sym); si++) {
839 if (!gelf_getsym(symbols, si, &sym))
841 if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL ||
842 GELF_ST_TYPE(sym.st_info) != STT_OBJECT)
845 sname = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
848 pr_warn("failed to get sym name string for var %s\n",
852 if (strcmp(name, sname) == 0) {
861 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
863 struct bpf_map *new_maps;
867 if (obj->nr_maps < obj->maps_cap)
868 return &obj->maps[obj->nr_maps++];
870 new_cap = max((size_t)4, obj->maps_cap * 3 / 2);
871 new_maps = realloc(obj->maps, new_cap * sizeof(*obj->maps));
873 pr_warn("alloc maps for object failed\n");
874 return ERR_PTR(-ENOMEM);
877 obj->maps_cap = new_cap;
878 obj->maps = new_maps;
880 /* zero out new maps */
881 memset(obj->maps + obj->nr_maps, 0,
882 (obj->maps_cap - obj->nr_maps) * sizeof(*obj->maps));
884 * fill all fd with -1 so won't close incorrect fd (fd=0 is stdin)
885 * when failure (zclose won't close negative fd)).
887 for (i = obj->nr_maps; i < obj->maps_cap; i++) {
888 obj->maps[i].fd = -1;
889 obj->maps[i].inner_map_fd = -1;
892 return &obj->maps[obj->nr_maps++];
895 static size_t bpf_map_mmap_sz(const struct bpf_map *map)
897 long page_sz = sysconf(_SC_PAGE_SIZE);
900 map_sz = roundup(map->def.value_size, 8) * map->def.max_entries;
901 map_sz = roundup(map_sz, page_sz);
906 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
907 int sec_idx, void *data, size_t data_sz)
909 char map_name[BPF_OBJ_NAME_LEN];
910 struct bpf_map_def *def;
914 map = bpf_object__add_map(obj);
918 map->libbpf_type = type;
919 map->sec_idx = sec_idx;
921 snprintf(map_name, sizeof(map_name), "%.8s%.7s", obj->name,
922 libbpf_type_to_btf_name[type]);
923 map->name = strdup(map_name);
925 pr_warn("failed to alloc map name\n");
930 def->type = BPF_MAP_TYPE_ARRAY;
931 def->key_size = sizeof(int);
932 def->value_size = data_sz;
933 def->max_entries = 1;
934 def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_EXTERN
935 ? BPF_F_RDONLY_PROG : 0;
936 def->map_flags |= BPF_F_MMAPABLE;
938 pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
939 map_name, map->sec_idx, map->sec_offset, def->map_flags);
941 map->mmaped = mmap(NULL, bpf_map_mmap_sz(map), PROT_READ | PROT_WRITE,
942 MAP_SHARED | MAP_ANONYMOUS, -1, 0);
943 if (map->mmaped == MAP_FAILED) {
946 pr_warn("failed to alloc map '%s' content buffer: %d\n",
953 memcpy(map->mmaped, data, data_sz);
955 pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
959 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
964 * Populate obj->maps with libbpf internal maps.
966 if (obj->efile.data_shndx >= 0) {
967 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
968 obj->efile.data_shndx,
969 obj->efile.data->d_buf,
970 obj->efile.data->d_size);
974 if (obj->efile.rodata_shndx >= 0) {
975 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
976 obj->efile.rodata_shndx,
977 obj->efile.rodata->d_buf,
978 obj->efile.rodata->d_size);
982 if (obj->efile.bss_shndx >= 0) {
983 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
984 obj->efile.bss_shndx,
986 obj->efile.bss->d_size);
994 static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
999 for (i = 0; i < obj->nr_extern; i++) {
1000 if (strcmp(obj->externs[i].name, name) == 0)
1001 return &obj->externs[i];
1006 static int set_ext_value_tri(struct extern_desc *ext, void *ext_val,
1009 switch (ext->type) {
1012 pr_warn("extern %s=%c should be tristate or char\n",
1016 *(bool *)ext_val = value == 'y' ? true : false;
1020 *(enum libbpf_tristate *)ext_val = TRI_YES;
1021 else if (value == 'm')
1022 *(enum libbpf_tristate *)ext_val = TRI_MODULE;
1023 else /* value == 'n' */
1024 *(enum libbpf_tristate *)ext_val = TRI_NO;
1027 *(char *)ext_val = value;
1033 pr_warn("extern %s=%c should be bool, tristate, or char\n",
1041 static int set_ext_value_str(struct extern_desc *ext, char *ext_val,
1046 if (ext->type != EXT_CHAR_ARR) {
1047 pr_warn("extern %s=%s should char array\n", ext->name, value);
1051 len = strlen(value);
1052 if (value[len - 1] != '"') {
1053 pr_warn("extern '%s': invalid string config '%s'\n",
1060 if (len >= ext->sz) {
1061 pr_warn("extern '%s': long string config %s of (%zu bytes) truncated to %d bytes\n",
1062 ext->name, value, len, ext->sz - 1);
1065 memcpy(ext_val, value + 1, len);
1066 ext_val[len] = '\0';
1071 static int parse_u64(const char *value, __u64 *res)
1077 *res = strtoull(value, &value_end, 0);
1080 pr_warn("failed to parse '%s' as integer: %d\n", value, err);
1084 pr_warn("failed to parse '%s' as integer completely\n", value);
1090 static bool is_ext_value_in_range(const struct extern_desc *ext, __u64 v)
1092 int bit_sz = ext->sz * 8;
1097 /* Validate that value stored in u64 fits in integer of `ext->sz`
1098 * bytes size without any loss of information. If the target integer
1099 * is signed, we rely on the following limits of integer type of
1100 * Y bits and subsequent transformation:
1102 * -2^(Y-1) <= X <= 2^(Y-1) - 1
1103 * 0 <= X + 2^(Y-1) <= 2^Y - 1
1104 * 0 <= X + 2^(Y-1) < 2^Y
1106 * For unsigned target integer, check that all the (64 - Y) bits are
1110 return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
1112 return (v >> bit_sz) == 0;
1115 static int set_ext_value_num(struct extern_desc *ext, void *ext_val,
1118 if (ext->type != EXT_INT && ext->type != EXT_CHAR) {
1119 pr_warn("extern %s=%llu should be integer\n",
1123 if (!is_ext_value_in_range(ext, value)) {
1124 pr_warn("extern %s=%llu value doesn't fit in %d bytes\n",
1125 ext->name, value, ext->sz);
1129 case 1: *(__u8 *)ext_val = value; break;
1130 case 2: *(__u16 *)ext_val = value; break;
1131 case 4: *(__u32 *)ext_val = value; break;
1132 case 8: *(__u64 *)ext_val = value; break;
1140 static int bpf_object__read_kernel_config(struct bpf_object *obj,
1141 const char *config_path,
1144 char buf[PATH_MAX], *sep, *value;
1145 struct extern_desc *ext;
1152 file = gzopen(config_path, "r");
1157 len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
1160 else if (len >= PATH_MAX)
1161 return -ENAMETOOLONG;
1162 /* gzopen also accepts uncompressed files. */
1163 file = gzopen(buf, "r");
1165 file = gzopen("/proc/config.gz", "r");
1168 pr_warn("failed to read kernel config at '%s'\n", config_path);
1172 while (gzgets(file, buf, sizeof(buf))) {
1173 if (strncmp(buf, "CONFIG_", 7))
1176 sep = strchr(buf, '=');
1179 pr_warn("failed to parse '%s': no separator\n", buf);
1182 /* Trim ending '\n' */
1184 if (buf[len - 1] == '\n')
1185 buf[len - 1] = '\0';
1186 /* Split on '=' and ensure that a value is present. */
1191 pr_warn("failed to parse '%s': no value\n", buf);
1195 ext = find_extern_by_name(obj, buf);
1200 pr_warn("re-defining extern '%s' not allowed\n", buf);
1204 ext_val = data + ext->data_off;
1208 case 'y': case 'n': case 'm':
1209 err = set_ext_value_tri(ext, ext_val, *value);
1212 err = set_ext_value_str(ext, ext_val, value);
1215 /* assume integer */
1216 err = parse_u64(value, &num);
1218 pr_warn("extern %s=%s should be integer\n",
1222 err = set_ext_value_num(ext, ext_val, num);
1227 pr_debug("extern %s=%s\n", ext->name, value);
1235 static int bpf_object__init_extern_map(struct bpf_object *obj)
1237 struct extern_desc *last_ext;
1241 if (obj->nr_extern == 0)
1244 last_ext = &obj->externs[obj->nr_extern - 1];
1245 map_sz = last_ext->data_off + last_ext->sz;
1247 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_EXTERN,
1248 obj->efile.symbols_shndx,
1253 obj->extern_map_idx = obj->nr_maps - 1;
1258 static int bpf_object__init_user_maps(struct bpf_object *obj, bool strict)
1260 Elf_Data *symbols = obj->efile.symbols;
1261 int i, map_def_sz = 0, nr_maps = 0, nr_syms;
1262 Elf_Data *data = NULL;
1265 if (obj->efile.maps_shndx < 0)
1271 scn = elf_getscn(obj->efile.elf, obj->efile.maps_shndx);
1273 data = elf_getdata(scn, NULL);
1274 if (!scn || !data) {
1275 pr_warn("failed to get Elf_Data from map section %d\n",
1276 obj->efile.maps_shndx);
1281 * Count number of maps. Each map has a name.
1282 * Array of maps is not supported: only the first element is
1285 * TODO: Detect array of map and report error.
1287 nr_syms = symbols->d_size / sizeof(GElf_Sym);
1288 for (i = 0; i < nr_syms; i++) {
1291 if (!gelf_getsym(symbols, i, &sym))
1293 if (sym.st_shndx != obj->efile.maps_shndx)
1297 /* Assume equally sized map definitions */
1298 pr_debug("maps in %s: %d maps in %zd bytes\n",
1299 obj->path, nr_maps, data->d_size);
1301 if (!data->d_size || nr_maps == 0 || (data->d_size % nr_maps) != 0) {
1302 pr_warn("unable to determine map definition size section %s, %d maps in %zd bytes\n",
1303 obj->path, nr_maps, data->d_size);
1306 map_def_sz = data->d_size / nr_maps;
1308 /* Fill obj->maps using data in "maps" section. */
1309 for (i = 0; i < nr_syms; i++) {
1311 const char *map_name;
1312 struct bpf_map_def *def;
1313 struct bpf_map *map;
1315 if (!gelf_getsym(symbols, i, &sym))
1317 if (sym.st_shndx != obj->efile.maps_shndx)
1320 map = bpf_object__add_map(obj);
1322 return PTR_ERR(map);
1324 map_name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
1327 pr_warn("failed to get map #%d name sym string for obj %s\n",
1329 return -LIBBPF_ERRNO__FORMAT;
1332 map->libbpf_type = LIBBPF_MAP_UNSPEC;
1333 map->sec_idx = sym.st_shndx;
1334 map->sec_offset = sym.st_value;
1335 pr_debug("map '%s' (legacy): at sec_idx %d, offset %zu.\n",
1336 map_name, map->sec_idx, map->sec_offset);
1337 if (sym.st_value + map_def_sz > data->d_size) {
1338 pr_warn("corrupted maps section in %s: last map \"%s\" too small\n",
1339 obj->path, map_name);
1343 map->name = strdup(map_name);
1345 pr_warn("failed to alloc map name\n");
1348 pr_debug("map %d is \"%s\"\n", i, map->name);
1349 def = (struct bpf_map_def *)(data->d_buf + sym.st_value);
1351 * If the definition of the map in the object file fits in
1352 * bpf_map_def, copy it. Any extra fields in our version
1353 * of bpf_map_def will default to zero as a result of the
1356 if (map_def_sz <= sizeof(struct bpf_map_def)) {
1357 memcpy(&map->def, def, map_def_sz);
1360 * Here the map structure being read is bigger than what
1361 * we expect, truncate if the excess bits are all zero.
1362 * If they are not zero, reject this map as
1367 for (b = ((char *)def) + sizeof(struct bpf_map_def);
1368 b < ((char *)def) + map_def_sz; b++) {
1370 pr_warn("maps section in %s: \"%s\" has unrecognized, non-zero options\n",
1371 obj->path, map_name);
1376 memcpy(&map->def, def, sizeof(struct bpf_map_def));
1382 static const struct btf_type *
1383 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
1385 const struct btf_type *t = btf__type_by_id(btf, id);
1390 while (btf_is_mod(t) || btf_is_typedef(t)) {
1393 t = btf__type_by_id(btf, t->type);
1400 * Fetch integer attribute of BTF map definition. Such attributes are
1401 * represented using a pointer to an array, in which dimensionality of array
1402 * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
1403 * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
1404 * type definition, while using only sizeof(void *) space in ELF data section.
1406 static bool get_map_field_int(const char *map_name, const struct btf *btf,
1407 const struct btf_type *def,
1408 const struct btf_member *m, __u32 *res)
1410 const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
1411 const char *name = btf__name_by_offset(btf, m->name_off);
1412 const struct btf_array *arr_info;
1413 const struct btf_type *arr_t;
1415 if (!btf_is_ptr(t)) {
1416 pr_warn("map '%s': attr '%s': expected PTR, got %u.\n",
1417 map_name, name, btf_kind(t));
1421 arr_t = btf__type_by_id(btf, t->type);
1423 pr_warn("map '%s': attr '%s': type [%u] not found.\n",
1424 map_name, name, t->type);
1427 if (!btf_is_array(arr_t)) {
1428 pr_warn("map '%s': attr '%s': expected ARRAY, got %u.\n",
1429 map_name, name, btf_kind(arr_t));
1432 arr_info = btf_array(arr_t);
1433 *res = arr_info->nelems;
1437 static int build_map_pin_path(struct bpf_map *map, const char *path)
1443 path = "/sys/fs/bpf";
1445 len = snprintf(buf, PATH_MAX, "%s/%s", path, bpf_map__name(map));
1448 else if (len >= PATH_MAX)
1449 return -ENAMETOOLONG;
1451 err = bpf_map__set_pin_path(map, buf);
1458 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
1459 const struct btf_type *sec,
1460 int var_idx, int sec_idx,
1461 const Elf_Data *data, bool strict,
1462 const char *pin_root_path)
1464 const struct btf_type *var, *def, *t;
1465 const struct btf_var_secinfo *vi;
1466 const struct btf_var *var_extra;
1467 const struct btf_member *m;
1468 const char *map_name;
1469 struct bpf_map *map;
1472 vi = btf_var_secinfos(sec) + var_idx;
1473 var = btf__type_by_id(obj->btf, vi->type);
1474 var_extra = btf_var(var);
1475 map_name = btf__name_by_offset(obj->btf, var->name_off);
1476 vlen = btf_vlen(var);
1478 if (map_name == NULL || map_name[0] == '\0') {
1479 pr_warn("map #%d: empty name.\n", var_idx);
1482 if ((__u64)vi->offset + vi->size > data->d_size) {
1483 pr_warn("map '%s' BTF data is corrupted.\n", map_name);
1486 if (!btf_is_var(var)) {
1487 pr_warn("map '%s': unexpected var kind %u.\n",
1488 map_name, btf_kind(var));
1491 if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED &&
1492 var_extra->linkage != BTF_VAR_STATIC) {
1493 pr_warn("map '%s': unsupported var linkage %u.\n",
1494 map_name, var_extra->linkage);
1498 def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
1499 if (!btf_is_struct(def)) {
1500 pr_warn("map '%s': unexpected def kind %u.\n",
1501 map_name, btf_kind(var));
1504 if (def->size > vi->size) {
1505 pr_warn("map '%s': invalid def size.\n", map_name);
1509 map = bpf_object__add_map(obj);
1511 return PTR_ERR(map);
1512 map->name = strdup(map_name);
1514 pr_warn("map '%s': failed to alloc map name.\n", map_name);
1517 map->libbpf_type = LIBBPF_MAP_UNSPEC;
1518 map->def.type = BPF_MAP_TYPE_UNSPEC;
1519 map->sec_idx = sec_idx;
1520 map->sec_offset = vi->offset;
1521 pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
1522 map_name, map->sec_idx, map->sec_offset);
1524 vlen = btf_vlen(def);
1525 m = btf_members(def);
1526 for (i = 0; i < vlen; i++, m++) {
1527 const char *name = btf__name_by_offset(obj->btf, m->name_off);
1530 pr_warn("map '%s': invalid field #%d.\n", map_name, i);
1533 if (strcmp(name, "type") == 0) {
1534 if (!get_map_field_int(map_name, obj->btf, def, m,
1537 pr_debug("map '%s': found type = %u.\n",
1538 map_name, map->def.type);
1539 } else if (strcmp(name, "max_entries") == 0) {
1540 if (!get_map_field_int(map_name, obj->btf, def, m,
1541 &map->def.max_entries))
1543 pr_debug("map '%s': found max_entries = %u.\n",
1544 map_name, map->def.max_entries);
1545 } else if (strcmp(name, "map_flags") == 0) {
1546 if (!get_map_field_int(map_name, obj->btf, def, m,
1547 &map->def.map_flags))
1549 pr_debug("map '%s': found map_flags = %u.\n",
1550 map_name, map->def.map_flags);
1551 } else if (strcmp(name, "key_size") == 0) {
1554 if (!get_map_field_int(map_name, obj->btf, def, m,
1557 pr_debug("map '%s': found key_size = %u.\n",
1559 if (map->def.key_size && map->def.key_size != sz) {
1560 pr_warn("map '%s': conflicting key size %u != %u.\n",
1561 map_name, map->def.key_size, sz);
1564 map->def.key_size = sz;
1565 } else if (strcmp(name, "key") == 0) {
1568 t = btf__type_by_id(obj->btf, m->type);
1570 pr_warn("map '%s': key type [%d] not found.\n",
1574 if (!btf_is_ptr(t)) {
1575 pr_warn("map '%s': key spec is not PTR: %u.\n",
1576 map_name, btf_kind(t));
1579 sz = btf__resolve_size(obj->btf, t->type);
1581 pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
1582 map_name, t->type, (ssize_t)sz);
1585 pr_debug("map '%s': found key [%u], sz = %zd.\n",
1586 map_name, t->type, (ssize_t)sz);
1587 if (map->def.key_size && map->def.key_size != sz) {
1588 pr_warn("map '%s': conflicting key size %u != %zd.\n",
1589 map_name, map->def.key_size, (ssize_t)sz);
1592 map->def.key_size = sz;
1593 map->btf_key_type_id = t->type;
1594 } else if (strcmp(name, "value_size") == 0) {
1597 if (!get_map_field_int(map_name, obj->btf, def, m,
1600 pr_debug("map '%s': found value_size = %u.\n",
1602 if (map->def.value_size && map->def.value_size != sz) {
1603 pr_warn("map '%s': conflicting value size %u != %u.\n",
1604 map_name, map->def.value_size, sz);
1607 map->def.value_size = sz;
1608 } else if (strcmp(name, "value") == 0) {
1611 t = btf__type_by_id(obj->btf, m->type);
1613 pr_warn("map '%s': value type [%d] not found.\n",
1617 if (!btf_is_ptr(t)) {
1618 pr_warn("map '%s': value spec is not PTR: %u.\n",
1619 map_name, btf_kind(t));
1622 sz = btf__resolve_size(obj->btf, t->type);
1624 pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
1625 map_name, t->type, (ssize_t)sz);
1628 pr_debug("map '%s': found value [%u], sz = %zd.\n",
1629 map_name, t->type, (ssize_t)sz);
1630 if (map->def.value_size && map->def.value_size != sz) {
1631 pr_warn("map '%s': conflicting value size %u != %zd.\n",
1632 map_name, map->def.value_size, (ssize_t)sz);
1635 map->def.value_size = sz;
1636 map->btf_value_type_id = t->type;
1637 } else if (strcmp(name, "pinning") == 0) {
1641 if (!get_map_field_int(map_name, obj->btf, def, m,
1644 pr_debug("map '%s': found pinning = %u.\n",
1647 if (val != LIBBPF_PIN_NONE &&
1648 val != LIBBPF_PIN_BY_NAME) {
1649 pr_warn("map '%s': invalid pinning value %u.\n",
1653 if (val == LIBBPF_PIN_BY_NAME) {
1654 err = build_map_pin_path(map, pin_root_path);
1656 pr_warn("map '%s': couldn't build pin path.\n",
1663 pr_warn("map '%s': unknown field '%s'.\n",
1667 pr_debug("map '%s': ignoring unknown field '%s'.\n",
1672 if (map->def.type == BPF_MAP_TYPE_UNSPEC) {
1673 pr_warn("map '%s': map type isn't specified.\n", map_name);
1680 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
1681 const char *pin_root_path)
1683 const struct btf_type *sec = NULL;
1684 int nr_types, i, vlen, err;
1685 const struct btf_type *t;
1690 if (obj->efile.btf_maps_shndx < 0)
1693 scn = elf_getscn(obj->efile.elf, obj->efile.btf_maps_shndx);
1695 data = elf_getdata(scn, NULL);
1696 if (!scn || !data) {
1697 pr_warn("failed to get Elf_Data from map section %d (%s)\n",
1698 obj->efile.maps_shndx, MAPS_ELF_SEC);
1702 nr_types = btf__get_nr_types(obj->btf);
1703 for (i = 1; i <= nr_types; i++) {
1704 t = btf__type_by_id(obj->btf, i);
1705 if (!btf_is_datasec(t))
1707 name = btf__name_by_offset(obj->btf, t->name_off);
1708 if (strcmp(name, MAPS_ELF_SEC) == 0) {
1715 pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
1719 vlen = btf_vlen(sec);
1720 for (i = 0; i < vlen; i++) {
1721 err = bpf_object__init_user_btf_map(obj, sec, i,
1722 obj->efile.btf_maps_shndx,
1732 static int bpf_object__init_maps(struct bpf_object *obj,
1733 const struct bpf_object_open_opts *opts)
1735 const char *pin_root_path;
1739 strict = !OPTS_GET(opts, relaxed_maps, false);
1740 pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
1742 err = bpf_object__init_user_maps(obj, strict);
1743 err = err ?: bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
1744 err = err ?: bpf_object__init_global_data_maps(obj);
1745 err = err ?: bpf_object__init_extern_map(obj);
1750 qsort(obj->maps, obj->nr_maps, sizeof(obj->maps[0]),
1756 static bool section_have_execinstr(struct bpf_object *obj, int idx)
1761 scn = elf_getscn(obj->efile.elf, idx);
1765 if (gelf_getshdr(scn, &sh) != &sh)
1768 if (sh.sh_flags & SHF_EXECINSTR)
1774 static void bpf_object__sanitize_btf(struct bpf_object *obj)
1776 bool has_datasec = obj->caps.btf_datasec;
1777 bool has_func = obj->caps.btf_func;
1778 struct btf *btf = obj->btf;
1782 if (!obj->btf || (has_func && has_datasec))
1785 for (i = 1; i <= btf__get_nr_types(btf); i++) {
1786 t = (struct btf_type *)btf__type_by_id(btf, i);
1788 if (!has_datasec && btf_is_var(t)) {
1789 /* replace VAR with INT */
1790 t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
1792 * using size = 1 is the safest choice, 4 will be too
1793 * big and cause kernel BTF validation failure if
1794 * original variable took less than 4 bytes
1797 *(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
1798 } else if (!has_datasec && btf_is_datasec(t)) {
1799 /* replace DATASEC with STRUCT */
1800 const struct btf_var_secinfo *v = btf_var_secinfos(t);
1801 struct btf_member *m = btf_members(t);
1802 struct btf_type *vt;
1805 name = (char *)btf__name_by_offset(btf, t->name_off);
1813 t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
1814 for (j = 0; j < vlen; j++, v++, m++) {
1815 /* order of field assignments is important */
1816 m->offset = v->offset * 8;
1818 /* preserve variable name as member name */
1819 vt = (void *)btf__type_by_id(btf, v->type);
1820 m->name_off = vt->name_off;
1822 } else if (!has_func && btf_is_func_proto(t)) {
1823 /* replace FUNC_PROTO with ENUM */
1825 t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
1826 t->size = sizeof(__u32); /* kernel enforced */
1827 } else if (!has_func && btf_is_func(t)) {
1828 /* replace FUNC with TYPEDEF */
1829 t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
1834 static void bpf_object__sanitize_btf_ext(struct bpf_object *obj)
1839 if (!obj->caps.btf_func) {
1840 btf_ext__free(obj->btf_ext);
1841 obj->btf_ext = NULL;
1845 static bool bpf_object__is_btf_mandatory(const struct bpf_object *obj)
1847 return obj->efile.btf_maps_shndx >= 0;
1850 static int bpf_object__init_btf(struct bpf_object *obj,
1852 Elf_Data *btf_ext_data)
1854 bool btf_required = bpf_object__is_btf_mandatory(obj);
1858 obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
1859 if (IS_ERR(obj->btf)) {
1860 pr_warn("Error loading ELF section %s: %d.\n",
1867 pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
1868 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
1871 obj->btf_ext = btf_ext__new(btf_ext_data->d_buf,
1872 btf_ext_data->d_size);
1873 if (IS_ERR(obj->btf_ext)) {
1874 pr_warn("Error loading ELF section %s: %ld. Ignored and continue.\n",
1875 BTF_EXT_ELF_SEC, PTR_ERR(obj->btf_ext));
1876 obj->btf_ext = NULL;
1881 if (err || IS_ERR(obj->btf)) {
1883 err = err ? : PTR_ERR(obj->btf);
1886 if (!IS_ERR_OR_NULL(obj->btf))
1887 btf__free(obj->btf);
1890 if (btf_required && !obj->btf) {
1891 pr_warn("BTF is required, but is missing or corrupted.\n");
1892 return err == 0 ? -ENOENT : err;
1897 static int bpf_object__finalize_btf(struct bpf_object *obj)
1904 err = btf__finalize_data(obj, obj->btf);
1908 pr_warn("Error finalizing %s: %d.\n", BTF_ELF_SEC, err);
1909 btf__free(obj->btf);
1911 btf_ext__free(obj->btf_ext);
1912 obj->btf_ext = NULL;
1914 if (bpf_object__is_btf_mandatory(obj)) {
1915 pr_warn("BTF is required, but is missing or corrupted.\n");
1921 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
1928 bpf_object__sanitize_btf(obj);
1929 bpf_object__sanitize_btf_ext(obj);
1931 err = btf__load(obj->btf);
1933 pr_warn("Error loading %s into kernel: %d.\n",
1935 btf__free(obj->btf);
1937 /* btf_ext can't exist without btf, so free it as well */
1939 btf_ext__free(obj->btf_ext);
1940 obj->btf_ext = NULL;
1943 if (bpf_object__is_btf_mandatory(obj))
1949 static int bpf_object__elf_collect(struct bpf_object *obj)
1951 Elf *elf = obj->efile.elf;
1952 GElf_Ehdr *ep = &obj->efile.ehdr;
1953 Elf_Data *btf_ext_data = NULL;
1954 Elf_Data *btf_data = NULL;
1955 Elf_Scn *scn = NULL;
1956 int idx = 0, err = 0;
1958 /* Elf is corrupted/truncated, avoid calling elf_strptr. */
1959 if (!elf_rawdata(elf_getscn(elf, ep->e_shstrndx), NULL)) {
1960 pr_warn("failed to get e_shstrndx from %s\n", obj->path);
1961 return -LIBBPF_ERRNO__FORMAT;
1964 while ((scn = elf_nextscn(elf, scn)) != NULL) {
1970 if (gelf_getshdr(scn, &sh) != &sh) {
1971 pr_warn("failed to get section(%d) header from %s\n",
1973 return -LIBBPF_ERRNO__FORMAT;
1976 name = elf_strptr(elf, ep->e_shstrndx, sh.sh_name);
1978 pr_warn("failed to get section(%d) name from %s\n",
1980 return -LIBBPF_ERRNO__FORMAT;
1983 data = elf_getdata(scn, 0);
1985 pr_warn("failed to get section(%d) data from %s(%s)\n",
1986 idx, name, obj->path);
1987 return -LIBBPF_ERRNO__FORMAT;
1989 pr_debug("section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
1990 idx, name, (unsigned long)data->d_size,
1991 (int)sh.sh_link, (unsigned long)sh.sh_flags,
1994 if (strcmp(name, "license") == 0) {
1995 err = bpf_object__init_license(obj,
2000 } else if (strcmp(name, "version") == 0) {
2001 err = bpf_object__init_kversion(obj,
2006 } else if (strcmp(name, "maps") == 0) {
2007 obj->efile.maps_shndx = idx;
2008 } else if (strcmp(name, MAPS_ELF_SEC) == 0) {
2009 obj->efile.btf_maps_shndx = idx;
2010 } else if (strcmp(name, BTF_ELF_SEC) == 0) {
2012 } else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
2013 btf_ext_data = data;
2014 } else if (sh.sh_type == SHT_SYMTAB) {
2015 if (obj->efile.symbols) {
2016 pr_warn("bpf: multiple SYMTAB in %s\n",
2018 return -LIBBPF_ERRNO__FORMAT;
2020 obj->efile.symbols = data;
2021 obj->efile.symbols_shndx = idx;
2022 obj->efile.strtabidx = sh.sh_link;
2023 } else if (sh.sh_type == SHT_PROGBITS && data->d_size > 0) {
2024 if (sh.sh_flags & SHF_EXECINSTR) {
2025 if (strcmp(name, ".text") == 0)
2026 obj->efile.text_shndx = idx;
2027 err = bpf_object__add_program(obj, data->d_buf,
2031 char errmsg[STRERR_BUFSIZE];
2034 cp = libbpf_strerror_r(-err, errmsg,
2036 pr_warn("failed to alloc program %s (%s): %s",
2037 name, obj->path, cp);
2040 } else if (strcmp(name, DATA_SEC) == 0) {
2041 obj->efile.data = data;
2042 obj->efile.data_shndx = idx;
2043 } else if (strcmp(name, RODATA_SEC) == 0) {
2044 obj->efile.rodata = data;
2045 obj->efile.rodata_shndx = idx;
2047 pr_debug("skip section(%d) %s\n", idx, name);
2049 } else if (sh.sh_type == SHT_REL) {
2050 int nr_sects = obj->efile.nr_reloc_sects;
2051 void *sects = obj->efile.reloc_sects;
2052 int sec = sh.sh_info; /* points to other section */
2054 /* Only do relo for section with exec instructions */
2055 if (!section_have_execinstr(obj, sec)) {
2056 pr_debug("skip relo %s(%d) for section(%d)\n",
2061 sects = reallocarray(sects, nr_sects + 1,
2062 sizeof(*obj->efile.reloc_sects));
2064 pr_warn("reloc_sects realloc failed\n");
2068 obj->efile.reloc_sects = sects;
2069 obj->efile.nr_reloc_sects++;
2071 obj->efile.reloc_sects[nr_sects].shdr = sh;
2072 obj->efile.reloc_sects[nr_sects].data = data;
2073 } else if (sh.sh_type == SHT_NOBITS &&
2074 strcmp(name, BSS_SEC) == 0) {
2075 obj->efile.bss = data;
2076 obj->efile.bss_shndx = idx;
2078 pr_debug("skip section(%d) %s\n", idx, name);
2082 if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
2083 pr_warn("Corrupted ELF file: index of strtab invalid\n");
2084 return -LIBBPF_ERRNO__FORMAT;
2086 return bpf_object__init_btf(obj, btf_data, btf_ext_data);
2089 static bool sym_is_extern(const GElf_Sym *sym)
2091 int bind = GELF_ST_BIND(sym->st_info);
2092 /* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
2093 return sym->st_shndx == SHN_UNDEF &&
2094 (bind == STB_GLOBAL || bind == STB_WEAK) &&
2095 GELF_ST_TYPE(sym->st_info) == STT_NOTYPE;
2098 static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
2100 const struct btf_type *t;
2101 const char *var_name;
2107 n = btf__get_nr_types(btf);
2108 for (i = 1; i <= n; i++) {
2109 t = btf__type_by_id(btf, i);
2114 var_name = btf__name_by_offset(btf, t->name_off);
2115 if (strcmp(var_name, ext_name))
2118 if (btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
2127 static enum extern_type find_extern_type(const struct btf *btf, int id,
2130 const struct btf_type *t;
2133 t = skip_mods_and_typedefs(btf, id, NULL);
2134 name = btf__name_by_offset(btf, t->name_off);
2138 switch (btf_kind(t)) {
2139 case BTF_KIND_INT: {
2140 int enc = btf_int_encoding(t);
2142 if (enc & BTF_INT_BOOL)
2143 return t->size == 1 ? EXT_BOOL : EXT_UNKNOWN;
2145 *is_signed = enc & BTF_INT_SIGNED;
2148 if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
2155 if (strcmp(name, "libbpf_tristate"))
2157 return EXT_TRISTATE;
2158 case BTF_KIND_ARRAY:
2159 if (btf_array(t)->nelems == 0)
2161 if (find_extern_type(btf, btf_array(t)->type, NULL) != EXT_CHAR)
2163 return EXT_CHAR_ARR;
2169 static int cmp_externs(const void *_a, const void *_b)
2171 const struct extern_desc *a = _a;
2172 const struct extern_desc *b = _b;
2174 /* descending order by alignment requirements */
2175 if (a->align != b->align)
2176 return a->align > b->align ? -1 : 1;
2177 /* ascending order by size, within same alignment class */
2179 return a->sz < b->sz ? -1 : 1;
2180 /* resolve ties by name */
2181 return strcmp(a->name, b->name);
2184 static int bpf_object__collect_externs(struct bpf_object *obj)
2186 const struct btf_type *t;
2187 struct extern_desc *ext;
2188 int i, n, off, btf_id;
2189 struct btf_type *sec;
2190 const char *ext_name;
2194 if (!obj->efile.symbols)
2197 scn = elf_getscn(obj->efile.elf, obj->efile.symbols_shndx);
2199 return -LIBBPF_ERRNO__FORMAT;
2200 if (gelf_getshdr(scn, &sh) != &sh)
2201 return -LIBBPF_ERRNO__FORMAT;
2202 n = sh.sh_size / sh.sh_entsize;
2204 pr_debug("looking for externs among %d symbols...\n", n);
2205 for (i = 0; i < n; i++) {
2208 if (!gelf_getsym(obj->efile.symbols, i, &sym))
2209 return -LIBBPF_ERRNO__FORMAT;
2210 if (!sym_is_extern(&sym))
2212 ext_name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
2214 if (!ext_name || !ext_name[0])
2218 ext = reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
2222 ext = &ext[obj->nr_extern];
2223 memset(ext, 0, sizeof(*ext));
2226 ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
2227 if (ext->btf_id <= 0) {
2228 pr_warn("failed to find BTF for extern '%s': %d\n",
2229 ext_name, ext->btf_id);
2232 t = btf__type_by_id(obj->btf, ext->btf_id);
2233 ext->name = btf__name_by_offset(obj->btf, t->name_off);
2235 ext->is_weak = GELF_ST_BIND(sym.st_info) == STB_WEAK;
2236 ext->sz = btf__resolve_size(obj->btf, t->type);
2238 pr_warn("failed to resolve size of extern '%s': %d\n",
2242 ext->align = btf__align_of(obj->btf, t->type);
2243 if (ext->align <= 0) {
2244 pr_warn("failed to determine alignment of extern '%s': %d\n",
2245 ext_name, ext->align);
2248 ext->type = find_extern_type(obj->btf, t->type,
2250 if (ext->type == EXT_UNKNOWN) {
2251 pr_warn("extern '%s' type is unsupported\n", ext_name);
2255 pr_debug("collected %d externs total\n", obj->nr_extern);
2257 if (!obj->nr_extern)
2260 /* sort externs by (alignment, size, name) and calculate their offsets
2262 qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
2264 for (i = 0; i < obj->nr_extern; i++) {
2265 ext = &obj->externs[i];
2266 ext->data_off = roundup(off, ext->align);
2267 off = ext->data_off + ext->sz;
2268 pr_debug("extern #%d: symbol %d, off %u, name %s\n",
2269 i, ext->sym_idx, ext->data_off, ext->name);
2272 btf_id = btf__find_by_name(obj->btf, EXTERN_SEC);
2274 pr_warn("no BTF info found for '%s' datasec\n", EXTERN_SEC);
2278 sec = (struct btf_type *)btf__type_by_id(obj->btf, btf_id);
2281 for (i = 0; i < n; i++) {
2282 struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
2284 t = btf__type_by_id(obj->btf, vs->type);
2285 ext_name = btf__name_by_offset(obj->btf, t->name_off);
2286 ext = find_extern_by_name(obj, ext_name);
2288 pr_warn("failed to find extern definition for BTF var '%s'\n",
2292 vs->offset = ext->data_off;
2293 btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
2299 static struct bpf_program *
2300 bpf_object__find_prog_by_idx(struct bpf_object *obj, int idx)
2302 struct bpf_program *prog;
2305 for (i = 0; i < obj->nr_programs; i++) {
2306 prog = &obj->programs[i];
2307 if (prog->idx == idx)
2313 struct bpf_program *
2314 bpf_object__find_program_by_title(const struct bpf_object *obj,
2317 struct bpf_program *pos;
2319 bpf_object__for_each_program(pos, obj) {
2320 if (pos->section_name && !strcmp(pos->section_name, title))
2326 struct bpf_program *
2327 bpf_object__find_program_by_name(const struct bpf_object *obj,
2330 struct bpf_program *prog;
2332 bpf_object__for_each_program(prog, obj) {
2333 if (!strcmp(prog->name, name))
2339 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
2342 return shndx == obj->efile.data_shndx ||
2343 shndx == obj->efile.bss_shndx ||
2344 shndx == obj->efile.rodata_shndx;
2347 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
2350 return shndx == obj->efile.maps_shndx ||
2351 shndx == obj->efile.btf_maps_shndx;
2354 static enum libbpf_map_type
2355 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
2357 if (shndx == obj->efile.data_shndx)
2358 return LIBBPF_MAP_DATA;
2359 else if (shndx == obj->efile.bss_shndx)
2360 return LIBBPF_MAP_BSS;
2361 else if (shndx == obj->efile.rodata_shndx)
2362 return LIBBPF_MAP_RODATA;
2363 else if (shndx == obj->efile.symbols_shndx)
2364 return LIBBPF_MAP_EXTERN;
2366 return LIBBPF_MAP_UNSPEC;
2369 static int bpf_program__record_reloc(struct bpf_program *prog,
2370 struct reloc_desc *reloc_desc,
2371 __u32 insn_idx, const char *name,
2372 const GElf_Sym *sym, const GElf_Rel *rel)
2374 struct bpf_insn *insn = &prog->insns[insn_idx];
2375 size_t map_idx, nr_maps = prog->obj->nr_maps;
2376 struct bpf_object *obj = prog->obj;
2377 __u32 shdr_idx = sym->st_shndx;
2378 enum libbpf_map_type type;
2379 struct bpf_map *map;
2381 /* sub-program call relocation */
2382 if (insn->code == (BPF_JMP | BPF_CALL)) {
2383 if (insn->src_reg != BPF_PSEUDO_CALL) {
2384 pr_warn("incorrect bpf_call opcode\n");
2385 return -LIBBPF_ERRNO__RELOC;
2387 /* text_shndx can be 0, if no default "main" program exists */
2388 if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
2389 pr_warn("bad call relo against section %u\n", shdr_idx);
2390 return -LIBBPF_ERRNO__RELOC;
2392 if (sym->st_value % 8) {
2393 pr_warn("bad call relo offset: %zu\n",
2394 (size_t)sym->st_value);
2395 return -LIBBPF_ERRNO__RELOC;
2397 reloc_desc->type = RELO_CALL;
2398 reloc_desc->insn_idx = insn_idx;
2399 reloc_desc->sym_off = sym->st_value;
2400 obj->has_pseudo_calls = true;
2404 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) {
2405 pr_warn("invalid relo for insns[%d].code 0x%x\n",
2406 insn_idx, insn->code);
2407 return -LIBBPF_ERRNO__RELOC;
2410 if (sym_is_extern(sym)) {
2411 int sym_idx = GELF_R_SYM(rel->r_info);
2412 int i, n = obj->nr_extern;
2413 struct extern_desc *ext;
2415 for (i = 0; i < n; i++) {
2416 ext = &obj->externs[i];
2417 if (ext->sym_idx == sym_idx)
2421 pr_warn("extern relo failed to find extern for sym %d\n",
2423 return -LIBBPF_ERRNO__RELOC;
2425 pr_debug("found extern #%d '%s' (sym %d, off %u) for insn %u\n",
2426 i, ext->name, ext->sym_idx, ext->data_off, insn_idx);
2427 reloc_desc->type = RELO_EXTERN;
2428 reloc_desc->insn_idx = insn_idx;
2429 reloc_desc->sym_off = ext->data_off;
2433 if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
2434 pr_warn("invalid relo for \'%s\' in special section 0x%x; forgot to initialize global var?..\n",
2436 return -LIBBPF_ERRNO__RELOC;
2439 type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
2441 /* generic map reference relocation */
2442 if (type == LIBBPF_MAP_UNSPEC) {
2443 if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
2444 pr_warn("bad map relo against section %u\n",
2446 return -LIBBPF_ERRNO__RELOC;
2448 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
2449 map = &obj->maps[map_idx];
2450 if (map->libbpf_type != type ||
2451 map->sec_idx != sym->st_shndx ||
2452 map->sec_offset != sym->st_value)
2454 pr_debug("found map %zd (%s, sec %d, off %zu) for insn %u\n",
2455 map_idx, map->name, map->sec_idx,
2456 map->sec_offset, insn_idx);
2459 if (map_idx >= nr_maps) {
2460 pr_warn("map relo failed to find map for sec %u, off %zu\n",
2461 shdr_idx, (size_t)sym->st_value);
2462 return -LIBBPF_ERRNO__RELOC;
2464 reloc_desc->type = RELO_LD64;
2465 reloc_desc->insn_idx = insn_idx;
2466 reloc_desc->map_idx = map_idx;
2467 reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
2471 /* global data map relocation */
2472 if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
2473 pr_warn("bad data relo against section %u\n", shdr_idx);
2474 return -LIBBPF_ERRNO__RELOC;
2476 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
2477 map = &obj->maps[map_idx];
2478 if (map->libbpf_type != type)
2480 pr_debug("found data map %zd (%s, sec %d, off %zu) for insn %u\n",
2481 map_idx, map->name, map->sec_idx, map->sec_offset,
2485 if (map_idx >= nr_maps) {
2486 pr_warn("data relo failed to find map for sec %u\n",
2488 return -LIBBPF_ERRNO__RELOC;
2491 reloc_desc->type = RELO_DATA;
2492 reloc_desc->insn_idx = insn_idx;
2493 reloc_desc->map_idx = map_idx;
2494 reloc_desc->sym_off = sym->st_value;
2499 bpf_program__collect_reloc(struct bpf_program *prog, GElf_Shdr *shdr,
2500 Elf_Data *data, struct bpf_object *obj)
2502 Elf_Data *symbols = obj->efile.symbols;
2505 pr_debug("collecting relocating info for: '%s'\n", prog->section_name);
2506 nrels = shdr->sh_size / shdr->sh_entsize;
2508 prog->reloc_desc = malloc(sizeof(*prog->reloc_desc) * nrels);
2509 if (!prog->reloc_desc) {
2510 pr_warn("failed to alloc memory in relocation\n");
2513 prog->nr_reloc = nrels;
2515 for (i = 0; i < nrels; i++) {
2521 if (!gelf_getrel(data, i, &rel)) {
2522 pr_warn("relocation: failed to get %d reloc\n", i);
2523 return -LIBBPF_ERRNO__FORMAT;
2525 if (!gelf_getsym(symbols, GELF_R_SYM(rel.r_info), &sym)) {
2526 pr_warn("relocation: symbol %"PRIx64" not found\n",
2527 GELF_R_SYM(rel.r_info));
2528 return -LIBBPF_ERRNO__FORMAT;
2530 if (rel.r_offset % sizeof(struct bpf_insn))
2531 return -LIBBPF_ERRNO__FORMAT;
2533 insn_idx = rel.r_offset / sizeof(struct bpf_insn);
2534 name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
2535 sym.st_name) ? : "<?>";
2537 pr_debug("relo for shdr %u, symb %zu, value %zu, type %d, bind %d, name %d (\'%s\'), insn %u\n",
2538 (__u32)sym.st_shndx, (size_t)GELF_R_SYM(rel.r_info),
2539 (size_t)sym.st_value, GELF_ST_TYPE(sym.st_info),
2540 GELF_ST_BIND(sym.st_info), sym.st_name, name,
2543 err = bpf_program__record_reloc(prog, &prog->reloc_desc[i],
2544 insn_idx, name, &sym, &rel);
2551 static int bpf_map_find_btf_info(struct bpf_object *obj, struct bpf_map *map)
2553 struct bpf_map_def *def = &map->def;
2554 __u32 key_type_id = 0, value_type_id = 0;
2557 /* if it's BTF-defined map, we don't need to search for type IDs */
2558 if (map->sec_idx == obj->efile.btf_maps_shndx)
2561 if (!bpf_map__is_internal(map)) {
2562 ret = btf__get_map_kv_tids(obj->btf, map->name, def->key_size,
2563 def->value_size, &key_type_id,
2567 * LLVM annotates global data differently in BTF, that is,
2568 * only as '.data', '.bss' or '.rodata'.
2570 ret = btf__find_by_name(obj->btf,
2571 libbpf_type_to_btf_name[map->libbpf_type]);
2576 map->btf_key_type_id = key_type_id;
2577 map->btf_value_type_id = bpf_map__is_internal(map) ?
2578 ret : value_type_id;
2582 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
2584 struct bpf_map_info info = {};
2585 __u32 len = sizeof(info);
2589 err = bpf_obj_get_info_by_fd(fd, &info, &len);
2593 new_name = strdup(info.name);
2597 new_fd = open("/", O_RDONLY | O_CLOEXEC);
2600 goto err_free_new_name;
2603 new_fd = dup3(fd, new_fd, O_CLOEXEC);
2606 goto err_close_new_fd;
2609 err = zclose(map->fd);
2612 goto err_close_new_fd;
2617 map->name = new_name;
2618 map->def.type = info.type;
2619 map->def.key_size = info.key_size;
2620 map->def.value_size = info.value_size;
2621 map->def.max_entries = info.max_entries;
2622 map->def.map_flags = info.map_flags;
2623 map->btf_key_type_id = info.btf_key_type_id;
2624 map->btf_value_type_id = info.btf_value_type_id;
2636 int bpf_map__resize(struct bpf_map *map, __u32 max_entries)
2638 if (!map || !max_entries)
2641 /* If map already created, its attributes can't be changed. */
2645 map->def.max_entries = max_entries;
2651 bpf_object__probe_name(struct bpf_object *obj)
2653 struct bpf_load_program_attr attr;
2654 char *cp, errmsg[STRERR_BUFSIZE];
2655 struct bpf_insn insns[] = {
2656 BPF_MOV64_IMM(BPF_REG_0, 0),
2661 /* make sure basic loading works */
2663 memset(&attr, 0, sizeof(attr));
2664 attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
2666 attr.insns_cnt = ARRAY_SIZE(insns);
2667 attr.license = "GPL";
2669 ret = bpf_load_program_xattr(&attr, NULL, 0);
2671 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
2672 pr_warn("Error in %s():%s(%d). Couldn't load basic 'r0 = 0' BPF program.\n",
2673 __func__, cp, errno);
2678 /* now try the same program, but with the name */
2681 ret = bpf_load_program_xattr(&attr, NULL, 0);
2691 bpf_object__probe_global_data(struct bpf_object *obj)
2693 struct bpf_load_program_attr prg_attr;
2694 struct bpf_create_map_attr map_attr;
2695 char *cp, errmsg[STRERR_BUFSIZE];
2696 struct bpf_insn insns[] = {
2697 BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16),
2698 BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42),
2699 BPF_MOV64_IMM(BPF_REG_0, 0),
2704 memset(&map_attr, 0, sizeof(map_attr));
2705 map_attr.map_type = BPF_MAP_TYPE_ARRAY;
2706 map_attr.key_size = sizeof(int);
2707 map_attr.value_size = 32;
2708 map_attr.max_entries = 1;
2710 map = bpf_create_map_xattr(&map_attr);
2712 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
2713 pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
2714 __func__, cp, errno);
2720 memset(&prg_attr, 0, sizeof(prg_attr));
2721 prg_attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
2722 prg_attr.insns = insns;
2723 prg_attr.insns_cnt = ARRAY_SIZE(insns);
2724 prg_attr.license = "GPL";
2726 ret = bpf_load_program_xattr(&prg_attr, NULL, 0);
2728 obj->caps.global_data = 1;
2736 static int bpf_object__probe_btf_func(struct bpf_object *obj)
2738 static const char strs[] = "\0int\0x\0a";
2739 /* void x(int a) {} */
2742 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
2743 /* FUNC_PROTO */ /* [2] */
2744 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
2745 BTF_PARAM_ENC(7, 1),
2746 /* FUNC x */ /* [3] */
2747 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0), 2),
2751 btf_fd = libbpf__load_raw_btf((char *)types, sizeof(types),
2752 strs, sizeof(strs));
2754 obj->caps.btf_func = 1;
2762 static int bpf_object__probe_btf_datasec(struct bpf_object *obj)
2764 static const char strs[] = "\0x\0.data";
2768 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
2769 /* VAR x */ /* [2] */
2770 BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
2772 /* DATASEC val */ /* [3] */
2773 BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC, 0, 1), 4),
2774 BTF_VAR_SECINFO_ENC(2, 0, 4),
2778 btf_fd = libbpf__load_raw_btf((char *)types, sizeof(types),
2779 strs, sizeof(strs));
2781 obj->caps.btf_datasec = 1;
2789 static int bpf_object__probe_array_mmap(struct bpf_object *obj)
2791 struct bpf_create_map_attr attr = {
2792 .map_type = BPF_MAP_TYPE_ARRAY,
2793 .map_flags = BPF_F_MMAPABLE,
2794 .key_size = sizeof(int),
2795 .value_size = sizeof(int),
2800 fd = bpf_create_map_xattr(&attr);
2802 obj->caps.array_mmap = 1;
2811 bpf_object__probe_caps(struct bpf_object *obj)
2813 int (*probe_fn[])(struct bpf_object *obj) = {
2814 bpf_object__probe_name,
2815 bpf_object__probe_global_data,
2816 bpf_object__probe_btf_func,
2817 bpf_object__probe_btf_datasec,
2818 bpf_object__probe_array_mmap,
2822 for (i = 0; i < ARRAY_SIZE(probe_fn); i++) {
2823 ret = probe_fn[i](obj);
2825 pr_debug("Probe #%d failed with %d.\n", i, ret);
2831 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
2833 struct bpf_map_info map_info = {};
2834 char msg[STRERR_BUFSIZE];
2837 map_info_len = sizeof(map_info);
2839 if (bpf_obj_get_info_by_fd(map_fd, &map_info, &map_info_len)) {
2840 pr_warn("failed to get map info for map FD %d: %s\n",
2841 map_fd, libbpf_strerror_r(errno, msg, sizeof(msg)));
2845 return (map_info.type == map->def.type &&
2846 map_info.key_size == map->def.key_size &&
2847 map_info.value_size == map->def.value_size &&
2848 map_info.max_entries == map->def.max_entries &&
2849 map_info.map_flags == map->def.map_flags);
2853 bpf_object__reuse_map(struct bpf_map *map)
2855 char *cp, errmsg[STRERR_BUFSIZE];
2858 pin_fd = bpf_obj_get(map->pin_path);
2861 if (err == -ENOENT) {
2862 pr_debug("found no pinned map to reuse at '%s'\n",
2867 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
2868 pr_warn("couldn't retrieve pinned map '%s': %s\n",
2873 if (!map_is_reuse_compat(map, pin_fd)) {
2874 pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
2880 err = bpf_map__reuse_fd(map, pin_fd);
2886 pr_debug("reused pinned map at '%s'\n", map->pin_path);
2892 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
2894 enum libbpf_map_type map_type = map->libbpf_type;
2895 char *cp, errmsg[STRERR_BUFSIZE];
2898 /* kernel already zero-initializes .bss map. */
2899 if (map_type == LIBBPF_MAP_BSS)
2902 err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
2905 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
2906 pr_warn("Error setting initial map(%s) contents: %s\n",
2911 /* Freeze .rodata and .extern map as read-only from syscall side. */
2912 if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_EXTERN) {
2913 err = bpf_map_freeze(map->fd);
2916 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
2917 pr_warn("Error freezing map(%s) as read-only: %s\n",
2926 bpf_object__create_maps(struct bpf_object *obj)
2928 struct bpf_create_map_attr create_attr = {};
2933 for (i = 0; i < obj->nr_maps; i++) {
2934 struct bpf_map *map = &obj->maps[i];
2935 struct bpf_map_def *def = &map->def;
2936 char *cp, errmsg[STRERR_BUFSIZE];
2937 int *pfd = &map->fd;
2939 if (map->pin_path) {
2940 err = bpf_object__reuse_map(map);
2942 pr_warn("error reusing pinned map %s\n",
2949 pr_debug("skip map create (preset) %s: fd=%d\n",
2950 map->name, map->fd);
2955 create_attr.name = map->name;
2956 create_attr.map_ifindex = map->map_ifindex;
2957 create_attr.map_type = def->type;
2958 create_attr.map_flags = def->map_flags;
2959 create_attr.key_size = def->key_size;
2960 create_attr.value_size = def->value_size;
2961 if (def->type == BPF_MAP_TYPE_PERF_EVENT_ARRAY &&
2962 !def->max_entries) {
2964 nr_cpus = libbpf_num_possible_cpus();
2966 pr_warn("failed to determine number of system CPUs: %d\n",
2971 pr_debug("map '%s': setting size to %d\n",
2972 map->name, nr_cpus);
2973 create_attr.max_entries = nr_cpus;
2975 create_attr.max_entries = def->max_entries;
2977 create_attr.btf_fd = 0;
2978 create_attr.btf_key_type_id = 0;
2979 create_attr.btf_value_type_id = 0;
2980 if (bpf_map_type__is_map_in_map(def->type) &&
2981 map->inner_map_fd >= 0)
2982 create_attr.inner_map_fd = map->inner_map_fd;
2984 if (obj->btf && !bpf_map_find_btf_info(obj, map)) {
2985 create_attr.btf_fd = btf__fd(obj->btf);
2986 create_attr.btf_key_type_id = map->btf_key_type_id;
2987 create_attr.btf_value_type_id = map->btf_value_type_id;
2990 *pfd = bpf_create_map_xattr(&create_attr);
2991 if (*pfd < 0 && (create_attr.btf_key_type_id ||
2992 create_attr.btf_value_type_id)) {
2994 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
2995 pr_warn("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
2996 map->name, cp, err);
2997 create_attr.btf_fd = 0;
2998 create_attr.btf_key_type_id = 0;
2999 create_attr.btf_value_type_id = 0;
3000 map->btf_key_type_id = 0;
3001 map->btf_value_type_id = 0;
3002 *pfd = bpf_create_map_xattr(&create_attr);
3010 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
3011 pr_warn("failed to create map (name: '%s'): %s(%d)\n",
3012 map->name, cp, err);
3014 for (j = 0; j < i; j++)
3015 zclose(obj->maps[j].fd);
3019 if (bpf_map__is_internal(map)) {
3020 err = bpf_object__populate_internal_map(obj, map);
3027 if (map->pin_path && !map->pinned) {
3028 err = bpf_map__pin(map, NULL);
3030 pr_warn("failed to auto-pin map name '%s' at '%s'\n",
3031 map->name, map->pin_path);
3036 pr_debug("created map %s: fd=%d\n", map->name, *pfd);
3043 check_btf_ext_reloc_err(struct bpf_program *prog, int err,
3044 void *btf_prog_info, const char *info_name)
3046 if (err != -ENOENT) {
3047 pr_warn("Error in loading %s for sec %s.\n",
3048 info_name, prog->section_name);
3052 /* err == -ENOENT (i.e. prog->section_name not found in btf_ext) */
3054 if (btf_prog_info) {
3056 * Some info has already been found but has problem
3057 * in the last btf_ext reloc. Must have to error out.
3059 pr_warn("Error in relocating %s for sec %s.\n",
3060 info_name, prog->section_name);
3064 /* Have problem loading the very first info. Ignore the rest. */
3065 pr_warn("Cannot find %s for main program sec %s. Ignore all %s.\n",
3066 info_name, prog->section_name, info_name);
3071 bpf_program_reloc_btf_ext(struct bpf_program *prog, struct bpf_object *obj,
3072 const char *section_name, __u32 insn_offset)
3076 if (!insn_offset || prog->func_info) {
3078 * !insn_offset => main program
3080 * For sub prog, the main program's func_info has to
3081 * be loaded first (i.e. prog->func_info != NULL)
3083 err = btf_ext__reloc_func_info(obj->btf, obj->btf_ext,
3084 section_name, insn_offset,
3086 &prog->func_info_cnt);
3088 return check_btf_ext_reloc_err(prog, err,
3092 prog->func_info_rec_size = btf_ext__func_info_rec_size(obj->btf_ext);
3095 if (!insn_offset || prog->line_info) {
3096 err = btf_ext__reloc_line_info(obj->btf, obj->btf_ext,
3097 section_name, insn_offset,
3099 &prog->line_info_cnt);
3101 return check_btf_ext_reloc_err(prog, err,
3105 prog->line_info_rec_size = btf_ext__line_info_rec_size(obj->btf_ext);
3111 #define BPF_CORE_SPEC_MAX_LEN 64
3113 /* represents BPF CO-RE field or array element accessor */
3114 struct bpf_core_accessor {
3115 __u32 type_id; /* struct/union type or array element type */
3116 __u32 idx; /* field index or array index */
3117 const char *name; /* field name or NULL for array accessor */
3120 struct bpf_core_spec {
3121 const struct btf *btf;
3122 /* high-level spec: named fields and array indices only */
3123 struct bpf_core_accessor spec[BPF_CORE_SPEC_MAX_LEN];
3124 /* high-level spec length */
3126 /* raw, low-level spec: 1-to-1 with accessor spec string */
3127 int raw_spec[BPF_CORE_SPEC_MAX_LEN];
3128 /* raw spec length */
3130 /* field bit offset represented by spec */
3134 static bool str_is_empty(const char *s)
3139 static bool is_flex_arr(const struct btf *btf,
3140 const struct bpf_core_accessor *acc,
3141 const struct btf_array *arr)
3143 const struct btf_type *t;
3145 /* not a flexible array, if not inside a struct or has non-zero size */
3146 if (!acc->name || arr->nelems > 0)
3149 /* has to be the last member of enclosing struct */
3150 t = btf__type_by_id(btf, acc->type_id);
3151 return acc->idx == btf_vlen(t) - 1;
3155 * Turn bpf_field_reloc into a low- and high-level spec representation,
3156 * validating correctness along the way, as well as calculating resulting
3157 * field bit offset, specified by accessor string. Low-level spec captures
3158 * every single level of nestedness, including traversing anonymous
3159 * struct/union members. High-level one only captures semantically meaningful
3160 * "turning points": named fields and array indicies.
3161 * E.g., for this case:
3164 * int __unimportant;
3172 * struct sample *s = ...;
3174 * int x = &s->a[3]; // access string = '0:1:2:3'
3176 * Low-level spec has 1:1 mapping with each element of access string (it's
3177 * just a parsed access string representation): [0, 1, 2, 3].
3179 * High-level spec will capture only 3 points:
3180 * - intial zero-index access by pointer (&s->... is the same as &s[0]...);
3181 * - field 'a' access (corresponds to '2' in low-level spec);
3182 * - array element #3 access (corresponds to '3' in low-level spec).
3185 static int bpf_core_spec_parse(const struct btf *btf,
3187 const char *spec_str,
3188 struct bpf_core_spec *spec)
3190 int access_idx, parsed_len, i;
3191 struct bpf_core_accessor *acc;
3192 const struct btf_type *t;
3197 if (str_is_empty(spec_str) || *spec_str == ':')
3200 memset(spec, 0, sizeof(*spec));
3203 /* parse spec_str="0:1:2:3:4" into array raw_spec=[0, 1, 2, 3, 4] */
3205 if (*spec_str == ':')
3207 if (sscanf(spec_str, "%d%n", &access_idx, &parsed_len) != 1)
3209 if (spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
3211 spec_str += parsed_len;
3212 spec->raw_spec[spec->raw_len++] = access_idx;
3215 if (spec->raw_len == 0)
3218 /* first spec value is always reloc type array index */
3219 t = skip_mods_and_typedefs(btf, type_id, &id);
3223 access_idx = spec->raw_spec[0];
3224 spec->spec[0].type_id = id;
3225 spec->spec[0].idx = access_idx;
3228 sz = btf__resolve_size(btf, id);
3231 spec->bit_offset = access_idx * sz * 8;
3233 for (i = 1; i < spec->raw_len; i++) {
3234 t = skip_mods_and_typedefs(btf, id, &id);
3238 access_idx = spec->raw_spec[i];
3239 acc = &spec->spec[spec->len];
3241 if (btf_is_composite(t)) {
3242 const struct btf_member *m;
3245 if (access_idx >= btf_vlen(t))
3248 bit_offset = btf_member_bit_offset(t, access_idx);
3249 spec->bit_offset += bit_offset;
3251 m = btf_members(t) + access_idx;
3253 name = btf__name_by_offset(btf, m->name_off);
3254 if (str_is_empty(name))
3258 acc->idx = access_idx;
3264 } else if (btf_is_array(t)) {
3265 const struct btf_array *a = btf_array(t);
3268 t = skip_mods_and_typedefs(btf, a->type, &id);
3272 flex = is_flex_arr(btf, acc - 1, a);
3273 if (!flex && access_idx >= a->nelems)
3276 spec->spec[spec->len].type_id = id;
3277 spec->spec[spec->len].idx = access_idx;
3280 sz = btf__resolve_size(btf, id);
3283 spec->bit_offset += access_idx * sz * 8;
3285 pr_warn("relo for [%u] %s (at idx %d) captures type [%d] of unexpected kind %d\n",
3286 type_id, spec_str, i, id, btf_kind(t));
3294 static bool bpf_core_is_flavor_sep(const char *s)
3296 /* check X___Y name pattern, where X and Y are not underscores */
3297 return s[0] != '_' && /* X */
3298 s[1] == '_' && s[2] == '_' && s[3] == '_' && /* ___ */
3299 s[4] != '_'; /* Y */
3302 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
3303 * before last triple underscore. Struct name part after last triple
3304 * underscore is ignored by BPF CO-RE relocation during relocation matching.
3306 static size_t bpf_core_essential_name_len(const char *name)
3308 size_t n = strlen(name);
3311 for (i = n - 5; i >= 0; i--) {
3312 if (bpf_core_is_flavor_sep(name + i))
3318 /* dynamically sized list of type IDs */
3324 static void bpf_core_free_cands(struct ids_vec *cand_ids)
3326 free(cand_ids->data);
3330 static struct ids_vec *bpf_core_find_cands(const struct btf *local_btf,
3331 __u32 local_type_id,
3332 const struct btf *targ_btf)
3334 size_t local_essent_len, targ_essent_len;
3335 const char *local_name, *targ_name;
3336 const struct btf_type *t;
3337 struct ids_vec *cand_ids;
3341 t = btf__type_by_id(local_btf, local_type_id);
3343 return ERR_PTR(-EINVAL);
3345 local_name = btf__name_by_offset(local_btf, t->name_off);
3346 if (str_is_empty(local_name))
3347 return ERR_PTR(-EINVAL);
3348 local_essent_len = bpf_core_essential_name_len(local_name);
3350 cand_ids = calloc(1, sizeof(*cand_ids));
3352 return ERR_PTR(-ENOMEM);
3354 n = btf__get_nr_types(targ_btf);
3355 for (i = 1; i <= n; i++) {
3356 t = btf__type_by_id(targ_btf, i);
3357 targ_name = btf__name_by_offset(targ_btf, t->name_off);
3358 if (str_is_empty(targ_name))
3361 targ_essent_len = bpf_core_essential_name_len(targ_name);
3362 if (targ_essent_len != local_essent_len)
3365 if (strncmp(local_name, targ_name, local_essent_len) == 0) {
3366 pr_debug("[%d] %s: found candidate [%d] %s\n",
3367 local_type_id, local_name, i, targ_name);
3368 new_ids = realloc(cand_ids->data, cand_ids->len + 1);
3373 cand_ids->data = new_ids;
3374 cand_ids->data[cand_ids->len++] = i;
3379 bpf_core_free_cands(cand_ids);
3380 return ERR_PTR(err);
3383 /* Check two types for compatibility, skipping const/volatile/restrict and
3384 * typedefs, to ensure we are relocating compatible entities:
3385 * - any two STRUCTs/UNIONs are compatible and can be mixed;
3386 * - any two FWDs are compatible, if their names match (modulo flavor suffix);
3387 * - any two PTRs are always compatible;
3388 * - for ENUMs, names should be the same (ignoring flavor suffix) or at
3389 * least one of enums should be anonymous;
3390 * - for ENUMs, check sizes, names are ignored;
3391 * - for INT, size and signedness are ignored;
3392 * - for ARRAY, dimensionality is ignored, element types are checked for
3393 * compatibility recursively;
3394 * - everything else shouldn't be ever a target of relocation.
3395 * These rules are not set in stone and probably will be adjusted as we get
3396 * more experience with using BPF CO-RE relocations.
3398 static int bpf_core_fields_are_compat(const struct btf *local_btf,
3400 const struct btf *targ_btf,
3403 const struct btf_type *local_type, *targ_type;
3406 local_type = skip_mods_and_typedefs(local_btf, local_id, &local_id);
3407 targ_type = skip_mods_and_typedefs(targ_btf, targ_id, &targ_id);
3408 if (!local_type || !targ_type)
3411 if (btf_is_composite(local_type) && btf_is_composite(targ_type))
3413 if (btf_kind(local_type) != btf_kind(targ_type))
3416 switch (btf_kind(local_type)) {
3420 case BTF_KIND_ENUM: {
3421 const char *local_name, *targ_name;
3422 size_t local_len, targ_len;
3424 local_name = btf__name_by_offset(local_btf,
3425 local_type->name_off);
3426 targ_name = btf__name_by_offset(targ_btf, targ_type->name_off);
3427 local_len = bpf_core_essential_name_len(local_name);
3428 targ_len = bpf_core_essential_name_len(targ_name);
3429 /* one of them is anonymous or both w/ same flavor-less names */
3430 return local_len == 0 || targ_len == 0 ||
3431 (local_len == targ_len &&
3432 strncmp(local_name, targ_name, local_len) == 0);
3435 /* just reject deprecated bitfield-like integers; all other
3436 * integers are by default compatible between each other
3438 return btf_int_offset(local_type) == 0 &&
3439 btf_int_offset(targ_type) == 0;
3440 case BTF_KIND_ARRAY:
3441 local_id = btf_array(local_type)->type;
3442 targ_id = btf_array(targ_type)->type;
3445 pr_warn("unexpected kind %d relocated, local [%d], target [%d]\n",
3446 btf_kind(local_type), local_id, targ_id);
3452 * Given single high-level named field accessor in local type, find
3453 * corresponding high-level accessor for a target type. Along the way,
3454 * maintain low-level spec for target as well. Also keep updating target
3457 * Searching is performed through recursive exhaustive enumeration of all
3458 * fields of a struct/union. If there are any anonymous (embedded)
3459 * structs/unions, they are recursively searched as well. If field with
3460 * desired name is found, check compatibility between local and target types,
3461 * before returning result.
3463 * 1 is returned, if field is found.
3464 * 0 is returned if no compatible field is found.
3465 * <0 is returned on error.
3467 static int bpf_core_match_member(const struct btf *local_btf,
3468 const struct bpf_core_accessor *local_acc,
3469 const struct btf *targ_btf,
3471 struct bpf_core_spec *spec,
3472 __u32 *next_targ_id)
3474 const struct btf_type *local_type, *targ_type;
3475 const struct btf_member *local_member, *m;
3476 const char *local_name, *targ_name;
3480 targ_type = skip_mods_and_typedefs(targ_btf, targ_id, &targ_id);
3483 if (!btf_is_composite(targ_type))
3486 local_id = local_acc->type_id;
3487 local_type = btf__type_by_id(local_btf, local_id);
3488 local_member = btf_members(local_type) + local_acc->idx;
3489 local_name = btf__name_by_offset(local_btf, local_member->name_off);
3491 n = btf_vlen(targ_type);
3492 m = btf_members(targ_type);
3493 for (i = 0; i < n; i++, m++) {
3496 bit_offset = btf_member_bit_offset(targ_type, i);
3498 /* too deep struct/union/array nesting */
3499 if (spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
3502 /* speculate this member will be the good one */
3503 spec->bit_offset += bit_offset;
3504 spec->raw_spec[spec->raw_len++] = i;
3506 targ_name = btf__name_by_offset(targ_btf, m->name_off);
3507 if (str_is_empty(targ_name)) {
3508 /* embedded struct/union, we need to go deeper */
3509 found = bpf_core_match_member(local_btf, local_acc,
3511 spec, next_targ_id);
3512 if (found) /* either found or error */
3514 } else if (strcmp(local_name, targ_name) == 0) {
3515 /* matching named field */
3516 struct bpf_core_accessor *targ_acc;
3518 targ_acc = &spec->spec[spec->len++];
3519 targ_acc->type_id = targ_id;
3521 targ_acc->name = targ_name;
3523 *next_targ_id = m->type;
3524 found = bpf_core_fields_are_compat(local_btf,
3528 spec->len--; /* pop accessor */
3531 /* member turned out not to be what we looked for */
3532 spec->bit_offset -= bit_offset;
3540 * Try to match local spec to a target type and, if successful, produce full
3541 * target spec (high-level, low-level + bit offset).
3543 static int bpf_core_spec_match(struct bpf_core_spec *local_spec,
3544 const struct btf *targ_btf, __u32 targ_id,
3545 struct bpf_core_spec *targ_spec)
3547 const struct btf_type *targ_type;
3548 const struct bpf_core_accessor *local_acc;
3549 struct bpf_core_accessor *targ_acc;
3552 memset(targ_spec, 0, sizeof(*targ_spec));
3553 targ_spec->btf = targ_btf;
3555 local_acc = &local_spec->spec[0];
3556 targ_acc = &targ_spec->spec[0];
3558 for (i = 0; i < local_spec->len; i++, local_acc++, targ_acc++) {
3559 targ_type = skip_mods_and_typedefs(targ_spec->btf, targ_id,
3564 if (local_acc->name) {
3565 matched = bpf_core_match_member(local_spec->btf,
3568 targ_spec, &targ_id);
3572 /* for i=0, targ_id is already treated as array element
3573 * type (because it's the original struct), for others
3574 * we should find array element type first
3577 const struct btf_array *a;
3580 if (!btf_is_array(targ_type))
3583 a = btf_array(targ_type);
3584 flex = is_flex_arr(targ_btf, targ_acc - 1, a);
3585 if (!flex && local_acc->idx >= a->nelems)
3587 if (!skip_mods_and_typedefs(targ_btf, a->type,
3592 /* too deep struct/union/array nesting */
3593 if (targ_spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
3596 targ_acc->type_id = targ_id;
3597 targ_acc->idx = local_acc->idx;
3598 targ_acc->name = NULL;
3600 targ_spec->raw_spec[targ_spec->raw_len] = targ_acc->idx;
3601 targ_spec->raw_len++;
3603 sz = btf__resolve_size(targ_btf, targ_id);
3606 targ_spec->bit_offset += local_acc->idx * sz * 8;
3613 static int bpf_core_calc_field_relo(const struct bpf_program *prog,
3614 const struct bpf_field_reloc *relo,
3615 const struct bpf_core_spec *spec,
3616 __u32 *val, bool *validate)
3618 const struct bpf_core_accessor *acc = &spec->spec[spec->len - 1];
3619 const struct btf_type *t = btf__type_by_id(spec->btf, acc->type_id);
3620 __u32 byte_off, byte_sz, bit_off, bit_sz;
3621 const struct btf_member *m;
3622 const struct btf_type *mt;
3626 /* a[n] accessor needs special handling */
3628 if (relo->kind == BPF_FIELD_BYTE_OFFSET) {
3629 *val = spec->bit_offset / 8;
3630 } else if (relo->kind == BPF_FIELD_BYTE_SIZE) {
3631 sz = btf__resolve_size(spec->btf, acc->type_id);
3636 pr_warn("prog '%s': relo %d at insn #%d can't be applied to array access\n",
3637 bpf_program__title(prog, false),
3638 relo->kind, relo->insn_off / 8);
3646 m = btf_members(t) + acc->idx;
3647 mt = skip_mods_and_typedefs(spec->btf, m->type, NULL);
3648 bit_off = spec->bit_offset;
3649 bit_sz = btf_member_bitfield_size(t, acc->idx);
3651 bitfield = bit_sz > 0;
3654 byte_off = bit_off / 8 / byte_sz * byte_sz;
3655 /* figure out smallest int size necessary for bitfield load */
3656 while (bit_off + bit_sz - byte_off * 8 > byte_sz * 8) {
3658 /* bitfield can't be read with 64-bit read */
3659 pr_warn("prog '%s': relo %d at insn #%d can't be satisfied for bitfield\n",
3660 bpf_program__title(prog, false),
3661 relo->kind, relo->insn_off / 8);
3665 byte_off = bit_off / 8 / byte_sz * byte_sz;
3668 sz = btf__resolve_size(spec->btf, m->type);
3672 byte_off = spec->bit_offset / 8;
3673 bit_sz = byte_sz * 8;
3676 /* for bitfields, all the relocatable aspects are ambiguous and we
3677 * might disagree with compiler, so turn off validation of expected
3678 * value, except for signedness
3681 *validate = !bitfield;
3683 switch (relo->kind) {
3684 case BPF_FIELD_BYTE_OFFSET:
3687 case BPF_FIELD_BYTE_SIZE:
3690 case BPF_FIELD_SIGNED:
3691 /* enums will be assumed unsigned */
3692 *val = btf_is_enum(mt) ||
3693 (btf_int_encoding(mt) & BTF_INT_SIGNED);
3695 *validate = true; /* signedness is never ambiguous */
3697 case BPF_FIELD_LSHIFT_U64:
3698 #if __BYTE_ORDER == __LITTLE_ENDIAN
3699 *val = 64 - (bit_off + bit_sz - byte_off * 8);
3701 *val = (8 - byte_sz) * 8 + (bit_off - byte_off * 8);
3704 case BPF_FIELD_RSHIFT_U64:
3707 *validate = true; /* right shift is never ambiguous */
3709 case BPF_FIELD_EXISTS:
3711 pr_warn("prog '%s': unknown relo %d at insn #%d\n",
3712 bpf_program__title(prog, false),
3713 relo->kind, relo->insn_off / 8);
3721 * Patch relocatable BPF instruction.
3723 * Patched value is determined by relocation kind and target specification.
3724 * For field existence relocation target spec will be NULL if field is not
3726 * Expected insn->imm value is determined using relocation kind and local
3727 * spec, and is checked before patching instruction. If actual insn->imm value
3728 * is wrong, bail out with error.
3730 * Currently three kinds of BPF instructions are supported:
3731 * 1. rX = <imm> (assignment with immediate operand);
3732 * 2. rX += <imm> (arithmetic operations with immediate operand);
3734 static int bpf_core_reloc_insn(struct bpf_program *prog,
3735 const struct bpf_field_reloc *relo,
3736 const struct bpf_core_spec *local_spec,
3737 const struct bpf_core_spec *targ_spec)
3739 bool failed = false, validate = true;
3740 __u32 orig_val, new_val;
3741 struct bpf_insn *insn;
3745 if (relo->insn_off % sizeof(struct bpf_insn))
3747 insn_idx = relo->insn_off / sizeof(struct bpf_insn);
3749 if (relo->kind == BPF_FIELD_EXISTS) {
3750 orig_val = 1; /* can't generate EXISTS relo w/o local field */
3751 new_val = targ_spec ? 1 : 0;
3752 } else if (!targ_spec) {
3754 new_val = (__u32)-1;
3756 err = bpf_core_calc_field_relo(prog, relo, local_spec,
3757 &orig_val, &validate);
3760 err = bpf_core_calc_field_relo(prog, relo, targ_spec,
3766 insn = &prog->insns[insn_idx];
3767 class = BPF_CLASS(insn->code);
3769 if (class == BPF_ALU || class == BPF_ALU64) {
3770 if (BPF_SRC(insn->code) != BPF_K)
3772 if (!failed && validate && insn->imm != orig_val) {
3773 pr_warn("prog '%s': unexpected insn #%d value: got %u, exp %u -> %u\n",
3774 bpf_program__title(prog, false), insn_idx,
3775 insn->imm, orig_val, new_val);
3778 orig_val = insn->imm;
3779 insn->imm = new_val;
3780 pr_debug("prog '%s': patched insn #%d (ALU/ALU64)%s imm %u -> %u\n",
3781 bpf_program__title(prog, false), insn_idx,
3782 failed ? " w/ failed reloc" : "", orig_val, new_val);
3784 pr_warn("prog '%s': trying to relocate unrecognized insn #%d, code:%x, src:%x, dst:%x, off:%x, imm:%x\n",
3785 bpf_program__title(prog, false),
3786 insn_idx, insn->code, insn->src_reg, insn->dst_reg,
3787 insn->off, insn->imm);
3794 static struct btf *btf_load_raw(const char *path)
3802 if (stat(path, &st))
3803 return ERR_PTR(-errno);
3805 data = malloc(st.st_size);
3807 return ERR_PTR(-ENOMEM);
3809 f = fopen(path, "rb");
3811 btf = ERR_PTR(-errno);
3815 read_cnt = fread(data, 1, st.st_size, f);
3817 if (read_cnt < st.st_size) {
3818 btf = ERR_PTR(-EBADF);
3822 btf = btf__new(data, read_cnt);
3830 * Probe few well-known locations for vmlinux kernel image and try to load BTF
3831 * data out of it to use for target BTF.
3833 static struct btf *bpf_core_find_kernel_btf(void)
3836 const char *path_fmt;
3839 /* try canonical vmlinux BTF through sysfs first */
3840 { "/sys/kernel/btf/vmlinux", true /* raw BTF */ },
3841 /* fall back to trying to find vmlinux ELF on disk otherwise */
3842 { "/boot/vmlinux-%1$s" },
3843 { "/lib/modules/%1$s/vmlinux-%1$s" },
3844 { "/lib/modules/%1$s/build/vmlinux" },
3845 { "/usr/lib/modules/%1$s/kernel/vmlinux" },
3846 { "/usr/lib/debug/boot/vmlinux-%1$s" },
3847 { "/usr/lib/debug/boot/vmlinux-%1$s.debug" },
3848 { "/usr/lib/debug/lib/modules/%1$s/vmlinux" },
3850 char path[PATH_MAX + 1];
3857 for (i = 0; i < ARRAY_SIZE(locations); i++) {
3858 snprintf(path, PATH_MAX, locations[i].path_fmt, buf.release);
3860 if (access(path, R_OK))
3863 if (locations[i].raw_btf)
3864 btf = btf_load_raw(path);
3866 btf = btf__parse_elf(path, NULL);
3868 pr_debug("loading kernel BTF '%s': %ld\n",
3869 path, IS_ERR(btf) ? PTR_ERR(btf) : 0);
3876 pr_warn("failed to find valid kernel BTF\n");
3877 return ERR_PTR(-ESRCH);
3880 /* Output spec definition in the format:
3881 * [<type-id>] (<type-name>) + <raw-spec> => <offset>@<spec>,
3882 * where <spec> is a C-syntax view of recorded field access, e.g.: x.a[3].b
3884 static void bpf_core_dump_spec(int level, const struct bpf_core_spec *spec)
3886 const struct btf_type *t;
3891 type_id = spec->spec[0].type_id;
3892 t = btf__type_by_id(spec->btf, type_id);
3893 s = btf__name_by_offset(spec->btf, t->name_off);
3894 libbpf_print(level, "[%u] %s + ", type_id, s);
3896 for (i = 0; i < spec->raw_len; i++)
3897 libbpf_print(level, "%d%s", spec->raw_spec[i],
3898 i == spec->raw_len - 1 ? " => " : ":");
3900 libbpf_print(level, "%u.%u @ &x",
3901 spec->bit_offset / 8, spec->bit_offset % 8);
3903 for (i = 0; i < spec->len; i++) {
3904 if (spec->spec[i].name)
3905 libbpf_print(level, ".%s", spec->spec[i].name);
3907 libbpf_print(level, "[%u]", spec->spec[i].idx);
3912 static size_t bpf_core_hash_fn(const void *key, void *ctx)
3917 static bool bpf_core_equal_fn(const void *k1, const void *k2, void *ctx)
3922 static void *u32_as_hash_key(__u32 x)
3924 return (void *)(uintptr_t)x;
3928 * CO-RE relocate single instruction.
3930 * The outline and important points of the algorithm:
3931 * 1. For given local type, find corresponding candidate target types.
3932 * Candidate type is a type with the same "essential" name, ignoring
3933 * everything after last triple underscore (___). E.g., `sample`,
3934 * `sample___flavor_one`, `sample___flavor_another_one`, are all candidates
3935 * for each other. Names with triple underscore are referred to as
3936 * "flavors" and are useful, among other things, to allow to
3937 * specify/support incompatible variations of the same kernel struct, which
3938 * might differ between different kernel versions and/or build
3941 * N.B. Struct "flavors" could be generated by bpftool's BTF-to-C
3942 * converter, when deduplicated BTF of a kernel still contains more than
3943 * one different types with the same name. In that case, ___2, ___3, etc
3944 * are appended starting from second name conflict. But start flavors are
3945 * also useful to be defined "locally", in BPF program, to extract same
3946 * data from incompatible changes between different kernel
3947 * versions/configurations. For instance, to handle field renames between
3948 * kernel versions, one can use two flavors of the struct name with the
3949 * same common name and use conditional relocations to extract that field,
3950 * depending on target kernel version.
3951 * 2. For each candidate type, try to match local specification to this
3952 * candidate target type. Matching involves finding corresponding
3953 * high-level spec accessors, meaning that all named fields should match,
3954 * as well as all array accesses should be within the actual bounds. Also,
3955 * types should be compatible (see bpf_core_fields_are_compat for details).
3956 * 3. It is supported and expected that there might be multiple flavors
3957 * matching the spec. As long as all the specs resolve to the same set of
3958 * offsets across all candidates, there is no error. If there is any
3959 * ambiguity, CO-RE relocation will fail. This is necessary to accomodate
3960 * imprefection of BTF deduplication, which can cause slight duplication of
3961 * the same BTF type, if some directly or indirectly referenced (by
3962 * pointer) type gets resolved to different actual types in different
3963 * object files. If such situation occurs, deduplicated BTF will end up
3964 * with two (or more) structurally identical types, which differ only in
3965 * types they refer to through pointer. This should be OK in most cases and
3967 * 4. Candidate types search is performed by linearly scanning through all
3968 * types in target BTF. It is anticipated that this is overall more
3969 * efficient memory-wise and not significantly worse (if not better)
3970 * CPU-wise compared to prebuilding a map from all local type names to
3971 * a list of candidate type names. It's also sped up by caching resolved
3972 * list of matching candidates per each local "root" type ID, that has at
3973 * least one bpf_field_reloc associated with it. This list is shared
3974 * between multiple relocations for the same type ID and is updated as some
3975 * of the candidates are pruned due to structural incompatibility.
3977 static int bpf_core_reloc_field(struct bpf_program *prog,
3978 const struct bpf_field_reloc *relo,
3980 const struct btf *local_btf,
3981 const struct btf *targ_btf,
3982 struct hashmap *cand_cache)
3984 const char *prog_name = bpf_program__title(prog, false);
3985 struct bpf_core_spec local_spec, cand_spec, targ_spec;
3986 const void *type_key = u32_as_hash_key(relo->type_id);
3987 const struct btf_type *local_type, *cand_type;
3988 const char *local_name, *cand_name;
3989 struct ids_vec *cand_ids;
3990 __u32 local_id, cand_id;
3991 const char *spec_str;
3994 local_id = relo->type_id;
3995 local_type = btf__type_by_id(local_btf, local_id);
3999 local_name = btf__name_by_offset(local_btf, local_type->name_off);
4000 if (str_is_empty(local_name))
4003 spec_str = btf__name_by_offset(local_btf, relo->access_str_off);
4004 if (str_is_empty(spec_str))
4007 err = bpf_core_spec_parse(local_btf, local_id, spec_str, &local_spec);
4009 pr_warn("prog '%s': relo #%d: parsing [%d] %s + %s failed: %d\n",
4010 prog_name, relo_idx, local_id, local_name, spec_str,
4015 pr_debug("prog '%s': relo #%d: kind %d, spec is ", prog_name, relo_idx,
4017 bpf_core_dump_spec(LIBBPF_DEBUG, &local_spec);
4018 libbpf_print(LIBBPF_DEBUG, "\n");
4020 if (!hashmap__find(cand_cache, type_key, (void **)&cand_ids)) {
4021 cand_ids = bpf_core_find_cands(local_btf, local_id, targ_btf);
4022 if (IS_ERR(cand_ids)) {
4023 pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s: %ld",
4024 prog_name, relo_idx, local_id, local_name,
4026 return PTR_ERR(cand_ids);
4028 err = hashmap__set(cand_cache, type_key, cand_ids, NULL, NULL);
4030 bpf_core_free_cands(cand_ids);
4035 for (i = 0, j = 0; i < cand_ids->len; i++) {
4036 cand_id = cand_ids->data[i];
4037 cand_type = btf__type_by_id(targ_btf, cand_id);
4038 cand_name = btf__name_by_offset(targ_btf, cand_type->name_off);
4040 err = bpf_core_spec_match(&local_spec, targ_btf,
4041 cand_id, &cand_spec);
4042 pr_debug("prog '%s': relo #%d: matching candidate #%d %s against spec ",
4043 prog_name, relo_idx, i, cand_name);
4044 bpf_core_dump_spec(LIBBPF_DEBUG, &cand_spec);
4045 libbpf_print(LIBBPF_DEBUG, ": %d\n", err);
4047 pr_warn("prog '%s': relo #%d: matching error: %d\n",
4048 prog_name, relo_idx, err);
4055 targ_spec = cand_spec;
4056 } else if (cand_spec.bit_offset != targ_spec.bit_offset) {
4057 /* if there are many candidates, they should all
4058 * resolve to the same bit offset
4060 pr_warn("prog '%s': relo #%d: offset ambiguity: %u != %u\n",
4061 prog_name, relo_idx, cand_spec.bit_offset,
4062 targ_spec.bit_offset);
4066 cand_ids->data[j++] = cand_spec.spec[0].type_id;
4070 * For BPF_FIELD_EXISTS relo or when relaxed CO-RE reloc mode is
4071 * requested, it's expected that we might not find any candidates.
4072 * In this case, if field wasn't found in any candidate, the list of
4073 * candidates shouldn't change at all, we'll just handle relocating
4074 * appropriately, depending on relo's kind.
4079 if (j == 0 && !prog->obj->relaxed_core_relocs &&
4080 relo->kind != BPF_FIELD_EXISTS) {
4081 pr_warn("prog '%s': relo #%d: no matching targets found for [%d] %s + %s\n",
4082 prog_name, relo_idx, local_id, local_name, spec_str);
4086 /* bpf_core_reloc_insn should know how to handle missing targ_spec */
4087 err = bpf_core_reloc_insn(prog, relo, &local_spec,
4088 j ? &targ_spec : NULL);
4090 pr_warn("prog '%s': relo #%d: failed to patch insn at offset %d: %d\n",
4091 prog_name, relo_idx, relo->insn_off, err);
4099 bpf_core_reloc_fields(struct bpf_object *obj, const char *targ_btf_path)
4101 const struct btf_ext_info_sec *sec;
4102 const struct bpf_field_reloc *rec;
4103 const struct btf_ext_info *seg;
4104 struct hashmap_entry *entry;
4105 struct hashmap *cand_cache = NULL;
4106 struct bpf_program *prog;
4107 struct btf *targ_btf;
4108 const char *sec_name;
4112 targ_btf = btf__parse_elf(targ_btf_path, NULL);
4114 targ_btf = bpf_core_find_kernel_btf();
4115 if (IS_ERR(targ_btf)) {
4116 pr_warn("failed to get target BTF: %ld\n", PTR_ERR(targ_btf));
4117 return PTR_ERR(targ_btf);
4120 cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
4121 if (IS_ERR(cand_cache)) {
4122 err = PTR_ERR(cand_cache);
4126 seg = &obj->btf_ext->field_reloc_info;
4127 for_each_btf_ext_sec(seg, sec) {
4128 sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
4129 if (str_is_empty(sec_name)) {
4133 prog = bpf_object__find_program_by_title(obj, sec_name);
4135 pr_warn("failed to find program '%s' for CO-RE offset relocation\n",
4141 pr_debug("prog '%s': performing %d CO-RE offset relocs\n",
4142 sec_name, sec->num_info);
4144 for_each_btf_ext_rec(seg, sec, i, rec) {
4145 err = bpf_core_reloc_field(prog, rec, i, obj->btf,
4146 targ_btf, cand_cache);
4148 pr_warn("prog '%s': relo #%d: failed to relocate: %d\n",
4156 btf__free(targ_btf);
4157 if (!IS_ERR_OR_NULL(cand_cache)) {
4158 hashmap__for_each_entry(cand_cache, entry, i) {
4159 bpf_core_free_cands(entry->value);
4161 hashmap__free(cand_cache);
4167 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
4171 if (obj->btf_ext->field_reloc_info.len)
4172 err = bpf_core_reloc_fields(obj, targ_btf_path);
4178 bpf_program__reloc_text(struct bpf_program *prog, struct bpf_object *obj,
4179 struct reloc_desc *relo)
4181 struct bpf_insn *insn, *new_insn;
4182 struct bpf_program *text;
4186 if (prog->idx == obj->efile.text_shndx) {
4187 pr_warn("relo in .text insn %d into off %d (insn #%d)\n",
4188 relo->insn_idx, relo->sym_off, relo->sym_off / 8);
4189 return -LIBBPF_ERRNO__RELOC;
4192 if (prog->main_prog_cnt == 0) {
4193 text = bpf_object__find_prog_by_idx(obj, obj->efile.text_shndx);
4195 pr_warn("no .text section found yet relo into text exist\n");
4196 return -LIBBPF_ERRNO__RELOC;
4198 new_cnt = prog->insns_cnt + text->insns_cnt;
4199 new_insn = reallocarray(prog->insns, new_cnt, sizeof(*insn));
4201 pr_warn("oom in prog realloc\n");
4204 prog->insns = new_insn;
4207 err = bpf_program_reloc_btf_ext(prog, obj,
4214 memcpy(new_insn + prog->insns_cnt, text->insns,
4215 text->insns_cnt * sizeof(*insn));
4216 prog->main_prog_cnt = prog->insns_cnt;
4217 prog->insns_cnt = new_cnt;
4218 pr_debug("added %zd insn from %s to prog %s\n",
4219 text->insns_cnt, text->section_name,
4220 prog->section_name);
4222 insn = &prog->insns[relo->insn_idx];
4223 insn->imm += relo->sym_off / 8 + prog->main_prog_cnt - relo->insn_idx;
4228 bpf_program__relocate(struct bpf_program *prog, struct bpf_object *obj)
4236 err = bpf_program_reloc_btf_ext(prog, obj,
4237 prog->section_name, 0);
4242 if (!prog->reloc_desc)
4245 for (i = 0; i < prog->nr_reloc; i++) {
4246 struct reloc_desc *relo = &prog->reloc_desc[i];
4247 struct bpf_insn *insn = &prog->insns[relo->insn_idx];
4249 if (relo->insn_idx + 1 >= (int)prog->insns_cnt) {
4250 pr_warn("relocation out of range: '%s'\n",
4251 prog->section_name);
4252 return -LIBBPF_ERRNO__RELOC;
4255 switch (relo->type) {
4257 insn[0].src_reg = BPF_PSEUDO_MAP_FD;
4258 insn[0].imm = obj->maps[relo->map_idx].fd;
4261 insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
4262 insn[1].imm = insn[0].imm + relo->sym_off;
4263 insn[0].imm = obj->maps[relo->map_idx].fd;
4266 insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
4267 insn[0].imm = obj->maps[obj->extern_map_idx].fd;
4268 insn[1].imm = relo->sym_off;
4271 err = bpf_program__reloc_text(prog, obj, relo);
4276 pr_warn("relo #%d: bad relo type %d\n", i, relo->type);
4281 zfree(&prog->reloc_desc);
4287 bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
4289 struct bpf_program *prog;
4294 err = bpf_object__relocate_core(obj, targ_btf_path);
4296 pr_warn("failed to perform CO-RE relocations: %d\n",
4301 for (i = 0; i < obj->nr_programs; i++) {
4302 prog = &obj->programs[i];
4304 err = bpf_program__relocate(prog, obj);
4306 pr_warn("failed to relocate '%s'\n", prog->section_name);
4313 static int bpf_object__collect_reloc(struct bpf_object *obj)
4317 if (!obj_elf_valid(obj)) {
4318 pr_warn("Internal error: elf object is closed\n");
4319 return -LIBBPF_ERRNO__INTERNAL;
4322 for (i = 0; i < obj->efile.nr_reloc_sects; i++) {
4323 GElf_Shdr *shdr = &obj->efile.reloc_sects[i].shdr;
4324 Elf_Data *data = obj->efile.reloc_sects[i].data;
4325 int idx = shdr->sh_info;
4326 struct bpf_program *prog;
4328 if (shdr->sh_type != SHT_REL) {
4329 pr_warn("internal error at %d\n", __LINE__);
4330 return -LIBBPF_ERRNO__INTERNAL;
4333 prog = bpf_object__find_prog_by_idx(obj, idx);
4335 pr_warn("relocation failed: no section(%d)\n", idx);
4336 return -LIBBPF_ERRNO__RELOC;
4339 err = bpf_program__collect_reloc(prog, shdr, data, obj);
4347 load_program(struct bpf_program *prog, struct bpf_insn *insns, int insns_cnt,
4348 char *license, __u32 kern_version, int *pfd)
4350 struct bpf_load_program_attr load_attr;
4351 char *cp, errmsg[STRERR_BUFSIZE];
4352 int log_buf_size = BPF_LOG_BUF_SIZE;
4356 if (!insns || !insns_cnt)
4359 memset(&load_attr, 0, sizeof(struct bpf_load_program_attr));
4360 load_attr.prog_type = prog->type;
4361 load_attr.expected_attach_type = prog->expected_attach_type;
4362 if (prog->caps->name)
4363 load_attr.name = prog->name;
4364 load_attr.insns = insns;
4365 load_attr.insns_cnt = insns_cnt;
4366 load_attr.license = license;
4367 if (prog->type == BPF_PROG_TYPE_TRACING) {
4368 load_attr.attach_prog_fd = prog->attach_prog_fd;
4369 load_attr.attach_btf_id = prog->attach_btf_id;
4371 load_attr.kern_version = kern_version;
4372 load_attr.prog_ifindex = prog->prog_ifindex;
4374 /* if .BTF.ext was loaded, kernel supports associated BTF for prog */
4375 if (prog->obj->btf_ext)
4376 btf_fd = bpf_object__btf_fd(prog->obj);
4379 load_attr.prog_btf_fd = btf_fd >= 0 ? btf_fd : 0;
4380 load_attr.func_info = prog->func_info;
4381 load_attr.func_info_rec_size = prog->func_info_rec_size;
4382 load_attr.func_info_cnt = prog->func_info_cnt;
4383 load_attr.line_info = prog->line_info;
4384 load_attr.line_info_rec_size = prog->line_info_rec_size;
4385 load_attr.line_info_cnt = prog->line_info_cnt;
4386 load_attr.log_level = prog->log_level;
4387 load_attr.prog_flags = prog->prog_flags;
4390 log_buf = malloc(log_buf_size);
4392 pr_warn("Alloc log buffer for bpf loader error, continue without log\n");
4394 ret = bpf_load_program_xattr(&load_attr, log_buf, log_buf_size);
4397 if (load_attr.log_level)
4398 pr_debug("verifier log:\n%s", log_buf);
4404 if (errno == ENOSPC) {
4410 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
4411 pr_warn("load bpf program failed: %s\n", cp);
4414 if (log_buf && log_buf[0] != '\0') {
4415 ret = -LIBBPF_ERRNO__VERIFY;
4416 pr_warn("-- BEGIN DUMP LOG ---\n");
4417 pr_warn("\n%s\n", log_buf);
4418 pr_warn("-- END LOG --\n");
4419 } else if (load_attr.insns_cnt >= BPF_MAXINSNS) {
4420 pr_warn("Program too large (%zu insns), at most %d insns\n",
4421 load_attr.insns_cnt, BPF_MAXINSNS);
4422 ret = -LIBBPF_ERRNO__PROG2BIG;
4423 } else if (load_attr.prog_type != BPF_PROG_TYPE_KPROBE) {
4424 /* Wrong program type? */
4427 load_attr.prog_type = BPF_PROG_TYPE_KPROBE;
4428 load_attr.expected_attach_type = 0;
4429 fd = bpf_load_program_xattr(&load_attr, NULL, 0);
4432 ret = -LIBBPF_ERRNO__PROGTYPE;
4442 static int libbpf_find_attach_btf_id(const char *name,
4443 enum bpf_attach_type attach_type,
4444 __u32 attach_prog_fd);
4446 int bpf_program__load(struct bpf_program *prog, char *license, __u32 kern_ver)
4448 int err = 0, fd, i, btf_id;
4450 if (prog->type == BPF_PROG_TYPE_TRACING) {
4451 btf_id = libbpf_find_attach_btf_id(prog->section_name,
4452 prog->expected_attach_type,
4453 prog->attach_prog_fd);
4456 prog->attach_btf_id = btf_id;
4459 if (prog->instances.nr < 0 || !prog->instances.fds) {
4460 if (prog->preprocessor) {
4461 pr_warn("Internal error: can't load program '%s'\n",
4462 prog->section_name);
4463 return -LIBBPF_ERRNO__INTERNAL;
4466 prog->instances.fds = malloc(sizeof(int));
4467 if (!prog->instances.fds) {
4468 pr_warn("Not enough memory for BPF fds\n");
4471 prog->instances.nr = 1;
4472 prog->instances.fds[0] = -1;
4475 if (!prog->preprocessor) {
4476 if (prog->instances.nr != 1) {
4477 pr_warn("Program '%s' is inconsistent: nr(%d) != 1\n",
4478 prog->section_name, prog->instances.nr);
4480 err = load_program(prog, prog->insns, prog->insns_cnt,
4481 license, kern_ver, &fd);
4483 prog->instances.fds[0] = fd;
4487 for (i = 0; i < prog->instances.nr; i++) {
4488 struct bpf_prog_prep_result result;
4489 bpf_program_prep_t preprocessor = prog->preprocessor;
4491 memset(&result, 0, sizeof(result));
4492 err = preprocessor(prog, i, prog->insns,
4493 prog->insns_cnt, &result);
4495 pr_warn("Preprocessing the %dth instance of program '%s' failed\n",
4496 i, prog->section_name);
4500 if (!result.new_insn_ptr || !result.new_insn_cnt) {
4501 pr_debug("Skip loading the %dth instance of program '%s'\n",
4502 i, prog->section_name);
4503 prog->instances.fds[i] = -1;
4509 err = load_program(prog, result.new_insn_ptr,
4510 result.new_insn_cnt, license, kern_ver, &fd);
4512 pr_warn("Loading the %dth instance of program '%s' failed\n",
4513 i, prog->section_name);
4519 prog->instances.fds[i] = fd;
4523 pr_warn("failed to load program '%s'\n", prog->section_name);
4524 zfree(&prog->insns);
4525 prog->insns_cnt = 0;
4529 static bool bpf_program__is_function_storage(const struct bpf_program *prog,
4530 const struct bpf_object *obj)
4532 return prog->idx == obj->efile.text_shndx && obj->has_pseudo_calls;
4536 bpf_object__load_progs(struct bpf_object *obj, int log_level)
4541 for (i = 0; i < obj->nr_programs; i++) {
4542 if (bpf_program__is_function_storage(&obj->programs[i], obj))
4544 obj->programs[i].log_level |= log_level;
4545 err = bpf_program__load(&obj->programs[i],
4554 static struct bpf_object *
4555 __bpf_object__open(const char *path, const void *obj_buf, size_t obj_buf_sz,
4556 const struct bpf_object_open_opts *opts)
4558 const char *obj_name, *kconfig_path;
4559 struct bpf_program *prog;
4560 struct bpf_object *obj;
4564 if (elf_version(EV_CURRENT) == EV_NONE) {
4565 pr_warn("failed to init libelf for %s\n",
4566 path ? : "(mem buf)");
4567 return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
4570 if (!OPTS_VALID(opts, bpf_object_open_opts))
4571 return ERR_PTR(-EINVAL);
4573 obj_name = OPTS_GET(opts, object_name, NULL);
4576 snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
4577 (unsigned long)obj_buf,
4578 (unsigned long)obj_buf_sz);
4579 obj_name = tmp_name;
4582 pr_debug("loading object '%s' from buffer\n", obj_name);
4585 obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
4589 obj->relaxed_core_relocs = OPTS_GET(opts, relaxed_core_relocs, false);
4590 kconfig_path = OPTS_GET(opts, kconfig_path, NULL);
4592 obj->kconfig_path = strdup(kconfig_path);
4593 if (!obj->kconfig_path)
4594 return ERR_PTR(-ENOMEM);
4597 err = bpf_object__elf_init(obj);
4598 err = err ? : bpf_object__check_endianness(obj);
4599 err = err ? : bpf_object__elf_collect(obj);
4600 err = err ? : bpf_object__collect_externs(obj);
4601 err = err ? : bpf_object__finalize_btf(obj);
4602 err = err ? : bpf_object__init_maps(obj, opts);
4603 err = err ? : bpf_object__init_prog_names(obj);
4604 err = err ? : bpf_object__collect_reloc(obj);
4607 bpf_object__elf_finish(obj);
4609 bpf_object__for_each_program(prog, obj) {
4610 enum bpf_prog_type prog_type;
4611 enum bpf_attach_type attach_type;
4613 err = libbpf_prog_type_by_name(prog->section_name, &prog_type,
4616 /* couldn't guess, but user might manually specify */
4621 bpf_program__set_type(prog, prog_type);
4622 bpf_program__set_expected_attach_type(prog, attach_type);
4623 if (prog_type == BPF_PROG_TYPE_TRACING)
4624 prog->attach_prog_fd = OPTS_GET(opts, attach_prog_fd, 0);
4629 bpf_object__close(obj);
4630 return ERR_PTR(err);
4633 static struct bpf_object *
4634 __bpf_object__open_xattr(struct bpf_object_open_attr *attr, int flags)
4636 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts,
4637 .relaxed_maps = flags & MAPS_RELAX_COMPAT,
4640 /* param validation */
4644 pr_debug("loading %s\n", attr->file);
4645 return __bpf_object__open(attr->file, NULL, 0, &opts);
4648 struct bpf_object *bpf_object__open_xattr(struct bpf_object_open_attr *attr)
4650 return __bpf_object__open_xattr(attr, 0);
4653 struct bpf_object *bpf_object__open(const char *path)
4655 struct bpf_object_open_attr attr = {
4657 .prog_type = BPF_PROG_TYPE_UNSPEC,
4660 return bpf_object__open_xattr(&attr);
4664 bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
4667 return ERR_PTR(-EINVAL);
4669 pr_debug("loading %s\n", path);
4671 return __bpf_object__open(path, NULL, 0, opts);
4675 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
4676 const struct bpf_object_open_opts *opts)
4678 if (!obj_buf || obj_buf_sz == 0)
4679 return ERR_PTR(-EINVAL);
4681 return __bpf_object__open(NULL, obj_buf, obj_buf_sz, opts);
4685 bpf_object__open_buffer(const void *obj_buf, size_t obj_buf_sz,
4688 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts,
4689 .object_name = name,
4690 /* wrong default, but backwards-compatible */
4691 .relaxed_maps = true,
4694 /* returning NULL is wrong, but backwards-compatible */
4695 if (!obj_buf || obj_buf_sz == 0)
4698 return bpf_object__open_mem(obj_buf, obj_buf_sz, &opts);
4701 int bpf_object__unload(struct bpf_object *obj)
4708 for (i = 0; i < obj->nr_maps; i++)
4709 zclose(obj->maps[i].fd);
4711 for (i = 0; i < obj->nr_programs; i++)
4712 bpf_program__unload(&obj->programs[i]);
4717 static int bpf_object__sanitize_maps(struct bpf_object *obj)
4721 bpf_object__for_each_map(m, obj) {
4722 if (!bpf_map__is_internal(m))
4724 if (!obj->caps.global_data) {
4725 pr_warn("kernel doesn't support global data\n");
4728 if (!obj->caps.array_mmap)
4729 m->def.map_flags ^= BPF_F_MMAPABLE;
4735 static int bpf_object__resolve_externs(struct bpf_object *obj,
4736 const char *config_path)
4738 bool need_config = false;
4739 struct extern_desc *ext;
4743 if (obj->nr_extern == 0)
4746 data = obj->maps[obj->extern_map_idx].mmaped;
4748 for (i = 0; i < obj->nr_extern; i++) {
4749 ext = &obj->externs[i];
4751 if (strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
4752 void *ext_val = data + ext->data_off;
4753 __u32 kver = get_kernel_version();
4756 pr_warn("failed to get kernel version\n");
4759 err = set_ext_value_num(ext, ext_val, kver);
4762 pr_debug("extern %s=0x%x\n", ext->name, kver);
4763 } else if (strncmp(ext->name, "CONFIG_", 7) == 0) {
4766 pr_warn("unrecognized extern '%s'\n", ext->name);
4771 err = bpf_object__read_kernel_config(obj, config_path, data);
4775 for (i = 0; i < obj->nr_extern; i++) {
4776 ext = &obj->externs[i];
4778 if (!ext->is_set && !ext->is_weak) {
4779 pr_warn("extern %s (strong) not resolved\n", ext->name);
4781 } else if (!ext->is_set) {
4782 pr_debug("extern %s (weak) not resolved, defaulting to zero\n",
4790 int bpf_object__load_xattr(struct bpf_object_load_attr *attr)
4792 struct bpf_object *obj;
4802 pr_warn("object should not be loaded twice\n");
4808 err = bpf_object__probe_caps(obj);
4809 err = err ? : bpf_object__resolve_externs(obj, obj->kconfig_path);
4810 err = err ? : bpf_object__sanitize_and_load_btf(obj);
4811 err = err ? : bpf_object__sanitize_maps(obj);
4812 err = err ? : bpf_object__create_maps(obj);
4813 err = err ? : bpf_object__relocate(obj, attr->target_btf_path);
4814 err = err ? : bpf_object__load_progs(obj, attr->log_level);
4820 /* unpin any maps that were auto-pinned during load */
4821 for (i = 0; i < obj->nr_maps; i++)
4822 if (obj->maps[i].pinned && !obj->maps[i].reused)
4823 bpf_map__unpin(&obj->maps[i], NULL);
4825 bpf_object__unload(obj);
4826 pr_warn("failed to load object '%s'\n", obj->path);
4830 int bpf_object__load(struct bpf_object *obj)
4832 struct bpf_object_load_attr attr = {
4836 return bpf_object__load_xattr(&attr);
4839 static int make_parent_dir(const char *path)
4841 char *cp, errmsg[STRERR_BUFSIZE];
4845 dname = strdup(path);
4849 dir = dirname(dname);
4850 if (mkdir(dir, 0700) && errno != EEXIST)
4855 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
4856 pr_warn("failed to mkdir %s: %s\n", path, cp);
4861 static int check_path(const char *path)
4863 char *cp, errmsg[STRERR_BUFSIZE];
4864 struct statfs st_fs;
4871 dname = strdup(path);
4875 dir = dirname(dname);
4876 if (statfs(dir, &st_fs)) {
4877 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
4878 pr_warn("failed to statfs %s: %s\n", dir, cp);
4883 if (!err && st_fs.f_type != BPF_FS_MAGIC) {
4884 pr_warn("specified path %s is not on BPF FS\n", path);
4891 int bpf_program__pin_instance(struct bpf_program *prog, const char *path,
4894 char *cp, errmsg[STRERR_BUFSIZE];
4897 err = make_parent_dir(path);
4901 err = check_path(path);
4906 pr_warn("invalid program pointer\n");
4910 if (instance < 0 || instance >= prog->instances.nr) {
4911 pr_warn("invalid prog instance %d of prog %s (max %d)\n",
4912 instance, prog->section_name, prog->instances.nr);
4916 if (bpf_obj_pin(prog->instances.fds[instance], path)) {
4917 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
4918 pr_warn("failed to pin program: %s\n", cp);
4921 pr_debug("pinned program '%s'\n", path);
4926 int bpf_program__unpin_instance(struct bpf_program *prog, const char *path,
4931 err = check_path(path);
4936 pr_warn("invalid program pointer\n");
4940 if (instance < 0 || instance >= prog->instances.nr) {
4941 pr_warn("invalid prog instance %d of prog %s (max %d)\n",
4942 instance, prog->section_name, prog->instances.nr);
4949 pr_debug("unpinned program '%s'\n", path);
4954 int bpf_program__pin(struct bpf_program *prog, const char *path)
4958 err = make_parent_dir(path);
4962 err = check_path(path);
4967 pr_warn("invalid program pointer\n");
4971 if (prog->instances.nr <= 0) {
4972 pr_warn("no instances of prog %s to pin\n",
4973 prog->section_name);
4977 if (prog->instances.nr == 1) {
4978 /* don't create subdirs when pinning single instance */
4979 return bpf_program__pin_instance(prog, path, 0);
4982 for (i = 0; i < prog->instances.nr; i++) {
4986 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
4990 } else if (len >= PATH_MAX) {
4991 err = -ENAMETOOLONG;
4995 err = bpf_program__pin_instance(prog, buf, i);
5003 for (i = i - 1; i >= 0; i--) {
5007 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
5010 else if (len >= PATH_MAX)
5013 bpf_program__unpin_instance(prog, buf, i);
5021 int bpf_program__unpin(struct bpf_program *prog, const char *path)
5025 err = check_path(path);
5030 pr_warn("invalid program pointer\n");
5034 if (prog->instances.nr <= 0) {
5035 pr_warn("no instances of prog %s to pin\n",
5036 prog->section_name);
5040 if (prog->instances.nr == 1) {
5041 /* don't create subdirs when pinning single instance */
5042 return bpf_program__unpin_instance(prog, path, 0);
5045 for (i = 0; i < prog->instances.nr; i++) {
5049 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
5052 else if (len >= PATH_MAX)
5053 return -ENAMETOOLONG;
5055 err = bpf_program__unpin_instance(prog, buf, i);
5067 int bpf_map__pin(struct bpf_map *map, const char *path)
5069 char *cp, errmsg[STRERR_BUFSIZE];
5073 pr_warn("invalid map pointer\n");
5077 if (map->pin_path) {
5078 if (path && strcmp(path, map->pin_path)) {
5079 pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
5080 bpf_map__name(map), map->pin_path, path);
5082 } else if (map->pinned) {
5083 pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
5084 bpf_map__name(map), map->pin_path);
5089 pr_warn("missing a path to pin map '%s' at\n",
5090 bpf_map__name(map));
5092 } else if (map->pinned) {
5093 pr_warn("map '%s' already pinned\n", bpf_map__name(map));
5097 map->pin_path = strdup(path);
5098 if (!map->pin_path) {
5104 err = make_parent_dir(map->pin_path);
5108 err = check_path(map->pin_path);
5112 if (bpf_obj_pin(map->fd, map->pin_path)) {
5118 pr_debug("pinned map '%s'\n", map->pin_path);
5123 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
5124 pr_warn("failed to pin map: %s\n", cp);
5128 int bpf_map__unpin(struct bpf_map *map, const char *path)
5133 pr_warn("invalid map pointer\n");
5137 if (map->pin_path) {
5138 if (path && strcmp(path, map->pin_path)) {
5139 pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
5140 bpf_map__name(map), map->pin_path, path);
5143 path = map->pin_path;
5145 pr_warn("no path to unpin map '%s' from\n",
5146 bpf_map__name(map));
5150 err = check_path(path);
5158 map->pinned = false;
5159 pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
5164 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
5174 free(map->pin_path);
5175 map->pin_path = new;
5179 const char *bpf_map__get_pin_path(const struct bpf_map *map)
5181 return map->pin_path;
5184 bool bpf_map__is_pinned(const struct bpf_map *map)
5189 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
5191 struct bpf_map *map;
5198 pr_warn("object not yet loaded; load it first\n");
5202 bpf_object__for_each_map(map, obj) {
5203 char *pin_path = NULL;
5209 len = snprintf(buf, PATH_MAX, "%s/%s", path,
5210 bpf_map__name(map));
5213 goto err_unpin_maps;
5214 } else if (len >= PATH_MAX) {
5215 err = -ENAMETOOLONG;
5216 goto err_unpin_maps;
5219 } else if (!map->pin_path) {
5223 err = bpf_map__pin(map, pin_path);
5225 goto err_unpin_maps;
5231 while ((map = bpf_map__prev(map, obj))) {
5235 bpf_map__unpin(map, NULL);
5241 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
5243 struct bpf_map *map;
5249 bpf_object__for_each_map(map, obj) {
5250 char *pin_path = NULL;
5256 len = snprintf(buf, PATH_MAX, "%s/%s", path,
5257 bpf_map__name(map));
5260 else if (len >= PATH_MAX)
5261 return -ENAMETOOLONG;
5263 } else if (!map->pin_path) {
5267 err = bpf_map__unpin(map, pin_path);
5275 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
5277 struct bpf_program *prog;
5284 pr_warn("object not yet loaded; load it first\n");
5288 bpf_object__for_each_program(prog, obj) {
5292 len = snprintf(buf, PATH_MAX, "%s/%s", path,
5296 goto err_unpin_programs;
5297 } else if (len >= PATH_MAX) {
5298 err = -ENAMETOOLONG;
5299 goto err_unpin_programs;
5302 err = bpf_program__pin(prog, buf);
5304 goto err_unpin_programs;
5310 while ((prog = bpf_program__prev(prog, obj))) {
5314 len = snprintf(buf, PATH_MAX, "%s/%s", path,
5318 else if (len >= PATH_MAX)
5321 bpf_program__unpin(prog, buf);
5327 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
5329 struct bpf_program *prog;
5335 bpf_object__for_each_program(prog, obj) {
5339 len = snprintf(buf, PATH_MAX, "%s/%s", path,
5343 else if (len >= PATH_MAX)
5344 return -ENAMETOOLONG;
5346 err = bpf_program__unpin(prog, buf);
5354 int bpf_object__pin(struct bpf_object *obj, const char *path)
5358 err = bpf_object__pin_maps(obj, path);
5362 err = bpf_object__pin_programs(obj, path);
5364 bpf_object__unpin_maps(obj, path);
5371 void bpf_object__close(struct bpf_object *obj)
5378 if (obj->clear_priv)
5379 obj->clear_priv(obj, obj->priv);
5381 bpf_object__elf_finish(obj);
5382 bpf_object__unload(obj);
5383 btf__free(obj->btf);
5384 btf_ext__free(obj->btf_ext);
5386 for (i = 0; i < obj->nr_maps; i++) {
5387 struct bpf_map *map = &obj->maps[i];
5389 if (map->clear_priv)
5390 map->clear_priv(map, map->priv);
5392 map->clear_priv = NULL;
5395 munmap(map->mmaped, bpf_map_mmap_sz(map));
5400 zfree(&map->pin_path);
5403 zfree(&obj->kconfig_path);
5404 zfree(&obj->externs);
5410 if (obj->programs && obj->nr_programs) {
5411 for (i = 0; i < obj->nr_programs; i++)
5412 bpf_program__exit(&obj->programs[i]);
5414 zfree(&obj->programs);
5416 list_del(&obj->list);
5421 bpf_object__next(struct bpf_object *prev)
5423 struct bpf_object *next;
5426 next = list_first_entry(&bpf_objects_list,
5430 next = list_next_entry(prev, list);
5432 /* Empty list is noticed here so don't need checking on entry. */
5433 if (&next->list == &bpf_objects_list)
5439 const char *bpf_object__name(const struct bpf_object *obj)
5441 return obj ? obj->name : ERR_PTR(-EINVAL);
5444 unsigned int bpf_object__kversion(const struct bpf_object *obj)
5446 return obj ? obj->kern_version : 0;
5449 struct btf *bpf_object__btf(const struct bpf_object *obj)
5451 return obj ? obj->btf : NULL;
5454 int bpf_object__btf_fd(const struct bpf_object *obj)
5456 return obj->btf ? btf__fd(obj->btf) : -1;
5459 int bpf_object__set_priv(struct bpf_object *obj, void *priv,
5460 bpf_object_clear_priv_t clear_priv)
5462 if (obj->priv && obj->clear_priv)
5463 obj->clear_priv(obj, obj->priv);
5466 obj->clear_priv = clear_priv;
5470 void *bpf_object__priv(const struct bpf_object *obj)
5472 return obj ? obj->priv : ERR_PTR(-EINVAL);
5475 static struct bpf_program *
5476 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
5479 size_t nr_programs = obj->nr_programs;
5486 /* Iter from the beginning */
5487 return forward ? &obj->programs[0] :
5488 &obj->programs[nr_programs - 1];
5490 if (p->obj != obj) {
5491 pr_warn("error: program handler doesn't match object\n");
5495 idx = (p - obj->programs) + (forward ? 1 : -1);
5496 if (idx >= obj->nr_programs || idx < 0)
5498 return &obj->programs[idx];
5501 struct bpf_program *
5502 bpf_program__next(struct bpf_program *prev, const struct bpf_object *obj)
5504 struct bpf_program *prog = prev;
5507 prog = __bpf_program__iter(prog, obj, true);
5508 } while (prog && bpf_program__is_function_storage(prog, obj));
5513 struct bpf_program *
5514 bpf_program__prev(struct bpf_program *next, const struct bpf_object *obj)
5516 struct bpf_program *prog = next;
5519 prog = __bpf_program__iter(prog, obj, false);
5520 } while (prog && bpf_program__is_function_storage(prog, obj));
5525 int bpf_program__set_priv(struct bpf_program *prog, void *priv,
5526 bpf_program_clear_priv_t clear_priv)
5528 if (prog->priv && prog->clear_priv)
5529 prog->clear_priv(prog, prog->priv);
5532 prog->clear_priv = clear_priv;
5536 void *bpf_program__priv(const struct bpf_program *prog)
5538 return prog ? prog->priv : ERR_PTR(-EINVAL);
5541 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
5543 prog->prog_ifindex = ifindex;
5546 const char *bpf_program__name(const struct bpf_program *prog)
5551 const char *bpf_program__title(const struct bpf_program *prog, bool needs_copy)
5555 title = prog->section_name;
5557 title = strdup(title);
5559 pr_warn("failed to strdup program title\n");
5560 return ERR_PTR(-ENOMEM);
5567 int bpf_program__fd(const struct bpf_program *prog)
5569 return bpf_program__nth_fd(prog, 0);
5572 size_t bpf_program__size(const struct bpf_program *prog)
5574 return prog->insns_cnt * sizeof(struct bpf_insn);
5577 int bpf_program__set_prep(struct bpf_program *prog, int nr_instances,
5578 bpf_program_prep_t prep)
5582 if (nr_instances <= 0 || !prep)
5585 if (prog->instances.nr > 0 || prog->instances.fds) {
5586 pr_warn("Can't set pre-processor after loading\n");
5590 instances_fds = malloc(sizeof(int) * nr_instances);
5591 if (!instances_fds) {
5592 pr_warn("alloc memory failed for fds\n");
5596 /* fill all fd with -1 */
5597 memset(instances_fds, -1, sizeof(int) * nr_instances);
5599 prog->instances.nr = nr_instances;
5600 prog->instances.fds = instances_fds;
5601 prog->preprocessor = prep;
5605 int bpf_program__nth_fd(const struct bpf_program *prog, int n)
5612 if (n >= prog->instances.nr || n < 0) {
5613 pr_warn("Can't get the %dth fd from program %s: only %d instances\n",
5614 n, prog->section_name, prog->instances.nr);
5618 fd = prog->instances.fds[n];
5620 pr_warn("%dth instance of program '%s' is invalid\n",
5621 n, prog->section_name);
5628 enum bpf_prog_type bpf_program__get_type(struct bpf_program *prog)
5633 void bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
5638 static bool bpf_program__is_type(const struct bpf_program *prog,
5639 enum bpf_prog_type type)
5641 return prog ? (prog->type == type) : false;
5644 #define BPF_PROG_TYPE_FNS(NAME, TYPE) \
5645 int bpf_program__set_##NAME(struct bpf_program *prog) \
5649 bpf_program__set_type(prog, TYPE); \
5653 bool bpf_program__is_##NAME(const struct bpf_program *prog) \
5655 return bpf_program__is_type(prog, TYPE); \
5658 BPF_PROG_TYPE_FNS(socket_filter, BPF_PROG_TYPE_SOCKET_FILTER);
5659 BPF_PROG_TYPE_FNS(kprobe, BPF_PROG_TYPE_KPROBE);
5660 BPF_PROG_TYPE_FNS(sched_cls, BPF_PROG_TYPE_SCHED_CLS);
5661 BPF_PROG_TYPE_FNS(sched_act, BPF_PROG_TYPE_SCHED_ACT);
5662 BPF_PROG_TYPE_FNS(tracepoint, BPF_PROG_TYPE_TRACEPOINT);
5663 BPF_PROG_TYPE_FNS(raw_tracepoint, BPF_PROG_TYPE_RAW_TRACEPOINT);
5664 BPF_PROG_TYPE_FNS(xdp, BPF_PROG_TYPE_XDP);
5665 BPF_PROG_TYPE_FNS(perf_event, BPF_PROG_TYPE_PERF_EVENT);
5666 BPF_PROG_TYPE_FNS(tracing, BPF_PROG_TYPE_TRACING);
5668 enum bpf_attach_type
5669 bpf_program__get_expected_attach_type(struct bpf_program *prog)
5671 return prog->expected_attach_type;
5674 void bpf_program__set_expected_attach_type(struct bpf_program *prog,
5675 enum bpf_attach_type type)
5677 prog->expected_attach_type = type;
5680 #define BPF_PROG_SEC_IMPL(string, ptype, eatype, is_attachable, btf, atype) \
5681 { string, sizeof(string) - 1, ptype, eatype, is_attachable, btf, atype }
5683 /* Programs that can NOT be attached. */
5684 #define BPF_PROG_SEC(string, ptype) BPF_PROG_SEC_IMPL(string, ptype, 0, 0, 0, 0)
5686 /* Programs that can be attached. */
5687 #define BPF_APROG_SEC(string, ptype, atype) \
5688 BPF_PROG_SEC_IMPL(string, ptype, 0, 1, 0, atype)
5690 /* Programs that must specify expected attach type at load time. */
5691 #define BPF_EAPROG_SEC(string, ptype, eatype) \
5692 BPF_PROG_SEC_IMPL(string, ptype, eatype, 1, 0, eatype)
5694 /* Programs that use BTF to identify attach point */
5695 #define BPF_PROG_BTF(string, ptype, eatype) \
5696 BPF_PROG_SEC_IMPL(string, ptype, eatype, 0, 1, 0)
5698 /* Programs that can be attached but attach type can't be identified by section
5699 * name. Kept for backward compatibility.
5701 #define BPF_APROG_COMPAT(string, ptype) BPF_PROG_SEC(string, ptype)
5703 #define SEC_DEF(sec_pfx, ptype, ...) { \
5705 .len = sizeof(sec_pfx) - 1, \
5706 .prog_type = BPF_PROG_TYPE_##ptype, \
5712 typedef struct bpf_link *(*attach_fn_t)(const struct bpf_sec_def *sec,
5713 struct bpf_program *prog);
5715 static struct bpf_link *attach_kprobe(const struct bpf_sec_def *sec,
5716 struct bpf_program *prog);
5717 static struct bpf_link *attach_tp(const struct bpf_sec_def *sec,
5718 struct bpf_program *prog);
5719 static struct bpf_link *attach_raw_tp(const struct bpf_sec_def *sec,
5720 struct bpf_program *prog);
5721 static struct bpf_link *attach_trace(const struct bpf_sec_def *sec,
5722 struct bpf_program *prog);
5724 struct bpf_sec_def {
5727 enum bpf_prog_type prog_type;
5728 enum bpf_attach_type expected_attach_type;
5731 enum bpf_attach_type attach_type;
5732 attach_fn_t attach_fn;
5735 static const struct bpf_sec_def section_defs[] = {
5736 BPF_PROG_SEC("socket", BPF_PROG_TYPE_SOCKET_FILTER),
5737 BPF_PROG_SEC("sk_reuseport", BPF_PROG_TYPE_SK_REUSEPORT),
5738 SEC_DEF("kprobe/", KPROBE,
5739 .attach_fn = attach_kprobe),
5740 BPF_PROG_SEC("uprobe/", BPF_PROG_TYPE_KPROBE),
5741 SEC_DEF("kretprobe/", KPROBE,
5742 .attach_fn = attach_kprobe),
5743 BPF_PROG_SEC("uretprobe/", BPF_PROG_TYPE_KPROBE),
5744 BPF_PROG_SEC("classifier", BPF_PROG_TYPE_SCHED_CLS),
5745 BPF_PROG_SEC("action", BPF_PROG_TYPE_SCHED_ACT),
5746 SEC_DEF("tracepoint/", TRACEPOINT,
5747 .attach_fn = attach_tp),
5748 SEC_DEF("tp/", TRACEPOINT,
5749 .attach_fn = attach_tp),
5750 SEC_DEF("raw_tracepoint/", RAW_TRACEPOINT,
5751 .attach_fn = attach_raw_tp),
5752 SEC_DEF("raw_tp/", RAW_TRACEPOINT,
5753 .attach_fn = attach_raw_tp),
5754 SEC_DEF("tp_btf/", TRACING,
5755 .expected_attach_type = BPF_TRACE_RAW_TP,
5756 .is_attach_btf = true,
5757 .attach_fn = attach_trace),
5758 SEC_DEF("fentry/", TRACING,
5759 .expected_attach_type = BPF_TRACE_FENTRY,
5760 .is_attach_btf = true,
5761 .attach_fn = attach_trace),
5762 SEC_DEF("fexit/", TRACING,
5763 .expected_attach_type = BPF_TRACE_FEXIT,
5764 .is_attach_btf = true,
5765 .attach_fn = attach_trace),
5766 BPF_PROG_SEC("xdp", BPF_PROG_TYPE_XDP),
5767 BPF_PROG_SEC("perf_event", BPF_PROG_TYPE_PERF_EVENT),
5768 BPF_PROG_SEC("lwt_in", BPF_PROG_TYPE_LWT_IN),
5769 BPF_PROG_SEC("lwt_out", BPF_PROG_TYPE_LWT_OUT),
5770 BPF_PROG_SEC("lwt_xmit", BPF_PROG_TYPE_LWT_XMIT),
5771 BPF_PROG_SEC("lwt_seg6local", BPF_PROG_TYPE_LWT_SEG6LOCAL),
5772 BPF_APROG_SEC("cgroup_skb/ingress", BPF_PROG_TYPE_CGROUP_SKB,
5773 BPF_CGROUP_INET_INGRESS),
5774 BPF_APROG_SEC("cgroup_skb/egress", BPF_PROG_TYPE_CGROUP_SKB,
5775 BPF_CGROUP_INET_EGRESS),
5776 BPF_APROG_COMPAT("cgroup/skb", BPF_PROG_TYPE_CGROUP_SKB),
5777 BPF_APROG_SEC("cgroup/sock", BPF_PROG_TYPE_CGROUP_SOCK,
5778 BPF_CGROUP_INET_SOCK_CREATE),
5779 BPF_EAPROG_SEC("cgroup/post_bind4", BPF_PROG_TYPE_CGROUP_SOCK,
5780 BPF_CGROUP_INET4_POST_BIND),
5781 BPF_EAPROG_SEC("cgroup/post_bind6", BPF_PROG_TYPE_CGROUP_SOCK,
5782 BPF_CGROUP_INET6_POST_BIND),
5783 BPF_APROG_SEC("cgroup/dev", BPF_PROG_TYPE_CGROUP_DEVICE,
5785 BPF_APROG_SEC("sockops", BPF_PROG_TYPE_SOCK_OPS,
5786 BPF_CGROUP_SOCK_OPS),
5787 BPF_APROG_SEC("sk_skb/stream_parser", BPF_PROG_TYPE_SK_SKB,
5788 BPF_SK_SKB_STREAM_PARSER),
5789 BPF_APROG_SEC("sk_skb/stream_verdict", BPF_PROG_TYPE_SK_SKB,
5790 BPF_SK_SKB_STREAM_VERDICT),
5791 BPF_APROG_COMPAT("sk_skb", BPF_PROG_TYPE_SK_SKB),
5792 BPF_APROG_SEC("sk_msg", BPF_PROG_TYPE_SK_MSG,
5793 BPF_SK_MSG_VERDICT),
5794 BPF_APROG_SEC("lirc_mode2", BPF_PROG_TYPE_LIRC_MODE2,
5796 BPF_APROG_SEC("flow_dissector", BPF_PROG_TYPE_FLOW_DISSECTOR,
5797 BPF_FLOW_DISSECTOR),
5798 BPF_EAPROG_SEC("cgroup/bind4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
5799 BPF_CGROUP_INET4_BIND),
5800 BPF_EAPROG_SEC("cgroup/bind6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
5801 BPF_CGROUP_INET6_BIND),
5802 BPF_EAPROG_SEC("cgroup/connect4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
5803 BPF_CGROUP_INET4_CONNECT),
5804 BPF_EAPROG_SEC("cgroup/connect6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
5805 BPF_CGROUP_INET6_CONNECT),
5806 BPF_EAPROG_SEC("cgroup/sendmsg4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
5807 BPF_CGROUP_UDP4_SENDMSG),
5808 BPF_EAPROG_SEC("cgroup/sendmsg6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
5809 BPF_CGROUP_UDP6_SENDMSG),
5810 BPF_EAPROG_SEC("cgroup/recvmsg4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
5811 BPF_CGROUP_UDP4_RECVMSG),
5812 BPF_EAPROG_SEC("cgroup/recvmsg6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
5813 BPF_CGROUP_UDP6_RECVMSG),
5814 BPF_EAPROG_SEC("cgroup/sysctl", BPF_PROG_TYPE_CGROUP_SYSCTL,
5816 BPF_EAPROG_SEC("cgroup/getsockopt", BPF_PROG_TYPE_CGROUP_SOCKOPT,
5817 BPF_CGROUP_GETSOCKOPT),
5818 BPF_EAPROG_SEC("cgroup/setsockopt", BPF_PROG_TYPE_CGROUP_SOCKOPT,
5819 BPF_CGROUP_SETSOCKOPT),
5822 #undef BPF_PROG_SEC_IMPL
5824 #undef BPF_APROG_SEC
5825 #undef BPF_EAPROG_SEC
5826 #undef BPF_APROG_COMPAT
5829 #define MAX_TYPE_NAME_SIZE 32
5831 static const struct bpf_sec_def *find_sec_def(const char *sec_name)
5833 int i, n = ARRAY_SIZE(section_defs);
5835 for (i = 0; i < n; i++) {
5836 if (strncmp(sec_name,
5837 section_defs[i].sec, section_defs[i].len))
5839 return §ion_defs[i];
5844 static char *libbpf_get_type_names(bool attach_type)
5846 int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
5854 /* Forge string buf with all available names */
5855 for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
5856 if (attach_type && !section_defs[i].is_attachable)
5859 if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
5864 strcat(buf, section_defs[i].sec);
5870 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
5871 enum bpf_attach_type *expected_attach_type)
5873 const struct bpf_sec_def *sec_def;
5879 sec_def = find_sec_def(name);
5881 *prog_type = sec_def->prog_type;
5882 *expected_attach_type = sec_def->expected_attach_type;
5886 pr_debug("failed to guess program type from ELF section '%s'\n", name);
5887 type_names = libbpf_get_type_names(false);
5888 if (type_names != NULL) {
5889 pr_debug("supported section(type) names are:%s\n", type_names);
5896 #define BTF_PREFIX "btf_trace_"
5897 int libbpf_find_vmlinux_btf_id(const char *name,
5898 enum bpf_attach_type attach_type)
5900 struct btf *btf = bpf_core_find_kernel_btf();
5901 char raw_tp_btf[128] = BTF_PREFIX;
5902 char *dst = raw_tp_btf + sizeof(BTF_PREFIX) - 1;
5903 const char *btf_name;
5908 pr_warn("vmlinux BTF is not found\n");
5912 if (attach_type == BPF_TRACE_RAW_TP) {
5913 /* prepend "btf_trace_" prefix per kernel convention */
5914 strncat(dst, name, sizeof(raw_tp_btf) - sizeof(BTF_PREFIX));
5915 btf_name = raw_tp_btf;
5916 kind = BTF_KIND_TYPEDEF;
5919 kind = BTF_KIND_FUNC;
5921 err = btf__find_by_name_kind(btf, btf_name, kind);
5926 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd)
5928 struct bpf_prog_info_linear *info_linear;
5929 struct bpf_prog_info *info;
5930 struct btf *btf = NULL;
5933 info_linear = bpf_program__get_prog_info_linear(attach_prog_fd, 0);
5934 if (IS_ERR_OR_NULL(info_linear)) {
5935 pr_warn("failed get_prog_info_linear for FD %d\n",
5939 info = &info_linear->info;
5940 if (!info->btf_id) {
5941 pr_warn("The target program doesn't have BTF\n");
5944 if (btf__get_from_id(info->btf_id, &btf)) {
5945 pr_warn("Failed to get BTF of the program\n");
5948 err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
5951 pr_warn("%s is not found in prog's BTF\n", name);
5959 static int libbpf_find_attach_btf_id(const char *name,
5960 enum bpf_attach_type attach_type,
5961 __u32 attach_prog_fd)
5968 for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
5969 if (!section_defs[i].is_attach_btf)
5971 if (strncmp(name, section_defs[i].sec, section_defs[i].len))
5974 err = libbpf_find_prog_btf_id(name + section_defs[i].len,
5977 err = libbpf_find_vmlinux_btf_id(name + section_defs[i].len,
5980 pr_warn("%s is not found in vmlinux BTF\n", name);
5983 pr_warn("failed to identify btf_id based on ELF section name '%s'\n", name);
5987 int libbpf_attach_type_by_name(const char *name,
5988 enum bpf_attach_type *attach_type)
5996 for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
5997 if (strncmp(name, section_defs[i].sec, section_defs[i].len))
5999 if (!section_defs[i].is_attachable)
6001 *attach_type = section_defs[i].attach_type;
6004 pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
6005 type_names = libbpf_get_type_names(true);
6006 if (type_names != NULL) {
6007 pr_debug("attachable section(type) names are:%s\n", type_names);
6014 int bpf_map__fd(const struct bpf_map *map)
6016 return map ? map->fd : -EINVAL;
6019 const struct bpf_map_def *bpf_map__def(const struct bpf_map *map)
6021 return map ? &map->def : ERR_PTR(-EINVAL);
6024 const char *bpf_map__name(const struct bpf_map *map)
6026 return map ? map->name : NULL;
6029 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
6031 return map ? map->btf_key_type_id : 0;
6034 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
6036 return map ? map->btf_value_type_id : 0;
6039 int bpf_map__set_priv(struct bpf_map *map, void *priv,
6040 bpf_map_clear_priv_t clear_priv)
6046 if (map->clear_priv)
6047 map->clear_priv(map, map->priv);
6051 map->clear_priv = clear_priv;
6055 void *bpf_map__priv(const struct bpf_map *map)
6057 return map ? map->priv : ERR_PTR(-EINVAL);
6060 bool bpf_map__is_offload_neutral(const struct bpf_map *map)
6062 return map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY;
6065 bool bpf_map__is_internal(const struct bpf_map *map)
6067 return map->libbpf_type != LIBBPF_MAP_UNSPEC;
6070 void bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
6072 map->map_ifindex = ifindex;
6075 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
6077 if (!bpf_map_type__is_map_in_map(map->def.type)) {
6078 pr_warn("error: unsupported map type\n");
6081 if (map->inner_map_fd != -1) {
6082 pr_warn("error: inner_map_fd already specified\n");
6085 map->inner_map_fd = fd;
6089 static struct bpf_map *
6090 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
6093 struct bpf_map *s, *e;
6095 if (!obj || !obj->maps)
6099 e = obj->maps + obj->nr_maps;
6101 if ((m < s) || (m >= e)) {
6102 pr_warn("error in %s: map handler doesn't belong to object\n",
6107 idx = (m - obj->maps) + i;
6108 if (idx >= obj->nr_maps || idx < 0)
6110 return &obj->maps[idx];
6114 bpf_map__next(const struct bpf_map *prev, const struct bpf_object *obj)
6119 return __bpf_map__iter(prev, obj, 1);
6123 bpf_map__prev(const struct bpf_map *next, const struct bpf_object *obj)
6128 return obj->maps + obj->nr_maps - 1;
6131 return __bpf_map__iter(next, obj, -1);
6135 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
6137 struct bpf_map *pos;
6139 bpf_object__for_each_map(pos, obj) {
6140 if (pos->name && !strcmp(pos->name, name))
6147 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
6149 return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
6153 bpf_object__find_map_by_offset(struct bpf_object *obj, size_t offset)
6155 return ERR_PTR(-ENOTSUP);
6158 long libbpf_get_error(const void *ptr)
6160 return PTR_ERR_OR_ZERO(ptr);
6163 int bpf_prog_load(const char *file, enum bpf_prog_type type,
6164 struct bpf_object **pobj, int *prog_fd)
6166 struct bpf_prog_load_attr attr;
6168 memset(&attr, 0, sizeof(struct bpf_prog_load_attr));
6170 attr.prog_type = type;
6171 attr.expected_attach_type = 0;
6173 return bpf_prog_load_xattr(&attr, pobj, prog_fd);
6176 int bpf_prog_load_xattr(const struct bpf_prog_load_attr *attr,
6177 struct bpf_object **pobj, int *prog_fd)
6179 struct bpf_object_open_attr open_attr = {};
6180 struct bpf_program *prog, *first_prog = NULL;
6181 struct bpf_object *obj;
6182 struct bpf_map *map;
6190 open_attr.file = attr->file;
6191 open_attr.prog_type = attr->prog_type;
6193 obj = bpf_object__open_xattr(&open_attr);
6194 if (IS_ERR_OR_NULL(obj))
6197 bpf_object__for_each_program(prog, obj) {
6198 enum bpf_attach_type attach_type = attr->expected_attach_type;
6200 * to preserve backwards compatibility, bpf_prog_load treats
6201 * attr->prog_type, if specified, as an override to whatever
6202 * bpf_object__open guessed
6204 if (attr->prog_type != BPF_PROG_TYPE_UNSPEC) {
6205 bpf_program__set_type(prog, attr->prog_type);
6206 bpf_program__set_expected_attach_type(prog,
6209 if (bpf_program__get_type(prog) == BPF_PROG_TYPE_UNSPEC) {
6211 * we haven't guessed from section name and user
6212 * didn't provide a fallback type, too bad...
6214 bpf_object__close(obj);
6218 prog->prog_ifindex = attr->ifindex;
6219 prog->log_level = attr->log_level;
6220 prog->prog_flags = attr->prog_flags;
6225 bpf_object__for_each_map(map, obj) {
6226 if (!bpf_map__is_offload_neutral(map))
6227 map->map_ifindex = attr->ifindex;
6231 pr_warn("object file doesn't contain bpf program\n");
6232 bpf_object__close(obj);
6236 err = bpf_object__load(obj);
6238 bpf_object__close(obj);
6243 *prog_fd = bpf_program__fd(first_prog);
6248 int (*detach)(struct bpf_link *link);
6249 int (*destroy)(struct bpf_link *link);
6253 /* Release "ownership" of underlying BPF resource (typically, BPF program
6254 * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
6255 * link, when destructed through bpf_link__destroy() call won't attempt to
6256 * detach/unregisted that BPF resource. This is useful in situations where,
6257 * say, attached BPF program has to outlive userspace program that attached it
6258 * in the system. Depending on type of BPF program, though, there might be
6259 * additional steps (like pinning BPF program in BPF FS) necessary to ensure
6260 * exit of userspace program doesn't trigger automatic detachment and clean up
6261 * inside the kernel.
6263 void bpf_link__disconnect(struct bpf_link *link)
6265 link->disconnected = true;
6268 int bpf_link__destroy(struct bpf_link *link)
6275 if (!link->disconnected && link->detach)
6276 err = link->detach(link);
6278 link->destroy(link);
6284 struct bpf_link_fd {
6285 struct bpf_link link; /* has to be at the top of struct */
6286 int fd; /* hook FD */
6289 static int bpf_link__detach_perf_event(struct bpf_link *link)
6291 struct bpf_link_fd *l = (void *)link;
6294 err = ioctl(l->fd, PERF_EVENT_IOC_DISABLE, 0);
6302 struct bpf_link *bpf_program__attach_perf_event(struct bpf_program *prog,
6305 char errmsg[STRERR_BUFSIZE];
6306 struct bpf_link_fd *link;
6310 pr_warn("program '%s': invalid perf event FD %d\n",
6311 bpf_program__title(prog, false), pfd);
6312 return ERR_PTR(-EINVAL);
6314 prog_fd = bpf_program__fd(prog);
6316 pr_warn("program '%s': can't attach BPF program w/o FD (did you load it?)\n",
6317 bpf_program__title(prog, false));
6318 return ERR_PTR(-EINVAL);
6321 link = calloc(1, sizeof(*link));
6323 return ERR_PTR(-ENOMEM);
6324 link->link.detach = &bpf_link__detach_perf_event;
6327 if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
6330 pr_warn("program '%s': failed to attach to pfd %d: %s\n",
6331 bpf_program__title(prog, false), pfd,
6332 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
6333 return ERR_PTR(err);
6335 if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
6338 pr_warn("program '%s': failed to enable pfd %d: %s\n",
6339 bpf_program__title(prog, false), pfd,
6340 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
6341 return ERR_PTR(err);
6343 return (struct bpf_link *)link;
6347 * this function is expected to parse integer in the range of [0, 2^31-1] from
6348 * given file using scanf format string fmt. If actual parsed value is
6349 * negative, the result might be indistinguishable from error
6351 static int parse_uint_from_file(const char *file, const char *fmt)
6353 char buf[STRERR_BUFSIZE];
6357 f = fopen(file, "r");
6360 pr_debug("failed to open '%s': %s\n", file,
6361 libbpf_strerror_r(err, buf, sizeof(buf)));
6364 err = fscanf(f, fmt, &ret);
6366 err = err == EOF ? -EIO : -errno;
6367 pr_debug("failed to parse '%s': %s\n", file,
6368 libbpf_strerror_r(err, buf, sizeof(buf)));
6376 static int determine_kprobe_perf_type(void)
6378 const char *file = "/sys/bus/event_source/devices/kprobe/type";
6380 return parse_uint_from_file(file, "%d\n");
6383 static int determine_uprobe_perf_type(void)
6385 const char *file = "/sys/bus/event_source/devices/uprobe/type";
6387 return parse_uint_from_file(file, "%d\n");
6390 static int determine_kprobe_retprobe_bit(void)
6392 const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
6394 return parse_uint_from_file(file, "config:%d\n");
6397 static int determine_uprobe_retprobe_bit(void)
6399 const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
6401 return parse_uint_from_file(file, "config:%d\n");
6404 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
6405 uint64_t offset, int pid)
6407 struct perf_event_attr attr = {};
6408 char errmsg[STRERR_BUFSIZE];
6411 type = uprobe ? determine_uprobe_perf_type()
6412 : determine_kprobe_perf_type();
6414 pr_warn("failed to determine %s perf type: %s\n",
6415 uprobe ? "uprobe" : "kprobe",
6416 libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
6420 int bit = uprobe ? determine_uprobe_retprobe_bit()
6421 : determine_kprobe_retprobe_bit();
6424 pr_warn("failed to determine %s retprobe bit: %s\n",
6425 uprobe ? "uprobe" : "kprobe",
6426 libbpf_strerror_r(bit, errmsg, sizeof(errmsg)));
6429 attr.config |= 1 << bit;
6431 attr.size = sizeof(attr);
6433 attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
6434 attr.config2 = offset; /* kprobe_addr or probe_offset */
6436 /* pid filter is meaningful only for uprobes */
6437 pfd = syscall(__NR_perf_event_open, &attr,
6438 pid < 0 ? -1 : pid /* pid */,
6439 pid == -1 ? 0 : -1 /* cpu */,
6440 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
6443 pr_warn("%s perf_event_open() failed: %s\n",
6444 uprobe ? "uprobe" : "kprobe",
6445 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
6451 struct bpf_link *bpf_program__attach_kprobe(struct bpf_program *prog,
6453 const char *func_name)
6455 char errmsg[STRERR_BUFSIZE];
6456 struct bpf_link *link;
6459 pfd = perf_event_open_probe(false /* uprobe */, retprobe, func_name,
6460 0 /* offset */, -1 /* pid */);
6462 pr_warn("program '%s': failed to create %s '%s' perf event: %s\n",
6463 bpf_program__title(prog, false),
6464 retprobe ? "kretprobe" : "kprobe", func_name,
6465 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
6466 return ERR_PTR(pfd);
6468 link = bpf_program__attach_perf_event(prog, pfd);
6471 err = PTR_ERR(link);
6472 pr_warn("program '%s': failed to attach to %s '%s': %s\n",
6473 bpf_program__title(prog, false),
6474 retprobe ? "kretprobe" : "kprobe", func_name,
6475 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
6481 static struct bpf_link *attach_kprobe(const struct bpf_sec_def *sec,
6482 struct bpf_program *prog)
6484 const char *func_name;
6487 func_name = bpf_program__title(prog, false) + sec->len;
6488 retprobe = strcmp(sec->sec, "kretprobe/") == 0;
6490 return bpf_program__attach_kprobe(prog, retprobe, func_name);
6493 struct bpf_link *bpf_program__attach_uprobe(struct bpf_program *prog,
6494 bool retprobe, pid_t pid,
6495 const char *binary_path,
6498 char errmsg[STRERR_BUFSIZE];
6499 struct bpf_link *link;
6502 pfd = perf_event_open_probe(true /* uprobe */, retprobe,
6503 binary_path, func_offset, pid);
6505 pr_warn("program '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
6506 bpf_program__title(prog, false),
6507 retprobe ? "uretprobe" : "uprobe",
6508 binary_path, func_offset,
6509 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
6510 return ERR_PTR(pfd);
6512 link = bpf_program__attach_perf_event(prog, pfd);
6515 err = PTR_ERR(link);
6516 pr_warn("program '%s': failed to attach to %s '%s:0x%zx': %s\n",
6517 bpf_program__title(prog, false),
6518 retprobe ? "uretprobe" : "uprobe",
6519 binary_path, func_offset,
6520 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
6526 static int determine_tracepoint_id(const char *tp_category,
6527 const char *tp_name)
6529 char file[PATH_MAX];
6532 ret = snprintf(file, sizeof(file),
6533 "/sys/kernel/debug/tracing/events/%s/%s/id",
6534 tp_category, tp_name);
6537 if (ret >= sizeof(file)) {
6538 pr_debug("tracepoint %s/%s path is too long\n",
6539 tp_category, tp_name);
6542 return parse_uint_from_file(file, "%d\n");
6545 static int perf_event_open_tracepoint(const char *tp_category,
6546 const char *tp_name)
6548 struct perf_event_attr attr = {};
6549 char errmsg[STRERR_BUFSIZE];
6550 int tp_id, pfd, err;
6552 tp_id = determine_tracepoint_id(tp_category, tp_name);
6554 pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
6555 tp_category, tp_name,
6556 libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
6560 attr.type = PERF_TYPE_TRACEPOINT;
6561 attr.size = sizeof(attr);
6562 attr.config = tp_id;
6564 pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
6565 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
6568 pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
6569 tp_category, tp_name,
6570 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
6576 struct bpf_link *bpf_program__attach_tracepoint(struct bpf_program *prog,
6577 const char *tp_category,
6578 const char *tp_name)
6580 char errmsg[STRERR_BUFSIZE];
6581 struct bpf_link *link;
6584 pfd = perf_event_open_tracepoint(tp_category, tp_name);
6586 pr_warn("program '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
6587 bpf_program__title(prog, false),
6588 tp_category, tp_name,
6589 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
6590 return ERR_PTR(pfd);
6592 link = bpf_program__attach_perf_event(prog, pfd);
6595 err = PTR_ERR(link);
6596 pr_warn("program '%s': failed to attach to tracepoint '%s/%s': %s\n",
6597 bpf_program__title(prog, false),
6598 tp_category, tp_name,
6599 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
6605 static struct bpf_link *attach_tp(const struct bpf_sec_def *sec,
6606 struct bpf_program *prog)
6608 char *sec_name, *tp_cat, *tp_name;
6609 struct bpf_link *link;
6611 sec_name = strdup(bpf_program__title(prog, false));
6613 return ERR_PTR(-ENOMEM);
6615 /* extract "tp/<category>/<name>" */
6616 tp_cat = sec_name + sec->len;
6617 tp_name = strchr(tp_cat, '/');
6619 link = ERR_PTR(-EINVAL);
6625 link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
6631 static int bpf_link__detach_fd(struct bpf_link *link)
6633 struct bpf_link_fd *l = (void *)link;
6635 return close(l->fd);
6638 struct bpf_link *bpf_program__attach_raw_tracepoint(struct bpf_program *prog,
6639 const char *tp_name)
6641 char errmsg[STRERR_BUFSIZE];
6642 struct bpf_link_fd *link;
6645 prog_fd = bpf_program__fd(prog);
6647 pr_warn("program '%s': can't attach before loaded\n",
6648 bpf_program__title(prog, false));
6649 return ERR_PTR(-EINVAL);
6652 link = calloc(1, sizeof(*link));
6654 return ERR_PTR(-ENOMEM);
6655 link->link.detach = &bpf_link__detach_fd;
6657 pfd = bpf_raw_tracepoint_open(tp_name, prog_fd);
6661 pr_warn("program '%s': failed to attach to raw tracepoint '%s': %s\n",
6662 bpf_program__title(prog, false), tp_name,
6663 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
6664 return ERR_PTR(pfd);
6667 return (struct bpf_link *)link;
6670 static struct bpf_link *attach_raw_tp(const struct bpf_sec_def *sec,
6671 struct bpf_program *prog)
6673 const char *tp_name = bpf_program__title(prog, false) + sec->len;
6675 return bpf_program__attach_raw_tracepoint(prog, tp_name);
6678 struct bpf_link *bpf_program__attach_trace(struct bpf_program *prog)
6680 char errmsg[STRERR_BUFSIZE];
6681 struct bpf_link_fd *link;
6684 prog_fd = bpf_program__fd(prog);
6686 pr_warn("program '%s': can't attach before loaded\n",
6687 bpf_program__title(prog, false));
6688 return ERR_PTR(-EINVAL);
6691 link = calloc(1, sizeof(*link));
6693 return ERR_PTR(-ENOMEM);
6694 link->link.detach = &bpf_link__detach_fd;
6696 pfd = bpf_raw_tracepoint_open(NULL, prog_fd);
6700 pr_warn("program '%s': failed to attach to trace: %s\n",
6701 bpf_program__title(prog, false),
6702 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
6703 return ERR_PTR(pfd);
6706 return (struct bpf_link *)link;
6709 static struct bpf_link *attach_trace(const struct bpf_sec_def *sec,
6710 struct bpf_program *prog)
6712 return bpf_program__attach_trace(prog);
6715 struct bpf_link *bpf_program__attach(struct bpf_program *prog)
6717 const struct bpf_sec_def *sec_def;
6719 sec_def = find_sec_def(bpf_program__title(prog, false));
6720 if (!sec_def || !sec_def->attach_fn)
6721 return ERR_PTR(-ESRCH);
6723 return sec_def->attach_fn(sec_def, prog);
6726 enum bpf_perf_event_ret
6727 bpf_perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
6728 void **copy_mem, size_t *copy_size,
6729 bpf_perf_event_print_t fn, void *private_data)
6731 struct perf_event_mmap_page *header = mmap_mem;
6732 __u64 data_head = ring_buffer_read_head(header);
6733 __u64 data_tail = header->data_tail;
6734 void *base = ((__u8 *)header) + page_size;
6735 int ret = LIBBPF_PERF_EVENT_CONT;
6736 struct perf_event_header *ehdr;
6739 while (data_head != data_tail) {
6740 ehdr = base + (data_tail & (mmap_size - 1));
6741 ehdr_size = ehdr->size;
6743 if (((void *)ehdr) + ehdr_size > base + mmap_size) {
6744 void *copy_start = ehdr;
6745 size_t len_first = base + mmap_size - copy_start;
6746 size_t len_secnd = ehdr_size - len_first;
6748 if (*copy_size < ehdr_size) {
6750 *copy_mem = malloc(ehdr_size);
6753 ret = LIBBPF_PERF_EVENT_ERROR;
6756 *copy_size = ehdr_size;
6759 memcpy(*copy_mem, copy_start, len_first);
6760 memcpy(*copy_mem + len_first, base, len_secnd);
6764 ret = fn(ehdr, private_data);
6765 data_tail += ehdr_size;
6766 if (ret != LIBBPF_PERF_EVENT_CONT)
6770 ring_buffer_write_tail(header, data_tail);
6776 struct perf_buffer_params {
6777 struct perf_event_attr *attr;
6778 /* if event_cb is specified, it takes precendence */
6779 perf_buffer_event_fn event_cb;
6780 /* sample_cb and lost_cb are higher-level common-case callbacks */
6781 perf_buffer_sample_fn sample_cb;
6782 perf_buffer_lost_fn lost_cb;
6789 struct perf_cpu_buf {
6790 struct perf_buffer *pb;
6791 void *base; /* mmap()'ed memory */
6792 void *buf; /* for reconstructing segmented data */
6799 struct perf_buffer {
6800 perf_buffer_event_fn event_cb;
6801 perf_buffer_sample_fn sample_cb;
6802 perf_buffer_lost_fn lost_cb;
6803 void *ctx; /* passed into callbacks */
6807 struct perf_cpu_buf **cpu_bufs;
6808 struct epoll_event *events;
6809 int cpu_cnt; /* number of allocated CPU buffers */
6810 int epoll_fd; /* perf event FD */
6811 int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
6814 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
6815 struct perf_cpu_buf *cpu_buf)
6819 if (cpu_buf->base &&
6820 munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
6821 pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
6822 if (cpu_buf->fd >= 0) {
6823 ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
6830 void perf_buffer__free(struct perf_buffer *pb)
6837 for (i = 0; i < pb->cpu_cnt && pb->cpu_bufs[i]; i++) {
6838 struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
6840 bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
6841 perf_buffer__free_cpu_buf(pb, cpu_buf);
6845 if (pb->epoll_fd >= 0)
6846 close(pb->epoll_fd);
6851 static struct perf_cpu_buf *
6852 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
6853 int cpu, int map_key)
6855 struct perf_cpu_buf *cpu_buf;
6856 char msg[STRERR_BUFSIZE];
6859 cpu_buf = calloc(1, sizeof(*cpu_buf));
6861 return ERR_PTR(-ENOMEM);
6865 cpu_buf->map_key = map_key;
6867 cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
6868 -1, PERF_FLAG_FD_CLOEXEC);
6869 if (cpu_buf->fd < 0) {
6871 pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
6872 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
6876 cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
6877 PROT_READ | PROT_WRITE, MAP_SHARED,
6879 if (cpu_buf->base == MAP_FAILED) {
6880 cpu_buf->base = NULL;
6882 pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
6883 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
6887 if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
6889 pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
6890 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
6897 perf_buffer__free_cpu_buf(pb, cpu_buf);
6898 return (struct perf_cpu_buf *)ERR_PTR(err);
6901 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
6902 struct perf_buffer_params *p);
6904 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
6905 const struct perf_buffer_opts *opts)
6907 struct perf_buffer_params p = {};
6908 struct perf_event_attr attr = { 0, };
6910 attr.config = PERF_COUNT_SW_BPF_OUTPUT,
6911 attr.type = PERF_TYPE_SOFTWARE;
6912 attr.sample_type = PERF_SAMPLE_RAW;
6913 attr.sample_period = 1;
6914 attr.wakeup_events = 1;
6917 p.sample_cb = opts ? opts->sample_cb : NULL;
6918 p.lost_cb = opts ? opts->lost_cb : NULL;
6919 p.ctx = opts ? opts->ctx : NULL;
6921 return __perf_buffer__new(map_fd, page_cnt, &p);
6924 struct perf_buffer *
6925 perf_buffer__new_raw(int map_fd, size_t page_cnt,
6926 const struct perf_buffer_raw_opts *opts)
6928 struct perf_buffer_params p = {};
6930 p.attr = opts->attr;
6931 p.event_cb = opts->event_cb;
6933 p.cpu_cnt = opts->cpu_cnt;
6934 p.cpus = opts->cpus;
6935 p.map_keys = opts->map_keys;
6937 return __perf_buffer__new(map_fd, page_cnt, &p);
6940 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
6941 struct perf_buffer_params *p)
6943 const char *online_cpus_file = "/sys/devices/system/cpu/online";
6944 struct bpf_map_info map = {};
6945 char msg[STRERR_BUFSIZE];
6946 struct perf_buffer *pb;
6947 bool *online = NULL;
6951 if (page_cnt & (page_cnt - 1)) {
6952 pr_warn("page count should be power of two, but is %zu\n",
6954 return ERR_PTR(-EINVAL);
6957 map_info_len = sizeof(map);
6958 err = bpf_obj_get_info_by_fd(map_fd, &map, &map_info_len);
6961 pr_warn("failed to get map info for map FD %d: %s\n",
6962 map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
6963 return ERR_PTR(err);
6966 if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
6967 pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
6969 return ERR_PTR(-EINVAL);
6972 pb = calloc(1, sizeof(*pb));
6974 return ERR_PTR(-ENOMEM);
6976 pb->event_cb = p->event_cb;
6977 pb->sample_cb = p->sample_cb;
6978 pb->lost_cb = p->lost_cb;
6981 pb->page_size = getpagesize();
6982 pb->mmap_size = pb->page_size * page_cnt;
6983 pb->map_fd = map_fd;
6985 pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
6986 if (pb->epoll_fd < 0) {
6988 pr_warn("failed to create epoll instance: %s\n",
6989 libbpf_strerror_r(err, msg, sizeof(msg)));
6993 if (p->cpu_cnt > 0) {
6994 pb->cpu_cnt = p->cpu_cnt;
6996 pb->cpu_cnt = libbpf_num_possible_cpus();
6997 if (pb->cpu_cnt < 0) {
7001 if (map.max_entries < pb->cpu_cnt)
7002 pb->cpu_cnt = map.max_entries;
7005 pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
7008 pr_warn("failed to allocate events: out of memory\n");
7011 pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
7012 if (!pb->cpu_bufs) {
7014 pr_warn("failed to allocate buffers: out of memory\n");
7018 err = parse_cpu_mask_file(online_cpus_file, &online, &n);
7020 pr_warn("failed to get online CPU mask: %d\n", err);
7024 for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
7025 struct perf_cpu_buf *cpu_buf;
7028 cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
7029 map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
7031 /* in case user didn't explicitly requested particular CPUs to
7032 * be attached to, skip offline/not present CPUs
7034 if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
7037 cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
7038 if (IS_ERR(cpu_buf)) {
7039 err = PTR_ERR(cpu_buf);
7043 pb->cpu_bufs[j] = cpu_buf;
7045 err = bpf_map_update_elem(pb->map_fd, &map_key,
7049 pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
7050 cpu, map_key, cpu_buf->fd,
7051 libbpf_strerror_r(err, msg, sizeof(msg)));
7055 pb->events[j].events = EPOLLIN;
7056 pb->events[j].data.ptr = cpu_buf;
7057 if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
7058 &pb->events[j]) < 0) {
7060 pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
7062 libbpf_strerror_r(err, msg, sizeof(msg)));
7075 perf_buffer__free(pb);
7076 return ERR_PTR(err);
7079 struct perf_sample_raw {
7080 struct perf_event_header header;
7085 struct perf_sample_lost {
7086 struct perf_event_header header;
7092 static enum bpf_perf_event_ret
7093 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
7095 struct perf_cpu_buf *cpu_buf = ctx;
7096 struct perf_buffer *pb = cpu_buf->pb;
7099 /* user wants full control over parsing perf event */
7101 return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
7104 case PERF_RECORD_SAMPLE: {
7105 struct perf_sample_raw *s = data;
7108 pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
7111 case PERF_RECORD_LOST: {
7112 struct perf_sample_lost *s = data;
7115 pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
7119 pr_warn("unknown perf sample type %d\n", e->type);
7120 return LIBBPF_PERF_EVENT_ERROR;
7122 return LIBBPF_PERF_EVENT_CONT;
7125 static int perf_buffer__process_records(struct perf_buffer *pb,
7126 struct perf_cpu_buf *cpu_buf)
7128 enum bpf_perf_event_ret ret;
7130 ret = bpf_perf_event_read_simple(cpu_buf->base, pb->mmap_size,
7131 pb->page_size, &cpu_buf->buf,
7133 perf_buffer__process_record, cpu_buf);
7134 if (ret != LIBBPF_PERF_EVENT_CONT)
7139 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
7143 cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
7144 for (i = 0; i < cnt; i++) {
7145 struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
7147 err = perf_buffer__process_records(pb, cpu_buf);
7149 pr_warn("error while processing records: %d\n", err);
7153 return cnt < 0 ? -errno : cnt;
7156 struct bpf_prog_info_array_desc {
7157 int array_offset; /* e.g. offset of jited_prog_insns */
7158 int count_offset; /* e.g. offset of jited_prog_len */
7159 int size_offset; /* > 0: offset of rec size,
7160 * < 0: fix size of -size_offset
7164 static struct bpf_prog_info_array_desc bpf_prog_info_array_desc[] = {
7165 [BPF_PROG_INFO_JITED_INSNS] = {
7166 offsetof(struct bpf_prog_info, jited_prog_insns),
7167 offsetof(struct bpf_prog_info, jited_prog_len),
7170 [BPF_PROG_INFO_XLATED_INSNS] = {
7171 offsetof(struct bpf_prog_info, xlated_prog_insns),
7172 offsetof(struct bpf_prog_info, xlated_prog_len),
7175 [BPF_PROG_INFO_MAP_IDS] = {
7176 offsetof(struct bpf_prog_info, map_ids),
7177 offsetof(struct bpf_prog_info, nr_map_ids),
7178 -(int)sizeof(__u32),
7180 [BPF_PROG_INFO_JITED_KSYMS] = {
7181 offsetof(struct bpf_prog_info, jited_ksyms),
7182 offsetof(struct bpf_prog_info, nr_jited_ksyms),
7183 -(int)sizeof(__u64),
7185 [BPF_PROG_INFO_JITED_FUNC_LENS] = {
7186 offsetof(struct bpf_prog_info, jited_func_lens),
7187 offsetof(struct bpf_prog_info, nr_jited_func_lens),
7188 -(int)sizeof(__u32),
7190 [BPF_PROG_INFO_FUNC_INFO] = {
7191 offsetof(struct bpf_prog_info, func_info),
7192 offsetof(struct bpf_prog_info, nr_func_info),
7193 offsetof(struct bpf_prog_info, func_info_rec_size),
7195 [BPF_PROG_INFO_LINE_INFO] = {
7196 offsetof(struct bpf_prog_info, line_info),
7197 offsetof(struct bpf_prog_info, nr_line_info),
7198 offsetof(struct bpf_prog_info, line_info_rec_size),
7200 [BPF_PROG_INFO_JITED_LINE_INFO] = {
7201 offsetof(struct bpf_prog_info, jited_line_info),
7202 offsetof(struct bpf_prog_info, nr_jited_line_info),
7203 offsetof(struct bpf_prog_info, jited_line_info_rec_size),
7205 [BPF_PROG_INFO_PROG_TAGS] = {
7206 offsetof(struct bpf_prog_info, prog_tags),
7207 offsetof(struct bpf_prog_info, nr_prog_tags),
7208 -(int)sizeof(__u8) * BPF_TAG_SIZE,
7213 static __u32 bpf_prog_info_read_offset_u32(struct bpf_prog_info *info,
7216 __u32 *array = (__u32 *)info;
7219 return array[offset / sizeof(__u32)];
7220 return -(int)offset;
7223 static __u64 bpf_prog_info_read_offset_u64(struct bpf_prog_info *info,
7226 __u64 *array = (__u64 *)info;
7229 return array[offset / sizeof(__u64)];
7230 return -(int)offset;
7233 static void bpf_prog_info_set_offset_u32(struct bpf_prog_info *info, int offset,
7236 __u32 *array = (__u32 *)info;
7239 array[offset / sizeof(__u32)] = val;
7242 static void bpf_prog_info_set_offset_u64(struct bpf_prog_info *info, int offset,
7245 __u64 *array = (__u64 *)info;
7248 array[offset / sizeof(__u64)] = val;
7251 struct bpf_prog_info_linear *
7252 bpf_program__get_prog_info_linear(int fd, __u64 arrays)
7254 struct bpf_prog_info_linear *info_linear;
7255 struct bpf_prog_info info = {};
7256 __u32 info_len = sizeof(info);
7261 if (arrays >> BPF_PROG_INFO_LAST_ARRAY)
7262 return ERR_PTR(-EINVAL);
7264 /* step 1: get array dimensions */
7265 err = bpf_obj_get_info_by_fd(fd, &info, &info_len);
7267 pr_debug("can't get prog info: %s", strerror(errno));
7268 return ERR_PTR(-EFAULT);
7271 /* step 2: calculate total size of all arrays */
7272 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
7273 bool include_array = (arrays & (1UL << i)) > 0;
7274 struct bpf_prog_info_array_desc *desc;
7277 desc = bpf_prog_info_array_desc + i;
7279 /* kernel is too old to support this field */
7280 if (info_len < desc->array_offset + sizeof(__u32) ||
7281 info_len < desc->count_offset + sizeof(__u32) ||
7282 (desc->size_offset > 0 && info_len < desc->size_offset))
7283 include_array = false;
7285 if (!include_array) {
7286 arrays &= ~(1UL << i); /* clear the bit */
7290 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
7291 size = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
7293 data_len += count * size;
7296 /* step 3: allocate continuous memory */
7297 data_len = roundup(data_len, sizeof(__u64));
7298 info_linear = malloc(sizeof(struct bpf_prog_info_linear) + data_len);
7300 return ERR_PTR(-ENOMEM);
7302 /* step 4: fill data to info_linear->info */
7303 info_linear->arrays = arrays;
7304 memset(&info_linear->info, 0, sizeof(info));
7305 ptr = info_linear->data;
7307 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
7308 struct bpf_prog_info_array_desc *desc;
7311 if ((arrays & (1UL << i)) == 0)
7314 desc = bpf_prog_info_array_desc + i;
7315 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
7316 size = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
7317 bpf_prog_info_set_offset_u32(&info_linear->info,
7318 desc->count_offset, count);
7319 bpf_prog_info_set_offset_u32(&info_linear->info,
7320 desc->size_offset, size);
7321 bpf_prog_info_set_offset_u64(&info_linear->info,
7324 ptr += count * size;
7327 /* step 5: call syscall again to get required arrays */
7328 err = bpf_obj_get_info_by_fd(fd, &info_linear->info, &info_len);
7330 pr_debug("can't get prog info: %s", strerror(errno));
7332 return ERR_PTR(-EFAULT);
7335 /* step 6: verify the data */
7336 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
7337 struct bpf_prog_info_array_desc *desc;
7340 if ((arrays & (1UL << i)) == 0)
7343 desc = bpf_prog_info_array_desc + i;
7344 v1 = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
7345 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
7346 desc->count_offset);
7348 pr_warn("%s: mismatch in element count\n", __func__);
7350 v1 = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
7351 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
7354 pr_warn("%s: mismatch in rec size\n", __func__);
7357 /* step 7: update info_len and data_len */
7358 info_linear->info_len = sizeof(struct bpf_prog_info);
7359 info_linear->data_len = data_len;
7364 void bpf_program__bpil_addr_to_offs(struct bpf_prog_info_linear *info_linear)
7368 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
7369 struct bpf_prog_info_array_desc *desc;
7372 if ((info_linear->arrays & (1UL << i)) == 0)
7375 desc = bpf_prog_info_array_desc + i;
7376 addr = bpf_prog_info_read_offset_u64(&info_linear->info,
7377 desc->array_offset);
7378 offs = addr - ptr_to_u64(info_linear->data);
7379 bpf_prog_info_set_offset_u64(&info_linear->info,
7380 desc->array_offset, offs);
7384 void bpf_program__bpil_offs_to_addr(struct bpf_prog_info_linear *info_linear)
7388 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
7389 struct bpf_prog_info_array_desc *desc;
7392 if ((info_linear->arrays & (1UL << i)) == 0)
7395 desc = bpf_prog_info_array_desc + i;
7396 offs = bpf_prog_info_read_offset_u64(&info_linear->info,
7397 desc->array_offset);
7398 addr = offs + ptr_to_u64(info_linear->data);
7399 bpf_prog_info_set_offset_u64(&info_linear->info,
7400 desc->array_offset, addr);
7404 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
7406 int err = 0, n, len, start, end = -1;
7412 /* Each sub string separated by ',' has format \d+-\d+ or \d+ */
7414 if (*s == ',' || *s == '\n') {
7418 n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
7419 if (n <= 0 || n > 2) {
7420 pr_warn("Failed to get CPU range %s: %d\n", s, n);
7423 } else if (n == 1) {
7426 if (start < 0 || start > end) {
7427 pr_warn("Invalid CPU range [%d,%d] in %s\n",
7432 tmp = realloc(*mask, end + 1);
7438 memset(tmp + *mask_sz, 0, start - *mask_sz);
7439 memset(tmp + start, 1, end - start + 1);
7444 pr_warn("Empty CPU range\n");
7454 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
7456 int fd, err = 0, len;
7459 fd = open(fcpu, O_RDONLY);
7462 pr_warn("Failed to open cpu mask file %s: %d\n", fcpu, err);
7465 len = read(fd, buf, sizeof(buf));
7468 err = len ? -errno : -EINVAL;
7469 pr_warn("Failed to read cpu mask from %s: %d\n", fcpu, err);
7472 if (len >= sizeof(buf)) {
7473 pr_warn("CPU mask is too big in file %s\n", fcpu);
7478 return parse_cpu_mask_str(buf, mask, mask_sz);
7481 int libbpf_num_possible_cpus(void)
7483 static const char *fcpu = "/sys/devices/system/cpu/possible";
7485 int err, n, i, tmp_cpus;
7488 tmp_cpus = READ_ONCE(cpus);
7492 err = parse_cpu_mask_file(fcpu, &mask, &n);
7497 for (i = 0; i < n; i++) {
7503 WRITE_ONCE(cpus, tmp_cpus);
7507 int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
7508 const struct bpf_object_open_opts *opts)
7510 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, skel_opts,
7511 .object_name = s->name,
7513 struct bpf_object *obj;
7516 /* Attempt to preserve opts->object_name, unless overriden by user
7517 * explicitly. Overwriting object name for skeletons is discouraged,
7518 * as it breaks global data maps, because they contain object name
7519 * prefix as their own map name prefix. When skeleton is generated,
7520 * bpftool is making an assumption that this name will stay the same.
7523 memcpy(&skel_opts, opts, sizeof(*opts));
7524 if (!opts->object_name)
7525 skel_opts.object_name = s->name;
7528 obj = bpf_object__open_mem(s->data, s->data_sz, &skel_opts);
7530 pr_warn("failed to initialize skeleton BPF object '%s': %ld\n",
7531 s->name, PTR_ERR(obj));
7532 return PTR_ERR(obj);
7537 for (i = 0; i < s->map_cnt; i++) {
7538 struct bpf_map **map = s->maps[i].map;
7539 const char *name = s->maps[i].name;
7540 void **mmaped = s->maps[i].mmaped;
7542 *map = bpf_object__find_map_by_name(obj, name);
7544 pr_warn("failed to find skeleton map '%s'\n", name);
7548 /* externs shouldn't be pre-setup from user code */
7549 if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_EXTERN)
7550 *mmaped = (*map)->mmaped;
7553 for (i = 0; i < s->prog_cnt; i++) {
7554 struct bpf_program **prog = s->progs[i].prog;
7555 const char *name = s->progs[i].name;
7557 *prog = bpf_object__find_program_by_name(obj, name);
7559 pr_warn("failed to find skeleton program '%s'\n", name);
7567 int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
7571 err = bpf_object__load(*s->obj);
7573 pr_warn("failed to load BPF skeleton '%s': %d\n", s->name, err);
7577 for (i = 0; i < s->map_cnt; i++) {
7578 struct bpf_map *map = *s->maps[i].map;
7579 size_t mmap_sz = bpf_map_mmap_sz(map);
7580 int prot, map_fd = bpf_map__fd(map);
7581 void **mmaped = s->maps[i].mmaped;
7586 if (!(map->def.map_flags & BPF_F_MMAPABLE)) {
7591 if (map->def.map_flags & BPF_F_RDONLY_PROG)
7594 prot = PROT_READ | PROT_WRITE;
7596 /* Remap anonymous mmap()-ed "map initialization image" as
7597 * a BPF map-backed mmap()-ed memory, but preserving the same
7598 * memory address. This will cause kernel to change process'
7599 * page table to point to a different piece of kernel memory,
7600 * but from userspace point of view memory address (and its
7601 * contents, being identical at this point) will stay the
7602 * same. This mapping will be released by bpf_object__close()
7603 * as per normal clean up procedure, so we don't need to worry
7604 * about it from skeleton's clean up perspective.
7606 *mmaped = mmap(map->mmaped, mmap_sz, prot,
7607 MAP_SHARED | MAP_FIXED, map_fd, 0);
7608 if (*mmaped == MAP_FAILED) {
7611 pr_warn("failed to re-mmap() map '%s': %d\n",
7612 bpf_map__name(map), err);
7620 int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
7624 for (i = 0; i < s->prog_cnt; i++) {
7625 struct bpf_program *prog = *s->progs[i].prog;
7626 struct bpf_link **link = s->progs[i].link;
7627 const struct bpf_sec_def *sec_def;
7628 const char *sec_name = bpf_program__title(prog, false);
7630 sec_def = find_sec_def(sec_name);
7631 if (!sec_def || !sec_def->attach_fn)
7634 *link = sec_def->attach_fn(sec_def, prog);
7635 if (IS_ERR(*link)) {
7636 pr_warn("failed to auto-attach program '%s': %ld\n",
7637 bpf_program__name(prog), PTR_ERR(*link));
7638 return PTR_ERR(*link);
7645 void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
7649 for (i = 0; i < s->prog_cnt; i++) {
7650 struct bpf_link **link = s->progs[i].link;
7652 if (!IS_ERR_OR_NULL(*link))
7653 bpf_link__destroy(*link);
7658 void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
7661 bpf_object__detach_skeleton(s);
7663 bpf_object__close(*s->obj);