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.
28 #include <asm/unistd.h>
29 #include <linux/err.h>
30 #include <linux/kernel.h>
31 #include <linux/bpf.h>
32 #include <linux/btf.h>
33 #include <linux/filter.h>
34 #include <linux/list.h>
35 #include <linux/limits.h>
36 #include <linux/perf_event.h>
37 #include <linux/ring_buffer.h>
38 #include <linux/version.h>
39 #include <sys/epoll.h>
40 #include <sys/ioctl.h>
43 #include <sys/types.h>
45 #include <sys/utsname.h>
46 #include <sys/resource.h>
47 #include <tools/libc_compat.h>
55 #include "str_error.h"
56 #include "libbpf_internal.h"
59 /* make sure libbpf doesn't use kernel-only integer typedefs */
60 #pragma GCC poison u8 u16 u32 u64 s8 s16 s32 s64
67 #define BPF_FS_MAGIC 0xcafe4a11
70 /* vsprintf() in __base_pr() uses nonliteral format string. It may break
71 * compilation if user enables corresponding warning. Disable it explicitly.
73 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
75 #define __printf(a, b) __attribute__((format(printf, a, b)))
77 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj);
78 static struct bpf_program *bpf_object__find_prog_by_idx(struct bpf_object *obj,
80 static const struct btf_type *
81 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id);
83 static int __base_pr(enum libbpf_print_level level, const char *format,
86 if (level == LIBBPF_DEBUG)
89 return vfprintf(stderr, format, args);
92 static libbpf_print_fn_t __libbpf_pr = __base_pr;
94 libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn)
96 libbpf_print_fn_t old_print_fn = __libbpf_pr;
103 void libbpf_print(enum libbpf_print_level level, const char *format, ...)
110 va_start(args, format);
111 __libbpf_pr(level, format, args);
115 static void pr_perm_msg(int err)
120 if (err != -EPERM || geteuid() != 0)
123 err = getrlimit(RLIMIT_MEMLOCK, &limit);
127 if (limit.rlim_cur == RLIM_INFINITY)
130 if (limit.rlim_cur < 1024)
131 snprintf(buf, sizeof(buf), "%zu bytes", (size_t)limit.rlim_cur);
132 else if (limit.rlim_cur < 1024*1024)
133 snprintf(buf, sizeof(buf), "%.1f KiB", (double)limit.rlim_cur / 1024);
135 snprintf(buf, sizeof(buf), "%.1f MiB", (double)limit.rlim_cur / (1024*1024));
137 pr_warn("permission error while running as root; try raising 'ulimit -l'? current value: %s\n",
141 #define STRERR_BUFSIZE 128
143 /* Copied from tools/perf/util/util.h */
145 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
149 # define zclose(fd) ({ \
152 ___err = close((fd)); \
157 #ifdef HAVE_LIBELF_MMAP_SUPPORT
158 # define LIBBPF_ELF_C_READ_MMAP ELF_C_READ_MMAP
160 # define LIBBPF_ELF_C_READ_MMAP ELF_C_READ
163 static inline __u64 ptr_to_u64(const void *ptr)
165 return (__u64) (unsigned long) ptr;
168 struct bpf_capabilities {
169 /* v4.14: kernel support for program & map names. */
171 /* v5.2: kernel support for global data sections. */
173 /* BTF_KIND_FUNC and BTF_KIND_FUNC_PROTO support */
175 /* BTF_KIND_VAR and BTF_KIND_DATASEC support */
177 /* BPF_F_MMAPABLE is supported for arrays */
179 /* BTF_FUNC_GLOBAL is supported */
180 __u32 btf_func_global:1;
181 /* kernel support for expected_attach_type in BPF_PROG_LOAD */
182 __u32 exp_attach_type:1;
193 enum reloc_type type;
201 typedef struct bpf_link *(*attach_fn_t)(const struct bpf_sec_def *sec,
202 struct bpf_program *prog);
207 enum bpf_prog_type prog_type;
208 enum bpf_attach_type expected_attach_type;
209 bool is_exp_attach_type_optional;
212 attach_fn_t attach_fn;
216 * bpf_prog should be a better name but it has been used in
220 /* Index in elf obj file, for relocation use. */
225 const struct bpf_sec_def *sec_def;
226 /* section_name with / replaced by _; makes recursive pinning
227 * in bpf_object__pin_programs easier
230 struct bpf_insn *insns;
231 size_t insns_cnt, main_prog_cnt;
232 enum bpf_prog_type type;
235 struct reloc_desc *reloc_desc;
243 bpf_program_prep_t preprocessor;
245 struct bpf_object *obj;
247 bpf_program_clear_priv_t clear_priv;
249 enum bpf_attach_type expected_attach_type;
251 __u32 attach_prog_fd;
253 __u32 func_info_rec_size;
256 struct bpf_capabilities *caps;
259 __u32 line_info_rec_size;
264 struct bpf_struct_ops {
266 const struct btf_type *type;
267 struct bpf_program **progs;
268 __u32 *kern_func_off;
269 /* e.g. struct tcp_congestion_ops in bpf_prog's btf format */
271 /* e.g. struct bpf_struct_ops_tcp_congestion_ops in
272 * btf_vmlinux's format.
273 * struct bpf_struct_ops_tcp_congestion_ops {
274 * [... some other kernel fields ...]
275 * struct tcp_congestion_ops data;
277 * kern_vdata-size == sizeof(struct bpf_struct_ops_tcp_congestion_ops)
278 * bpf_map__init_kern_struct_ops() will populate the "kern_vdata"
285 #define DATA_SEC ".data"
286 #define BSS_SEC ".bss"
287 #define RODATA_SEC ".rodata"
288 #define KCONFIG_SEC ".kconfig"
289 #define KSYMS_SEC ".ksyms"
290 #define STRUCT_OPS_SEC ".struct_ops"
292 enum libbpf_map_type {
300 static const char * const libbpf_type_to_btf_name[] = {
301 [LIBBPF_MAP_DATA] = DATA_SEC,
302 [LIBBPF_MAP_BSS] = BSS_SEC,
303 [LIBBPF_MAP_RODATA] = RODATA_SEC,
304 [LIBBPF_MAP_KCONFIG] = KCONFIG_SEC,
314 struct bpf_map_def def;
317 __u32 btf_key_type_id;
318 __u32 btf_value_type_id;
319 __u32 btf_vmlinux_value_type_id;
321 bpf_map_clear_priv_t clear_priv;
322 enum libbpf_map_type libbpf_type;
324 struct bpf_struct_ops *st_ops;
325 struct bpf_map *inner_map;
349 enum extern_type type;
365 unsigned long long addr;
370 static LIST_HEAD(bpf_objects_list);
373 char name[BPF_OBJ_NAME_LEN];
377 struct bpf_program *programs;
379 struct bpf_map *maps;
384 struct extern_desc *externs;
389 bool has_pseudo_calls;
392 * Information when doing elf related work. Only valid if fd
405 Elf_Data *st_ops_data;
414 __u32 btf_maps_sec_btf_id;
423 * All loaded bpf_object is linked in a list, which is
424 * hidden to caller. bpf_objects__<func> handlers deal with
427 struct list_head list;
430 /* Parse and load BTF vmlinux if any of the programs in the object need
433 struct btf *btf_vmlinux;
434 struct btf_ext *btf_ext;
437 bpf_object_clear_priv_t clear_priv;
439 struct bpf_capabilities caps;
443 #define obj_elf_valid(o) ((o)->efile.elf)
445 void bpf_program__unload(struct bpf_program *prog)
453 * If the object is opened but the program was never loaded,
454 * it is possible that prog->instances.nr == -1.
456 if (prog->instances.nr > 0) {
457 for (i = 0; i < prog->instances.nr; i++)
458 zclose(prog->instances.fds[i]);
459 } else if (prog->instances.nr != -1) {
460 pr_warn("Internal error: instances.nr is %d\n",
464 prog->instances.nr = -1;
465 zfree(&prog->instances.fds);
467 zfree(&prog->func_info);
468 zfree(&prog->line_info);
471 static void bpf_program__exit(struct bpf_program *prog)
476 if (prog->clear_priv)
477 prog->clear_priv(prog, prog->priv);
480 prog->clear_priv = NULL;
482 bpf_program__unload(prog);
484 zfree(&prog->section_name);
485 zfree(&prog->pin_name);
487 zfree(&prog->reloc_desc);
494 static char *__bpf_program__pin_name(struct bpf_program *prog)
498 name = p = strdup(prog->section_name);
499 while ((p = strchr(p, '/')))
506 bpf_program__init(void *data, size_t size, char *section_name, int idx,
507 struct bpf_program *prog)
509 const size_t bpf_insn_sz = sizeof(struct bpf_insn);
511 if (size == 0 || size % bpf_insn_sz) {
512 pr_warn("corrupted section '%s', size: %zu\n",
517 memset(prog, 0, sizeof(*prog));
519 prog->section_name = strdup(section_name);
520 if (!prog->section_name) {
521 pr_warn("failed to alloc name for prog under section(%d) %s\n",
526 prog->pin_name = __bpf_program__pin_name(prog);
527 if (!prog->pin_name) {
528 pr_warn("failed to alloc pin name for prog under section(%d) %s\n",
533 prog->insns = malloc(size);
535 pr_warn("failed to alloc insns for prog under section %s\n",
539 prog->insns_cnt = size / bpf_insn_sz;
540 memcpy(prog->insns, data, size);
542 prog->instances.fds = NULL;
543 prog->instances.nr = -1;
544 prog->type = BPF_PROG_TYPE_UNSPEC;
549 bpf_program__exit(prog);
554 bpf_object__add_program(struct bpf_object *obj, void *data, size_t size,
555 char *section_name, int idx)
557 struct bpf_program prog, *progs;
560 err = bpf_program__init(data, size, section_name, idx, &prog);
564 prog.caps = &obj->caps;
565 progs = obj->programs;
566 nr_progs = obj->nr_programs;
568 progs = reallocarray(progs, nr_progs + 1, sizeof(progs[0]));
571 * In this case the original obj->programs
572 * is still valid, so don't need special treat for
573 * bpf_close_object().
575 pr_warn("failed to alloc a new program under section '%s'\n",
577 bpf_program__exit(&prog);
581 pr_debug("found program %s\n", prog.section_name);
582 obj->programs = progs;
583 obj->nr_programs = nr_progs + 1;
585 progs[nr_progs] = prog;
590 bpf_object__init_prog_names(struct bpf_object *obj)
592 Elf_Data *symbols = obj->efile.symbols;
593 struct bpf_program *prog;
596 for (pi = 0; pi < obj->nr_programs; pi++) {
597 const char *name = NULL;
599 prog = &obj->programs[pi];
601 for (si = 0; si < symbols->d_size / sizeof(GElf_Sym) && !name;
605 if (!gelf_getsym(symbols, si, &sym))
607 if (sym.st_shndx != prog->idx)
609 if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL)
612 name = elf_strptr(obj->efile.elf,
613 obj->efile.strtabidx,
616 pr_warn("failed to get sym name string for prog %s\n",
618 return -LIBBPF_ERRNO__LIBELF;
622 if (!name && prog->idx == obj->efile.text_shndx)
626 pr_warn("failed to find sym for prog %s\n",
631 prog->name = strdup(name);
633 pr_warn("failed to allocate memory for prog sym %s\n",
642 static __u32 get_kernel_version(void)
644 __u32 major, minor, patch;
648 if (sscanf(info.release, "%u.%u.%u", &major, &minor, &patch) != 3)
650 return KERNEL_VERSION(major, minor, patch);
653 static const struct btf_member *
654 find_member_by_offset(const struct btf_type *t, __u32 bit_offset)
656 struct btf_member *m;
659 for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
660 if (btf_member_bit_offset(t, i) == bit_offset)
667 static const struct btf_member *
668 find_member_by_name(const struct btf *btf, const struct btf_type *t,
671 struct btf_member *m;
674 for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
675 if (!strcmp(btf__name_by_offset(btf, m->name_off), name))
682 #define STRUCT_OPS_VALUE_PREFIX "bpf_struct_ops_"
683 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
684 const char *name, __u32 kind);
687 find_struct_ops_kern_types(const struct btf *btf, const char *tname,
688 const struct btf_type **type, __u32 *type_id,
689 const struct btf_type **vtype, __u32 *vtype_id,
690 const struct btf_member **data_member)
692 const struct btf_type *kern_type, *kern_vtype;
693 const struct btf_member *kern_data_member;
694 __s32 kern_vtype_id, kern_type_id;
697 kern_type_id = btf__find_by_name_kind(btf, tname, BTF_KIND_STRUCT);
698 if (kern_type_id < 0) {
699 pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n",
703 kern_type = btf__type_by_id(btf, kern_type_id);
705 /* Find the corresponding "map_value" type that will be used
706 * in map_update(BPF_MAP_TYPE_STRUCT_OPS). For example,
707 * find "struct bpf_struct_ops_tcp_congestion_ops" from the
710 kern_vtype_id = find_btf_by_prefix_kind(btf, STRUCT_OPS_VALUE_PREFIX,
711 tname, BTF_KIND_STRUCT);
712 if (kern_vtype_id < 0) {
713 pr_warn("struct_ops init_kern: struct %s%s is not found in kernel BTF\n",
714 STRUCT_OPS_VALUE_PREFIX, tname);
715 return kern_vtype_id;
717 kern_vtype = btf__type_by_id(btf, kern_vtype_id);
719 /* Find "struct tcp_congestion_ops" from
720 * struct bpf_struct_ops_tcp_congestion_ops {
722 * struct tcp_congestion_ops data;
725 kern_data_member = btf_members(kern_vtype);
726 for (i = 0; i < btf_vlen(kern_vtype); i++, kern_data_member++) {
727 if (kern_data_member->type == kern_type_id)
730 if (i == btf_vlen(kern_vtype)) {
731 pr_warn("struct_ops init_kern: struct %s data is not found in struct %s%s\n",
732 tname, STRUCT_OPS_VALUE_PREFIX, tname);
737 *type_id = kern_type_id;
739 *vtype_id = kern_vtype_id;
740 *data_member = kern_data_member;
745 static bool bpf_map__is_struct_ops(const struct bpf_map *map)
747 return map->def.type == BPF_MAP_TYPE_STRUCT_OPS;
750 /* Init the map's fields that depend on kern_btf */
751 static int bpf_map__init_kern_struct_ops(struct bpf_map *map,
752 const struct btf *btf,
753 const struct btf *kern_btf)
755 const struct btf_member *member, *kern_member, *kern_data_member;
756 const struct btf_type *type, *kern_type, *kern_vtype;
757 __u32 i, kern_type_id, kern_vtype_id, kern_data_off;
758 struct bpf_struct_ops *st_ops;
759 void *data, *kern_data;
763 st_ops = map->st_ops;
765 tname = st_ops->tname;
766 err = find_struct_ops_kern_types(kern_btf, tname,
767 &kern_type, &kern_type_id,
768 &kern_vtype, &kern_vtype_id,
773 pr_debug("struct_ops init_kern %s: type_id:%u kern_type_id:%u kern_vtype_id:%u\n",
774 map->name, st_ops->type_id, kern_type_id, kern_vtype_id);
776 map->def.value_size = kern_vtype->size;
777 map->btf_vmlinux_value_type_id = kern_vtype_id;
779 st_ops->kern_vdata = calloc(1, kern_vtype->size);
780 if (!st_ops->kern_vdata)
784 kern_data_off = kern_data_member->offset / 8;
785 kern_data = st_ops->kern_vdata + kern_data_off;
787 member = btf_members(type);
788 for (i = 0; i < btf_vlen(type); i++, member++) {
789 const struct btf_type *mtype, *kern_mtype;
790 __u32 mtype_id, kern_mtype_id;
791 void *mdata, *kern_mdata;
792 __s64 msize, kern_msize;
793 __u32 moff, kern_moff;
794 __u32 kern_member_idx;
797 mname = btf__name_by_offset(btf, member->name_off);
798 kern_member = find_member_by_name(kern_btf, kern_type, mname);
800 pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n",
805 kern_member_idx = kern_member - btf_members(kern_type);
806 if (btf_member_bitfield_size(type, i) ||
807 btf_member_bitfield_size(kern_type, kern_member_idx)) {
808 pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n",
813 moff = member->offset / 8;
814 kern_moff = kern_member->offset / 8;
817 kern_mdata = kern_data + kern_moff;
819 mtype = skip_mods_and_typedefs(btf, member->type, &mtype_id);
820 kern_mtype = skip_mods_and_typedefs(kern_btf, kern_member->type,
822 if (BTF_INFO_KIND(mtype->info) !=
823 BTF_INFO_KIND(kern_mtype->info)) {
824 pr_warn("struct_ops init_kern %s: Unmatched member type %s %u != %u(kernel)\n",
825 map->name, mname, BTF_INFO_KIND(mtype->info),
826 BTF_INFO_KIND(kern_mtype->info));
830 if (btf_is_ptr(mtype)) {
831 struct bpf_program *prog;
833 mtype = skip_mods_and_typedefs(btf, mtype->type, &mtype_id);
834 kern_mtype = skip_mods_and_typedefs(kern_btf,
837 if (!btf_is_func_proto(mtype) ||
838 !btf_is_func_proto(kern_mtype)) {
839 pr_warn("struct_ops init_kern %s: non func ptr %s is not supported\n",
844 prog = st_ops->progs[i];
846 pr_debug("struct_ops init_kern %s: func ptr %s is not set\n",
851 prog->attach_btf_id = kern_type_id;
852 prog->expected_attach_type = kern_member_idx;
854 st_ops->kern_func_off[i] = kern_data_off + kern_moff;
856 pr_debug("struct_ops init_kern %s: func ptr %s is set to prog %s from data(+%u) to kern_data(+%u)\n",
857 map->name, mname, prog->name, moff,
863 msize = btf__resolve_size(btf, mtype_id);
864 kern_msize = btf__resolve_size(kern_btf, kern_mtype_id);
865 if (msize < 0 || kern_msize < 0 || msize != kern_msize) {
866 pr_warn("struct_ops init_kern %s: Error in size of member %s: %zd != %zd(kernel)\n",
867 map->name, mname, (ssize_t)msize,
868 (ssize_t)kern_msize);
872 pr_debug("struct_ops init_kern %s: copy %s %u bytes from data(+%u) to kern_data(+%u)\n",
873 map->name, mname, (unsigned int)msize,
875 memcpy(kern_mdata, mdata, msize);
881 static int bpf_object__init_kern_struct_ops_maps(struct bpf_object *obj)
887 for (i = 0; i < obj->nr_maps; i++) {
890 if (!bpf_map__is_struct_ops(map))
893 err = bpf_map__init_kern_struct_ops(map, obj->btf,
902 static int bpf_object__init_struct_ops_maps(struct bpf_object *obj)
904 const struct btf_type *type, *datasec;
905 const struct btf_var_secinfo *vsi;
906 struct bpf_struct_ops *st_ops;
907 const char *tname, *var_name;
908 __s32 type_id, datasec_id;
909 const struct btf *btf;
913 if (obj->efile.st_ops_shndx == -1)
917 datasec_id = btf__find_by_name_kind(btf, STRUCT_OPS_SEC,
919 if (datasec_id < 0) {
920 pr_warn("struct_ops init: DATASEC %s not found\n",
925 datasec = btf__type_by_id(btf, datasec_id);
926 vsi = btf_var_secinfos(datasec);
927 for (i = 0; i < btf_vlen(datasec); i++, vsi++) {
928 type = btf__type_by_id(obj->btf, vsi->type);
929 var_name = btf__name_by_offset(obj->btf, type->name_off);
931 type_id = btf__resolve_type(obj->btf, vsi->type);
933 pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
934 vsi->type, STRUCT_OPS_SEC);
938 type = btf__type_by_id(obj->btf, type_id);
939 tname = btf__name_by_offset(obj->btf, type->name_off);
941 pr_warn("struct_ops init: anonymous type is not supported\n");
944 if (!btf_is_struct(type)) {
945 pr_warn("struct_ops init: %s is not a struct\n", tname);
949 map = bpf_object__add_map(obj);
953 map->sec_idx = obj->efile.st_ops_shndx;
954 map->sec_offset = vsi->offset;
955 map->name = strdup(var_name);
959 map->def.type = BPF_MAP_TYPE_STRUCT_OPS;
960 map->def.key_size = sizeof(int);
961 map->def.value_size = type->size;
962 map->def.max_entries = 1;
964 map->st_ops = calloc(1, sizeof(*map->st_ops));
967 st_ops = map->st_ops;
968 st_ops->data = malloc(type->size);
969 st_ops->progs = calloc(btf_vlen(type), sizeof(*st_ops->progs));
970 st_ops->kern_func_off = malloc(btf_vlen(type) *
971 sizeof(*st_ops->kern_func_off));
972 if (!st_ops->data || !st_ops->progs || !st_ops->kern_func_off)
975 if (vsi->offset + type->size > obj->efile.st_ops_data->d_size) {
976 pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
977 var_name, STRUCT_OPS_SEC);
982 obj->efile.st_ops_data->d_buf + vsi->offset,
984 st_ops->tname = tname;
986 st_ops->type_id = type_id;
988 pr_debug("struct_ops init: struct %s(type_id=%u) %s found at offset %u\n",
989 tname, type_id, var_name, vsi->offset);
995 static struct bpf_object *bpf_object__new(const char *path,
998 const char *obj_name)
1000 struct bpf_object *obj;
1003 obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
1005 pr_warn("alloc memory failed for %s\n", path);
1006 return ERR_PTR(-ENOMEM);
1009 strcpy(obj->path, path);
1011 strncpy(obj->name, obj_name, sizeof(obj->name) - 1);
1012 obj->name[sizeof(obj->name) - 1] = 0;
1014 /* Using basename() GNU version which doesn't modify arg. */
1015 strncpy(obj->name, basename((void *)path),
1016 sizeof(obj->name) - 1);
1017 end = strchr(obj->name, '.');
1024 * Caller of this function should also call
1025 * bpf_object__elf_finish() after data collection to return
1026 * obj_buf to user. If not, we should duplicate the buffer to
1027 * avoid user freeing them before elf finish.
1029 obj->efile.obj_buf = obj_buf;
1030 obj->efile.obj_buf_sz = obj_buf_sz;
1031 obj->efile.maps_shndx = -1;
1032 obj->efile.btf_maps_shndx = -1;
1033 obj->efile.data_shndx = -1;
1034 obj->efile.rodata_shndx = -1;
1035 obj->efile.bss_shndx = -1;
1036 obj->efile.st_ops_shndx = -1;
1037 obj->kconfig_map_idx = -1;
1039 obj->kern_version = get_kernel_version();
1040 obj->loaded = false;
1042 INIT_LIST_HEAD(&obj->list);
1043 list_add(&obj->list, &bpf_objects_list);
1047 static void bpf_object__elf_finish(struct bpf_object *obj)
1049 if (!obj_elf_valid(obj))
1052 if (obj->efile.elf) {
1053 elf_end(obj->efile.elf);
1054 obj->efile.elf = NULL;
1056 obj->efile.symbols = NULL;
1057 obj->efile.data = NULL;
1058 obj->efile.rodata = NULL;
1059 obj->efile.bss = NULL;
1060 obj->efile.st_ops_data = NULL;
1062 zfree(&obj->efile.reloc_sects);
1063 obj->efile.nr_reloc_sects = 0;
1064 zclose(obj->efile.fd);
1065 obj->efile.obj_buf = NULL;
1066 obj->efile.obj_buf_sz = 0;
1069 static int bpf_object__elf_init(struct bpf_object *obj)
1074 if (obj_elf_valid(obj)) {
1075 pr_warn("elf init: internal error\n");
1076 return -LIBBPF_ERRNO__LIBELF;
1079 if (obj->efile.obj_buf_sz > 0) {
1081 * obj_buf should have been validated by
1082 * bpf_object__open_buffer().
1084 obj->efile.elf = elf_memory((char *)obj->efile.obj_buf,
1085 obj->efile.obj_buf_sz);
1087 obj->efile.fd = open(obj->path, O_RDONLY);
1088 if (obj->efile.fd < 0) {
1089 char errmsg[STRERR_BUFSIZE], *cp;
1092 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
1093 pr_warn("failed to open %s: %s\n", obj->path, cp);
1097 obj->efile.elf = elf_begin(obj->efile.fd,
1098 LIBBPF_ELF_C_READ_MMAP, NULL);
1101 if (!obj->efile.elf) {
1102 pr_warn("failed to open %s as ELF file\n", obj->path);
1103 err = -LIBBPF_ERRNO__LIBELF;
1107 if (!gelf_getehdr(obj->efile.elf, &obj->efile.ehdr)) {
1108 pr_warn("failed to get EHDR from %s\n", obj->path);
1109 err = -LIBBPF_ERRNO__FORMAT;
1112 ep = &obj->efile.ehdr;
1114 /* Old LLVM set e_machine to EM_NONE */
1115 if (ep->e_type != ET_REL ||
1116 (ep->e_machine && ep->e_machine != EM_BPF)) {
1117 pr_warn("%s is not an eBPF object file\n", obj->path);
1118 err = -LIBBPF_ERRNO__FORMAT;
1124 bpf_object__elf_finish(obj);
1128 static int bpf_object__check_endianness(struct bpf_object *obj)
1130 #if __BYTE_ORDER == __LITTLE_ENDIAN
1131 if (obj->efile.ehdr.e_ident[EI_DATA] == ELFDATA2LSB)
1133 #elif __BYTE_ORDER == __BIG_ENDIAN
1134 if (obj->efile.ehdr.e_ident[EI_DATA] == ELFDATA2MSB)
1137 # error "Unrecognized __BYTE_ORDER__"
1139 pr_warn("endianness mismatch.\n");
1140 return -LIBBPF_ERRNO__ENDIAN;
1144 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
1146 memcpy(obj->license, data, min(size, sizeof(obj->license) - 1));
1147 pr_debug("license of %s is %s\n", obj->path, obj->license);
1152 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
1156 if (size != sizeof(kver)) {
1157 pr_warn("invalid kver section in %s\n", obj->path);
1158 return -LIBBPF_ERRNO__FORMAT;
1160 memcpy(&kver, data, sizeof(kver));
1161 obj->kern_version = kver;
1162 pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
1166 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
1168 if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
1169 type == BPF_MAP_TYPE_HASH_OF_MAPS)
1174 static int bpf_object_search_section_size(const struct bpf_object *obj,
1175 const char *name, size_t *d_size)
1177 const GElf_Ehdr *ep = &obj->efile.ehdr;
1178 Elf *elf = obj->efile.elf;
1179 Elf_Scn *scn = NULL;
1182 while ((scn = elf_nextscn(elf, scn)) != NULL) {
1183 const char *sec_name;
1188 if (gelf_getshdr(scn, &sh) != &sh) {
1189 pr_warn("failed to get section(%d) header from %s\n",
1194 sec_name = elf_strptr(elf, ep->e_shstrndx, sh.sh_name);
1196 pr_warn("failed to get section(%d) name from %s\n",
1201 if (strcmp(name, sec_name))
1204 data = elf_getdata(scn, 0);
1206 pr_warn("failed to get section(%d) data from %s(%s)\n",
1207 idx, name, obj->path);
1211 *d_size = data->d_size;
1218 int bpf_object__section_size(const struct bpf_object *obj, const char *name,
1227 } else if (!strcmp(name, DATA_SEC)) {
1228 if (obj->efile.data)
1229 *size = obj->efile.data->d_size;
1230 } else if (!strcmp(name, BSS_SEC)) {
1232 *size = obj->efile.bss->d_size;
1233 } else if (!strcmp(name, RODATA_SEC)) {
1234 if (obj->efile.rodata)
1235 *size = obj->efile.rodata->d_size;
1236 } else if (!strcmp(name, STRUCT_OPS_SEC)) {
1237 if (obj->efile.st_ops_data)
1238 *size = obj->efile.st_ops_data->d_size;
1240 ret = bpf_object_search_section_size(obj, name, &d_size);
1245 return *size ? 0 : ret;
1248 int bpf_object__variable_offset(const struct bpf_object *obj, const char *name,
1251 Elf_Data *symbols = obj->efile.symbols;
1258 for (si = 0; si < symbols->d_size / sizeof(GElf_Sym); si++) {
1261 if (!gelf_getsym(symbols, si, &sym))
1263 if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL ||
1264 GELF_ST_TYPE(sym.st_info) != STT_OBJECT)
1267 sname = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
1270 pr_warn("failed to get sym name string for var %s\n",
1274 if (strcmp(name, sname) == 0) {
1275 *off = sym.st_value;
1283 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
1285 struct bpf_map *new_maps;
1289 if (obj->nr_maps < obj->maps_cap)
1290 return &obj->maps[obj->nr_maps++];
1292 new_cap = max((size_t)4, obj->maps_cap * 3 / 2);
1293 new_maps = realloc(obj->maps, new_cap * sizeof(*obj->maps));
1295 pr_warn("alloc maps for object failed\n");
1296 return ERR_PTR(-ENOMEM);
1299 obj->maps_cap = new_cap;
1300 obj->maps = new_maps;
1302 /* zero out new maps */
1303 memset(obj->maps + obj->nr_maps, 0,
1304 (obj->maps_cap - obj->nr_maps) * sizeof(*obj->maps));
1306 * fill all fd with -1 so won't close incorrect fd (fd=0 is stdin)
1307 * when failure (zclose won't close negative fd)).
1309 for (i = obj->nr_maps; i < obj->maps_cap; i++) {
1310 obj->maps[i].fd = -1;
1311 obj->maps[i].inner_map_fd = -1;
1314 return &obj->maps[obj->nr_maps++];
1317 static size_t bpf_map_mmap_sz(const struct bpf_map *map)
1319 long page_sz = sysconf(_SC_PAGE_SIZE);
1322 map_sz = (size_t)roundup(map->def.value_size, 8) * map->def.max_entries;
1323 map_sz = roundup(map_sz, page_sz);
1327 static char *internal_map_name(struct bpf_object *obj,
1328 enum libbpf_map_type type)
1330 char map_name[BPF_OBJ_NAME_LEN], *p;
1331 const char *sfx = libbpf_type_to_btf_name[type];
1332 int sfx_len = max((size_t)7, strlen(sfx));
1333 int pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1,
1336 snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
1337 sfx_len, libbpf_type_to_btf_name[type]);
1339 /* sanitise map name to characters allowed by kernel */
1340 for (p = map_name; *p && p < map_name + sizeof(map_name); p++)
1341 if (!isalnum(*p) && *p != '_' && *p != '.')
1344 return strdup(map_name);
1348 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
1349 int sec_idx, void *data, size_t data_sz)
1351 struct bpf_map_def *def;
1352 struct bpf_map *map;
1355 map = bpf_object__add_map(obj);
1357 return PTR_ERR(map);
1359 map->libbpf_type = type;
1360 map->sec_idx = sec_idx;
1361 map->sec_offset = 0;
1362 map->name = internal_map_name(obj, type);
1364 pr_warn("failed to alloc map name\n");
1369 def->type = BPF_MAP_TYPE_ARRAY;
1370 def->key_size = sizeof(int);
1371 def->value_size = data_sz;
1372 def->max_entries = 1;
1373 def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
1374 ? BPF_F_RDONLY_PROG : 0;
1375 def->map_flags |= BPF_F_MMAPABLE;
1377 pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
1378 map->name, map->sec_idx, map->sec_offset, def->map_flags);
1380 map->mmaped = mmap(NULL, bpf_map_mmap_sz(map), PROT_READ | PROT_WRITE,
1381 MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1382 if (map->mmaped == MAP_FAILED) {
1385 pr_warn("failed to alloc map '%s' content buffer: %d\n",
1392 memcpy(map->mmaped, data, data_sz);
1394 pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
1398 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
1403 * Populate obj->maps with libbpf internal maps.
1405 if (obj->efile.data_shndx >= 0) {
1406 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
1407 obj->efile.data_shndx,
1408 obj->efile.data->d_buf,
1409 obj->efile.data->d_size);
1413 if (obj->efile.rodata_shndx >= 0) {
1414 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
1415 obj->efile.rodata_shndx,
1416 obj->efile.rodata->d_buf,
1417 obj->efile.rodata->d_size);
1421 if (obj->efile.bss_shndx >= 0) {
1422 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
1423 obj->efile.bss_shndx,
1425 obj->efile.bss->d_size);
1433 static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
1438 for (i = 0; i < obj->nr_extern; i++) {
1439 if (strcmp(obj->externs[i].name, name) == 0)
1440 return &obj->externs[i];
1445 static int set_kcfg_value_tri(struct extern_desc *ext, void *ext_val,
1448 switch (ext->kcfg.type) {
1451 pr_warn("extern (kcfg) %s=%c should be tristate or char\n",
1455 *(bool *)ext_val = value == 'y' ? true : false;
1459 *(enum libbpf_tristate *)ext_val = TRI_YES;
1460 else if (value == 'm')
1461 *(enum libbpf_tristate *)ext_val = TRI_MODULE;
1462 else /* value == 'n' */
1463 *(enum libbpf_tristate *)ext_val = TRI_NO;
1466 *(char *)ext_val = value;
1472 pr_warn("extern (kcfg) %s=%c should be bool, tristate, or char\n",
1480 static int set_kcfg_value_str(struct extern_desc *ext, char *ext_val,
1485 if (ext->kcfg.type != KCFG_CHAR_ARR) {
1486 pr_warn("extern (kcfg) %s=%s should be char array\n", ext->name, value);
1490 len = strlen(value);
1491 if (value[len - 1] != '"') {
1492 pr_warn("extern (kcfg) '%s': invalid string config '%s'\n",
1499 if (len >= ext->kcfg.sz) {
1500 pr_warn("extern (kcfg) '%s': long string config %s of (%zu bytes) truncated to %d bytes\n",
1501 ext->name, value, len, ext->kcfg.sz - 1);
1502 len = ext->kcfg.sz - 1;
1504 memcpy(ext_val, value + 1, len);
1505 ext_val[len] = '\0';
1510 static int parse_u64(const char *value, __u64 *res)
1516 *res = strtoull(value, &value_end, 0);
1519 pr_warn("failed to parse '%s' as integer: %d\n", value, err);
1523 pr_warn("failed to parse '%s' as integer completely\n", value);
1529 static bool is_kcfg_value_in_range(const struct extern_desc *ext, __u64 v)
1531 int bit_sz = ext->kcfg.sz * 8;
1533 if (ext->kcfg.sz == 8)
1536 /* Validate that value stored in u64 fits in integer of `ext->sz`
1537 * bytes size without any loss of information. If the target integer
1538 * is signed, we rely on the following limits of integer type of
1539 * Y bits and subsequent transformation:
1541 * -2^(Y-1) <= X <= 2^(Y-1) - 1
1542 * 0 <= X + 2^(Y-1) <= 2^Y - 1
1543 * 0 <= X + 2^(Y-1) < 2^Y
1545 * For unsigned target integer, check that all the (64 - Y) bits are
1548 if (ext->kcfg.is_signed)
1549 return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
1551 return (v >> bit_sz) == 0;
1554 static int set_kcfg_value_num(struct extern_desc *ext, void *ext_val,
1557 if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR) {
1558 pr_warn("extern (kcfg) %s=%llu should be integer\n",
1559 ext->name, (unsigned long long)value);
1562 if (!is_kcfg_value_in_range(ext, value)) {
1563 pr_warn("extern (kcfg) %s=%llu value doesn't fit in %d bytes\n",
1564 ext->name, (unsigned long long)value, ext->kcfg.sz);
1567 switch (ext->kcfg.sz) {
1568 case 1: *(__u8 *)ext_val = value; break;
1569 case 2: *(__u16 *)ext_val = value; break;
1570 case 4: *(__u32 *)ext_val = value; break;
1571 case 8: *(__u64 *)ext_val = value; break;
1579 static int bpf_object__process_kconfig_line(struct bpf_object *obj,
1580 char *buf, void *data)
1582 struct extern_desc *ext;
1588 if (strncmp(buf, "CONFIG_", 7))
1591 sep = strchr(buf, '=');
1593 pr_warn("failed to parse '%s': no separator\n", buf);
1597 /* Trim ending '\n' */
1599 if (buf[len - 1] == '\n')
1600 buf[len - 1] = '\0';
1601 /* Split on '=' and ensure that a value is present. */
1605 pr_warn("failed to parse '%s': no value\n", buf);
1609 ext = find_extern_by_name(obj, buf);
1610 if (!ext || ext->is_set)
1613 ext_val = data + ext->kcfg.data_off;
1617 case 'y': case 'n': case 'm':
1618 err = set_kcfg_value_tri(ext, ext_val, *value);
1621 err = set_kcfg_value_str(ext, ext_val, value);
1624 /* assume integer */
1625 err = parse_u64(value, &num);
1627 pr_warn("extern (kcfg) %s=%s should be integer\n",
1631 err = set_kcfg_value_num(ext, ext_val, num);
1636 pr_debug("extern (kcfg) %s=%s\n", ext->name, value);
1640 static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
1648 len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
1651 else if (len >= PATH_MAX)
1652 return -ENAMETOOLONG;
1654 /* gzopen also accepts uncompressed files. */
1655 file = gzopen(buf, "r");
1657 file = gzopen("/proc/config.gz", "r");
1660 pr_warn("failed to open system Kconfig\n");
1664 while (gzgets(file, buf, sizeof(buf))) {
1665 err = bpf_object__process_kconfig_line(obj, buf, data);
1667 pr_warn("error parsing system Kconfig line '%s': %d\n",
1678 static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
1679 const char *config, void *data)
1685 file = fmemopen((void *)config, strlen(config), "r");
1688 pr_warn("failed to open in-memory Kconfig: %d\n", err);
1692 while (fgets(buf, sizeof(buf), file)) {
1693 err = bpf_object__process_kconfig_line(obj, buf, data);
1695 pr_warn("error parsing in-memory Kconfig line '%s': %d\n",
1705 static int bpf_object__init_kconfig_map(struct bpf_object *obj)
1707 struct extern_desc *last_ext = NULL, *ext;
1711 for (i = 0; i < obj->nr_extern; i++) {
1712 ext = &obj->externs[i];
1713 if (ext->type == EXT_KCFG)
1720 map_sz = last_ext->kcfg.data_off + last_ext->kcfg.sz;
1721 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
1722 obj->efile.symbols_shndx,
1727 obj->kconfig_map_idx = obj->nr_maps - 1;
1732 static int bpf_object__init_user_maps(struct bpf_object *obj, bool strict)
1734 Elf_Data *symbols = obj->efile.symbols;
1735 int i, map_def_sz = 0, nr_maps = 0, nr_syms;
1736 Elf_Data *data = NULL;
1739 if (obj->efile.maps_shndx < 0)
1745 scn = elf_getscn(obj->efile.elf, obj->efile.maps_shndx);
1747 data = elf_getdata(scn, NULL);
1748 if (!scn || !data) {
1749 pr_warn("failed to get Elf_Data from map section %d\n",
1750 obj->efile.maps_shndx);
1755 * Count number of maps. Each map has a name.
1756 * Array of maps is not supported: only the first element is
1759 * TODO: Detect array of map and report error.
1761 nr_syms = symbols->d_size / sizeof(GElf_Sym);
1762 for (i = 0; i < nr_syms; i++) {
1765 if (!gelf_getsym(symbols, i, &sym))
1767 if (sym.st_shndx != obj->efile.maps_shndx)
1771 /* Assume equally sized map definitions */
1772 pr_debug("maps in %s: %d maps in %zd bytes\n",
1773 obj->path, nr_maps, data->d_size);
1775 if (!data->d_size || nr_maps == 0 || (data->d_size % nr_maps) != 0) {
1776 pr_warn("unable to determine map definition size section %s, %d maps in %zd bytes\n",
1777 obj->path, nr_maps, data->d_size);
1780 map_def_sz = data->d_size / nr_maps;
1782 /* Fill obj->maps using data in "maps" section. */
1783 for (i = 0; i < nr_syms; i++) {
1785 const char *map_name;
1786 struct bpf_map_def *def;
1787 struct bpf_map *map;
1789 if (!gelf_getsym(symbols, i, &sym))
1791 if (sym.st_shndx != obj->efile.maps_shndx)
1794 map = bpf_object__add_map(obj);
1796 return PTR_ERR(map);
1798 map_name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
1801 pr_warn("failed to get map #%d name sym string for obj %s\n",
1803 return -LIBBPF_ERRNO__FORMAT;
1806 map->libbpf_type = LIBBPF_MAP_UNSPEC;
1807 map->sec_idx = sym.st_shndx;
1808 map->sec_offset = sym.st_value;
1809 pr_debug("map '%s' (legacy): at sec_idx %d, offset %zu.\n",
1810 map_name, map->sec_idx, map->sec_offset);
1811 if (sym.st_value + map_def_sz > data->d_size) {
1812 pr_warn("corrupted maps section in %s: last map \"%s\" too small\n",
1813 obj->path, map_name);
1817 map->name = strdup(map_name);
1819 pr_warn("failed to alloc map name\n");
1822 pr_debug("map %d is \"%s\"\n", i, map->name);
1823 def = (struct bpf_map_def *)(data->d_buf + sym.st_value);
1825 * If the definition of the map in the object file fits in
1826 * bpf_map_def, copy it. Any extra fields in our version
1827 * of bpf_map_def will default to zero as a result of the
1830 if (map_def_sz <= sizeof(struct bpf_map_def)) {
1831 memcpy(&map->def, def, map_def_sz);
1834 * Here the map structure being read is bigger than what
1835 * we expect, truncate if the excess bits are all zero.
1836 * If they are not zero, reject this map as
1841 for (b = ((char *)def) + sizeof(struct bpf_map_def);
1842 b < ((char *)def) + map_def_sz; b++) {
1844 pr_warn("maps section in %s: \"%s\" has unrecognized, non-zero options\n",
1845 obj->path, map_name);
1850 memcpy(&map->def, def, sizeof(struct bpf_map_def));
1856 static const struct btf_type *
1857 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
1859 const struct btf_type *t = btf__type_by_id(btf, id);
1864 while (btf_is_mod(t) || btf_is_typedef(t)) {
1867 t = btf__type_by_id(btf, t->type);
1873 static const struct btf_type *
1874 resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
1876 const struct btf_type *t;
1878 t = skip_mods_and_typedefs(btf, id, NULL);
1882 t = skip_mods_and_typedefs(btf, t->type, res_id);
1884 return btf_is_func_proto(t) ? t : NULL;
1888 * Fetch integer attribute of BTF map definition. Such attributes are
1889 * represented using a pointer to an array, in which dimensionality of array
1890 * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
1891 * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
1892 * type definition, while using only sizeof(void *) space in ELF data section.
1894 static bool get_map_field_int(const char *map_name, const struct btf *btf,
1895 const struct btf_member *m, __u32 *res)
1897 const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
1898 const char *name = btf__name_by_offset(btf, m->name_off);
1899 const struct btf_array *arr_info;
1900 const struct btf_type *arr_t;
1902 if (!btf_is_ptr(t)) {
1903 pr_warn("map '%s': attr '%s': expected PTR, got %u.\n",
1904 map_name, name, btf_kind(t));
1908 arr_t = btf__type_by_id(btf, t->type);
1910 pr_warn("map '%s': attr '%s': type [%u] not found.\n",
1911 map_name, name, t->type);
1914 if (!btf_is_array(arr_t)) {
1915 pr_warn("map '%s': attr '%s': expected ARRAY, got %u.\n",
1916 map_name, name, btf_kind(arr_t));
1919 arr_info = btf_array(arr_t);
1920 *res = arr_info->nelems;
1924 static int build_map_pin_path(struct bpf_map *map, const char *path)
1930 path = "/sys/fs/bpf";
1932 len = snprintf(buf, PATH_MAX, "%s/%s", path, bpf_map__name(map));
1935 else if (len >= PATH_MAX)
1936 return -ENAMETOOLONG;
1938 err = bpf_map__set_pin_path(map, buf);
1946 static int parse_btf_map_def(struct bpf_object *obj,
1947 struct bpf_map *map,
1948 const struct btf_type *def,
1949 bool strict, bool is_inner,
1950 const char *pin_root_path)
1952 const struct btf_type *t;
1953 const struct btf_member *m;
1956 vlen = btf_vlen(def);
1957 m = btf_members(def);
1958 for (i = 0; i < vlen; i++, m++) {
1959 const char *name = btf__name_by_offset(obj->btf, m->name_off);
1962 pr_warn("map '%s': invalid field #%d.\n", map->name, i);
1965 if (strcmp(name, "type") == 0) {
1966 if (!get_map_field_int(map->name, obj->btf, m,
1969 pr_debug("map '%s': found type = %u.\n",
1970 map->name, map->def.type);
1971 } else if (strcmp(name, "max_entries") == 0) {
1972 if (!get_map_field_int(map->name, obj->btf, m,
1973 &map->def.max_entries))
1975 pr_debug("map '%s': found max_entries = %u.\n",
1976 map->name, map->def.max_entries);
1977 } else if (strcmp(name, "map_flags") == 0) {
1978 if (!get_map_field_int(map->name, obj->btf, m,
1979 &map->def.map_flags))
1981 pr_debug("map '%s': found map_flags = %u.\n",
1982 map->name, map->def.map_flags);
1983 } else if (strcmp(name, "numa_node") == 0) {
1984 if (!get_map_field_int(map->name, obj->btf, m, &map->numa_node))
1986 pr_debug("map '%s': found numa_node = %u.\n", map->name, map->numa_node);
1987 } else if (strcmp(name, "key_size") == 0) {
1990 if (!get_map_field_int(map->name, obj->btf, m, &sz))
1992 pr_debug("map '%s': found key_size = %u.\n",
1994 if (map->def.key_size && map->def.key_size != sz) {
1995 pr_warn("map '%s': conflicting key size %u != %u.\n",
1996 map->name, map->def.key_size, sz);
1999 map->def.key_size = sz;
2000 } else if (strcmp(name, "key") == 0) {
2003 t = btf__type_by_id(obj->btf, m->type);
2005 pr_warn("map '%s': key type [%d] not found.\n",
2006 map->name, m->type);
2009 if (!btf_is_ptr(t)) {
2010 pr_warn("map '%s': key spec is not PTR: %u.\n",
2011 map->name, btf_kind(t));
2014 sz = btf__resolve_size(obj->btf, t->type);
2016 pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
2017 map->name, t->type, (ssize_t)sz);
2020 pr_debug("map '%s': found key [%u], sz = %zd.\n",
2021 map->name, t->type, (ssize_t)sz);
2022 if (map->def.key_size && map->def.key_size != sz) {
2023 pr_warn("map '%s': conflicting key size %u != %zd.\n",
2024 map->name, map->def.key_size, (ssize_t)sz);
2027 map->def.key_size = sz;
2028 map->btf_key_type_id = t->type;
2029 } else if (strcmp(name, "value_size") == 0) {
2032 if (!get_map_field_int(map->name, obj->btf, m, &sz))
2034 pr_debug("map '%s': found value_size = %u.\n",
2036 if (map->def.value_size && map->def.value_size != sz) {
2037 pr_warn("map '%s': conflicting value size %u != %u.\n",
2038 map->name, map->def.value_size, sz);
2041 map->def.value_size = sz;
2042 } else if (strcmp(name, "value") == 0) {
2045 t = btf__type_by_id(obj->btf, m->type);
2047 pr_warn("map '%s': value type [%d] not found.\n",
2048 map->name, m->type);
2051 if (!btf_is_ptr(t)) {
2052 pr_warn("map '%s': value spec is not PTR: %u.\n",
2053 map->name, btf_kind(t));
2056 sz = btf__resolve_size(obj->btf, t->type);
2058 pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
2059 map->name, t->type, (ssize_t)sz);
2062 pr_debug("map '%s': found value [%u], sz = %zd.\n",
2063 map->name, t->type, (ssize_t)sz);
2064 if (map->def.value_size && map->def.value_size != sz) {
2065 pr_warn("map '%s': conflicting value size %u != %zd.\n",
2066 map->name, map->def.value_size, (ssize_t)sz);
2069 map->def.value_size = sz;
2070 map->btf_value_type_id = t->type;
2072 else if (strcmp(name, "values") == 0) {
2076 pr_warn("map '%s': multi-level inner maps not supported.\n",
2080 if (i != vlen - 1) {
2081 pr_warn("map '%s': '%s' member should be last.\n",
2085 if (!bpf_map_type__is_map_in_map(map->def.type)) {
2086 pr_warn("map '%s': should be map-in-map.\n",
2090 if (map->def.value_size && map->def.value_size != 4) {
2091 pr_warn("map '%s': conflicting value size %u != 4.\n",
2092 map->name, map->def.value_size);
2095 map->def.value_size = 4;
2096 t = btf__type_by_id(obj->btf, m->type);
2098 pr_warn("map '%s': map-in-map inner type [%d] not found.\n",
2099 map->name, m->type);
2102 if (!btf_is_array(t) || btf_array(t)->nelems) {
2103 pr_warn("map '%s': map-in-map inner spec is not a zero-sized array.\n",
2107 t = skip_mods_and_typedefs(obj->btf, btf_array(t)->type,
2109 if (!btf_is_ptr(t)) {
2110 pr_warn("map '%s': map-in-map inner def is of unexpected kind %u.\n",
2111 map->name, btf_kind(t));
2114 t = skip_mods_and_typedefs(obj->btf, t->type, NULL);
2115 if (!btf_is_struct(t)) {
2116 pr_warn("map '%s': map-in-map inner def is of unexpected kind %u.\n",
2117 map->name, btf_kind(t));
2121 map->inner_map = calloc(1, sizeof(*map->inner_map));
2122 if (!map->inner_map)
2124 map->inner_map->sec_idx = obj->efile.btf_maps_shndx;
2125 map->inner_map->name = malloc(strlen(map->name) +
2126 sizeof(".inner") + 1);
2127 if (!map->inner_map->name)
2129 sprintf(map->inner_map->name, "%s.inner", map->name);
2131 err = parse_btf_map_def(obj, map->inner_map, t, strict,
2132 true /* is_inner */, NULL);
2135 } else if (strcmp(name, "pinning") == 0) {
2140 pr_debug("map '%s': inner def can't be pinned.\n",
2144 if (!get_map_field_int(map->name, obj->btf, m, &val))
2146 pr_debug("map '%s': found pinning = %u.\n",
2149 if (val != LIBBPF_PIN_NONE &&
2150 val != LIBBPF_PIN_BY_NAME) {
2151 pr_warn("map '%s': invalid pinning value %u.\n",
2155 if (val == LIBBPF_PIN_BY_NAME) {
2156 err = build_map_pin_path(map, pin_root_path);
2158 pr_warn("map '%s': couldn't build pin path.\n",
2165 pr_warn("map '%s': unknown field '%s'.\n",
2169 pr_debug("map '%s': ignoring unknown field '%s'.\n",
2174 if (map->def.type == BPF_MAP_TYPE_UNSPEC) {
2175 pr_warn("map '%s': map type isn't specified.\n", map->name);
2182 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
2183 const struct btf_type *sec,
2184 int var_idx, int sec_idx,
2185 const Elf_Data *data, bool strict,
2186 const char *pin_root_path)
2188 const struct btf_type *var, *def;
2189 const struct btf_var_secinfo *vi;
2190 const struct btf_var *var_extra;
2191 const char *map_name;
2192 struct bpf_map *map;
2194 vi = btf_var_secinfos(sec) + var_idx;
2195 var = btf__type_by_id(obj->btf, vi->type);
2196 var_extra = btf_var(var);
2197 map_name = btf__name_by_offset(obj->btf, var->name_off);
2199 if (map_name == NULL || map_name[0] == '\0') {
2200 pr_warn("map #%d: empty name.\n", var_idx);
2203 if ((__u64)vi->offset + vi->size > data->d_size) {
2204 pr_warn("map '%s' BTF data is corrupted.\n", map_name);
2207 if (!btf_is_var(var)) {
2208 pr_warn("map '%s': unexpected var kind %u.\n",
2209 map_name, btf_kind(var));
2212 if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED &&
2213 var_extra->linkage != BTF_VAR_STATIC) {
2214 pr_warn("map '%s': unsupported var linkage %u.\n",
2215 map_name, var_extra->linkage);
2219 def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
2220 if (!btf_is_struct(def)) {
2221 pr_warn("map '%s': unexpected def kind %u.\n",
2222 map_name, btf_kind(var));
2225 if (def->size > vi->size) {
2226 pr_warn("map '%s': invalid def size.\n", map_name);
2230 map = bpf_object__add_map(obj);
2232 return PTR_ERR(map);
2233 map->name = strdup(map_name);
2235 pr_warn("map '%s': failed to alloc map name.\n", map_name);
2238 map->libbpf_type = LIBBPF_MAP_UNSPEC;
2239 map->def.type = BPF_MAP_TYPE_UNSPEC;
2240 map->sec_idx = sec_idx;
2241 map->sec_offset = vi->offset;
2242 map->btf_var_idx = var_idx;
2243 pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
2244 map_name, map->sec_idx, map->sec_offset);
2246 return parse_btf_map_def(obj, map, def, strict, false, pin_root_path);
2249 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
2250 const char *pin_root_path)
2252 const struct btf_type *sec = NULL;
2253 int nr_types, i, vlen, err;
2254 const struct btf_type *t;
2259 if (obj->efile.btf_maps_shndx < 0)
2262 scn = elf_getscn(obj->efile.elf, obj->efile.btf_maps_shndx);
2264 data = elf_getdata(scn, NULL);
2265 if (!scn || !data) {
2266 pr_warn("failed to get Elf_Data from map section %d (%s)\n",
2267 obj->efile.maps_shndx, MAPS_ELF_SEC);
2271 nr_types = btf__get_nr_types(obj->btf);
2272 for (i = 1; i <= nr_types; i++) {
2273 t = btf__type_by_id(obj->btf, i);
2274 if (!btf_is_datasec(t))
2276 name = btf__name_by_offset(obj->btf, t->name_off);
2277 if (strcmp(name, MAPS_ELF_SEC) == 0) {
2279 obj->efile.btf_maps_sec_btf_id = i;
2285 pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
2289 vlen = btf_vlen(sec);
2290 for (i = 0; i < vlen; i++) {
2291 err = bpf_object__init_user_btf_map(obj, sec, i,
2292 obj->efile.btf_maps_shndx,
2302 static int bpf_object__init_maps(struct bpf_object *obj,
2303 const struct bpf_object_open_opts *opts)
2305 const char *pin_root_path;
2309 strict = !OPTS_GET(opts, relaxed_maps, false);
2310 pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
2312 err = bpf_object__init_user_maps(obj, strict);
2313 err = err ?: bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
2314 err = err ?: bpf_object__init_global_data_maps(obj);
2315 err = err ?: bpf_object__init_kconfig_map(obj);
2316 err = err ?: bpf_object__init_struct_ops_maps(obj);
2323 static bool section_have_execinstr(struct bpf_object *obj, int idx)
2328 scn = elf_getscn(obj->efile.elf, idx);
2332 if (gelf_getshdr(scn, &sh) != &sh)
2335 if (sh.sh_flags & SHF_EXECINSTR)
2341 static bool btf_needs_sanitization(struct bpf_object *obj)
2343 bool has_func_global = obj->caps.btf_func_global;
2344 bool has_datasec = obj->caps.btf_datasec;
2345 bool has_func = obj->caps.btf_func;
2347 return !has_func || !has_datasec || !has_func_global;
2350 static void bpf_object__sanitize_btf(struct bpf_object *obj, struct btf *btf)
2352 bool has_func_global = obj->caps.btf_func_global;
2353 bool has_datasec = obj->caps.btf_datasec;
2354 bool has_func = obj->caps.btf_func;
2358 for (i = 1; i <= btf__get_nr_types(btf); i++) {
2359 t = (struct btf_type *)btf__type_by_id(btf, i);
2361 if (!has_datasec && btf_is_var(t)) {
2362 /* replace VAR with INT */
2363 t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
2365 * using size = 1 is the safest choice, 4 will be too
2366 * big and cause kernel BTF validation failure if
2367 * original variable took less than 4 bytes
2370 *(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
2371 } else if (!has_datasec && btf_is_datasec(t)) {
2372 /* replace DATASEC with STRUCT */
2373 const struct btf_var_secinfo *v = btf_var_secinfos(t);
2374 struct btf_member *m = btf_members(t);
2375 struct btf_type *vt;
2378 name = (char *)btf__name_by_offset(btf, t->name_off);
2386 t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
2387 for (j = 0; j < vlen; j++, v++, m++) {
2388 /* order of field assignments is important */
2389 m->offset = v->offset * 8;
2391 /* preserve variable name as member name */
2392 vt = (void *)btf__type_by_id(btf, v->type);
2393 m->name_off = vt->name_off;
2395 } else if (!has_func && btf_is_func_proto(t)) {
2396 /* replace FUNC_PROTO with ENUM */
2398 t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
2399 t->size = sizeof(__u32); /* kernel enforced */
2400 } else if (!has_func && btf_is_func(t)) {
2401 /* replace FUNC with TYPEDEF */
2402 t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
2403 } else if (!has_func_global && btf_is_func(t)) {
2404 /* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
2405 t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
2410 static bool libbpf_needs_btf(const struct bpf_object *obj)
2412 return obj->efile.btf_maps_shndx >= 0 ||
2413 obj->efile.st_ops_shndx >= 0 ||
2417 static bool kernel_needs_btf(const struct bpf_object *obj)
2419 return obj->efile.st_ops_shndx >= 0;
2422 static int bpf_object__init_btf(struct bpf_object *obj,
2424 Elf_Data *btf_ext_data)
2429 obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
2430 if (IS_ERR(obj->btf)) {
2431 err = PTR_ERR(obj->btf);
2433 pr_warn("Error loading ELF section %s: %d.\n",
2437 /* enforce 8-byte pointers for BPF-targeted BTFs */
2438 btf__set_pointer_size(obj->btf, 8);
2443 pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
2444 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
2447 obj->btf_ext = btf_ext__new(btf_ext_data->d_buf,
2448 btf_ext_data->d_size);
2449 if (IS_ERR(obj->btf_ext)) {
2450 pr_warn("Error loading ELF section %s: %ld. Ignored and continue.\n",
2451 BTF_EXT_ELF_SEC, PTR_ERR(obj->btf_ext));
2452 obj->btf_ext = NULL;
2457 if (err && libbpf_needs_btf(obj)) {
2458 pr_warn("BTF is required, but is missing or corrupted.\n");
2464 static int bpf_object__finalize_btf(struct bpf_object *obj)
2471 err = btf__finalize_data(obj, obj->btf);
2473 pr_warn("Error finalizing %s: %d.\n", BTF_ELF_SEC, err);
2480 static inline bool libbpf_prog_needs_vmlinux_btf(struct bpf_program *prog)
2482 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
2483 prog->type == BPF_PROG_TYPE_LSM)
2486 /* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
2487 * also need vmlinux BTF
2489 if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd)
2495 static int bpf_object__load_vmlinux_btf(struct bpf_object *obj)
2497 bool need_vmlinux_btf = false;
2498 struct bpf_program *prog;
2501 /* CO-RE relocations need kernel BTF */
2502 if (obj->btf_ext && obj->btf_ext->field_reloc_info.len)
2503 need_vmlinux_btf = true;
2505 bpf_object__for_each_program(prog, obj) {
2508 if (libbpf_prog_needs_vmlinux_btf(prog)) {
2509 need_vmlinux_btf = true;
2514 if (!need_vmlinux_btf)
2517 obj->btf_vmlinux = libbpf_find_kernel_btf();
2518 if (IS_ERR(obj->btf_vmlinux)) {
2519 err = PTR_ERR(obj->btf_vmlinux);
2520 pr_warn("Error loading vmlinux BTF: %d\n", err);
2521 obj->btf_vmlinux = NULL;
2527 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
2529 struct btf *kern_btf = obj->btf;
2530 bool btf_mandatory, sanitize;
2536 sanitize = btf_needs_sanitization(obj);
2538 const void *raw_data;
2541 /* clone BTF to sanitize a copy and leave the original intact */
2542 raw_data = btf__get_raw_data(obj->btf, &sz);
2543 kern_btf = btf__new(raw_data, sz);
2544 if (IS_ERR(kern_btf))
2545 return PTR_ERR(kern_btf);
2547 /* enforce 8-byte pointers for BPF-targeted BTFs */
2548 btf__set_pointer_size(obj->btf, 8);
2549 bpf_object__sanitize_btf(obj, kern_btf);
2552 err = btf__load(kern_btf);
2555 /* move fd to libbpf's BTF */
2556 btf__set_fd(obj->btf, btf__fd(kern_btf));
2557 btf__set_fd(kern_btf, -1);
2559 btf__free(kern_btf);
2562 btf_mandatory = kernel_needs_btf(obj);
2563 pr_warn("Error loading .BTF into kernel: %d. %s\n", err,
2564 btf_mandatory ? "BTF is mandatory, can't proceed."
2565 : "BTF is optional, ignoring.");
2572 static int bpf_object__elf_collect(struct bpf_object *obj)
2574 Elf *elf = obj->efile.elf;
2575 GElf_Ehdr *ep = &obj->efile.ehdr;
2576 Elf_Data *btf_ext_data = NULL;
2577 Elf_Data *btf_data = NULL;
2578 Elf_Scn *scn = NULL;
2579 int idx = 0, err = 0;
2581 /* Elf is corrupted/truncated, avoid calling elf_strptr. */
2582 if (!elf_rawdata(elf_getscn(elf, ep->e_shstrndx), NULL)) {
2583 pr_warn("failed to get e_shstrndx from %s\n", obj->path);
2584 return -LIBBPF_ERRNO__FORMAT;
2587 while ((scn = elf_nextscn(elf, scn)) != NULL) {
2593 if (gelf_getshdr(scn, &sh) != &sh) {
2594 pr_warn("failed to get section(%d) header from %s\n",
2596 return -LIBBPF_ERRNO__FORMAT;
2599 name = elf_strptr(elf, ep->e_shstrndx, sh.sh_name);
2601 pr_warn("failed to get section(%d) name from %s\n",
2603 return -LIBBPF_ERRNO__FORMAT;
2606 data = elf_getdata(scn, 0);
2608 pr_warn("failed to get section(%d) data from %s(%s)\n",
2609 idx, name, obj->path);
2610 return -LIBBPF_ERRNO__FORMAT;
2612 pr_debug("section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
2613 idx, name, (unsigned long)data->d_size,
2614 (int)sh.sh_link, (unsigned long)sh.sh_flags,
2617 if (strcmp(name, "license") == 0) {
2618 err = bpf_object__init_license(obj,
2623 } else if (strcmp(name, "version") == 0) {
2624 err = bpf_object__init_kversion(obj,
2629 } else if (strcmp(name, "maps") == 0) {
2630 obj->efile.maps_shndx = idx;
2631 } else if (strcmp(name, MAPS_ELF_SEC) == 0) {
2632 obj->efile.btf_maps_shndx = idx;
2633 } else if (strcmp(name, BTF_ELF_SEC) == 0) {
2635 } else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
2636 btf_ext_data = data;
2637 } else if (sh.sh_type == SHT_SYMTAB) {
2638 if (obj->efile.symbols) {
2639 pr_warn("bpf: multiple SYMTAB in %s\n",
2641 return -LIBBPF_ERRNO__FORMAT;
2643 obj->efile.symbols = data;
2644 obj->efile.symbols_shndx = idx;
2645 obj->efile.strtabidx = sh.sh_link;
2646 } else if (sh.sh_type == SHT_PROGBITS && data->d_size > 0) {
2647 if (sh.sh_flags & SHF_EXECINSTR) {
2648 if (strcmp(name, ".text") == 0)
2649 obj->efile.text_shndx = idx;
2650 err = bpf_object__add_program(obj, data->d_buf,
2654 char errmsg[STRERR_BUFSIZE];
2657 cp = libbpf_strerror_r(-err, errmsg,
2659 pr_warn("failed to alloc program %s (%s): %s",
2660 name, obj->path, cp);
2663 } else if (strcmp(name, DATA_SEC) == 0) {
2664 obj->efile.data = data;
2665 obj->efile.data_shndx = idx;
2666 } else if (strcmp(name, RODATA_SEC) == 0) {
2667 obj->efile.rodata = data;
2668 obj->efile.rodata_shndx = idx;
2669 } else if (strcmp(name, STRUCT_OPS_SEC) == 0) {
2670 obj->efile.st_ops_data = data;
2671 obj->efile.st_ops_shndx = idx;
2673 pr_debug("skip section(%d) %s\n", idx, name);
2675 } else if (sh.sh_type == SHT_REL) {
2676 int nr_sects = obj->efile.nr_reloc_sects;
2677 void *sects = obj->efile.reloc_sects;
2678 int sec = sh.sh_info; /* points to other section */
2680 /* Only do relo for section with exec instructions */
2681 if (!section_have_execinstr(obj, sec) &&
2682 strcmp(name, ".rel" STRUCT_OPS_SEC) &&
2683 strcmp(name, ".rel" MAPS_ELF_SEC)) {
2684 pr_debug("skip relo %s(%d) for section(%d)\n",
2689 sects = reallocarray(sects, nr_sects + 1,
2690 sizeof(*obj->efile.reloc_sects));
2692 pr_warn("reloc_sects realloc failed\n");
2696 obj->efile.reloc_sects = sects;
2697 obj->efile.nr_reloc_sects++;
2699 obj->efile.reloc_sects[nr_sects].shdr = sh;
2700 obj->efile.reloc_sects[nr_sects].data = data;
2701 } else if (sh.sh_type == SHT_NOBITS &&
2702 strcmp(name, BSS_SEC) == 0) {
2703 obj->efile.bss = data;
2704 obj->efile.bss_shndx = idx;
2706 pr_debug("skip section(%d) %s\n", idx, name);
2710 if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
2711 pr_warn("Corrupted ELF file: index of strtab invalid\n");
2712 return -LIBBPF_ERRNO__FORMAT;
2714 return bpf_object__init_btf(obj, btf_data, btf_ext_data);
2717 static bool sym_is_extern(const GElf_Sym *sym)
2719 int bind = GELF_ST_BIND(sym->st_info);
2720 /* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
2721 return sym->st_shndx == SHN_UNDEF &&
2722 (bind == STB_GLOBAL || bind == STB_WEAK) &&
2723 GELF_ST_TYPE(sym->st_info) == STT_NOTYPE;
2726 static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
2728 const struct btf_type *t;
2729 const char *var_name;
2735 n = btf__get_nr_types(btf);
2736 for (i = 1; i <= n; i++) {
2737 t = btf__type_by_id(btf, i);
2742 var_name = btf__name_by_offset(btf, t->name_off);
2743 if (strcmp(var_name, ext_name))
2746 if (btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
2755 static int find_extern_sec_btf_id(struct btf *btf, int ext_btf_id) {
2756 const struct btf_var_secinfo *vs;
2757 const struct btf_type *t;
2763 n = btf__get_nr_types(btf);
2764 for (i = 1; i <= n; i++) {
2765 t = btf__type_by_id(btf, i);
2767 if (!btf_is_datasec(t))
2770 vs = btf_var_secinfos(t);
2771 for (j = 0; j < btf_vlen(t); j++, vs++) {
2772 if (vs->type == ext_btf_id)
2780 static enum kcfg_type find_kcfg_type(const struct btf *btf, int id,
2783 const struct btf_type *t;
2786 t = skip_mods_and_typedefs(btf, id, NULL);
2787 name = btf__name_by_offset(btf, t->name_off);
2791 switch (btf_kind(t)) {
2792 case BTF_KIND_INT: {
2793 int enc = btf_int_encoding(t);
2795 if (enc & BTF_INT_BOOL)
2796 return t->size == 1 ? KCFG_BOOL : KCFG_UNKNOWN;
2798 *is_signed = enc & BTF_INT_SIGNED;
2801 if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
2802 return KCFG_UNKNOWN;
2807 return KCFG_UNKNOWN;
2808 if (strcmp(name, "libbpf_tristate"))
2809 return KCFG_UNKNOWN;
2810 return KCFG_TRISTATE;
2811 case BTF_KIND_ARRAY:
2812 if (btf_array(t)->nelems == 0)
2813 return KCFG_UNKNOWN;
2814 if (find_kcfg_type(btf, btf_array(t)->type, NULL) != KCFG_CHAR)
2815 return KCFG_UNKNOWN;
2816 return KCFG_CHAR_ARR;
2818 return KCFG_UNKNOWN;
2822 static int cmp_externs(const void *_a, const void *_b)
2824 const struct extern_desc *a = _a;
2825 const struct extern_desc *b = _b;
2827 if (a->type != b->type)
2828 return a->type < b->type ? -1 : 1;
2830 if (a->type == EXT_KCFG) {
2831 /* descending order by alignment requirements */
2832 if (a->kcfg.align != b->kcfg.align)
2833 return a->kcfg.align > b->kcfg.align ? -1 : 1;
2834 /* ascending order by size, within same alignment class */
2835 if (a->kcfg.sz != b->kcfg.sz)
2836 return a->kcfg.sz < b->kcfg.sz ? -1 : 1;
2839 /* resolve ties by name */
2840 return strcmp(a->name, b->name);
2843 static int find_int_btf_id(const struct btf *btf)
2845 const struct btf_type *t;
2848 n = btf__get_nr_types(btf);
2849 for (i = 1; i <= n; i++) {
2850 t = btf__type_by_id(btf, i);
2852 if (btf_is_int(t) && btf_int_bits(t) == 32)
2859 static int bpf_object__collect_externs(struct bpf_object *obj)
2861 struct btf_type *sec, *kcfg_sec = NULL, *ksym_sec = NULL;
2862 const struct btf_type *t;
2863 struct extern_desc *ext;
2865 const char *ext_name, *sec_name;
2869 if (!obj->efile.symbols)
2872 scn = elf_getscn(obj->efile.elf, obj->efile.symbols_shndx);
2874 return -LIBBPF_ERRNO__FORMAT;
2875 if (gelf_getshdr(scn, &sh) != &sh)
2876 return -LIBBPF_ERRNO__FORMAT;
2877 n = sh.sh_size / sh.sh_entsize;
2879 pr_debug("looking for externs among %d symbols...\n", n);
2880 for (i = 0; i < n; i++) {
2883 if (!gelf_getsym(obj->efile.symbols, i, &sym))
2884 return -LIBBPF_ERRNO__FORMAT;
2885 if (!sym_is_extern(&sym))
2887 ext_name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
2889 if (!ext_name || !ext_name[0])
2893 ext = reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
2897 ext = &ext[obj->nr_extern];
2898 memset(ext, 0, sizeof(*ext));
2901 ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
2902 if (ext->btf_id <= 0) {
2903 pr_warn("failed to find BTF for extern '%s': %d\n",
2904 ext_name, ext->btf_id);
2907 t = btf__type_by_id(obj->btf, ext->btf_id);
2908 ext->name = btf__name_by_offset(obj->btf, t->name_off);
2910 ext->is_weak = GELF_ST_BIND(sym.st_info) == STB_WEAK;
2912 ext->sec_btf_id = find_extern_sec_btf_id(obj->btf, ext->btf_id);
2913 if (ext->sec_btf_id <= 0) {
2914 pr_warn("failed to find BTF for extern '%s' [%d] section: %d\n",
2915 ext_name, ext->btf_id, ext->sec_btf_id);
2916 return ext->sec_btf_id;
2918 sec = (void *)btf__type_by_id(obj->btf, ext->sec_btf_id);
2919 sec_name = btf__name_by_offset(obj->btf, sec->name_off);
2921 if (strcmp(sec_name, KCONFIG_SEC) == 0) {
2923 ext->type = EXT_KCFG;
2924 ext->kcfg.sz = btf__resolve_size(obj->btf, t->type);
2925 if (ext->kcfg.sz <= 0) {
2926 pr_warn("failed to resolve size of extern (kcfg) '%s': %d\n",
2927 ext_name, ext->kcfg.sz);
2928 return ext->kcfg.sz;
2930 ext->kcfg.align = btf__align_of(obj->btf, t->type);
2931 if (ext->kcfg.align <= 0) {
2932 pr_warn("failed to determine alignment of extern (kcfg) '%s': %d\n",
2933 ext_name, ext->kcfg.align);
2936 ext->kcfg.type = find_kcfg_type(obj->btf, t->type,
2937 &ext->kcfg.is_signed);
2938 if (ext->kcfg.type == KCFG_UNKNOWN) {
2939 pr_warn("extern (kcfg) '%s' type is unsupported\n", ext_name);
2942 } else if (strcmp(sec_name, KSYMS_SEC) == 0) {
2943 const struct btf_type *vt;
2946 ext->type = EXT_KSYM;
2948 vt = skip_mods_and_typedefs(obj->btf, t->type, NULL);
2949 if (!btf_is_void(vt)) {
2950 pr_warn("extern (ksym) '%s' is not typeless (void)\n", ext_name);
2954 pr_warn("unrecognized extern section '%s'\n", sec_name);
2958 pr_debug("collected %d externs total\n", obj->nr_extern);
2960 if (!obj->nr_extern)
2963 /* sort externs by type, for kcfg ones also by (align, size, name) */
2964 qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
2966 /* for .ksyms section, we need to turn all externs into allocated
2967 * variables in BTF to pass kernel verification; we do this by
2968 * pretending that each extern is a 8-byte variable
2971 /* find existing 4-byte integer type in BTF to use for fake
2972 * extern variables in DATASEC
2974 int int_btf_id = find_int_btf_id(obj->btf);
2976 for (i = 0; i < obj->nr_extern; i++) {
2977 ext = &obj->externs[i];
2978 if (ext->type != EXT_KSYM)
2980 pr_debug("extern (ksym) #%d: symbol %d, name %s\n",
2981 i, ext->sym_idx, ext->name);
2986 for (i = 0, off = 0; i < n; i++, off += sizeof(int)) {
2987 struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
2988 struct btf_type *vt;
2990 vt = (void *)btf__type_by_id(obj->btf, vs->type);
2991 ext_name = btf__name_by_offset(obj->btf, vt->name_off);
2992 ext = find_extern_by_name(obj, ext_name);
2994 pr_warn("failed to find extern definition for BTF var '%s'\n",
2998 btf_var(vt)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
2999 vt->type = int_btf_id;
3001 vs->size = sizeof(int);
3008 /* for kcfg externs calculate their offsets within a .kconfig map */
3010 for (i = 0; i < obj->nr_extern; i++) {
3011 ext = &obj->externs[i];
3012 if (ext->type != EXT_KCFG)
3015 ext->kcfg.data_off = roundup(off, ext->kcfg.align);
3016 off = ext->kcfg.data_off + ext->kcfg.sz;
3017 pr_debug("extern (kcfg) #%d: symbol %d, off %u, name %s\n",
3018 i, ext->sym_idx, ext->kcfg.data_off, ext->name);
3022 for (i = 0; i < n; i++) {
3023 struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
3025 t = btf__type_by_id(obj->btf, vs->type);
3026 ext_name = btf__name_by_offset(obj->btf, t->name_off);
3027 ext = find_extern_by_name(obj, ext_name);
3029 pr_warn("failed to find extern definition for BTF var '%s'\n",
3033 btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
3034 vs->offset = ext->kcfg.data_off;
3040 static struct bpf_program *
3041 bpf_object__find_prog_by_idx(struct bpf_object *obj, int idx)
3043 struct bpf_program *prog;
3046 for (i = 0; i < obj->nr_programs; i++) {
3047 prog = &obj->programs[i];
3048 if (prog->idx == idx)
3054 struct bpf_program *
3055 bpf_object__find_program_by_title(const struct bpf_object *obj,
3058 struct bpf_program *pos;
3060 bpf_object__for_each_program(pos, obj) {
3061 if (pos->section_name && !strcmp(pos->section_name, title))
3067 struct bpf_program *
3068 bpf_object__find_program_by_name(const struct bpf_object *obj,
3071 struct bpf_program *prog;
3073 bpf_object__for_each_program(prog, obj) {
3074 if (!strcmp(prog->name, name))
3080 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
3083 return shndx == obj->efile.data_shndx ||
3084 shndx == obj->efile.bss_shndx ||
3085 shndx == obj->efile.rodata_shndx;
3088 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
3091 return shndx == obj->efile.maps_shndx ||
3092 shndx == obj->efile.btf_maps_shndx;
3095 static enum libbpf_map_type
3096 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
3098 if (shndx == obj->efile.data_shndx)
3099 return LIBBPF_MAP_DATA;
3100 else if (shndx == obj->efile.bss_shndx)
3101 return LIBBPF_MAP_BSS;
3102 else if (shndx == obj->efile.rodata_shndx)
3103 return LIBBPF_MAP_RODATA;
3104 else if (shndx == obj->efile.symbols_shndx)
3105 return LIBBPF_MAP_KCONFIG;
3107 return LIBBPF_MAP_UNSPEC;
3110 static int bpf_program__record_reloc(struct bpf_program *prog,
3111 struct reloc_desc *reloc_desc,
3112 __u32 insn_idx, const char *name,
3113 const GElf_Sym *sym, const GElf_Rel *rel)
3115 struct bpf_insn *insn = &prog->insns[insn_idx];
3116 size_t map_idx, nr_maps = prog->obj->nr_maps;
3117 struct bpf_object *obj = prog->obj;
3118 __u32 shdr_idx = sym->st_shndx;
3119 enum libbpf_map_type type;
3120 struct bpf_map *map;
3122 /* sub-program call relocation */
3123 if (insn->code == (BPF_JMP | BPF_CALL)) {
3124 if (insn->src_reg != BPF_PSEUDO_CALL) {
3125 pr_warn("incorrect bpf_call opcode\n");
3126 return -LIBBPF_ERRNO__RELOC;
3128 /* text_shndx can be 0, if no default "main" program exists */
3129 if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
3130 pr_warn("bad call relo against section %u\n", shdr_idx);
3131 return -LIBBPF_ERRNO__RELOC;
3133 if (sym->st_value % 8) {
3134 pr_warn("bad call relo offset: %zu\n",
3135 (size_t)sym->st_value);
3136 return -LIBBPF_ERRNO__RELOC;
3138 reloc_desc->type = RELO_CALL;
3139 reloc_desc->insn_idx = insn_idx;
3140 reloc_desc->sym_off = sym->st_value;
3141 obj->has_pseudo_calls = true;
3145 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) {
3146 pr_warn("invalid relo for insns[%d].code 0x%x\n",
3147 insn_idx, insn->code);
3148 return -LIBBPF_ERRNO__RELOC;
3151 if (sym_is_extern(sym)) {
3152 int sym_idx = GELF_R_SYM(rel->r_info);
3153 int i, n = obj->nr_extern;
3154 struct extern_desc *ext;
3156 for (i = 0; i < n; i++) {
3157 ext = &obj->externs[i];
3158 if (ext->sym_idx == sym_idx)
3162 pr_warn("extern relo failed to find extern for sym %d\n",
3164 return -LIBBPF_ERRNO__RELOC;
3166 pr_debug("found extern #%d '%s' (sym %d) for insn %u\n",
3167 i, ext->name, ext->sym_idx, insn_idx);
3168 reloc_desc->type = RELO_EXTERN;
3169 reloc_desc->insn_idx = insn_idx;
3170 reloc_desc->sym_off = i; /* sym_off stores extern index */
3174 if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
3175 pr_warn("invalid relo for \'%s\' in special section 0x%x; forgot to initialize global var?..\n",
3177 return -LIBBPF_ERRNO__RELOC;
3180 type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
3182 /* generic map reference relocation */
3183 if (type == LIBBPF_MAP_UNSPEC) {
3184 if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
3185 pr_warn("bad map relo against section %u\n",
3187 return -LIBBPF_ERRNO__RELOC;
3189 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
3190 map = &obj->maps[map_idx];
3191 if (map->libbpf_type != type ||
3192 map->sec_idx != sym->st_shndx ||
3193 map->sec_offset != sym->st_value)
3195 pr_debug("found map %zd (%s, sec %d, off %zu) for insn %u\n",
3196 map_idx, map->name, map->sec_idx,
3197 map->sec_offset, insn_idx);
3200 if (map_idx >= nr_maps) {
3201 pr_warn("map relo failed to find map for sec %u, off %zu\n",
3202 shdr_idx, (size_t)sym->st_value);
3203 return -LIBBPF_ERRNO__RELOC;
3205 reloc_desc->type = RELO_LD64;
3206 reloc_desc->insn_idx = insn_idx;
3207 reloc_desc->map_idx = map_idx;
3208 reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
3212 /* global data map relocation */
3213 if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
3214 pr_warn("bad data relo against section %u\n", shdr_idx);
3215 return -LIBBPF_ERRNO__RELOC;
3217 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
3218 map = &obj->maps[map_idx];
3219 if (map->libbpf_type != type)
3221 pr_debug("found data map %zd (%s, sec %d, off %zu) for insn %u\n",
3222 map_idx, map->name, map->sec_idx, map->sec_offset,
3226 if (map_idx >= nr_maps) {
3227 pr_warn("data relo failed to find map for sec %u\n",
3229 return -LIBBPF_ERRNO__RELOC;
3232 reloc_desc->type = RELO_DATA;
3233 reloc_desc->insn_idx = insn_idx;
3234 reloc_desc->map_idx = map_idx;
3235 reloc_desc->sym_off = sym->st_value;
3240 bpf_program__collect_reloc(struct bpf_program *prog, GElf_Shdr *shdr,
3241 Elf_Data *data, struct bpf_object *obj)
3243 Elf_Data *symbols = obj->efile.symbols;
3246 pr_debug("collecting relocating info for: '%s'\n", prog->section_name);
3247 nrels = shdr->sh_size / shdr->sh_entsize;
3249 prog->reloc_desc = malloc(sizeof(*prog->reloc_desc) * nrels);
3250 if (!prog->reloc_desc) {
3251 pr_warn("failed to alloc memory in relocation\n");
3254 prog->nr_reloc = nrels;
3256 for (i = 0; i < nrels; i++) {
3262 if (!gelf_getrel(data, i, &rel)) {
3263 pr_warn("relocation: failed to get %d reloc\n", i);
3264 return -LIBBPF_ERRNO__FORMAT;
3266 if (!gelf_getsym(symbols, GELF_R_SYM(rel.r_info), &sym)) {
3267 pr_warn("relocation: symbol %"PRIx64" not found\n",
3268 GELF_R_SYM(rel.r_info));
3269 return -LIBBPF_ERRNO__FORMAT;
3271 if (rel.r_offset % sizeof(struct bpf_insn))
3272 return -LIBBPF_ERRNO__FORMAT;
3274 insn_idx = rel.r_offset / sizeof(struct bpf_insn);
3275 name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
3276 sym.st_name) ? : "<?>";
3278 pr_debug("relo for shdr %u, symb %zu, value %zu, type %d, bind %d, name %d (\'%s\'), insn %u\n",
3279 (__u32)sym.st_shndx, (size_t)GELF_R_SYM(rel.r_info),
3280 (size_t)sym.st_value, GELF_ST_TYPE(sym.st_info),
3281 GELF_ST_BIND(sym.st_info), sym.st_name, name,
3284 err = bpf_program__record_reloc(prog, &prog->reloc_desc[i],
3285 insn_idx, name, &sym, &rel);
3292 static int bpf_map_find_btf_info(struct bpf_object *obj, struct bpf_map *map)
3294 struct bpf_map_def *def = &map->def;
3295 __u32 key_type_id = 0, value_type_id = 0;
3298 /* if it's BTF-defined map, we don't need to search for type IDs.
3299 * For struct_ops map, it does not need btf_key_type_id and
3300 * btf_value_type_id.
3302 if (map->sec_idx == obj->efile.btf_maps_shndx ||
3303 bpf_map__is_struct_ops(map))
3306 if (!bpf_map__is_internal(map)) {
3307 ret = btf__get_map_kv_tids(obj->btf, map->name, def->key_size,
3308 def->value_size, &key_type_id,
3312 * LLVM annotates global data differently in BTF, that is,
3313 * only as '.data', '.bss' or '.rodata'.
3315 ret = btf__find_by_name(obj->btf,
3316 libbpf_type_to_btf_name[map->libbpf_type]);
3321 map->btf_key_type_id = key_type_id;
3322 map->btf_value_type_id = bpf_map__is_internal(map) ?
3323 ret : value_type_id;
3327 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
3329 struct bpf_map_info info = {};
3330 __u32 len = sizeof(info);
3334 err = bpf_obj_get_info_by_fd(fd, &info, &len);
3338 new_name = strdup(info.name);
3342 new_fd = open("/", O_RDONLY | O_CLOEXEC);
3345 goto err_free_new_name;
3348 new_fd = dup3(fd, new_fd, O_CLOEXEC);
3351 goto err_close_new_fd;
3354 err = zclose(map->fd);
3357 goto err_close_new_fd;
3362 map->name = new_name;
3363 map->def.type = info.type;
3364 map->def.key_size = info.key_size;
3365 map->def.value_size = info.value_size;
3366 map->def.max_entries = info.max_entries;
3367 map->def.map_flags = info.map_flags;
3368 map->btf_key_type_id = info.btf_key_type_id;
3369 map->btf_value_type_id = info.btf_value_type_id;
3381 __u32 bpf_map__max_entries(const struct bpf_map *map)
3383 return map->def.max_entries;
3386 int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries)
3390 map->def.max_entries = max_entries;
3394 int bpf_map__resize(struct bpf_map *map, __u32 max_entries)
3396 if (!map || !max_entries)
3399 return bpf_map__set_max_entries(map, max_entries);
3403 bpf_object__probe_loading(struct bpf_object *obj)
3405 struct bpf_load_program_attr attr;
3406 char *cp, errmsg[STRERR_BUFSIZE];
3407 struct bpf_insn insns[] = {
3408 BPF_MOV64_IMM(BPF_REG_0, 0),
3413 /* make sure basic loading works */
3415 memset(&attr, 0, sizeof(attr));
3416 attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
3418 attr.insns_cnt = ARRAY_SIZE(insns);
3419 attr.license = "GPL";
3421 ret = bpf_load_program_xattr(&attr, NULL, 0);
3424 cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
3425 pr_warn("Error in %s():%s(%d). Couldn't load trivial BPF "
3426 "program. Make sure your kernel supports BPF "
3427 "(CONFIG_BPF_SYSCALL=y) and/or that RLIMIT_MEMLOCK is "
3428 "set to big enough value.\n", __func__, cp, ret);
3437 bpf_object__probe_name(struct bpf_object *obj)
3439 struct bpf_load_program_attr attr;
3440 struct bpf_insn insns[] = {
3441 BPF_MOV64_IMM(BPF_REG_0, 0),
3446 /* make sure loading with name works */
3448 memset(&attr, 0, sizeof(attr));
3449 attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
3451 attr.insns_cnt = ARRAY_SIZE(insns);
3452 attr.license = "GPL";
3454 ret = bpf_load_program_xattr(&attr, NULL, 0);
3464 bpf_object__probe_global_data(struct bpf_object *obj)
3466 struct bpf_load_program_attr prg_attr;
3467 struct bpf_create_map_attr map_attr;
3468 char *cp, errmsg[STRERR_BUFSIZE];
3469 struct bpf_insn insns[] = {
3470 BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16),
3471 BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42),
3472 BPF_MOV64_IMM(BPF_REG_0, 0),
3477 memset(&map_attr, 0, sizeof(map_attr));
3478 map_attr.map_type = BPF_MAP_TYPE_ARRAY;
3479 map_attr.key_size = sizeof(int);
3480 map_attr.value_size = 32;
3481 map_attr.max_entries = 1;
3483 map = bpf_create_map_xattr(&map_attr);
3486 cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
3487 pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
3488 __func__, cp, -ret);
3494 memset(&prg_attr, 0, sizeof(prg_attr));
3495 prg_attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
3496 prg_attr.insns = insns;
3497 prg_attr.insns_cnt = ARRAY_SIZE(insns);
3498 prg_attr.license = "GPL";
3500 ret = bpf_load_program_xattr(&prg_attr, NULL, 0);
3502 obj->caps.global_data = 1;
3510 static int bpf_object__probe_btf_func(struct bpf_object *obj)
3512 static const char strs[] = "\0int\0x\0a";
3513 /* void x(int a) {} */
3516 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
3517 /* FUNC_PROTO */ /* [2] */
3518 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
3519 BTF_PARAM_ENC(7, 1),
3520 /* FUNC x */ /* [3] */
3521 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0), 2),
3525 btf_fd = libbpf__load_raw_btf((char *)types, sizeof(types),
3526 strs, sizeof(strs));
3528 obj->caps.btf_func = 1;
3536 static int bpf_object__probe_btf_func_global(struct bpf_object *obj)
3538 static const char strs[] = "\0int\0x\0a";
3539 /* static void x(int a) {} */
3542 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
3543 /* FUNC_PROTO */ /* [2] */
3544 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
3545 BTF_PARAM_ENC(7, 1),
3546 /* FUNC x BTF_FUNC_GLOBAL */ /* [3] */
3547 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, BTF_FUNC_GLOBAL), 2),
3551 btf_fd = libbpf__load_raw_btf((char *)types, sizeof(types),
3552 strs, sizeof(strs));
3554 obj->caps.btf_func_global = 1;
3562 static int bpf_object__probe_btf_datasec(struct bpf_object *obj)
3564 static const char strs[] = "\0x\0.data";
3568 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
3569 /* VAR x */ /* [2] */
3570 BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
3572 /* DATASEC val */ /* [3] */
3573 BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC, 0, 1), 4),
3574 BTF_VAR_SECINFO_ENC(2, 0, 4),
3578 btf_fd = libbpf__load_raw_btf((char *)types, sizeof(types),
3579 strs, sizeof(strs));
3581 obj->caps.btf_datasec = 1;
3589 static int bpf_object__probe_array_mmap(struct bpf_object *obj)
3591 struct bpf_create_map_attr attr = {
3592 .map_type = BPF_MAP_TYPE_ARRAY,
3593 .map_flags = BPF_F_MMAPABLE,
3594 .key_size = sizeof(int),
3595 .value_size = sizeof(int),
3600 fd = bpf_create_map_xattr(&attr);
3602 obj->caps.array_mmap = 1;
3611 bpf_object__probe_exp_attach_type(struct bpf_object *obj)
3613 struct bpf_load_program_attr attr;
3614 struct bpf_insn insns[] = {
3615 BPF_MOV64_IMM(BPF_REG_0, 0),
3620 memset(&attr, 0, sizeof(attr));
3621 /* use any valid combination of program type and (optional)
3622 * non-zero expected attach type (i.e., not a BPF_CGROUP_INET_INGRESS)
3623 * to see if kernel supports expected_attach_type field for
3624 * BPF_PROG_LOAD command
3626 attr.prog_type = BPF_PROG_TYPE_CGROUP_SOCK;
3627 attr.expected_attach_type = BPF_CGROUP_INET_SOCK_CREATE;
3629 attr.insns_cnt = ARRAY_SIZE(insns);
3630 attr.license = "GPL";
3632 fd = bpf_load_program_xattr(&attr, NULL, 0);
3634 obj->caps.exp_attach_type = 1;
3642 bpf_object__probe_caps(struct bpf_object *obj)
3644 int (*probe_fn[])(struct bpf_object *obj) = {
3645 bpf_object__probe_name,
3646 bpf_object__probe_global_data,
3647 bpf_object__probe_btf_func,
3648 bpf_object__probe_btf_func_global,
3649 bpf_object__probe_btf_datasec,
3650 bpf_object__probe_array_mmap,
3651 bpf_object__probe_exp_attach_type,
3655 for (i = 0; i < ARRAY_SIZE(probe_fn); i++) {
3656 ret = probe_fn[i](obj);
3658 pr_debug("Probe #%d failed with %d.\n", i, ret);
3664 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
3666 struct bpf_map_info map_info = {};
3667 char msg[STRERR_BUFSIZE];
3670 map_info_len = sizeof(map_info);
3672 if (bpf_obj_get_info_by_fd(map_fd, &map_info, &map_info_len)) {
3673 pr_warn("failed to get map info for map FD %d: %s\n",
3674 map_fd, libbpf_strerror_r(errno, msg, sizeof(msg)));
3678 return (map_info.type == map->def.type &&
3679 map_info.key_size == map->def.key_size &&
3680 map_info.value_size == map->def.value_size &&
3681 map_info.max_entries == map->def.max_entries &&
3682 map_info.map_flags == map->def.map_flags);
3686 bpf_object__reuse_map(struct bpf_map *map)
3688 char *cp, errmsg[STRERR_BUFSIZE];
3691 pin_fd = bpf_obj_get(map->pin_path);
3694 if (err == -ENOENT) {
3695 pr_debug("found no pinned map to reuse at '%s'\n",
3700 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
3701 pr_warn("couldn't retrieve pinned map '%s': %s\n",
3706 if (!map_is_reuse_compat(map, pin_fd)) {
3707 pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
3713 err = bpf_map__reuse_fd(map, pin_fd);
3719 pr_debug("reused pinned map at '%s'\n", map->pin_path);
3725 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
3727 enum libbpf_map_type map_type = map->libbpf_type;
3728 char *cp, errmsg[STRERR_BUFSIZE];
3731 err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
3734 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
3735 pr_warn("Error setting initial map(%s) contents: %s\n",
3740 /* Freeze .rodata and .kconfig map as read-only from syscall side. */
3741 if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
3742 err = bpf_map_freeze(map->fd);
3745 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
3746 pr_warn("Error freezing map(%s) as read-only: %s\n",
3754 static void bpf_map__destroy(struct bpf_map *map);
3756 static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map)
3758 struct bpf_create_map_attr create_attr;
3759 struct bpf_map_def *def = &map->def;
3761 memset(&create_attr, 0, sizeof(create_attr));
3764 create_attr.name = map->name;
3765 create_attr.map_ifindex = map->map_ifindex;
3766 create_attr.map_type = def->type;
3767 create_attr.map_flags = def->map_flags;
3768 create_attr.key_size = def->key_size;
3769 create_attr.value_size = def->value_size;
3770 create_attr.numa_node = map->numa_node;
3772 if (def->type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !def->max_entries) {
3775 nr_cpus = libbpf_num_possible_cpus();
3777 pr_warn("map '%s': failed to determine number of system CPUs: %d\n",
3778 map->name, nr_cpus);
3781 pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus);
3782 create_attr.max_entries = nr_cpus;
3784 create_attr.max_entries = def->max_entries;
3787 if (bpf_map__is_struct_ops(map))
3788 create_attr.btf_vmlinux_value_type_id =
3789 map->btf_vmlinux_value_type_id;
3791 create_attr.btf_fd = 0;
3792 create_attr.btf_key_type_id = 0;
3793 create_attr.btf_value_type_id = 0;
3794 if (obj->btf && btf__fd(obj->btf) >= 0 && !bpf_map_find_btf_info(obj, map)) {
3795 create_attr.btf_fd = btf__fd(obj->btf);
3796 create_attr.btf_key_type_id = map->btf_key_type_id;
3797 create_attr.btf_value_type_id = map->btf_value_type_id;
3800 if (bpf_map_type__is_map_in_map(def->type)) {
3801 if (map->inner_map) {
3804 err = bpf_object__create_map(obj, map->inner_map);
3806 pr_warn("map '%s': failed to create inner map: %d\n",
3810 map->inner_map_fd = bpf_map__fd(map->inner_map);
3812 if (map->inner_map_fd >= 0)
3813 create_attr.inner_map_fd = map->inner_map_fd;
3816 map->fd = bpf_create_map_xattr(&create_attr);
3817 if (map->fd < 0 && (create_attr.btf_key_type_id ||
3818 create_attr.btf_value_type_id)) {
3819 char *cp, errmsg[STRERR_BUFSIZE];
3822 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
3823 pr_warn("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
3824 map->name, cp, err);
3825 create_attr.btf_fd = 0;
3826 create_attr.btf_key_type_id = 0;
3827 create_attr.btf_value_type_id = 0;
3828 map->btf_key_type_id = 0;
3829 map->btf_value_type_id = 0;
3830 map->fd = bpf_create_map_xattr(&create_attr);
3836 if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) {
3837 bpf_map__destroy(map->inner_map);
3838 zfree(&map->inner_map);
3845 bpf_object__create_maps(struct bpf_object *obj)
3847 struct bpf_map *map;
3848 char *cp, errmsg[STRERR_BUFSIZE];
3852 for (i = 0; i < obj->nr_maps; i++) {
3853 map = &obj->maps[i];
3855 if (map->pin_path) {
3856 err = bpf_object__reuse_map(map);
3858 pr_warn("map '%s': error reusing pinned map\n",
3865 pr_debug("map '%s': skipping creation (preset fd=%d)\n",
3866 map->name, map->fd);
3870 err = bpf_object__create_map(obj, map);
3874 pr_debug("map '%s': created successfully, fd=%d\n", map->name,
3877 if (bpf_map__is_internal(map)) {
3878 err = bpf_object__populate_internal_map(obj, map);
3885 if (map->init_slots_sz) {
3886 for (j = 0; j < map->init_slots_sz; j++) {
3887 const struct bpf_map *targ_map;
3890 if (!map->init_slots[j])
3893 targ_map = map->init_slots[j];
3894 fd = bpf_map__fd(targ_map);
3895 err = bpf_map_update_elem(map->fd, &j, &fd, 0);
3898 pr_warn("map '%s': failed to initialize slot [%d] to map '%s' fd=%d: %d\n",
3899 map->name, j, targ_map->name,
3903 pr_debug("map '%s': slot [%d] set to map '%s' fd=%d\n",
3904 map->name, j, targ_map->name, fd);
3906 zfree(&map->init_slots);
3907 map->init_slots_sz = 0;
3910 if (map->pin_path && !map->pinned) {
3911 err = bpf_map__pin(map, NULL);
3913 pr_warn("map '%s': failed to auto-pin at '%s': %d\n",
3914 map->name, map->pin_path, err);
3924 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
3925 pr_warn("map '%s': failed to create: %s(%d)\n", map->name, cp, err);
3927 for (j = 0; j < i; j++)
3928 zclose(obj->maps[j].fd);
3933 check_btf_ext_reloc_err(struct bpf_program *prog, int err,
3934 void *btf_prog_info, const char *info_name)
3936 if (err != -ENOENT) {
3937 pr_warn("Error in loading %s for sec %s.\n",
3938 info_name, prog->section_name);
3942 /* err == -ENOENT (i.e. prog->section_name not found in btf_ext) */
3944 if (btf_prog_info) {
3946 * Some info has already been found but has problem
3947 * in the last btf_ext reloc. Must have to error out.
3949 pr_warn("Error in relocating %s for sec %s.\n",
3950 info_name, prog->section_name);
3954 /* Have problem loading the very first info. Ignore the rest. */
3955 pr_warn("Cannot find %s for main program sec %s. Ignore all %s.\n",
3956 info_name, prog->section_name, info_name);
3961 bpf_program_reloc_btf_ext(struct bpf_program *prog, struct bpf_object *obj,
3962 const char *section_name, __u32 insn_offset)
3966 if (!insn_offset || prog->func_info) {
3968 * !insn_offset => main program
3970 * For sub prog, the main program's func_info has to
3971 * be loaded first (i.e. prog->func_info != NULL)
3973 err = btf_ext__reloc_func_info(obj->btf, obj->btf_ext,
3974 section_name, insn_offset,
3976 &prog->func_info_cnt);
3978 return check_btf_ext_reloc_err(prog, err,
3982 prog->func_info_rec_size = btf_ext__func_info_rec_size(obj->btf_ext);
3985 if (!insn_offset || prog->line_info) {
3986 err = btf_ext__reloc_line_info(obj->btf, obj->btf_ext,
3987 section_name, insn_offset,
3989 &prog->line_info_cnt);
3991 return check_btf_ext_reloc_err(prog, err,
3995 prog->line_info_rec_size = btf_ext__line_info_rec_size(obj->btf_ext);
4001 #define BPF_CORE_SPEC_MAX_LEN 64
4003 /* represents BPF CO-RE field or array element accessor */
4004 struct bpf_core_accessor {
4005 __u32 type_id; /* struct/union type or array element type */
4006 __u32 idx; /* field index or array index */
4007 const char *name; /* field name or NULL for array accessor */
4010 struct bpf_core_spec {
4011 const struct btf *btf;
4012 /* high-level spec: named fields and array indices only */
4013 struct bpf_core_accessor spec[BPF_CORE_SPEC_MAX_LEN];
4014 /* high-level spec length */
4016 /* raw, low-level spec: 1-to-1 with accessor spec string */
4017 int raw_spec[BPF_CORE_SPEC_MAX_LEN];
4018 /* raw spec length */
4020 /* field bit offset represented by spec */
4024 static bool str_is_empty(const char *s)
4029 static bool is_flex_arr(const struct btf *btf,
4030 const struct bpf_core_accessor *acc,
4031 const struct btf_array *arr)
4033 const struct btf_type *t;
4035 /* not a flexible array, if not inside a struct or has non-zero size */
4036 if (!acc->name || arr->nelems > 0)
4039 /* has to be the last member of enclosing struct */
4040 t = btf__type_by_id(btf, acc->type_id);
4041 return acc->idx == btf_vlen(t) - 1;
4045 * Turn bpf_field_reloc into a low- and high-level spec representation,
4046 * validating correctness along the way, as well as calculating resulting
4047 * field bit offset, specified by accessor string. Low-level spec captures
4048 * every single level of nestedness, including traversing anonymous
4049 * struct/union members. High-level one only captures semantically meaningful
4050 * "turning points": named fields and array indicies.
4051 * E.g., for this case:
4054 * int __unimportant;
4062 * struct sample *s = ...;
4064 * int x = &s->a[3]; // access string = '0:1:2:3'
4066 * Low-level spec has 1:1 mapping with each element of access string (it's
4067 * just a parsed access string representation): [0, 1, 2, 3].
4069 * High-level spec will capture only 3 points:
4070 * - intial zero-index access by pointer (&s->... is the same as &s[0]...);
4071 * - field 'a' access (corresponds to '2' in low-level spec);
4072 * - array element #3 access (corresponds to '3' in low-level spec).
4075 static int bpf_core_spec_parse(const struct btf *btf,
4077 const char *spec_str,
4078 struct bpf_core_spec *spec)
4080 int access_idx, parsed_len, i;
4081 struct bpf_core_accessor *acc;
4082 const struct btf_type *t;
4087 if (str_is_empty(spec_str) || *spec_str == ':')
4090 memset(spec, 0, sizeof(*spec));
4093 /* parse spec_str="0:1:2:3:4" into array raw_spec=[0, 1, 2, 3, 4] */
4095 if (*spec_str == ':')
4097 if (sscanf(spec_str, "%d%n", &access_idx, &parsed_len) != 1)
4099 if (spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
4101 spec_str += parsed_len;
4102 spec->raw_spec[spec->raw_len++] = access_idx;
4105 if (spec->raw_len == 0)
4108 /* first spec value is always reloc type array index */
4109 t = skip_mods_and_typedefs(btf, type_id, &id);
4113 access_idx = spec->raw_spec[0];
4114 spec->spec[0].type_id = id;
4115 spec->spec[0].idx = access_idx;
4118 sz = btf__resolve_size(btf, id);
4121 spec->bit_offset = access_idx * sz * 8;
4123 for (i = 1; i < spec->raw_len; i++) {
4124 t = skip_mods_and_typedefs(btf, id, &id);
4128 access_idx = spec->raw_spec[i];
4129 acc = &spec->spec[spec->len];
4131 if (btf_is_composite(t)) {
4132 const struct btf_member *m;
4135 if (access_idx >= btf_vlen(t))
4138 bit_offset = btf_member_bit_offset(t, access_idx);
4139 spec->bit_offset += bit_offset;
4141 m = btf_members(t) + access_idx;
4143 name = btf__name_by_offset(btf, m->name_off);
4144 if (str_is_empty(name))
4148 acc->idx = access_idx;
4154 } else if (btf_is_array(t)) {
4155 const struct btf_array *a = btf_array(t);
4158 t = skip_mods_and_typedefs(btf, a->type, &id);
4162 flex = is_flex_arr(btf, acc - 1, a);
4163 if (!flex && access_idx >= a->nelems)
4166 spec->spec[spec->len].type_id = id;
4167 spec->spec[spec->len].idx = access_idx;
4170 sz = btf__resolve_size(btf, id);
4173 spec->bit_offset += access_idx * sz * 8;
4175 pr_warn("relo for [%u] %s (at idx %d) captures type [%d] of unexpected kind %d\n",
4176 type_id, spec_str, i, id, btf_kind(t));
4184 static bool bpf_core_is_flavor_sep(const char *s)
4186 /* check X___Y name pattern, where X and Y are not underscores */
4187 return s[0] != '_' && /* X */
4188 s[1] == '_' && s[2] == '_' && s[3] == '_' && /* ___ */
4189 s[4] != '_'; /* Y */
4192 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
4193 * before last triple underscore. Struct name part after last triple
4194 * underscore is ignored by BPF CO-RE relocation during relocation matching.
4196 static size_t bpf_core_essential_name_len(const char *name)
4198 size_t n = strlen(name);
4201 for (i = n - 5; i >= 0; i--) {
4202 if (bpf_core_is_flavor_sep(name + i))
4208 /* dynamically sized list of type IDs */
4214 static void bpf_core_free_cands(struct ids_vec *cand_ids)
4216 free(cand_ids->data);
4220 static struct ids_vec *bpf_core_find_cands(const struct btf *local_btf,
4221 __u32 local_type_id,
4222 const struct btf *targ_btf)
4224 size_t local_essent_len, targ_essent_len;
4225 const char *local_name, *targ_name;
4226 const struct btf_type *t;
4227 struct ids_vec *cand_ids;
4231 t = btf__type_by_id(local_btf, local_type_id);
4233 return ERR_PTR(-EINVAL);
4235 local_name = btf__name_by_offset(local_btf, t->name_off);
4236 if (str_is_empty(local_name))
4237 return ERR_PTR(-EINVAL);
4238 local_essent_len = bpf_core_essential_name_len(local_name);
4240 cand_ids = calloc(1, sizeof(*cand_ids));
4242 return ERR_PTR(-ENOMEM);
4244 n = btf__get_nr_types(targ_btf);
4245 for (i = 1; i <= n; i++) {
4246 t = btf__type_by_id(targ_btf, i);
4247 targ_name = btf__name_by_offset(targ_btf, t->name_off);
4248 if (str_is_empty(targ_name))
4251 t = skip_mods_and_typedefs(targ_btf, i, NULL);
4252 if (!btf_is_composite(t) && !btf_is_array(t))
4255 targ_essent_len = bpf_core_essential_name_len(targ_name);
4256 if (targ_essent_len != local_essent_len)
4259 if (strncmp(local_name, targ_name, local_essent_len) == 0) {
4260 pr_debug("[%d] %s: found candidate [%d] %s\n",
4261 local_type_id, local_name, i, targ_name);
4262 new_ids = reallocarray(cand_ids->data,
4264 sizeof(*cand_ids->data));
4269 cand_ids->data = new_ids;
4270 cand_ids->data[cand_ids->len++] = i;
4275 bpf_core_free_cands(cand_ids);
4276 return ERR_PTR(err);
4279 /* Check two types for compatibility, skipping const/volatile/restrict and
4280 * typedefs, to ensure we are relocating compatible entities:
4281 * - any two STRUCTs/UNIONs are compatible and can be mixed;
4282 * - any two FWDs are compatible, if their names match (modulo flavor suffix);
4283 * - any two PTRs are always compatible;
4284 * - for ENUMs, names should be the same (ignoring flavor suffix) or at
4285 * least one of enums should be anonymous;
4286 * - for ENUMs, check sizes, names are ignored;
4287 * - for INT, size and signedness are ignored;
4288 * - for ARRAY, dimensionality is ignored, element types are checked for
4289 * compatibility recursively;
4290 * - everything else shouldn't be ever a target of relocation.
4291 * These rules are not set in stone and probably will be adjusted as we get
4292 * more experience with using BPF CO-RE relocations.
4294 static int bpf_core_fields_are_compat(const struct btf *local_btf,
4296 const struct btf *targ_btf,
4299 const struct btf_type *local_type, *targ_type;
4302 local_type = skip_mods_and_typedefs(local_btf, local_id, &local_id);
4303 targ_type = skip_mods_and_typedefs(targ_btf, targ_id, &targ_id);
4304 if (!local_type || !targ_type)
4307 if (btf_is_composite(local_type) && btf_is_composite(targ_type))
4309 if (btf_kind(local_type) != btf_kind(targ_type))
4312 switch (btf_kind(local_type)) {
4316 case BTF_KIND_ENUM: {
4317 const char *local_name, *targ_name;
4318 size_t local_len, targ_len;
4320 local_name = btf__name_by_offset(local_btf,
4321 local_type->name_off);
4322 targ_name = btf__name_by_offset(targ_btf, targ_type->name_off);
4323 local_len = bpf_core_essential_name_len(local_name);
4324 targ_len = bpf_core_essential_name_len(targ_name);
4325 /* one of them is anonymous or both w/ same flavor-less names */
4326 return local_len == 0 || targ_len == 0 ||
4327 (local_len == targ_len &&
4328 strncmp(local_name, targ_name, local_len) == 0);
4331 /* just reject deprecated bitfield-like integers; all other
4332 * integers are by default compatible between each other
4334 return btf_int_offset(local_type) == 0 &&
4335 btf_int_offset(targ_type) == 0;
4336 case BTF_KIND_ARRAY:
4337 local_id = btf_array(local_type)->type;
4338 targ_id = btf_array(targ_type)->type;
4341 pr_warn("unexpected kind %d relocated, local [%d], target [%d]\n",
4342 btf_kind(local_type), local_id, targ_id);
4348 * Given single high-level named field accessor in local type, find
4349 * corresponding high-level accessor for a target type. Along the way,
4350 * maintain low-level spec for target as well. Also keep updating target
4353 * Searching is performed through recursive exhaustive enumeration of all
4354 * fields of a struct/union. If there are any anonymous (embedded)
4355 * structs/unions, they are recursively searched as well. If field with
4356 * desired name is found, check compatibility between local and target types,
4357 * before returning result.
4359 * 1 is returned, if field is found.
4360 * 0 is returned if no compatible field is found.
4361 * <0 is returned on error.
4363 static int bpf_core_match_member(const struct btf *local_btf,
4364 const struct bpf_core_accessor *local_acc,
4365 const struct btf *targ_btf,
4367 struct bpf_core_spec *spec,
4368 __u32 *next_targ_id)
4370 const struct btf_type *local_type, *targ_type;
4371 const struct btf_member *local_member, *m;
4372 const char *local_name, *targ_name;
4376 targ_type = skip_mods_and_typedefs(targ_btf, targ_id, &targ_id);
4379 if (!btf_is_composite(targ_type))
4382 local_id = local_acc->type_id;
4383 local_type = btf__type_by_id(local_btf, local_id);
4384 local_member = btf_members(local_type) + local_acc->idx;
4385 local_name = btf__name_by_offset(local_btf, local_member->name_off);
4387 n = btf_vlen(targ_type);
4388 m = btf_members(targ_type);
4389 for (i = 0; i < n; i++, m++) {
4392 bit_offset = btf_member_bit_offset(targ_type, i);
4394 /* too deep struct/union/array nesting */
4395 if (spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
4398 /* speculate this member will be the good one */
4399 spec->bit_offset += bit_offset;
4400 spec->raw_spec[spec->raw_len++] = i;
4402 targ_name = btf__name_by_offset(targ_btf, m->name_off);
4403 if (str_is_empty(targ_name)) {
4404 /* embedded struct/union, we need to go deeper */
4405 found = bpf_core_match_member(local_btf, local_acc,
4407 spec, next_targ_id);
4408 if (found) /* either found or error */
4410 } else if (strcmp(local_name, targ_name) == 0) {
4411 /* matching named field */
4412 struct bpf_core_accessor *targ_acc;
4414 targ_acc = &spec->spec[spec->len++];
4415 targ_acc->type_id = targ_id;
4417 targ_acc->name = targ_name;
4419 *next_targ_id = m->type;
4420 found = bpf_core_fields_are_compat(local_btf,
4424 spec->len--; /* pop accessor */
4427 /* member turned out not to be what we looked for */
4428 spec->bit_offset -= bit_offset;
4436 * Try to match local spec to a target type and, if successful, produce full
4437 * target spec (high-level, low-level + bit offset).
4439 static int bpf_core_spec_match(struct bpf_core_spec *local_spec,
4440 const struct btf *targ_btf, __u32 targ_id,
4441 struct bpf_core_spec *targ_spec)
4443 const struct btf_type *targ_type;
4444 const struct bpf_core_accessor *local_acc;
4445 struct bpf_core_accessor *targ_acc;
4448 memset(targ_spec, 0, sizeof(*targ_spec));
4449 targ_spec->btf = targ_btf;
4451 local_acc = &local_spec->spec[0];
4452 targ_acc = &targ_spec->spec[0];
4454 for (i = 0; i < local_spec->len; i++, local_acc++, targ_acc++) {
4455 targ_type = skip_mods_and_typedefs(targ_spec->btf, targ_id,
4460 if (local_acc->name) {
4461 matched = bpf_core_match_member(local_spec->btf,
4464 targ_spec, &targ_id);
4468 /* for i=0, targ_id is already treated as array element
4469 * type (because it's the original struct), for others
4470 * we should find array element type first
4473 const struct btf_array *a;
4476 if (!btf_is_array(targ_type))
4479 a = btf_array(targ_type);
4480 flex = is_flex_arr(targ_btf, targ_acc - 1, a);
4481 if (!flex && local_acc->idx >= a->nelems)
4483 if (!skip_mods_and_typedefs(targ_btf, a->type,
4488 /* too deep struct/union/array nesting */
4489 if (targ_spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
4492 targ_acc->type_id = targ_id;
4493 targ_acc->idx = local_acc->idx;
4494 targ_acc->name = NULL;
4496 targ_spec->raw_spec[targ_spec->raw_len] = targ_acc->idx;
4497 targ_spec->raw_len++;
4499 sz = btf__resolve_size(targ_btf, targ_id);
4502 targ_spec->bit_offset += local_acc->idx * sz * 8;
4509 static int bpf_core_calc_field_relo(const struct bpf_program *prog,
4510 const struct bpf_field_reloc *relo,
4511 const struct bpf_core_spec *spec,
4512 __u32 *val, bool *validate)
4514 const struct bpf_core_accessor *acc = &spec->spec[spec->len - 1];
4515 const struct btf_type *t = btf__type_by_id(spec->btf, acc->type_id);
4516 __u32 byte_off, byte_sz, bit_off, bit_sz;
4517 const struct btf_member *m;
4518 const struct btf_type *mt;
4522 /* a[n] accessor needs special handling */
4524 if (relo->kind == BPF_FIELD_BYTE_OFFSET) {
4525 *val = spec->bit_offset / 8;
4526 } else if (relo->kind == BPF_FIELD_BYTE_SIZE) {
4527 sz = btf__resolve_size(spec->btf, acc->type_id);
4532 pr_warn("prog '%s': relo %d at insn #%d can't be applied to array access\n",
4533 bpf_program__title(prog, false),
4534 relo->kind, relo->insn_off / 8);
4542 m = btf_members(t) + acc->idx;
4543 mt = skip_mods_and_typedefs(spec->btf, m->type, NULL);
4544 bit_off = spec->bit_offset;
4545 bit_sz = btf_member_bitfield_size(t, acc->idx);
4547 bitfield = bit_sz > 0;
4550 byte_off = bit_off / 8 / byte_sz * byte_sz;
4551 /* figure out smallest int size necessary for bitfield load */
4552 while (bit_off + bit_sz - byte_off * 8 > byte_sz * 8) {
4554 /* bitfield can't be read with 64-bit read */
4555 pr_warn("prog '%s': relo %d at insn #%d can't be satisfied for bitfield\n",
4556 bpf_program__title(prog, false),
4557 relo->kind, relo->insn_off / 8);
4561 byte_off = bit_off / 8 / byte_sz * byte_sz;
4564 sz = btf__resolve_size(spec->btf, m->type);
4568 byte_off = spec->bit_offset / 8;
4569 bit_sz = byte_sz * 8;
4572 /* for bitfields, all the relocatable aspects are ambiguous and we
4573 * might disagree with compiler, so turn off validation of expected
4574 * value, except for signedness
4577 *validate = !bitfield;
4579 switch (relo->kind) {
4580 case BPF_FIELD_BYTE_OFFSET:
4583 case BPF_FIELD_BYTE_SIZE:
4586 case BPF_FIELD_SIGNED:
4587 /* enums will be assumed unsigned */
4588 *val = btf_is_enum(mt) ||
4589 (btf_int_encoding(mt) & BTF_INT_SIGNED);
4591 *validate = true; /* signedness is never ambiguous */
4593 case BPF_FIELD_LSHIFT_U64:
4594 #if __BYTE_ORDER == __LITTLE_ENDIAN
4595 *val = 64 - (bit_off + bit_sz - byte_off * 8);
4597 *val = (8 - byte_sz) * 8 + (bit_off - byte_off * 8);
4600 case BPF_FIELD_RSHIFT_U64:
4603 *validate = true; /* right shift is never ambiguous */
4605 case BPF_FIELD_EXISTS:
4607 pr_warn("prog '%s': unknown relo %d at insn #%d\n",
4608 bpf_program__title(prog, false),
4609 relo->kind, relo->insn_off / 8);
4617 * Patch relocatable BPF instruction.
4619 * Patched value is determined by relocation kind and target specification.
4620 * For field existence relocation target spec will be NULL if field is not
4622 * Expected insn->imm value is determined using relocation kind and local
4623 * spec, and is checked before patching instruction. If actual insn->imm value
4624 * is wrong, bail out with error.
4626 * Currently three kinds of BPF instructions are supported:
4627 * 1. rX = <imm> (assignment with immediate operand);
4628 * 2. rX += <imm> (arithmetic operations with immediate operand);
4630 static int bpf_core_reloc_insn(struct bpf_program *prog,
4631 const struct bpf_field_reloc *relo,
4633 const struct bpf_core_spec *local_spec,
4634 const struct bpf_core_spec *targ_spec)
4636 __u32 orig_val, new_val;
4637 struct bpf_insn *insn;
4638 bool validate = true;
4642 if (relo->insn_off % sizeof(struct bpf_insn))
4644 insn_idx = relo->insn_off / sizeof(struct bpf_insn);
4645 insn = &prog->insns[insn_idx];
4646 class = BPF_CLASS(insn->code);
4648 if (relo->kind == BPF_FIELD_EXISTS) {
4649 orig_val = 1; /* can't generate EXISTS relo w/o local field */
4650 new_val = targ_spec ? 1 : 0;
4651 } else if (!targ_spec) {
4652 pr_debug("prog '%s': relo #%d: substituting insn #%d w/ invalid insn\n",
4653 bpf_program__title(prog, false), relo_idx, insn_idx);
4654 insn->code = BPF_JMP | BPF_CALL;
4658 /* if this instruction is reachable (not a dead code),
4659 * verifier will complain with the following message:
4660 * invalid func unknown#195896080
4662 insn->imm = 195896080; /* => 0xbad2310 => "bad relo" */
4665 err = bpf_core_calc_field_relo(prog, relo, local_spec,
4666 &orig_val, &validate);
4669 err = bpf_core_calc_field_relo(prog, relo, targ_spec,
4678 if (BPF_SRC(insn->code) != BPF_K)
4680 if (validate && insn->imm != orig_val) {
4681 pr_warn("prog '%s': relo #%d: unexpected insn #%d (ALU/ALU64) value: got %u, exp %u -> %u\n",
4682 bpf_program__title(prog, false), relo_idx,
4683 insn_idx, insn->imm, orig_val, new_val);
4686 orig_val = insn->imm;
4687 insn->imm = new_val;
4688 pr_debug("prog '%s': relo #%d: patched insn #%d (ALU/ALU64) imm %u -> %u\n",
4689 bpf_program__title(prog, false), relo_idx, insn_idx,
4695 if (validate && insn->off != orig_val) {
4696 pr_warn("prog '%s': relo #%d: unexpected insn #%d (LD/LDX/ST/STX) value: got %u, exp %u -> %u\n",
4697 bpf_program__title(prog, false), relo_idx,
4698 insn_idx, insn->off, orig_val, new_val);
4701 if (new_val > SHRT_MAX) {
4702 pr_warn("prog '%s': relo #%d: insn #%d (LDX/ST/STX) value too big: %u\n",
4703 bpf_program__title(prog, false), relo_idx,
4707 orig_val = insn->off;
4708 insn->off = new_val;
4709 pr_debug("prog '%s': relo #%d: patched insn #%d (LDX/ST/STX) off %u -> %u\n",
4710 bpf_program__title(prog, false), relo_idx, insn_idx,
4714 pr_warn("prog '%s': relo #%d: trying to relocate unrecognized insn #%d, code:%x, src:%x, dst:%x, off:%x, imm:%x\n",
4715 bpf_program__title(prog, false), relo_idx,
4716 insn_idx, insn->code, insn->src_reg, insn->dst_reg,
4717 insn->off, insn->imm);
4724 /* Output spec definition in the format:
4725 * [<type-id>] (<type-name>) + <raw-spec> => <offset>@<spec>,
4726 * where <spec> is a C-syntax view of recorded field access, e.g.: x.a[3].b
4728 static void bpf_core_dump_spec(int level, const struct bpf_core_spec *spec)
4730 const struct btf_type *t;
4735 type_id = spec->spec[0].type_id;
4736 t = btf__type_by_id(spec->btf, type_id);
4737 s = btf__name_by_offset(spec->btf, t->name_off);
4738 libbpf_print(level, "[%u] %s + ", type_id, s);
4740 for (i = 0; i < spec->raw_len; i++)
4741 libbpf_print(level, "%d%s", spec->raw_spec[i],
4742 i == spec->raw_len - 1 ? " => " : ":");
4744 libbpf_print(level, "%u.%u @ &x",
4745 spec->bit_offset / 8, spec->bit_offset % 8);
4747 for (i = 0; i < spec->len; i++) {
4748 if (spec->spec[i].name)
4749 libbpf_print(level, ".%s", spec->spec[i].name);
4751 libbpf_print(level, "[%u]", spec->spec[i].idx);
4756 static size_t bpf_core_hash_fn(const void *key, void *ctx)
4761 static bool bpf_core_equal_fn(const void *k1, const void *k2, void *ctx)
4766 static void *u32_as_hash_key(__u32 x)
4768 return (void *)(uintptr_t)x;
4772 * CO-RE relocate single instruction.
4774 * The outline and important points of the algorithm:
4775 * 1. For given local type, find corresponding candidate target types.
4776 * Candidate type is a type with the same "essential" name, ignoring
4777 * everything after last triple underscore (___). E.g., `sample`,
4778 * `sample___flavor_one`, `sample___flavor_another_one`, are all candidates
4779 * for each other. Names with triple underscore are referred to as
4780 * "flavors" and are useful, among other things, to allow to
4781 * specify/support incompatible variations of the same kernel struct, which
4782 * might differ between different kernel versions and/or build
4785 * N.B. Struct "flavors" could be generated by bpftool's BTF-to-C
4786 * converter, when deduplicated BTF of a kernel still contains more than
4787 * one different types with the same name. In that case, ___2, ___3, etc
4788 * are appended starting from second name conflict. But start flavors are
4789 * also useful to be defined "locally", in BPF program, to extract same
4790 * data from incompatible changes between different kernel
4791 * versions/configurations. For instance, to handle field renames between
4792 * kernel versions, one can use two flavors of the struct name with the
4793 * same common name and use conditional relocations to extract that field,
4794 * depending on target kernel version.
4795 * 2. For each candidate type, try to match local specification to this
4796 * candidate target type. Matching involves finding corresponding
4797 * high-level spec accessors, meaning that all named fields should match,
4798 * as well as all array accesses should be within the actual bounds. Also,
4799 * types should be compatible (see bpf_core_fields_are_compat for details).
4800 * 3. It is supported and expected that there might be multiple flavors
4801 * matching the spec. As long as all the specs resolve to the same set of
4802 * offsets across all candidates, there is no error. If there is any
4803 * ambiguity, CO-RE relocation will fail. This is necessary to accomodate
4804 * imprefection of BTF deduplication, which can cause slight duplication of
4805 * the same BTF type, if some directly or indirectly referenced (by
4806 * pointer) type gets resolved to different actual types in different
4807 * object files. If such situation occurs, deduplicated BTF will end up
4808 * with two (or more) structurally identical types, which differ only in
4809 * types they refer to through pointer. This should be OK in most cases and
4811 * 4. Candidate types search is performed by linearly scanning through all
4812 * types in target BTF. It is anticipated that this is overall more
4813 * efficient memory-wise and not significantly worse (if not better)
4814 * CPU-wise compared to prebuilding a map from all local type names to
4815 * a list of candidate type names. It's also sped up by caching resolved
4816 * list of matching candidates per each local "root" type ID, that has at
4817 * least one bpf_field_reloc associated with it. This list is shared
4818 * between multiple relocations for the same type ID and is updated as some
4819 * of the candidates are pruned due to structural incompatibility.
4821 static int bpf_core_reloc_field(struct bpf_program *prog,
4822 const struct bpf_field_reloc *relo,
4824 const struct btf *local_btf,
4825 const struct btf *targ_btf,
4826 struct hashmap *cand_cache)
4828 const char *prog_name = bpf_program__title(prog, false);
4829 struct bpf_core_spec local_spec, cand_spec, targ_spec;
4830 const void *type_key = u32_as_hash_key(relo->type_id);
4831 const struct btf_type *local_type, *cand_type;
4832 const char *local_name, *cand_name;
4833 struct ids_vec *cand_ids;
4834 __u32 local_id, cand_id;
4835 const char *spec_str;
4838 local_id = relo->type_id;
4839 local_type = btf__type_by_id(local_btf, local_id);
4843 local_name = btf__name_by_offset(local_btf, local_type->name_off);
4844 if (str_is_empty(local_name))
4847 spec_str = btf__name_by_offset(local_btf, relo->access_str_off);
4848 if (str_is_empty(spec_str))
4851 err = bpf_core_spec_parse(local_btf, local_id, spec_str, &local_spec);
4853 pr_warn("prog '%s': relo #%d: parsing [%d] %s + %s failed: %d\n",
4854 prog_name, relo_idx, local_id, local_name, spec_str,
4859 pr_debug("prog '%s': relo #%d: kind %d, spec is ", prog_name, relo_idx,
4861 bpf_core_dump_spec(LIBBPF_DEBUG, &local_spec);
4862 libbpf_print(LIBBPF_DEBUG, "\n");
4864 if (!hashmap__find(cand_cache, type_key, (void **)&cand_ids)) {
4865 cand_ids = bpf_core_find_cands(local_btf, local_id, targ_btf);
4866 if (IS_ERR(cand_ids)) {
4867 pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s: %ld",
4868 prog_name, relo_idx, local_id, local_name,
4870 return PTR_ERR(cand_ids);
4872 err = hashmap__set(cand_cache, type_key, cand_ids, NULL, NULL);
4874 bpf_core_free_cands(cand_ids);
4879 for (i = 0, j = 0; i < cand_ids->len; i++) {
4880 cand_id = cand_ids->data[i];
4881 cand_type = btf__type_by_id(targ_btf, cand_id);
4882 cand_name = btf__name_by_offset(targ_btf, cand_type->name_off);
4884 err = bpf_core_spec_match(&local_spec, targ_btf,
4885 cand_id, &cand_spec);
4886 pr_debug("prog '%s': relo #%d: matching candidate #%d %s against spec ",
4887 prog_name, relo_idx, i, cand_name);
4888 bpf_core_dump_spec(LIBBPF_DEBUG, &cand_spec);
4889 libbpf_print(LIBBPF_DEBUG, ": %d\n", err);
4891 pr_warn("prog '%s': relo #%d: matching error: %d\n",
4892 prog_name, relo_idx, err);
4899 targ_spec = cand_spec;
4900 } else if (cand_spec.bit_offset != targ_spec.bit_offset) {
4901 /* if there are many candidates, they should all
4902 * resolve to the same bit offset
4904 pr_warn("prog '%s': relo #%d: offset ambiguity: %u != %u\n",
4905 prog_name, relo_idx, cand_spec.bit_offset,
4906 targ_spec.bit_offset);
4910 cand_ids->data[j++] = cand_spec.spec[0].type_id;
4914 * For BPF_FIELD_EXISTS relo or when used BPF program has field
4915 * existence checks or kernel version/config checks, it's expected
4916 * that we might not find any candidates. In this case, if field
4917 * wasn't found in any candidate, the list of candidates shouldn't
4918 * change at all, we'll just handle relocating appropriately,
4919 * depending on relo's kind.
4925 * If no candidates were found, it might be both a programmer error,
4926 * as well as expected case, depending whether instruction w/
4927 * relocation is guarded in some way that makes it unreachable (dead
4928 * code) if relocation can't be resolved. This is handled in
4929 * bpf_core_reloc_insn() uniformly by replacing that instruction with
4930 * BPF helper call insn (using invalid helper ID). If that instruction
4931 * is indeed unreachable, then it will be ignored and eliminated by
4932 * verifier. If it was an error, then verifier will complain and point
4933 * to a specific instruction number in its log.
4936 pr_debug("prog '%s': relo #%d: no matching targets found for [%d] %s + %s\n",
4937 prog_name, relo_idx, local_id, local_name, spec_str);
4939 /* bpf_core_reloc_insn should know how to handle missing targ_spec */
4940 err = bpf_core_reloc_insn(prog, relo, relo_idx, &local_spec,
4941 j ? &targ_spec : NULL);
4943 pr_warn("prog '%s': relo #%d: failed to patch insn at offset %d: %d\n",
4944 prog_name, relo_idx, relo->insn_off, err);
4952 bpf_core_reloc_fields(struct bpf_object *obj, const char *targ_btf_path)
4954 const struct btf_ext_info_sec *sec;
4955 const struct bpf_field_reloc *rec;
4956 const struct btf_ext_info *seg;
4957 struct hashmap_entry *entry;
4958 struct hashmap *cand_cache = NULL;
4959 struct bpf_program *prog;
4960 struct btf *targ_btf;
4961 const char *sec_name;
4965 targ_btf = btf__parse_elf(targ_btf_path, NULL);
4967 targ_btf = obj->btf_vmlinux;
4968 if (IS_ERR_OR_NULL(targ_btf)) {
4969 pr_warn("failed to get target BTF: %ld\n", PTR_ERR(targ_btf));
4970 return PTR_ERR(targ_btf);
4973 cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
4974 if (IS_ERR(cand_cache)) {
4975 err = PTR_ERR(cand_cache);
4979 seg = &obj->btf_ext->field_reloc_info;
4980 for_each_btf_ext_sec(seg, sec) {
4981 sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
4982 if (str_is_empty(sec_name)) {
4987 for (i = 0; i < obj->nr_programs; i++) {
4988 if (!strcmp(obj->programs[i].section_name, sec_name)) {
4989 prog = &obj->programs[i];
4994 pr_warn("failed to find program '%s' for CO-RE offset relocation\n",
5000 pr_debug("prog '%s': performing %d CO-RE offset relocs\n",
5001 sec_name, sec->num_info);
5003 for_each_btf_ext_rec(seg, sec, i, rec) {
5004 err = bpf_core_reloc_field(prog, rec, i, obj->btf,
5005 targ_btf, cand_cache);
5007 pr_warn("prog '%s': relo #%d: failed to relocate: %d\n",
5015 /* obj->btf_vmlinux is freed at the end of object load phase */
5016 if (targ_btf != obj->btf_vmlinux)
5017 btf__free(targ_btf);
5018 if (!IS_ERR_OR_NULL(cand_cache)) {
5019 hashmap__for_each_entry(cand_cache, entry, i) {
5020 bpf_core_free_cands(entry->value);
5022 hashmap__free(cand_cache);
5028 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
5032 if (obj->btf_ext->field_reloc_info.len)
5033 err = bpf_core_reloc_fields(obj, targ_btf_path);
5039 bpf_program__reloc_text(struct bpf_program *prog, struct bpf_object *obj,
5040 struct reloc_desc *relo)
5042 struct bpf_insn *insn, *new_insn;
5043 struct bpf_program *text;
5047 if (prog->idx != obj->efile.text_shndx && prog->main_prog_cnt == 0) {
5048 text = bpf_object__find_prog_by_idx(obj, obj->efile.text_shndx);
5050 pr_warn("no .text section found yet relo into text exist\n");
5051 return -LIBBPF_ERRNO__RELOC;
5053 new_cnt = prog->insns_cnt + text->insns_cnt;
5054 new_insn = reallocarray(prog->insns, new_cnt, sizeof(*insn));
5056 pr_warn("oom in prog realloc\n");
5059 prog->insns = new_insn;
5062 err = bpf_program_reloc_btf_ext(prog, obj,
5069 memcpy(new_insn + prog->insns_cnt, text->insns,
5070 text->insns_cnt * sizeof(*insn));
5071 prog->main_prog_cnt = prog->insns_cnt;
5072 prog->insns_cnt = new_cnt;
5073 pr_debug("added %zd insn from %s to prog %s\n",
5074 text->insns_cnt, text->section_name,
5075 prog->section_name);
5078 insn = &prog->insns[relo->insn_idx];
5079 insn->imm += relo->sym_off / 8 + prog->main_prog_cnt - relo->insn_idx;
5084 bpf_program__relocate(struct bpf_program *prog, struct bpf_object *obj)
5092 err = bpf_program_reloc_btf_ext(prog, obj,
5093 prog->section_name, 0);
5098 if (!prog->reloc_desc)
5101 for (i = 0; i < prog->nr_reloc; i++) {
5102 struct reloc_desc *relo = &prog->reloc_desc[i];
5103 struct bpf_insn *insn = &prog->insns[relo->insn_idx];
5104 struct extern_desc *ext;
5106 if (relo->insn_idx + 1 >= (int)prog->insns_cnt) {
5107 pr_warn("relocation out of range: '%s'\n",
5108 prog->section_name);
5109 return -LIBBPF_ERRNO__RELOC;
5112 switch (relo->type) {
5114 insn[0].src_reg = BPF_PSEUDO_MAP_FD;
5115 insn[0].imm = obj->maps[relo->map_idx].fd;
5118 insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
5119 insn[1].imm = insn[0].imm + relo->sym_off;
5120 insn[0].imm = obj->maps[relo->map_idx].fd;
5123 ext = &obj->externs[relo->sym_off];
5124 if (ext->type == EXT_KCFG) {
5125 insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
5126 insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
5127 insn[1].imm = ext->kcfg.data_off;
5128 } else /* EXT_KSYM */ {
5129 insn[0].imm = (__u32)ext->ksym.addr;
5130 insn[1].imm = ext->ksym.addr >> 32;
5134 err = bpf_program__reloc_text(prog, obj, relo);
5139 pr_warn("relo #%d: bad relo type %d\n", i, relo->type);
5144 zfree(&prog->reloc_desc);
5150 bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
5152 struct bpf_program *prog;
5157 err = bpf_object__relocate_core(obj, targ_btf_path);
5159 pr_warn("failed to perform CO-RE relocations: %d\n",
5164 /* ensure .text is relocated first, as it's going to be copied as-is
5165 * later for sub-program calls
5167 for (i = 0; i < obj->nr_programs; i++) {
5168 prog = &obj->programs[i];
5169 if (prog->idx != obj->efile.text_shndx)
5172 err = bpf_program__relocate(prog, obj);
5174 pr_warn("failed to relocate '%s'\n", prog->section_name);
5179 /* now relocate everything but .text, which by now is relocated
5180 * properly, so we can copy raw sub-program instructions as is safely
5182 for (i = 0; i < obj->nr_programs; i++) {
5183 prog = &obj->programs[i];
5184 if (prog->idx == obj->efile.text_shndx)
5187 err = bpf_program__relocate(prog, obj);
5189 pr_warn("failed to relocate '%s'\n", prog->section_name);
5196 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
5197 GElf_Shdr *shdr, Elf_Data *data);
5199 static int bpf_object__collect_map_relos(struct bpf_object *obj,
5200 GElf_Shdr *shdr, Elf_Data *data)
5202 const int bpf_ptr_sz = 8, host_ptr_sz = sizeof(void *);
5203 int i, j, nrels, new_sz;
5204 const struct btf_var_secinfo *vi = NULL;
5205 const struct btf_type *sec, *var, *def;
5206 const struct btf_member *member;
5207 struct bpf_map *map, *targ_map;
5208 const char *name, *mname;
5215 if (!obj->efile.btf_maps_sec_btf_id || !obj->btf)
5217 sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id);
5221 symbols = obj->efile.symbols;
5222 nrels = shdr->sh_size / shdr->sh_entsize;
5223 for (i = 0; i < nrels; i++) {
5224 if (!gelf_getrel(data, i, &rel)) {
5225 pr_warn(".maps relo #%d: failed to get ELF relo\n", i);
5226 return -LIBBPF_ERRNO__FORMAT;
5228 if (!gelf_getsym(symbols, GELF_R_SYM(rel.r_info), &sym)) {
5229 pr_warn(".maps relo #%d: symbol %zx not found\n",
5230 i, (size_t)GELF_R_SYM(rel.r_info));
5231 return -LIBBPF_ERRNO__FORMAT;
5233 name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
5234 sym.st_name) ? : "<?>";
5235 if (sym.st_shndx != obj->efile.btf_maps_shndx) {
5236 pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
5238 return -LIBBPF_ERRNO__RELOC;
5241 pr_debug(".maps relo #%d: for %zd value %zd rel.r_offset %zu name %d ('%s')\n",
5242 i, (ssize_t)(rel.r_info >> 32), (size_t)sym.st_value,
5243 (size_t)rel.r_offset, sym.st_name, name);
5245 for (j = 0; j < obj->nr_maps; j++) {
5246 map = &obj->maps[j];
5247 if (map->sec_idx != obj->efile.btf_maps_shndx)
5250 vi = btf_var_secinfos(sec) + map->btf_var_idx;
5251 if (vi->offset <= rel.r_offset &&
5252 rel.r_offset + bpf_ptr_sz <= vi->offset + vi->size)
5255 if (j == obj->nr_maps) {
5256 pr_warn(".maps relo #%d: cannot find map '%s' at rel.r_offset %zu\n",
5257 i, name, (size_t)rel.r_offset);
5261 if (!bpf_map_type__is_map_in_map(map->def.type))
5263 if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
5264 map->def.key_size != sizeof(int)) {
5265 pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
5266 i, map->name, sizeof(int));
5270 targ_map = bpf_object__find_map_by_name(obj, name);
5274 var = btf__type_by_id(obj->btf, vi->type);
5275 def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
5276 if (btf_vlen(def) == 0)
5278 member = btf_members(def) + btf_vlen(def) - 1;
5279 mname = btf__name_by_offset(obj->btf, member->name_off);
5280 if (strcmp(mname, "values"))
5283 moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8;
5284 if (rel.r_offset - vi->offset < moff)
5287 moff = rel.r_offset - vi->offset - moff;
5288 /* here we use BPF pointer size, which is always 64 bit, as we
5289 * are parsing ELF that was built for BPF target
5291 if (moff % bpf_ptr_sz)
5294 if (moff >= map->init_slots_sz) {
5296 tmp = realloc(map->init_slots, new_sz * host_ptr_sz);
5299 map->init_slots = tmp;
5300 memset(map->init_slots + map->init_slots_sz, 0,
5301 (new_sz - map->init_slots_sz) * host_ptr_sz);
5302 map->init_slots_sz = new_sz;
5304 map->init_slots[moff] = targ_map;
5306 pr_debug(".maps relo #%d: map '%s' slot [%d] points to map '%s'\n",
5307 i, map->name, moff, name);
5313 static int bpf_object__collect_reloc(struct bpf_object *obj)
5317 if (!obj_elf_valid(obj)) {
5318 pr_warn("Internal error: elf object is closed\n");
5319 return -LIBBPF_ERRNO__INTERNAL;
5322 for (i = 0; i < obj->efile.nr_reloc_sects; i++) {
5323 GElf_Shdr *shdr = &obj->efile.reloc_sects[i].shdr;
5324 Elf_Data *data = obj->efile.reloc_sects[i].data;
5325 int idx = shdr->sh_info;
5326 struct bpf_program *prog;
5328 if (shdr->sh_type != SHT_REL) {
5329 pr_warn("internal error at %d\n", __LINE__);
5330 return -LIBBPF_ERRNO__INTERNAL;
5333 if (idx == obj->efile.st_ops_shndx) {
5334 err = bpf_object__collect_st_ops_relos(obj, shdr, data);
5335 } else if (idx == obj->efile.btf_maps_shndx) {
5336 err = bpf_object__collect_map_relos(obj, shdr, data);
5338 prog = bpf_object__find_prog_by_idx(obj, idx);
5340 pr_warn("relocation failed: no prog in section(%d)\n", idx);
5341 return -LIBBPF_ERRNO__RELOC;
5343 err = bpf_program__collect_reloc(prog, shdr, data, obj);
5352 load_program(struct bpf_program *prog, struct bpf_insn *insns, int insns_cnt,
5353 char *license, __u32 kern_version, int *pfd)
5355 struct bpf_load_program_attr load_attr;
5356 char *cp, errmsg[STRERR_BUFSIZE];
5357 size_t log_buf_size = 0;
5358 char *log_buf = NULL;
5361 if (!insns || !insns_cnt)
5364 memset(&load_attr, 0, sizeof(struct bpf_load_program_attr));
5365 load_attr.prog_type = prog->type;
5366 /* old kernels might not support specifying expected_attach_type */
5367 if (!prog->caps->exp_attach_type && prog->sec_def &&
5368 prog->sec_def->is_exp_attach_type_optional)
5369 load_attr.expected_attach_type = 0;
5371 load_attr.expected_attach_type = prog->expected_attach_type;
5372 if (prog->caps->name)
5373 load_attr.name = prog->name;
5374 load_attr.insns = insns;
5375 load_attr.insns_cnt = insns_cnt;
5376 load_attr.license = license;
5377 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
5378 prog->type == BPF_PROG_TYPE_LSM) {
5379 load_attr.attach_btf_id = prog->attach_btf_id;
5380 } else if (prog->type == BPF_PROG_TYPE_TRACING ||
5381 prog->type == BPF_PROG_TYPE_EXT) {
5382 load_attr.attach_prog_fd = prog->attach_prog_fd;
5383 load_attr.attach_btf_id = prog->attach_btf_id;
5385 load_attr.kern_version = kern_version;
5386 load_attr.prog_ifindex = prog->prog_ifindex;
5388 /* specify func_info/line_info only if kernel supports them */
5389 btf_fd = bpf_object__btf_fd(prog->obj);
5390 if (btf_fd >= 0 && prog->obj->caps.btf_func) {
5391 load_attr.prog_btf_fd = btf_fd;
5392 load_attr.func_info = prog->func_info;
5393 load_attr.func_info_rec_size = prog->func_info_rec_size;
5394 load_attr.func_info_cnt = prog->func_info_cnt;
5395 load_attr.line_info = prog->line_info;
5396 load_attr.line_info_rec_size = prog->line_info_rec_size;
5397 load_attr.line_info_cnt = prog->line_info_cnt;
5399 load_attr.log_level = prog->log_level;
5400 load_attr.prog_flags = prog->prog_flags;
5404 log_buf = malloc(log_buf_size);
5411 ret = bpf_load_program_xattr(&load_attr, log_buf, log_buf_size);
5414 if (log_buf && load_attr.log_level)
5415 pr_debug("verifier log:\n%s", log_buf);
5421 if (!log_buf || errno == ENOSPC) {
5422 log_buf_size = max((size_t)BPF_LOG_BUF_SIZE,
5429 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
5430 pr_warn("load bpf program failed: %s\n", cp);
5433 if (log_buf && log_buf[0] != '\0') {
5434 ret = -LIBBPF_ERRNO__VERIFY;
5435 pr_warn("-- BEGIN DUMP LOG ---\n");
5436 pr_warn("\n%s\n", log_buf);
5437 pr_warn("-- END LOG --\n");
5438 } else if (load_attr.insns_cnt >= BPF_MAXINSNS) {
5439 pr_warn("Program too large (%zu insns), at most %d insns\n",
5440 load_attr.insns_cnt, BPF_MAXINSNS);
5441 ret = -LIBBPF_ERRNO__PROG2BIG;
5442 } else if (load_attr.prog_type != BPF_PROG_TYPE_KPROBE) {
5443 /* Wrong program type? */
5446 load_attr.prog_type = BPF_PROG_TYPE_KPROBE;
5447 load_attr.expected_attach_type = 0;
5448 fd = bpf_load_program_xattr(&load_attr, NULL, 0);
5451 ret = -LIBBPF_ERRNO__PROGTYPE;
5461 static int libbpf_find_attach_btf_id(struct bpf_program *prog);
5463 int bpf_program__load(struct bpf_program *prog, char *license, __u32 kern_ver)
5465 int err = 0, fd, i, btf_id;
5467 if (prog->obj->loaded) {
5468 pr_warn("prog '%s'('%s'): can't load after object was loaded\n",
5469 prog->name, prog->section_name);
5473 if ((prog->type == BPF_PROG_TYPE_TRACING ||
5474 prog->type == BPF_PROG_TYPE_LSM ||
5475 prog->type == BPF_PROG_TYPE_EXT) && !prog->attach_btf_id) {
5476 btf_id = libbpf_find_attach_btf_id(prog);
5479 prog->attach_btf_id = btf_id;
5482 if (prog->instances.nr < 0 || !prog->instances.fds) {
5483 if (prog->preprocessor) {
5484 pr_warn("Internal error: can't load program '%s'\n",
5485 prog->section_name);
5486 return -LIBBPF_ERRNO__INTERNAL;
5489 prog->instances.fds = malloc(sizeof(int));
5490 if (!prog->instances.fds) {
5491 pr_warn("Not enough memory for BPF fds\n");
5494 prog->instances.nr = 1;
5495 prog->instances.fds[0] = -1;
5498 if (!prog->preprocessor) {
5499 if (prog->instances.nr != 1) {
5500 pr_warn("Program '%s' is inconsistent: nr(%d) != 1\n",
5501 prog->section_name, prog->instances.nr);
5503 err = load_program(prog, prog->insns, prog->insns_cnt,
5504 license, kern_ver, &fd);
5506 prog->instances.fds[0] = fd;
5510 for (i = 0; i < prog->instances.nr; i++) {
5511 struct bpf_prog_prep_result result;
5512 bpf_program_prep_t preprocessor = prog->preprocessor;
5514 memset(&result, 0, sizeof(result));
5515 err = preprocessor(prog, i, prog->insns,
5516 prog->insns_cnt, &result);
5518 pr_warn("Preprocessing the %dth instance of program '%s' failed\n",
5519 i, prog->section_name);
5523 if (!result.new_insn_ptr || !result.new_insn_cnt) {
5524 pr_debug("Skip loading the %dth instance of program '%s'\n",
5525 i, prog->section_name);
5526 prog->instances.fds[i] = -1;
5532 err = load_program(prog, result.new_insn_ptr,
5533 result.new_insn_cnt, license, kern_ver, &fd);
5535 pr_warn("Loading the %dth instance of program '%s' failed\n",
5536 i, prog->section_name);
5542 prog->instances.fds[i] = fd;
5546 pr_warn("failed to load program '%s'\n", prog->section_name);
5547 zfree(&prog->insns);
5548 prog->insns_cnt = 0;
5552 static bool bpf_program__is_function_storage(const struct bpf_program *prog,
5553 const struct bpf_object *obj)
5555 return prog->idx == obj->efile.text_shndx && obj->has_pseudo_calls;
5559 bpf_object__load_progs(struct bpf_object *obj, int log_level)
5561 struct bpf_program *prog;
5565 for (i = 0; i < obj->nr_programs; i++) {
5566 prog = &obj->programs[i];
5567 if (bpf_program__is_function_storage(prog, obj))
5570 pr_debug("prog '%s'('%s'): skipped loading\n",
5571 prog->name, prog->section_name);
5574 prog->log_level |= log_level;
5575 err = bpf_program__load(prog, obj->license, obj->kern_version);
5582 static const struct bpf_sec_def *find_sec_def(const char *sec_name);
5584 static struct bpf_object *
5585 __bpf_object__open(const char *path, const void *obj_buf, size_t obj_buf_sz,
5586 const struct bpf_object_open_opts *opts)
5588 const char *obj_name, *kconfig;
5589 struct bpf_program *prog;
5590 struct bpf_object *obj;
5594 if (elf_version(EV_CURRENT) == EV_NONE) {
5595 pr_warn("failed to init libelf for %s\n",
5596 path ? : "(mem buf)");
5597 return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
5600 if (!OPTS_VALID(opts, bpf_object_open_opts))
5601 return ERR_PTR(-EINVAL);
5603 obj_name = OPTS_GET(opts, object_name, NULL);
5606 snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
5607 (unsigned long)obj_buf,
5608 (unsigned long)obj_buf_sz);
5609 obj_name = tmp_name;
5612 pr_debug("loading object '%s' from buffer\n", obj_name);
5615 obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
5619 kconfig = OPTS_GET(opts, kconfig, NULL);
5621 obj->kconfig = strdup(kconfig);
5623 return ERR_PTR(-ENOMEM);
5626 err = bpf_object__elf_init(obj);
5627 err = err ? : bpf_object__check_endianness(obj);
5628 err = err ? : bpf_object__elf_collect(obj);
5629 err = err ? : bpf_object__collect_externs(obj);
5630 err = err ? : bpf_object__finalize_btf(obj);
5631 err = err ? : bpf_object__init_maps(obj, opts);
5632 err = err ? : bpf_object__init_prog_names(obj);
5633 err = err ? : bpf_object__collect_reloc(obj);
5636 bpf_object__elf_finish(obj);
5638 bpf_object__for_each_program(prog, obj) {
5639 prog->sec_def = find_sec_def(prog->section_name);
5641 /* couldn't guess, but user might manually specify */
5644 bpf_program__set_type(prog, prog->sec_def->prog_type);
5645 bpf_program__set_expected_attach_type(prog,
5646 prog->sec_def->expected_attach_type);
5648 if (prog->sec_def->prog_type == BPF_PROG_TYPE_TRACING ||
5649 prog->sec_def->prog_type == BPF_PROG_TYPE_EXT)
5650 prog->attach_prog_fd = OPTS_GET(opts, attach_prog_fd, 0);
5655 bpf_object__close(obj);
5656 return ERR_PTR(err);
5659 static struct bpf_object *
5660 __bpf_object__open_xattr(struct bpf_object_open_attr *attr, int flags)
5662 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts,
5663 .relaxed_maps = flags & MAPS_RELAX_COMPAT,
5666 /* param validation */
5670 pr_debug("loading %s\n", attr->file);
5671 return __bpf_object__open(attr->file, NULL, 0, &opts);
5674 struct bpf_object *bpf_object__open_xattr(struct bpf_object_open_attr *attr)
5676 return __bpf_object__open_xattr(attr, 0);
5679 struct bpf_object *bpf_object__open(const char *path)
5681 struct bpf_object_open_attr attr = {
5683 .prog_type = BPF_PROG_TYPE_UNSPEC,
5686 return bpf_object__open_xattr(&attr);
5690 bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
5693 return ERR_PTR(-EINVAL);
5695 pr_debug("loading %s\n", path);
5697 return __bpf_object__open(path, NULL, 0, opts);
5701 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
5702 const struct bpf_object_open_opts *opts)
5704 if (!obj_buf || obj_buf_sz == 0)
5705 return ERR_PTR(-EINVAL);
5707 return __bpf_object__open(NULL, obj_buf, obj_buf_sz, opts);
5711 bpf_object__open_buffer(const void *obj_buf, size_t obj_buf_sz,
5714 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts,
5715 .object_name = name,
5716 /* wrong default, but backwards-compatible */
5717 .relaxed_maps = true,
5720 /* returning NULL is wrong, but backwards-compatible */
5721 if (!obj_buf || obj_buf_sz == 0)
5724 return bpf_object__open_mem(obj_buf, obj_buf_sz, &opts);
5727 int bpf_object__unload(struct bpf_object *obj)
5734 for (i = 0; i < obj->nr_maps; i++) {
5735 zclose(obj->maps[i].fd);
5736 if (obj->maps[i].st_ops)
5737 zfree(&obj->maps[i].st_ops->kern_vdata);
5740 for (i = 0; i < obj->nr_programs; i++)
5741 bpf_program__unload(&obj->programs[i]);
5746 static int bpf_object__sanitize_maps(struct bpf_object *obj)
5750 bpf_object__for_each_map(m, obj) {
5751 if (!bpf_map__is_internal(m))
5753 if (!obj->caps.global_data) {
5754 pr_warn("kernel doesn't support global data\n");
5757 if (!obj->caps.array_mmap)
5758 m->def.map_flags ^= BPF_F_MMAPABLE;
5764 static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
5766 char sym_type, sym_name[500];
5767 unsigned long long sym_addr;
5768 struct extern_desc *ext;
5772 f = fopen("/proc/kallsyms", "r");
5775 pr_warn("failed to open /proc/kallsyms: %d\n", err);
5780 ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
5781 &sym_addr, &sym_type, sym_name);
5782 if (ret == EOF && feof(f))
5785 pr_warn("failed to read kallsyms entry: %d\n", ret);
5790 ext = find_extern_by_name(obj, sym_name);
5791 if (!ext || ext->type != EXT_KSYM)
5794 if (ext->is_set && ext->ksym.addr != sym_addr) {
5795 pr_warn("extern (ksym) '%s' resolution is ambiguous: 0x%llx or 0x%llx\n",
5796 sym_name, ext->ksym.addr, sym_addr);
5802 ext->ksym.addr = sym_addr;
5803 pr_debug("extern (ksym) %s=0x%llx\n", sym_name, sym_addr);
5812 static int bpf_object__resolve_externs(struct bpf_object *obj,
5813 const char *extra_kconfig)
5815 bool need_config = false, need_kallsyms = false;
5816 struct extern_desc *ext;
5817 void *kcfg_data = NULL;
5820 if (obj->nr_extern == 0)
5823 if (obj->kconfig_map_idx >= 0)
5824 kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped;
5826 for (i = 0; i < obj->nr_extern; i++) {
5827 ext = &obj->externs[i];
5829 if (ext->type == EXT_KCFG &&
5830 strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
5831 void *ext_val = kcfg_data + ext->kcfg.data_off;
5832 __u32 kver = get_kernel_version();
5835 pr_warn("failed to get kernel version\n");
5838 err = set_kcfg_value_num(ext, ext_val, kver);
5841 pr_debug("extern (kcfg) %s=0x%x\n", ext->name, kver);
5842 } else if (ext->type == EXT_KCFG &&
5843 strncmp(ext->name, "CONFIG_", 7) == 0) {
5845 } else if (ext->type == EXT_KSYM) {
5846 need_kallsyms = true;
5848 pr_warn("unrecognized extern '%s'\n", ext->name);
5852 if (need_config && extra_kconfig) {
5853 err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data);
5856 need_config = false;
5857 for (i = 0; i < obj->nr_extern; i++) {
5858 ext = &obj->externs[i];
5859 if (ext->type == EXT_KCFG && !ext->is_set) {
5866 err = bpf_object__read_kconfig_file(obj, kcfg_data);
5870 if (need_kallsyms) {
5871 err = bpf_object__read_kallsyms_file(obj);
5875 for (i = 0; i < obj->nr_extern; i++) {
5876 ext = &obj->externs[i];
5878 if (!ext->is_set && !ext->is_weak) {
5879 pr_warn("extern %s (strong) not resolved\n", ext->name);
5881 } else if (!ext->is_set) {
5882 pr_debug("extern %s (weak) not resolved, defaulting to zero\n",
5890 int bpf_object__load_xattr(struct bpf_object_load_attr *attr)
5892 struct bpf_object *obj;
5902 pr_warn("object '%s': load can't be attempted twice\n", obj->name);
5906 err = bpf_object__probe_loading(obj);
5907 err = err ? : bpf_object__probe_caps(obj);
5908 err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
5909 err = err ? : bpf_object__sanitize_and_load_btf(obj);
5910 err = err ? : bpf_object__sanitize_maps(obj);
5911 err = err ? : bpf_object__load_vmlinux_btf(obj);
5912 err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
5913 err = err ? : bpf_object__create_maps(obj);
5914 err = err ? : bpf_object__relocate(obj, attr->target_btf_path);
5915 err = err ? : bpf_object__load_progs(obj, attr->log_level);
5917 btf__free(obj->btf_vmlinux);
5918 obj->btf_vmlinux = NULL;
5920 obj->loaded = true; /* doesn't matter if successfully or not */
5927 /* unpin any maps that were auto-pinned during load */
5928 for (i = 0; i < obj->nr_maps; i++)
5929 if (obj->maps[i].pinned && !obj->maps[i].reused)
5930 bpf_map__unpin(&obj->maps[i], NULL);
5932 bpf_object__unload(obj);
5933 pr_warn("failed to load object '%s'\n", obj->path);
5937 int bpf_object__load(struct bpf_object *obj)
5939 struct bpf_object_load_attr attr = {
5943 return bpf_object__load_xattr(&attr);
5946 static int make_parent_dir(const char *path)
5948 char *cp, errmsg[STRERR_BUFSIZE];
5952 dname = strdup(path);
5956 dir = dirname(dname);
5957 if (mkdir(dir, 0700) && errno != EEXIST)
5962 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
5963 pr_warn("failed to mkdir %s: %s\n", path, cp);
5968 static int check_path(const char *path)
5970 char *cp, errmsg[STRERR_BUFSIZE];
5971 struct statfs st_fs;
5978 dname = strdup(path);
5982 dir = dirname(dname);
5983 if (statfs(dir, &st_fs)) {
5984 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
5985 pr_warn("failed to statfs %s: %s\n", dir, cp);
5990 if (!err && st_fs.f_type != BPF_FS_MAGIC) {
5991 pr_warn("specified path %s is not on BPF FS\n", path);
5998 int bpf_program__pin_instance(struct bpf_program *prog, const char *path,
6001 char *cp, errmsg[STRERR_BUFSIZE];
6004 err = make_parent_dir(path);
6008 err = check_path(path);
6013 pr_warn("invalid program pointer\n");
6017 if (instance < 0 || instance >= prog->instances.nr) {
6018 pr_warn("invalid prog instance %d of prog %s (max %d)\n",
6019 instance, prog->section_name, prog->instances.nr);
6023 if (bpf_obj_pin(prog->instances.fds[instance], path)) {
6025 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
6026 pr_warn("failed to pin program: %s\n", cp);
6029 pr_debug("pinned program '%s'\n", path);
6034 int bpf_program__unpin_instance(struct bpf_program *prog, const char *path,
6039 err = check_path(path);
6044 pr_warn("invalid program pointer\n");
6048 if (instance < 0 || instance >= prog->instances.nr) {
6049 pr_warn("invalid prog instance %d of prog %s (max %d)\n",
6050 instance, prog->section_name, prog->instances.nr);
6057 pr_debug("unpinned program '%s'\n", path);
6062 int bpf_program__pin(struct bpf_program *prog, const char *path)
6066 err = make_parent_dir(path);
6070 err = check_path(path);
6075 pr_warn("invalid program pointer\n");
6079 if (prog->instances.nr <= 0) {
6080 pr_warn("no instances of prog %s to pin\n",
6081 prog->section_name);
6085 if (prog->instances.nr == 1) {
6086 /* don't create subdirs when pinning single instance */
6087 return bpf_program__pin_instance(prog, path, 0);
6090 for (i = 0; i < prog->instances.nr; i++) {
6094 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
6098 } else if (len >= PATH_MAX) {
6099 err = -ENAMETOOLONG;
6103 err = bpf_program__pin_instance(prog, buf, i);
6111 for (i = i - 1; i >= 0; i--) {
6115 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
6118 else if (len >= PATH_MAX)
6121 bpf_program__unpin_instance(prog, buf, i);
6129 int bpf_program__unpin(struct bpf_program *prog, const char *path)
6133 err = check_path(path);
6138 pr_warn("invalid program pointer\n");
6142 if (prog->instances.nr <= 0) {
6143 pr_warn("no instances of prog %s to pin\n",
6144 prog->section_name);
6148 if (prog->instances.nr == 1) {
6149 /* don't create subdirs when pinning single instance */
6150 return bpf_program__unpin_instance(prog, path, 0);
6153 for (i = 0; i < prog->instances.nr; i++) {
6157 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
6160 else if (len >= PATH_MAX)
6161 return -ENAMETOOLONG;
6163 err = bpf_program__unpin_instance(prog, buf, i);
6175 int bpf_map__pin(struct bpf_map *map, const char *path)
6177 char *cp, errmsg[STRERR_BUFSIZE];
6181 pr_warn("invalid map pointer\n");
6185 if (map->pin_path) {
6186 if (path && strcmp(path, map->pin_path)) {
6187 pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
6188 bpf_map__name(map), map->pin_path, path);
6190 } else if (map->pinned) {
6191 pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
6192 bpf_map__name(map), map->pin_path);
6197 pr_warn("missing a path to pin map '%s' at\n",
6198 bpf_map__name(map));
6200 } else if (map->pinned) {
6201 pr_warn("map '%s' already pinned\n", bpf_map__name(map));
6205 map->pin_path = strdup(path);
6206 if (!map->pin_path) {
6212 err = make_parent_dir(map->pin_path);
6216 err = check_path(map->pin_path);
6220 if (bpf_obj_pin(map->fd, map->pin_path)) {
6226 pr_debug("pinned map '%s'\n", map->pin_path);
6231 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
6232 pr_warn("failed to pin map: %s\n", cp);
6236 int bpf_map__unpin(struct bpf_map *map, const char *path)
6241 pr_warn("invalid map pointer\n");
6245 if (map->pin_path) {
6246 if (path && strcmp(path, map->pin_path)) {
6247 pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
6248 bpf_map__name(map), map->pin_path, path);
6251 path = map->pin_path;
6253 pr_warn("no path to unpin map '%s' from\n",
6254 bpf_map__name(map));
6258 err = check_path(path);
6266 map->pinned = false;
6267 pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
6272 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
6282 free(map->pin_path);
6283 map->pin_path = new;
6287 const char *bpf_map__get_pin_path(const struct bpf_map *map)
6289 return map->pin_path;
6292 bool bpf_map__is_pinned(const struct bpf_map *map)
6297 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
6299 struct bpf_map *map;
6306 pr_warn("object not yet loaded; load it first\n");
6310 bpf_object__for_each_map(map, obj) {
6311 char *pin_path = NULL;
6317 len = snprintf(buf, PATH_MAX, "%s/%s", path,
6318 bpf_map__name(map));
6321 goto err_unpin_maps;
6322 } else if (len >= PATH_MAX) {
6323 err = -ENAMETOOLONG;
6324 goto err_unpin_maps;
6327 } else if (!map->pin_path) {
6331 err = bpf_map__pin(map, pin_path);
6333 goto err_unpin_maps;
6339 while ((map = bpf_map__prev(map, obj))) {
6343 bpf_map__unpin(map, NULL);
6349 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
6351 struct bpf_map *map;
6357 bpf_object__for_each_map(map, obj) {
6358 char *pin_path = NULL;
6364 len = snprintf(buf, PATH_MAX, "%s/%s", path,
6365 bpf_map__name(map));
6368 else if (len >= PATH_MAX)
6369 return -ENAMETOOLONG;
6371 } else if (!map->pin_path) {
6375 err = bpf_map__unpin(map, pin_path);
6383 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
6385 struct bpf_program *prog;
6392 pr_warn("object not yet loaded; load it first\n");
6396 bpf_object__for_each_program(prog, obj) {
6400 len = snprintf(buf, PATH_MAX, "%s/%s", path,
6404 goto err_unpin_programs;
6405 } else if (len >= PATH_MAX) {
6406 err = -ENAMETOOLONG;
6407 goto err_unpin_programs;
6410 err = bpf_program__pin(prog, buf);
6412 goto err_unpin_programs;
6418 while ((prog = bpf_program__prev(prog, obj))) {
6422 len = snprintf(buf, PATH_MAX, "%s/%s", path,
6426 else if (len >= PATH_MAX)
6429 bpf_program__unpin(prog, buf);
6435 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
6437 struct bpf_program *prog;
6443 bpf_object__for_each_program(prog, obj) {
6447 len = snprintf(buf, PATH_MAX, "%s/%s", path,
6451 else if (len >= PATH_MAX)
6452 return -ENAMETOOLONG;
6454 err = bpf_program__unpin(prog, buf);
6462 int bpf_object__pin(struct bpf_object *obj, const char *path)
6466 err = bpf_object__pin_maps(obj, path);
6470 err = bpf_object__pin_programs(obj, path);
6472 bpf_object__unpin_maps(obj, path);
6479 static void bpf_map__destroy(struct bpf_map *map)
6481 if (map->clear_priv)
6482 map->clear_priv(map, map->priv);
6484 map->clear_priv = NULL;
6486 if (map->inner_map) {
6487 bpf_map__destroy(map->inner_map);
6488 zfree(&map->inner_map);
6491 zfree(&map->init_slots);
6492 map->init_slots_sz = 0;
6495 munmap(map->mmaped, bpf_map_mmap_sz(map));
6500 zfree(&map->st_ops->data);
6501 zfree(&map->st_ops->progs);
6502 zfree(&map->st_ops->kern_func_off);
6503 zfree(&map->st_ops);
6507 zfree(&map->pin_path);
6513 void bpf_object__close(struct bpf_object *obj)
6517 if (IS_ERR_OR_NULL(obj))
6520 if (obj->clear_priv)
6521 obj->clear_priv(obj, obj->priv);
6523 bpf_object__elf_finish(obj);
6524 bpf_object__unload(obj);
6525 btf__free(obj->btf);
6526 btf_ext__free(obj->btf_ext);
6528 for (i = 0; i < obj->nr_maps; i++)
6529 bpf_map__destroy(&obj->maps[i]);
6531 zfree(&obj->kconfig);
6532 zfree(&obj->externs);
6538 if (obj->programs && obj->nr_programs) {
6539 for (i = 0; i < obj->nr_programs; i++)
6540 bpf_program__exit(&obj->programs[i]);
6542 zfree(&obj->programs);
6544 list_del(&obj->list);
6549 bpf_object__next(struct bpf_object *prev)
6551 struct bpf_object *next;
6554 next = list_first_entry(&bpf_objects_list,
6558 next = list_next_entry(prev, list);
6560 /* Empty list is noticed here so don't need checking on entry. */
6561 if (&next->list == &bpf_objects_list)
6567 const char *bpf_object__name(const struct bpf_object *obj)
6569 return obj ? obj->name : ERR_PTR(-EINVAL);
6572 unsigned int bpf_object__kversion(const struct bpf_object *obj)
6574 return obj ? obj->kern_version : 0;
6577 struct btf *bpf_object__btf(const struct bpf_object *obj)
6579 return obj ? obj->btf : NULL;
6582 int bpf_object__btf_fd(const struct bpf_object *obj)
6584 return obj->btf ? btf__fd(obj->btf) : -1;
6587 int bpf_object__set_priv(struct bpf_object *obj, void *priv,
6588 bpf_object_clear_priv_t clear_priv)
6590 if (obj->priv && obj->clear_priv)
6591 obj->clear_priv(obj, obj->priv);
6594 obj->clear_priv = clear_priv;
6598 void *bpf_object__priv(const struct bpf_object *obj)
6600 return obj ? obj->priv : ERR_PTR(-EINVAL);
6603 static struct bpf_program *
6604 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
6607 size_t nr_programs = obj->nr_programs;
6614 /* Iter from the beginning */
6615 return forward ? &obj->programs[0] :
6616 &obj->programs[nr_programs - 1];
6618 if (p->obj != obj) {
6619 pr_warn("error: program handler doesn't match object\n");
6623 idx = (p - obj->programs) + (forward ? 1 : -1);
6624 if (idx >= obj->nr_programs || idx < 0)
6626 return &obj->programs[idx];
6629 struct bpf_program *
6630 bpf_program__next(struct bpf_program *prev, const struct bpf_object *obj)
6632 struct bpf_program *prog = prev;
6635 prog = __bpf_program__iter(prog, obj, true);
6636 } while (prog && bpf_program__is_function_storage(prog, obj));
6641 struct bpf_program *
6642 bpf_program__prev(struct bpf_program *next, const struct bpf_object *obj)
6644 struct bpf_program *prog = next;
6647 prog = __bpf_program__iter(prog, obj, false);
6648 } while (prog && bpf_program__is_function_storage(prog, obj));
6653 int bpf_program__set_priv(struct bpf_program *prog, void *priv,
6654 bpf_program_clear_priv_t clear_priv)
6656 if (prog->priv && prog->clear_priv)
6657 prog->clear_priv(prog, prog->priv);
6660 prog->clear_priv = clear_priv;
6664 void *bpf_program__priv(const struct bpf_program *prog)
6666 return prog ? prog->priv : ERR_PTR(-EINVAL);
6669 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
6671 prog->prog_ifindex = ifindex;
6674 const char *bpf_program__name(const struct bpf_program *prog)
6679 const char *bpf_program__title(const struct bpf_program *prog, bool needs_copy)
6683 title = prog->section_name;
6685 title = strdup(title);
6687 pr_warn("failed to strdup program title\n");
6688 return ERR_PTR(-ENOMEM);
6695 bool bpf_program__autoload(const struct bpf_program *prog)
6700 int bpf_program__set_autoload(struct bpf_program *prog, bool autoload)
6702 if (prog->obj->loaded)
6705 prog->load = autoload;
6709 int bpf_program__fd(const struct bpf_program *prog)
6711 return bpf_program__nth_fd(prog, 0);
6714 size_t bpf_program__size(const struct bpf_program *prog)
6716 return prog->insns_cnt * sizeof(struct bpf_insn);
6719 int bpf_program__set_prep(struct bpf_program *prog, int nr_instances,
6720 bpf_program_prep_t prep)
6724 if (nr_instances <= 0 || !prep)
6727 if (prog->instances.nr > 0 || prog->instances.fds) {
6728 pr_warn("Can't set pre-processor after loading\n");
6732 instances_fds = malloc(sizeof(int) * nr_instances);
6733 if (!instances_fds) {
6734 pr_warn("alloc memory failed for fds\n");
6738 /* fill all fd with -1 */
6739 memset(instances_fds, -1, sizeof(int) * nr_instances);
6741 prog->instances.nr = nr_instances;
6742 prog->instances.fds = instances_fds;
6743 prog->preprocessor = prep;
6747 int bpf_program__nth_fd(const struct bpf_program *prog, int n)
6754 if (n >= prog->instances.nr || n < 0) {
6755 pr_warn("Can't get the %dth fd from program %s: only %d instances\n",
6756 n, prog->section_name, prog->instances.nr);
6760 fd = prog->instances.fds[n];
6762 pr_warn("%dth instance of program '%s' is invalid\n",
6763 n, prog->section_name);
6770 enum bpf_prog_type bpf_program__get_type(struct bpf_program *prog)
6775 void bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
6780 static bool bpf_program__is_type(const struct bpf_program *prog,
6781 enum bpf_prog_type type)
6783 return prog ? (prog->type == type) : false;
6786 #define BPF_PROG_TYPE_FNS(NAME, TYPE) \
6787 int bpf_program__set_##NAME(struct bpf_program *prog) \
6791 bpf_program__set_type(prog, TYPE); \
6795 bool bpf_program__is_##NAME(const struct bpf_program *prog) \
6797 return bpf_program__is_type(prog, TYPE); \
6800 BPF_PROG_TYPE_FNS(socket_filter, BPF_PROG_TYPE_SOCKET_FILTER);
6801 BPF_PROG_TYPE_FNS(lsm, BPF_PROG_TYPE_LSM);
6802 BPF_PROG_TYPE_FNS(kprobe, BPF_PROG_TYPE_KPROBE);
6803 BPF_PROG_TYPE_FNS(sched_cls, BPF_PROG_TYPE_SCHED_CLS);
6804 BPF_PROG_TYPE_FNS(sched_act, BPF_PROG_TYPE_SCHED_ACT);
6805 BPF_PROG_TYPE_FNS(tracepoint, BPF_PROG_TYPE_TRACEPOINT);
6806 BPF_PROG_TYPE_FNS(raw_tracepoint, BPF_PROG_TYPE_RAW_TRACEPOINT);
6807 BPF_PROG_TYPE_FNS(xdp, BPF_PROG_TYPE_XDP);
6808 BPF_PROG_TYPE_FNS(perf_event, BPF_PROG_TYPE_PERF_EVENT);
6809 BPF_PROG_TYPE_FNS(tracing, BPF_PROG_TYPE_TRACING);
6810 BPF_PROG_TYPE_FNS(struct_ops, BPF_PROG_TYPE_STRUCT_OPS);
6811 BPF_PROG_TYPE_FNS(extension, BPF_PROG_TYPE_EXT);
6812 BPF_PROG_TYPE_FNS(sk_lookup, BPF_PROG_TYPE_SK_LOOKUP);
6814 enum bpf_attach_type
6815 bpf_program__get_expected_attach_type(struct bpf_program *prog)
6817 return prog->expected_attach_type;
6820 void bpf_program__set_expected_attach_type(struct bpf_program *prog,
6821 enum bpf_attach_type type)
6823 prog->expected_attach_type = type;
6826 #define BPF_PROG_SEC_IMPL(string, ptype, eatype, eatype_optional, \
6827 attachable, attach_btf) \
6830 .len = sizeof(string) - 1, \
6831 .prog_type = ptype, \
6832 .expected_attach_type = eatype, \
6833 .is_exp_attach_type_optional = eatype_optional, \
6834 .is_attachable = attachable, \
6835 .is_attach_btf = attach_btf, \
6838 /* Programs that can NOT be attached. */
6839 #define BPF_PROG_SEC(string, ptype) BPF_PROG_SEC_IMPL(string, ptype, 0, 0, 0, 0)
6841 /* Programs that can be attached. */
6842 #define BPF_APROG_SEC(string, ptype, atype) \
6843 BPF_PROG_SEC_IMPL(string, ptype, atype, true, 1, 0)
6845 /* Programs that must specify expected attach type at load time. */
6846 #define BPF_EAPROG_SEC(string, ptype, eatype) \
6847 BPF_PROG_SEC_IMPL(string, ptype, eatype, false, 1, 0)
6849 /* Programs that use BTF to identify attach point */
6850 #define BPF_PROG_BTF(string, ptype, eatype) \
6851 BPF_PROG_SEC_IMPL(string, ptype, eatype, false, 0, 1)
6853 /* Programs that can be attached but attach type can't be identified by section
6854 * name. Kept for backward compatibility.
6856 #define BPF_APROG_COMPAT(string, ptype) BPF_PROG_SEC(string, ptype)
6858 #define SEC_DEF(sec_pfx, ptype, ...) { \
6860 .len = sizeof(sec_pfx) - 1, \
6861 .prog_type = BPF_PROG_TYPE_##ptype, \
6865 static struct bpf_link *attach_kprobe(const struct bpf_sec_def *sec,
6866 struct bpf_program *prog);
6867 static struct bpf_link *attach_tp(const struct bpf_sec_def *sec,
6868 struct bpf_program *prog);
6869 static struct bpf_link *attach_raw_tp(const struct bpf_sec_def *sec,
6870 struct bpf_program *prog);
6871 static struct bpf_link *attach_trace(const struct bpf_sec_def *sec,
6872 struct bpf_program *prog);
6873 static struct bpf_link *attach_lsm(const struct bpf_sec_def *sec,
6874 struct bpf_program *prog);
6875 static struct bpf_link *attach_iter(const struct bpf_sec_def *sec,
6876 struct bpf_program *prog);
6878 static const struct bpf_sec_def section_defs[] = {
6879 BPF_PROG_SEC("socket", BPF_PROG_TYPE_SOCKET_FILTER),
6880 BPF_PROG_SEC("sk_reuseport", BPF_PROG_TYPE_SK_REUSEPORT),
6881 SEC_DEF("kprobe/", KPROBE,
6882 .attach_fn = attach_kprobe),
6883 BPF_PROG_SEC("uprobe/", BPF_PROG_TYPE_KPROBE),
6884 SEC_DEF("kretprobe/", KPROBE,
6885 .attach_fn = attach_kprobe),
6886 BPF_PROG_SEC("uretprobe/", BPF_PROG_TYPE_KPROBE),
6887 BPF_PROG_SEC("classifier", BPF_PROG_TYPE_SCHED_CLS),
6888 BPF_PROG_SEC("action", BPF_PROG_TYPE_SCHED_ACT),
6889 SEC_DEF("tracepoint/", TRACEPOINT,
6890 .attach_fn = attach_tp),
6891 SEC_DEF("tp/", TRACEPOINT,
6892 .attach_fn = attach_tp),
6893 SEC_DEF("raw_tracepoint/", RAW_TRACEPOINT,
6894 .attach_fn = attach_raw_tp),
6895 SEC_DEF("raw_tp/", RAW_TRACEPOINT,
6896 .attach_fn = attach_raw_tp),
6897 SEC_DEF("tp_btf/", TRACING,
6898 .expected_attach_type = BPF_TRACE_RAW_TP,
6899 .is_attach_btf = true,
6900 .attach_fn = attach_trace),
6901 SEC_DEF("fentry/", TRACING,
6902 .expected_attach_type = BPF_TRACE_FENTRY,
6903 .is_attach_btf = true,
6904 .attach_fn = attach_trace),
6905 SEC_DEF("fmod_ret/", TRACING,
6906 .expected_attach_type = BPF_MODIFY_RETURN,
6907 .is_attach_btf = true,
6908 .attach_fn = attach_trace),
6909 SEC_DEF("fexit/", TRACING,
6910 .expected_attach_type = BPF_TRACE_FEXIT,
6911 .is_attach_btf = true,
6912 .attach_fn = attach_trace),
6913 SEC_DEF("freplace/", EXT,
6914 .is_attach_btf = true,
6915 .attach_fn = attach_trace),
6916 SEC_DEF("lsm/", LSM,
6917 .is_attach_btf = true,
6918 .expected_attach_type = BPF_LSM_MAC,
6919 .attach_fn = attach_lsm),
6920 SEC_DEF("iter/", TRACING,
6921 .expected_attach_type = BPF_TRACE_ITER,
6922 .is_attach_btf = true,
6923 .attach_fn = attach_iter),
6924 BPF_EAPROG_SEC("xdp_devmap/", BPF_PROG_TYPE_XDP,
6926 BPF_EAPROG_SEC("xdp_cpumap/", BPF_PROG_TYPE_XDP,
6928 BPF_EAPROG_SEC("xdp", BPF_PROG_TYPE_XDP,
6930 BPF_PROG_SEC("perf_event", BPF_PROG_TYPE_PERF_EVENT),
6931 BPF_PROG_SEC("lwt_in", BPF_PROG_TYPE_LWT_IN),
6932 BPF_PROG_SEC("lwt_out", BPF_PROG_TYPE_LWT_OUT),
6933 BPF_PROG_SEC("lwt_xmit", BPF_PROG_TYPE_LWT_XMIT),
6934 BPF_PROG_SEC("lwt_seg6local", BPF_PROG_TYPE_LWT_SEG6LOCAL),
6935 BPF_APROG_SEC("cgroup_skb/ingress", BPF_PROG_TYPE_CGROUP_SKB,
6936 BPF_CGROUP_INET_INGRESS),
6937 BPF_APROG_SEC("cgroup_skb/egress", BPF_PROG_TYPE_CGROUP_SKB,
6938 BPF_CGROUP_INET_EGRESS),
6939 BPF_APROG_COMPAT("cgroup/skb", BPF_PROG_TYPE_CGROUP_SKB),
6940 BPF_EAPROG_SEC("cgroup/sock_create", BPF_PROG_TYPE_CGROUP_SOCK,
6941 BPF_CGROUP_INET_SOCK_CREATE),
6942 BPF_EAPROG_SEC("cgroup/sock_release", BPF_PROG_TYPE_CGROUP_SOCK,
6943 BPF_CGROUP_INET_SOCK_RELEASE),
6944 BPF_APROG_SEC("cgroup/sock", BPF_PROG_TYPE_CGROUP_SOCK,
6945 BPF_CGROUP_INET_SOCK_CREATE),
6946 BPF_EAPROG_SEC("cgroup/post_bind4", BPF_PROG_TYPE_CGROUP_SOCK,
6947 BPF_CGROUP_INET4_POST_BIND),
6948 BPF_EAPROG_SEC("cgroup/post_bind6", BPF_PROG_TYPE_CGROUP_SOCK,
6949 BPF_CGROUP_INET6_POST_BIND),
6950 BPF_APROG_SEC("cgroup/dev", BPF_PROG_TYPE_CGROUP_DEVICE,
6952 BPF_APROG_SEC("sockops", BPF_PROG_TYPE_SOCK_OPS,
6953 BPF_CGROUP_SOCK_OPS),
6954 BPF_APROG_SEC("sk_skb/stream_parser", BPF_PROG_TYPE_SK_SKB,
6955 BPF_SK_SKB_STREAM_PARSER),
6956 BPF_APROG_SEC("sk_skb/stream_verdict", BPF_PROG_TYPE_SK_SKB,
6957 BPF_SK_SKB_STREAM_VERDICT),
6958 BPF_APROG_COMPAT("sk_skb", BPF_PROG_TYPE_SK_SKB),
6959 BPF_APROG_SEC("sk_msg", BPF_PROG_TYPE_SK_MSG,
6960 BPF_SK_MSG_VERDICT),
6961 BPF_APROG_SEC("lirc_mode2", BPF_PROG_TYPE_LIRC_MODE2,
6963 BPF_APROG_SEC("flow_dissector", BPF_PROG_TYPE_FLOW_DISSECTOR,
6964 BPF_FLOW_DISSECTOR),
6965 BPF_EAPROG_SEC("cgroup/bind4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
6966 BPF_CGROUP_INET4_BIND),
6967 BPF_EAPROG_SEC("cgroup/bind6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
6968 BPF_CGROUP_INET6_BIND),
6969 BPF_EAPROG_SEC("cgroup/connect4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
6970 BPF_CGROUP_INET4_CONNECT),
6971 BPF_EAPROG_SEC("cgroup/connect6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
6972 BPF_CGROUP_INET6_CONNECT),
6973 BPF_EAPROG_SEC("cgroup/sendmsg4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
6974 BPF_CGROUP_UDP4_SENDMSG),
6975 BPF_EAPROG_SEC("cgroup/sendmsg6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
6976 BPF_CGROUP_UDP6_SENDMSG),
6977 BPF_EAPROG_SEC("cgroup/recvmsg4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
6978 BPF_CGROUP_UDP4_RECVMSG),
6979 BPF_EAPROG_SEC("cgroup/recvmsg6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
6980 BPF_CGROUP_UDP6_RECVMSG),
6981 BPF_EAPROG_SEC("cgroup/getpeername4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
6982 BPF_CGROUP_INET4_GETPEERNAME),
6983 BPF_EAPROG_SEC("cgroup/getpeername6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
6984 BPF_CGROUP_INET6_GETPEERNAME),
6985 BPF_EAPROG_SEC("cgroup/getsockname4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
6986 BPF_CGROUP_INET4_GETSOCKNAME),
6987 BPF_EAPROG_SEC("cgroup/getsockname6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
6988 BPF_CGROUP_INET6_GETSOCKNAME),
6989 BPF_EAPROG_SEC("cgroup/sysctl", BPF_PROG_TYPE_CGROUP_SYSCTL,
6991 BPF_EAPROG_SEC("cgroup/getsockopt", BPF_PROG_TYPE_CGROUP_SOCKOPT,
6992 BPF_CGROUP_GETSOCKOPT),
6993 BPF_EAPROG_SEC("cgroup/setsockopt", BPF_PROG_TYPE_CGROUP_SOCKOPT,
6994 BPF_CGROUP_SETSOCKOPT),
6995 BPF_PROG_SEC("struct_ops", BPF_PROG_TYPE_STRUCT_OPS),
6996 BPF_EAPROG_SEC("sk_lookup/", BPF_PROG_TYPE_SK_LOOKUP,
7000 #undef BPF_PROG_SEC_IMPL
7002 #undef BPF_APROG_SEC
7003 #undef BPF_EAPROG_SEC
7004 #undef BPF_APROG_COMPAT
7007 #define MAX_TYPE_NAME_SIZE 32
7009 static const struct bpf_sec_def *find_sec_def(const char *sec_name)
7011 int i, n = ARRAY_SIZE(section_defs);
7013 for (i = 0; i < n; i++) {
7014 if (strncmp(sec_name,
7015 section_defs[i].sec, section_defs[i].len))
7017 return §ion_defs[i];
7022 static char *libbpf_get_type_names(bool attach_type)
7024 int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
7032 /* Forge string buf with all available names */
7033 for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
7034 if (attach_type && !section_defs[i].is_attachable)
7037 if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
7042 strcat(buf, section_defs[i].sec);
7048 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
7049 enum bpf_attach_type *expected_attach_type)
7051 const struct bpf_sec_def *sec_def;
7057 sec_def = find_sec_def(name);
7059 *prog_type = sec_def->prog_type;
7060 *expected_attach_type = sec_def->expected_attach_type;
7064 pr_debug("failed to guess program type from ELF section '%s'\n", name);
7065 type_names = libbpf_get_type_names(false);
7066 if (type_names != NULL) {
7067 pr_debug("supported section(type) names are:%s\n", type_names);
7074 static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
7077 struct bpf_map *map;
7080 for (i = 0; i < obj->nr_maps; i++) {
7081 map = &obj->maps[i];
7082 if (!bpf_map__is_struct_ops(map))
7084 if (map->sec_offset <= offset &&
7085 offset - map->sec_offset < map->def.value_size)
7092 /* Collect the reloc from ELF and populate the st_ops->progs[] */
7093 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
7094 GElf_Shdr *shdr, Elf_Data *data)
7096 const struct btf_member *member;
7097 struct bpf_struct_ops *st_ops;
7098 struct bpf_program *prog;
7099 unsigned int shdr_idx;
7100 const struct btf *btf;
7101 struct bpf_map *map;
7110 symbols = obj->efile.symbols;
7112 nrels = shdr->sh_size / shdr->sh_entsize;
7113 for (i = 0; i < nrels; i++) {
7114 if (!gelf_getrel(data, i, &rel)) {
7115 pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
7116 return -LIBBPF_ERRNO__FORMAT;
7119 if (!gelf_getsym(symbols, GELF_R_SYM(rel.r_info), &sym)) {
7120 pr_warn("struct_ops reloc: symbol %zx not found\n",
7121 (size_t)GELF_R_SYM(rel.r_info));
7122 return -LIBBPF_ERRNO__FORMAT;
7125 name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
7126 sym.st_name) ? : "<?>";
7127 map = find_struct_ops_map_by_offset(obj, rel.r_offset);
7129 pr_warn("struct_ops reloc: cannot find map at rel.r_offset %zu\n",
7130 (size_t)rel.r_offset);
7134 moff = rel.r_offset - map->sec_offset;
7135 shdr_idx = sym.st_shndx;
7136 st_ops = map->st_ops;
7137 pr_debug("struct_ops reloc %s: for %lld value %lld shdr_idx %u rel.r_offset %zu map->sec_offset %zu name %d (\'%s\')\n",
7139 (long long)(rel.r_info >> 32),
7140 (long long)sym.st_value,
7141 shdr_idx, (size_t)rel.r_offset,
7142 map->sec_offset, sym.st_name, name);
7144 if (shdr_idx >= SHN_LORESERVE) {
7145 pr_warn("struct_ops reloc %s: rel.r_offset %zu shdr_idx %u unsupported non-static function\n",
7146 map->name, (size_t)rel.r_offset, shdr_idx);
7147 return -LIBBPF_ERRNO__RELOC;
7150 member = find_member_by_offset(st_ops->type, moff * 8);
7152 pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
7156 member_idx = member - btf_members(st_ops->type);
7157 name = btf__name_by_offset(btf, member->name_off);
7159 if (!resolve_func_ptr(btf, member->type, NULL)) {
7160 pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
7165 prog = bpf_object__find_prog_by_idx(obj, shdr_idx);
7167 pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
7168 map->name, shdr_idx, name);
7172 if (prog->type == BPF_PROG_TYPE_UNSPEC) {
7173 const struct bpf_sec_def *sec_def;
7175 sec_def = find_sec_def(prog->section_name);
7177 sec_def->prog_type != BPF_PROG_TYPE_STRUCT_OPS) {
7179 prog->type = sec_def->prog_type;
7183 prog->type = BPF_PROG_TYPE_STRUCT_OPS;
7184 prog->attach_btf_id = st_ops->type_id;
7185 prog->expected_attach_type = member_idx;
7186 } else if (prog->type != BPF_PROG_TYPE_STRUCT_OPS ||
7187 prog->attach_btf_id != st_ops->type_id ||
7188 prog->expected_attach_type != member_idx) {
7191 st_ops->progs[member_idx] = prog;
7197 pr_warn("struct_ops reloc %s: cannot use prog %s in sec %s with type %u attach_btf_id %u expected_attach_type %u for func ptr %s\n",
7198 map->name, prog->name, prog->section_name, prog->type,
7199 prog->attach_btf_id, prog->expected_attach_type, name);
7203 #define BTF_TRACE_PREFIX "btf_trace_"
7204 #define BTF_LSM_PREFIX "bpf_lsm_"
7205 #define BTF_ITER_PREFIX "bpf_iter_"
7206 #define BTF_MAX_NAME_SIZE 128
7208 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
7209 const char *name, __u32 kind)
7211 char btf_type_name[BTF_MAX_NAME_SIZE];
7214 ret = snprintf(btf_type_name, sizeof(btf_type_name),
7215 "%s%s", prefix, name);
7216 /* snprintf returns the number of characters written excluding the
7217 * the terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
7218 * indicates truncation.
7220 if (ret < 0 || ret >= sizeof(btf_type_name))
7221 return -ENAMETOOLONG;
7222 return btf__find_by_name_kind(btf, btf_type_name, kind);
7225 static inline int __find_vmlinux_btf_id(struct btf *btf, const char *name,
7226 enum bpf_attach_type attach_type)
7230 if (attach_type == BPF_TRACE_RAW_TP)
7231 err = find_btf_by_prefix_kind(btf, BTF_TRACE_PREFIX, name,
7233 else if (attach_type == BPF_LSM_MAC)
7234 err = find_btf_by_prefix_kind(btf, BTF_LSM_PREFIX, name,
7236 else if (attach_type == BPF_TRACE_ITER)
7237 err = find_btf_by_prefix_kind(btf, BTF_ITER_PREFIX, name,
7240 err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
7243 pr_warn("%s is not found in vmlinux BTF\n", name);
7248 int libbpf_find_vmlinux_btf_id(const char *name,
7249 enum bpf_attach_type attach_type)
7254 btf = libbpf_find_kernel_btf();
7256 pr_warn("vmlinux BTF is not found\n");
7260 err = __find_vmlinux_btf_id(btf, name, attach_type);
7265 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd)
7267 struct bpf_prog_info_linear *info_linear;
7268 struct bpf_prog_info *info;
7269 struct btf *btf = NULL;
7272 info_linear = bpf_program__get_prog_info_linear(attach_prog_fd, 0);
7273 if (IS_ERR_OR_NULL(info_linear)) {
7274 pr_warn("failed get_prog_info_linear for FD %d\n",
7278 info = &info_linear->info;
7279 if (!info->btf_id) {
7280 pr_warn("The target program doesn't have BTF\n");
7283 if (btf__get_from_id(info->btf_id, &btf)) {
7284 pr_warn("Failed to get BTF of the program\n");
7287 err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
7290 pr_warn("%s is not found in prog's BTF\n", name);
7298 static int libbpf_find_attach_btf_id(struct bpf_program *prog)
7300 enum bpf_attach_type attach_type = prog->expected_attach_type;
7301 __u32 attach_prog_fd = prog->attach_prog_fd;
7302 const char *name = prog->section_name;
7308 for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
7309 if (!section_defs[i].is_attach_btf)
7311 if (strncmp(name, section_defs[i].sec, section_defs[i].len))
7314 err = libbpf_find_prog_btf_id(name + section_defs[i].len,
7317 err = __find_vmlinux_btf_id(prog->obj->btf_vmlinux,
7318 name + section_defs[i].len,
7322 pr_warn("failed to identify btf_id based on ELF section name '%s'\n", name);
7326 int libbpf_attach_type_by_name(const char *name,
7327 enum bpf_attach_type *attach_type)
7335 for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
7336 if (strncmp(name, section_defs[i].sec, section_defs[i].len))
7338 if (!section_defs[i].is_attachable)
7340 *attach_type = section_defs[i].expected_attach_type;
7343 pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
7344 type_names = libbpf_get_type_names(true);
7345 if (type_names != NULL) {
7346 pr_debug("attachable section(type) names are:%s\n", type_names);
7353 int bpf_map__fd(const struct bpf_map *map)
7355 return map ? map->fd : -EINVAL;
7358 const struct bpf_map_def *bpf_map__def(const struct bpf_map *map)
7360 return map ? &map->def : ERR_PTR(-EINVAL);
7363 const char *bpf_map__name(const struct bpf_map *map)
7365 return map ? map->name : NULL;
7368 enum bpf_map_type bpf_map__type(const struct bpf_map *map)
7370 return map->def.type;
7373 int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type)
7377 map->def.type = type;
7381 __u32 bpf_map__map_flags(const struct bpf_map *map)
7383 return map->def.map_flags;
7386 int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags)
7390 map->def.map_flags = flags;
7394 __u32 bpf_map__numa_node(const struct bpf_map *map)
7396 return map->numa_node;
7399 int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node)
7403 map->numa_node = numa_node;
7407 __u32 bpf_map__key_size(const struct bpf_map *map)
7409 return map->def.key_size;
7412 int bpf_map__set_key_size(struct bpf_map *map, __u32 size)
7416 map->def.key_size = size;
7420 __u32 bpf_map__value_size(const struct bpf_map *map)
7422 return map->def.value_size;
7425 int bpf_map__set_value_size(struct bpf_map *map, __u32 size)
7429 map->def.value_size = size;
7433 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
7435 return map ? map->btf_key_type_id : 0;
7438 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
7440 return map ? map->btf_value_type_id : 0;
7443 int bpf_map__set_priv(struct bpf_map *map, void *priv,
7444 bpf_map_clear_priv_t clear_priv)
7450 if (map->clear_priv)
7451 map->clear_priv(map, map->priv);
7455 map->clear_priv = clear_priv;
7459 void *bpf_map__priv(const struct bpf_map *map)
7461 return map ? map->priv : ERR_PTR(-EINVAL);
7464 int bpf_map__set_initial_value(struct bpf_map *map,
7465 const void *data, size_t size)
7467 if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG ||
7468 size != map->def.value_size || map->fd >= 0)
7471 memcpy(map->mmaped, data, size);
7475 bool bpf_map__is_offload_neutral(const struct bpf_map *map)
7477 return map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY;
7480 bool bpf_map__is_internal(const struct bpf_map *map)
7482 return map->libbpf_type != LIBBPF_MAP_UNSPEC;
7485 __u32 bpf_map__ifindex(const struct bpf_map *map)
7487 return map->map_ifindex;
7490 int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
7494 map->map_ifindex = ifindex;
7498 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
7500 if (!bpf_map_type__is_map_in_map(map->def.type)) {
7501 pr_warn("error: unsupported map type\n");
7504 if (map->inner_map_fd != -1) {
7505 pr_warn("error: inner_map_fd already specified\n");
7508 map->inner_map_fd = fd;
7512 static struct bpf_map *
7513 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
7516 struct bpf_map *s, *e;
7518 if (!obj || !obj->maps)
7522 e = obj->maps + obj->nr_maps;
7524 if ((m < s) || (m >= e)) {
7525 pr_warn("error in %s: map handler doesn't belong to object\n",
7530 idx = (m - obj->maps) + i;
7531 if (idx >= obj->nr_maps || idx < 0)
7533 return &obj->maps[idx];
7537 bpf_map__next(const struct bpf_map *prev, const struct bpf_object *obj)
7542 return __bpf_map__iter(prev, obj, 1);
7546 bpf_map__prev(const struct bpf_map *next, const struct bpf_object *obj)
7551 return obj->maps + obj->nr_maps - 1;
7554 return __bpf_map__iter(next, obj, -1);
7558 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
7560 struct bpf_map *pos;
7562 bpf_object__for_each_map(pos, obj) {
7563 if (pos->name && !strcmp(pos->name, name))
7570 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
7572 return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
7576 bpf_object__find_map_by_offset(struct bpf_object *obj, size_t offset)
7578 return ERR_PTR(-ENOTSUP);
7581 long libbpf_get_error(const void *ptr)
7583 return PTR_ERR_OR_ZERO(ptr);
7586 int bpf_prog_load(const char *file, enum bpf_prog_type type,
7587 struct bpf_object **pobj, int *prog_fd)
7589 struct bpf_prog_load_attr attr;
7591 memset(&attr, 0, sizeof(struct bpf_prog_load_attr));
7593 attr.prog_type = type;
7594 attr.expected_attach_type = 0;
7596 return bpf_prog_load_xattr(&attr, pobj, prog_fd);
7599 int bpf_prog_load_xattr(const struct bpf_prog_load_attr *attr,
7600 struct bpf_object **pobj, int *prog_fd)
7602 struct bpf_object_open_attr open_attr = {};
7603 struct bpf_program *prog, *first_prog = NULL;
7604 struct bpf_object *obj;
7605 struct bpf_map *map;
7613 open_attr.file = attr->file;
7614 open_attr.prog_type = attr->prog_type;
7616 obj = bpf_object__open_xattr(&open_attr);
7617 if (IS_ERR_OR_NULL(obj))
7620 bpf_object__for_each_program(prog, obj) {
7621 enum bpf_attach_type attach_type = attr->expected_attach_type;
7623 * to preserve backwards compatibility, bpf_prog_load treats
7624 * attr->prog_type, if specified, as an override to whatever
7625 * bpf_object__open guessed
7627 if (attr->prog_type != BPF_PROG_TYPE_UNSPEC) {
7628 bpf_program__set_type(prog, attr->prog_type);
7629 bpf_program__set_expected_attach_type(prog,
7632 if (bpf_program__get_type(prog) == BPF_PROG_TYPE_UNSPEC) {
7634 * we haven't guessed from section name and user
7635 * didn't provide a fallback type, too bad...
7637 bpf_object__close(obj);
7641 prog->prog_ifindex = attr->ifindex;
7642 prog->log_level = attr->log_level;
7643 prog->prog_flags = attr->prog_flags;
7648 bpf_object__for_each_map(map, obj) {
7649 if (!bpf_map__is_offload_neutral(map))
7650 map->map_ifindex = attr->ifindex;
7654 pr_warn("object file doesn't contain bpf program\n");
7655 bpf_object__close(obj);
7659 err = bpf_object__load(obj);
7661 bpf_object__close(obj);
7666 *prog_fd = bpf_program__fd(first_prog);
7671 int (*detach)(struct bpf_link *link);
7672 int (*destroy)(struct bpf_link *link);
7673 char *pin_path; /* NULL, if not pinned */
7674 int fd; /* hook FD, -1 if not applicable */
7678 /* Replace link's underlying BPF program with the new one */
7679 int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
7681 return bpf_link_update(bpf_link__fd(link), bpf_program__fd(prog), NULL);
7684 /* Release "ownership" of underlying BPF resource (typically, BPF program
7685 * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
7686 * link, when destructed through bpf_link__destroy() call won't attempt to
7687 * detach/unregisted that BPF resource. This is useful in situations where,
7688 * say, attached BPF program has to outlive userspace program that attached it
7689 * in the system. Depending on type of BPF program, though, there might be
7690 * additional steps (like pinning BPF program in BPF FS) necessary to ensure
7691 * exit of userspace program doesn't trigger automatic detachment and clean up
7692 * inside the kernel.
7694 void bpf_link__disconnect(struct bpf_link *link)
7696 link->disconnected = true;
7699 int bpf_link__destroy(struct bpf_link *link)
7703 if (IS_ERR_OR_NULL(link))
7706 if (!link->disconnected && link->detach)
7707 err = link->detach(link);
7709 link->destroy(link);
7711 free(link->pin_path);
7717 int bpf_link__fd(const struct bpf_link *link)
7722 const char *bpf_link__pin_path(const struct bpf_link *link)
7724 return link->pin_path;
7727 static int bpf_link__detach_fd(struct bpf_link *link)
7729 return close(link->fd);
7732 struct bpf_link *bpf_link__open(const char *path)
7734 struct bpf_link *link;
7737 fd = bpf_obj_get(path);
7740 pr_warn("failed to open link at %s: %d\n", path, fd);
7744 link = calloc(1, sizeof(*link));
7747 return ERR_PTR(-ENOMEM);
7749 link->detach = &bpf_link__detach_fd;
7752 link->pin_path = strdup(path);
7753 if (!link->pin_path) {
7754 bpf_link__destroy(link);
7755 return ERR_PTR(-ENOMEM);
7761 int bpf_link__detach(struct bpf_link *link)
7763 return bpf_link_detach(link->fd) ? -errno : 0;
7766 int bpf_link__pin(struct bpf_link *link, const char *path)
7772 err = make_parent_dir(path);
7775 err = check_path(path);
7779 link->pin_path = strdup(path);
7780 if (!link->pin_path)
7783 if (bpf_obj_pin(link->fd, link->pin_path)) {
7785 zfree(&link->pin_path);
7789 pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
7793 int bpf_link__unpin(struct bpf_link *link)
7797 if (!link->pin_path)
7800 err = unlink(link->pin_path);
7804 pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
7805 zfree(&link->pin_path);
7809 static int bpf_link__detach_perf_event(struct bpf_link *link)
7813 err = ioctl(link->fd, PERF_EVENT_IOC_DISABLE, 0);
7821 struct bpf_link *bpf_program__attach_perf_event(struct bpf_program *prog,
7824 char errmsg[STRERR_BUFSIZE];
7825 struct bpf_link *link;
7829 pr_warn("program '%s': invalid perf event FD %d\n",
7830 bpf_program__title(prog, false), pfd);
7831 return ERR_PTR(-EINVAL);
7833 prog_fd = bpf_program__fd(prog);
7835 pr_warn("program '%s': can't attach BPF program w/o FD (did you load it?)\n",
7836 bpf_program__title(prog, false));
7837 return ERR_PTR(-EINVAL);
7840 link = calloc(1, sizeof(*link));
7842 return ERR_PTR(-ENOMEM);
7843 link->detach = &bpf_link__detach_perf_event;
7846 if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
7849 pr_warn("program '%s': failed to attach to pfd %d: %s\n",
7850 bpf_program__title(prog, false), pfd,
7851 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
7853 pr_warn("program '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n",
7854 bpf_program__title(prog, false), pfd);
7855 return ERR_PTR(err);
7857 if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
7860 pr_warn("program '%s': failed to enable pfd %d: %s\n",
7861 bpf_program__title(prog, false), pfd,
7862 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
7863 return ERR_PTR(err);
7869 * this function is expected to parse integer in the range of [0, 2^31-1] from
7870 * given file using scanf format string fmt. If actual parsed value is
7871 * negative, the result might be indistinguishable from error
7873 static int parse_uint_from_file(const char *file, const char *fmt)
7875 char buf[STRERR_BUFSIZE];
7879 f = fopen(file, "r");
7882 pr_debug("failed to open '%s': %s\n", file,
7883 libbpf_strerror_r(err, buf, sizeof(buf)));
7886 err = fscanf(f, fmt, &ret);
7888 err = err == EOF ? -EIO : -errno;
7889 pr_debug("failed to parse '%s': %s\n", file,
7890 libbpf_strerror_r(err, buf, sizeof(buf)));
7898 static int determine_kprobe_perf_type(void)
7900 const char *file = "/sys/bus/event_source/devices/kprobe/type";
7902 return parse_uint_from_file(file, "%d\n");
7905 static int determine_uprobe_perf_type(void)
7907 const char *file = "/sys/bus/event_source/devices/uprobe/type";
7909 return parse_uint_from_file(file, "%d\n");
7912 static int determine_kprobe_retprobe_bit(void)
7914 const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
7916 return parse_uint_from_file(file, "config:%d\n");
7919 static int determine_uprobe_retprobe_bit(void)
7921 const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
7923 return parse_uint_from_file(file, "config:%d\n");
7926 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
7927 uint64_t offset, int pid)
7929 struct perf_event_attr attr = {};
7930 char errmsg[STRERR_BUFSIZE];
7933 type = uprobe ? determine_uprobe_perf_type()
7934 : determine_kprobe_perf_type();
7936 pr_warn("failed to determine %s perf type: %s\n",
7937 uprobe ? "uprobe" : "kprobe",
7938 libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
7942 int bit = uprobe ? determine_uprobe_retprobe_bit()
7943 : determine_kprobe_retprobe_bit();
7946 pr_warn("failed to determine %s retprobe bit: %s\n",
7947 uprobe ? "uprobe" : "kprobe",
7948 libbpf_strerror_r(bit, errmsg, sizeof(errmsg)));
7951 attr.config |= 1 << bit;
7953 attr.size = sizeof(attr);
7955 attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
7956 attr.config2 = offset; /* kprobe_addr or probe_offset */
7958 /* pid filter is meaningful only for uprobes */
7959 pfd = syscall(__NR_perf_event_open, &attr,
7960 pid < 0 ? -1 : pid /* pid */,
7961 pid == -1 ? 0 : -1 /* cpu */,
7962 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
7965 pr_warn("%s perf_event_open() failed: %s\n",
7966 uprobe ? "uprobe" : "kprobe",
7967 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
7973 struct bpf_link *bpf_program__attach_kprobe(struct bpf_program *prog,
7975 const char *func_name)
7977 char errmsg[STRERR_BUFSIZE];
7978 struct bpf_link *link;
7981 pfd = perf_event_open_probe(false /* uprobe */, retprobe, func_name,
7982 0 /* offset */, -1 /* pid */);
7984 pr_warn("program '%s': failed to create %s '%s' perf event: %s\n",
7985 bpf_program__title(prog, false),
7986 retprobe ? "kretprobe" : "kprobe", func_name,
7987 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
7988 return ERR_PTR(pfd);
7990 link = bpf_program__attach_perf_event(prog, pfd);
7993 err = PTR_ERR(link);
7994 pr_warn("program '%s': failed to attach to %s '%s': %s\n",
7995 bpf_program__title(prog, false),
7996 retprobe ? "kretprobe" : "kprobe", func_name,
7997 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
8003 static struct bpf_link *attach_kprobe(const struct bpf_sec_def *sec,
8004 struct bpf_program *prog)
8006 const char *func_name;
8009 func_name = bpf_program__title(prog, false) + sec->len;
8010 retprobe = strcmp(sec->sec, "kretprobe/") == 0;
8012 return bpf_program__attach_kprobe(prog, retprobe, func_name);
8015 struct bpf_link *bpf_program__attach_uprobe(struct bpf_program *prog,
8016 bool retprobe, pid_t pid,
8017 const char *binary_path,
8020 char errmsg[STRERR_BUFSIZE];
8021 struct bpf_link *link;
8024 pfd = perf_event_open_probe(true /* uprobe */, retprobe,
8025 binary_path, func_offset, pid);
8027 pr_warn("program '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
8028 bpf_program__title(prog, false),
8029 retprobe ? "uretprobe" : "uprobe",
8030 binary_path, func_offset,
8031 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
8032 return ERR_PTR(pfd);
8034 link = bpf_program__attach_perf_event(prog, pfd);
8037 err = PTR_ERR(link);
8038 pr_warn("program '%s': failed to attach to %s '%s:0x%zx': %s\n",
8039 bpf_program__title(prog, false),
8040 retprobe ? "uretprobe" : "uprobe",
8041 binary_path, func_offset,
8042 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
8048 static int determine_tracepoint_id(const char *tp_category,
8049 const char *tp_name)
8051 char file[PATH_MAX];
8054 ret = snprintf(file, sizeof(file),
8055 "/sys/kernel/debug/tracing/events/%s/%s/id",
8056 tp_category, tp_name);
8059 if (ret >= sizeof(file)) {
8060 pr_debug("tracepoint %s/%s path is too long\n",
8061 tp_category, tp_name);
8064 return parse_uint_from_file(file, "%d\n");
8067 static int perf_event_open_tracepoint(const char *tp_category,
8068 const char *tp_name)
8070 struct perf_event_attr attr = {};
8071 char errmsg[STRERR_BUFSIZE];
8072 int tp_id, pfd, err;
8074 tp_id = determine_tracepoint_id(tp_category, tp_name);
8076 pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
8077 tp_category, tp_name,
8078 libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
8082 attr.type = PERF_TYPE_TRACEPOINT;
8083 attr.size = sizeof(attr);
8084 attr.config = tp_id;
8086 pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
8087 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
8090 pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
8091 tp_category, tp_name,
8092 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
8098 struct bpf_link *bpf_program__attach_tracepoint(struct bpf_program *prog,
8099 const char *tp_category,
8100 const char *tp_name)
8102 char errmsg[STRERR_BUFSIZE];
8103 struct bpf_link *link;
8106 pfd = perf_event_open_tracepoint(tp_category, tp_name);
8108 pr_warn("program '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
8109 bpf_program__title(prog, false),
8110 tp_category, tp_name,
8111 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
8112 return ERR_PTR(pfd);
8114 link = bpf_program__attach_perf_event(prog, pfd);
8117 err = PTR_ERR(link);
8118 pr_warn("program '%s': failed to attach to tracepoint '%s/%s': %s\n",
8119 bpf_program__title(prog, false),
8120 tp_category, tp_name,
8121 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
8127 static struct bpf_link *attach_tp(const struct bpf_sec_def *sec,
8128 struct bpf_program *prog)
8130 char *sec_name, *tp_cat, *tp_name;
8131 struct bpf_link *link;
8133 sec_name = strdup(bpf_program__title(prog, false));
8135 return ERR_PTR(-ENOMEM);
8137 /* extract "tp/<category>/<name>" */
8138 tp_cat = sec_name + sec->len;
8139 tp_name = strchr(tp_cat, '/');
8141 link = ERR_PTR(-EINVAL);
8147 link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
8153 struct bpf_link *bpf_program__attach_raw_tracepoint(struct bpf_program *prog,
8154 const char *tp_name)
8156 char errmsg[STRERR_BUFSIZE];
8157 struct bpf_link *link;
8160 prog_fd = bpf_program__fd(prog);
8162 pr_warn("program '%s': can't attach before loaded\n",
8163 bpf_program__title(prog, false));
8164 return ERR_PTR(-EINVAL);
8167 link = calloc(1, sizeof(*link));
8169 return ERR_PTR(-ENOMEM);
8170 link->detach = &bpf_link__detach_fd;
8172 pfd = bpf_raw_tracepoint_open(tp_name, prog_fd);
8176 pr_warn("program '%s': failed to attach to raw tracepoint '%s': %s\n",
8177 bpf_program__title(prog, false), tp_name,
8178 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
8179 return ERR_PTR(pfd);
8185 static struct bpf_link *attach_raw_tp(const struct bpf_sec_def *sec,
8186 struct bpf_program *prog)
8188 const char *tp_name = bpf_program__title(prog, false) + sec->len;
8190 return bpf_program__attach_raw_tracepoint(prog, tp_name);
8193 /* Common logic for all BPF program types that attach to a btf_id */
8194 static struct bpf_link *bpf_program__attach_btf_id(struct bpf_program *prog)
8196 char errmsg[STRERR_BUFSIZE];
8197 struct bpf_link *link;
8200 prog_fd = bpf_program__fd(prog);
8202 pr_warn("program '%s': can't attach before loaded\n",
8203 bpf_program__title(prog, false));
8204 return ERR_PTR(-EINVAL);
8207 link = calloc(1, sizeof(*link));
8209 return ERR_PTR(-ENOMEM);
8210 link->detach = &bpf_link__detach_fd;
8212 pfd = bpf_raw_tracepoint_open(NULL, prog_fd);
8216 pr_warn("program '%s': failed to attach: %s\n",
8217 bpf_program__title(prog, false),
8218 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
8219 return ERR_PTR(pfd);
8222 return (struct bpf_link *)link;
8225 struct bpf_link *bpf_program__attach_trace(struct bpf_program *prog)
8227 return bpf_program__attach_btf_id(prog);
8230 struct bpf_link *bpf_program__attach_lsm(struct bpf_program *prog)
8232 return bpf_program__attach_btf_id(prog);
8235 static struct bpf_link *attach_trace(const struct bpf_sec_def *sec,
8236 struct bpf_program *prog)
8238 return bpf_program__attach_trace(prog);
8241 static struct bpf_link *attach_lsm(const struct bpf_sec_def *sec,
8242 struct bpf_program *prog)
8244 return bpf_program__attach_lsm(prog);
8247 static struct bpf_link *attach_iter(const struct bpf_sec_def *sec,
8248 struct bpf_program *prog)
8250 return bpf_program__attach_iter(prog, NULL);
8253 static struct bpf_link *
8254 bpf_program__attach_fd(struct bpf_program *prog, int target_fd,
8255 const char *target_name)
8257 enum bpf_attach_type attach_type;
8258 char errmsg[STRERR_BUFSIZE];
8259 struct bpf_link *link;
8260 int prog_fd, link_fd;
8262 prog_fd = bpf_program__fd(prog);
8264 pr_warn("program '%s': can't attach before loaded\n",
8265 bpf_program__title(prog, false));
8266 return ERR_PTR(-EINVAL);
8269 link = calloc(1, sizeof(*link));
8271 return ERR_PTR(-ENOMEM);
8272 link->detach = &bpf_link__detach_fd;
8274 attach_type = bpf_program__get_expected_attach_type(prog);
8275 link_fd = bpf_link_create(prog_fd, target_fd, attach_type, NULL);
8279 pr_warn("program '%s': failed to attach to %s: %s\n",
8280 bpf_program__title(prog, false), target_name,
8281 libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
8282 return ERR_PTR(link_fd);
8289 bpf_program__attach_cgroup(struct bpf_program *prog, int cgroup_fd)
8291 return bpf_program__attach_fd(prog, cgroup_fd, "cgroup");
8295 bpf_program__attach_netns(struct bpf_program *prog, int netns_fd)
8297 return bpf_program__attach_fd(prog, netns_fd, "netns");
8300 struct bpf_link *bpf_program__attach_xdp(struct bpf_program *prog, int ifindex)
8302 /* target_fd/target_ifindex use the same field in LINK_CREATE */
8303 return bpf_program__attach_fd(prog, ifindex, "xdp");
8307 bpf_program__attach_iter(struct bpf_program *prog,
8308 const struct bpf_iter_attach_opts *opts)
8310 DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
8311 char errmsg[STRERR_BUFSIZE];
8312 struct bpf_link *link;
8313 int prog_fd, link_fd;
8314 __u32 target_fd = 0;
8316 if (!OPTS_VALID(opts, bpf_iter_attach_opts))
8317 return ERR_PTR(-EINVAL);
8319 link_create_opts.iter_info = OPTS_GET(opts, link_info, (void *)0);
8320 link_create_opts.iter_info_len = OPTS_GET(opts, link_info_len, 0);
8322 prog_fd = bpf_program__fd(prog);
8324 pr_warn("program '%s': can't attach before loaded\n",
8325 bpf_program__title(prog, false));
8326 return ERR_PTR(-EINVAL);
8329 link = calloc(1, sizeof(*link));
8331 return ERR_PTR(-ENOMEM);
8332 link->detach = &bpf_link__detach_fd;
8334 link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER,
8339 pr_warn("program '%s': failed to attach to iterator: %s\n",
8340 bpf_program__title(prog, false),
8341 libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
8342 return ERR_PTR(link_fd);
8348 struct bpf_link *bpf_program__attach(struct bpf_program *prog)
8350 const struct bpf_sec_def *sec_def;
8352 sec_def = find_sec_def(bpf_program__title(prog, false));
8353 if (!sec_def || !sec_def->attach_fn)
8354 return ERR_PTR(-ESRCH);
8356 return sec_def->attach_fn(sec_def, prog);
8359 static int bpf_link__detach_struct_ops(struct bpf_link *link)
8363 if (bpf_map_delete_elem(link->fd, &zero))
8369 struct bpf_link *bpf_map__attach_struct_ops(struct bpf_map *map)
8371 struct bpf_struct_ops *st_ops;
8372 struct bpf_link *link;
8376 if (!bpf_map__is_struct_ops(map) || map->fd == -1)
8377 return ERR_PTR(-EINVAL);
8379 link = calloc(1, sizeof(*link));
8381 return ERR_PTR(-EINVAL);
8383 st_ops = map->st_ops;
8384 for (i = 0; i < btf_vlen(st_ops->type); i++) {
8385 struct bpf_program *prog = st_ops->progs[i];
8392 prog_fd = bpf_program__fd(prog);
8393 kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
8394 *(unsigned long *)kern_data = prog_fd;
8397 err = bpf_map_update_elem(map->fd, &zero, st_ops->kern_vdata, 0);
8401 return ERR_PTR(err);
8404 link->detach = bpf_link__detach_struct_ops;
8410 enum bpf_perf_event_ret
8411 bpf_perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
8412 void **copy_mem, size_t *copy_size,
8413 bpf_perf_event_print_t fn, void *private_data)
8415 struct perf_event_mmap_page *header = mmap_mem;
8416 __u64 data_head = ring_buffer_read_head(header);
8417 __u64 data_tail = header->data_tail;
8418 void *base = ((__u8 *)header) + page_size;
8419 int ret = LIBBPF_PERF_EVENT_CONT;
8420 struct perf_event_header *ehdr;
8423 while (data_head != data_tail) {
8424 ehdr = base + (data_tail & (mmap_size - 1));
8425 ehdr_size = ehdr->size;
8427 if (((void *)ehdr) + ehdr_size > base + mmap_size) {
8428 void *copy_start = ehdr;
8429 size_t len_first = base + mmap_size - copy_start;
8430 size_t len_secnd = ehdr_size - len_first;
8432 if (*copy_size < ehdr_size) {
8434 *copy_mem = malloc(ehdr_size);
8437 ret = LIBBPF_PERF_EVENT_ERROR;
8440 *copy_size = ehdr_size;
8443 memcpy(*copy_mem, copy_start, len_first);
8444 memcpy(*copy_mem + len_first, base, len_secnd);
8448 ret = fn(ehdr, private_data);
8449 data_tail += ehdr_size;
8450 if (ret != LIBBPF_PERF_EVENT_CONT)
8454 ring_buffer_write_tail(header, data_tail);
8460 struct perf_buffer_params {
8461 struct perf_event_attr *attr;
8462 /* if event_cb is specified, it takes precendence */
8463 perf_buffer_event_fn event_cb;
8464 /* sample_cb and lost_cb are higher-level common-case callbacks */
8465 perf_buffer_sample_fn sample_cb;
8466 perf_buffer_lost_fn lost_cb;
8473 struct perf_cpu_buf {
8474 struct perf_buffer *pb;
8475 void *base; /* mmap()'ed memory */
8476 void *buf; /* for reconstructing segmented data */
8483 struct perf_buffer {
8484 perf_buffer_event_fn event_cb;
8485 perf_buffer_sample_fn sample_cb;
8486 perf_buffer_lost_fn lost_cb;
8487 void *ctx; /* passed into callbacks */
8491 struct perf_cpu_buf **cpu_bufs;
8492 struct epoll_event *events;
8493 int cpu_cnt; /* number of allocated CPU buffers */
8494 int epoll_fd; /* perf event FD */
8495 int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
8498 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
8499 struct perf_cpu_buf *cpu_buf)
8503 if (cpu_buf->base &&
8504 munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
8505 pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
8506 if (cpu_buf->fd >= 0) {
8507 ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
8514 void perf_buffer__free(struct perf_buffer *pb)
8518 if (IS_ERR_OR_NULL(pb))
8521 for (i = 0; i < pb->cpu_cnt; i++) {
8522 struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
8527 bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
8528 perf_buffer__free_cpu_buf(pb, cpu_buf);
8532 if (pb->epoll_fd >= 0)
8533 close(pb->epoll_fd);
8538 static struct perf_cpu_buf *
8539 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
8540 int cpu, int map_key)
8542 struct perf_cpu_buf *cpu_buf;
8543 char msg[STRERR_BUFSIZE];
8546 cpu_buf = calloc(1, sizeof(*cpu_buf));
8548 return ERR_PTR(-ENOMEM);
8552 cpu_buf->map_key = map_key;
8554 cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
8555 -1, PERF_FLAG_FD_CLOEXEC);
8556 if (cpu_buf->fd < 0) {
8558 pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
8559 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
8563 cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
8564 PROT_READ | PROT_WRITE, MAP_SHARED,
8566 if (cpu_buf->base == MAP_FAILED) {
8567 cpu_buf->base = NULL;
8569 pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
8570 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
8574 if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
8576 pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
8577 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
8584 perf_buffer__free_cpu_buf(pb, cpu_buf);
8585 return (struct perf_cpu_buf *)ERR_PTR(err);
8588 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
8589 struct perf_buffer_params *p);
8591 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
8592 const struct perf_buffer_opts *opts)
8594 struct perf_buffer_params p = {};
8595 struct perf_event_attr attr = { 0, };
8597 attr.config = PERF_COUNT_SW_BPF_OUTPUT;
8598 attr.type = PERF_TYPE_SOFTWARE;
8599 attr.sample_type = PERF_SAMPLE_RAW;
8600 attr.sample_period = 1;
8601 attr.wakeup_events = 1;
8604 p.sample_cb = opts ? opts->sample_cb : NULL;
8605 p.lost_cb = opts ? opts->lost_cb : NULL;
8606 p.ctx = opts ? opts->ctx : NULL;
8608 return __perf_buffer__new(map_fd, page_cnt, &p);
8611 struct perf_buffer *
8612 perf_buffer__new_raw(int map_fd, size_t page_cnt,
8613 const struct perf_buffer_raw_opts *opts)
8615 struct perf_buffer_params p = {};
8617 p.attr = opts->attr;
8618 p.event_cb = opts->event_cb;
8620 p.cpu_cnt = opts->cpu_cnt;
8621 p.cpus = opts->cpus;
8622 p.map_keys = opts->map_keys;
8624 return __perf_buffer__new(map_fd, page_cnt, &p);
8627 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
8628 struct perf_buffer_params *p)
8630 const char *online_cpus_file = "/sys/devices/system/cpu/online";
8631 struct bpf_map_info map;
8632 char msg[STRERR_BUFSIZE];
8633 struct perf_buffer *pb;
8634 bool *online = NULL;
8638 if (page_cnt & (page_cnt - 1)) {
8639 pr_warn("page count should be power of two, but is %zu\n",
8641 return ERR_PTR(-EINVAL);
8644 /* best-effort sanity checks */
8645 memset(&map, 0, sizeof(map));
8646 map_info_len = sizeof(map);
8647 err = bpf_obj_get_info_by_fd(map_fd, &map, &map_info_len);
8650 /* if BPF_OBJ_GET_INFO_BY_FD is supported, will return
8651 * -EBADFD, -EFAULT, or -E2BIG on real error
8653 if (err != -EINVAL) {
8654 pr_warn("failed to get map info for map FD %d: %s\n",
8655 map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
8656 return ERR_PTR(err);
8658 pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
8661 if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
8662 pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
8664 return ERR_PTR(-EINVAL);
8668 pb = calloc(1, sizeof(*pb));
8670 return ERR_PTR(-ENOMEM);
8672 pb->event_cb = p->event_cb;
8673 pb->sample_cb = p->sample_cb;
8674 pb->lost_cb = p->lost_cb;
8677 pb->page_size = getpagesize();
8678 pb->mmap_size = pb->page_size * page_cnt;
8679 pb->map_fd = map_fd;
8681 pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
8682 if (pb->epoll_fd < 0) {
8684 pr_warn("failed to create epoll instance: %s\n",
8685 libbpf_strerror_r(err, msg, sizeof(msg)));
8689 if (p->cpu_cnt > 0) {
8690 pb->cpu_cnt = p->cpu_cnt;
8692 pb->cpu_cnt = libbpf_num_possible_cpus();
8693 if (pb->cpu_cnt < 0) {
8697 if (map.max_entries && map.max_entries < pb->cpu_cnt)
8698 pb->cpu_cnt = map.max_entries;
8701 pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
8704 pr_warn("failed to allocate events: out of memory\n");
8707 pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
8708 if (!pb->cpu_bufs) {
8710 pr_warn("failed to allocate buffers: out of memory\n");
8714 err = parse_cpu_mask_file(online_cpus_file, &online, &n);
8716 pr_warn("failed to get online CPU mask: %d\n", err);
8720 for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
8721 struct perf_cpu_buf *cpu_buf;
8724 cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
8725 map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
8727 /* in case user didn't explicitly requested particular CPUs to
8728 * be attached to, skip offline/not present CPUs
8730 if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
8733 cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
8734 if (IS_ERR(cpu_buf)) {
8735 err = PTR_ERR(cpu_buf);
8739 pb->cpu_bufs[j] = cpu_buf;
8741 err = bpf_map_update_elem(pb->map_fd, &map_key,
8745 pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
8746 cpu, map_key, cpu_buf->fd,
8747 libbpf_strerror_r(err, msg, sizeof(msg)));
8751 pb->events[j].events = EPOLLIN;
8752 pb->events[j].data.ptr = cpu_buf;
8753 if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
8754 &pb->events[j]) < 0) {
8756 pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
8758 libbpf_strerror_r(err, msg, sizeof(msg)));
8771 perf_buffer__free(pb);
8772 return ERR_PTR(err);
8775 struct perf_sample_raw {
8776 struct perf_event_header header;
8781 struct perf_sample_lost {
8782 struct perf_event_header header;
8788 static enum bpf_perf_event_ret
8789 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
8791 struct perf_cpu_buf *cpu_buf = ctx;
8792 struct perf_buffer *pb = cpu_buf->pb;
8795 /* user wants full control over parsing perf event */
8797 return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
8800 case PERF_RECORD_SAMPLE: {
8801 struct perf_sample_raw *s = data;
8804 pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
8807 case PERF_RECORD_LOST: {
8808 struct perf_sample_lost *s = data;
8811 pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
8815 pr_warn("unknown perf sample type %d\n", e->type);
8816 return LIBBPF_PERF_EVENT_ERROR;
8818 return LIBBPF_PERF_EVENT_CONT;
8821 static int perf_buffer__process_records(struct perf_buffer *pb,
8822 struct perf_cpu_buf *cpu_buf)
8824 enum bpf_perf_event_ret ret;
8826 ret = bpf_perf_event_read_simple(cpu_buf->base, pb->mmap_size,
8827 pb->page_size, &cpu_buf->buf,
8829 perf_buffer__process_record, cpu_buf);
8830 if (ret != LIBBPF_PERF_EVENT_CONT)
8835 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
8839 cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
8840 for (i = 0; i < cnt; i++) {
8841 struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
8843 err = perf_buffer__process_records(pb, cpu_buf);
8845 pr_warn("error while processing records: %d\n", err);
8849 return cnt < 0 ? -errno : cnt;
8852 int perf_buffer__consume(struct perf_buffer *pb)
8856 for (i = 0; i < pb->cpu_cnt; i++) {
8857 struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
8862 err = perf_buffer__process_records(pb, cpu_buf);
8864 pr_warn("error while processing records: %d\n", err);
8871 struct bpf_prog_info_array_desc {
8872 int array_offset; /* e.g. offset of jited_prog_insns */
8873 int count_offset; /* e.g. offset of jited_prog_len */
8874 int size_offset; /* > 0: offset of rec size,
8875 * < 0: fix size of -size_offset
8879 static struct bpf_prog_info_array_desc bpf_prog_info_array_desc[] = {
8880 [BPF_PROG_INFO_JITED_INSNS] = {
8881 offsetof(struct bpf_prog_info, jited_prog_insns),
8882 offsetof(struct bpf_prog_info, jited_prog_len),
8885 [BPF_PROG_INFO_XLATED_INSNS] = {
8886 offsetof(struct bpf_prog_info, xlated_prog_insns),
8887 offsetof(struct bpf_prog_info, xlated_prog_len),
8890 [BPF_PROG_INFO_MAP_IDS] = {
8891 offsetof(struct bpf_prog_info, map_ids),
8892 offsetof(struct bpf_prog_info, nr_map_ids),
8893 -(int)sizeof(__u32),
8895 [BPF_PROG_INFO_JITED_KSYMS] = {
8896 offsetof(struct bpf_prog_info, jited_ksyms),
8897 offsetof(struct bpf_prog_info, nr_jited_ksyms),
8898 -(int)sizeof(__u64),
8900 [BPF_PROG_INFO_JITED_FUNC_LENS] = {
8901 offsetof(struct bpf_prog_info, jited_func_lens),
8902 offsetof(struct bpf_prog_info, nr_jited_func_lens),
8903 -(int)sizeof(__u32),
8905 [BPF_PROG_INFO_FUNC_INFO] = {
8906 offsetof(struct bpf_prog_info, func_info),
8907 offsetof(struct bpf_prog_info, nr_func_info),
8908 offsetof(struct bpf_prog_info, func_info_rec_size),
8910 [BPF_PROG_INFO_LINE_INFO] = {
8911 offsetof(struct bpf_prog_info, line_info),
8912 offsetof(struct bpf_prog_info, nr_line_info),
8913 offsetof(struct bpf_prog_info, line_info_rec_size),
8915 [BPF_PROG_INFO_JITED_LINE_INFO] = {
8916 offsetof(struct bpf_prog_info, jited_line_info),
8917 offsetof(struct bpf_prog_info, nr_jited_line_info),
8918 offsetof(struct bpf_prog_info, jited_line_info_rec_size),
8920 [BPF_PROG_INFO_PROG_TAGS] = {
8921 offsetof(struct bpf_prog_info, prog_tags),
8922 offsetof(struct bpf_prog_info, nr_prog_tags),
8923 -(int)sizeof(__u8) * BPF_TAG_SIZE,
8928 static __u32 bpf_prog_info_read_offset_u32(struct bpf_prog_info *info,
8931 __u32 *array = (__u32 *)info;
8934 return array[offset / sizeof(__u32)];
8935 return -(int)offset;
8938 static __u64 bpf_prog_info_read_offset_u64(struct bpf_prog_info *info,
8941 __u64 *array = (__u64 *)info;
8944 return array[offset / sizeof(__u64)];
8945 return -(int)offset;
8948 static void bpf_prog_info_set_offset_u32(struct bpf_prog_info *info, int offset,
8951 __u32 *array = (__u32 *)info;
8954 array[offset / sizeof(__u32)] = val;
8957 static void bpf_prog_info_set_offset_u64(struct bpf_prog_info *info, int offset,
8960 __u64 *array = (__u64 *)info;
8963 array[offset / sizeof(__u64)] = val;
8966 struct bpf_prog_info_linear *
8967 bpf_program__get_prog_info_linear(int fd, __u64 arrays)
8969 struct bpf_prog_info_linear *info_linear;
8970 struct bpf_prog_info info = {};
8971 __u32 info_len = sizeof(info);
8976 if (arrays >> BPF_PROG_INFO_LAST_ARRAY)
8977 return ERR_PTR(-EINVAL);
8979 /* step 1: get array dimensions */
8980 err = bpf_obj_get_info_by_fd(fd, &info, &info_len);
8982 pr_debug("can't get prog info: %s", strerror(errno));
8983 return ERR_PTR(-EFAULT);
8986 /* step 2: calculate total size of all arrays */
8987 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
8988 bool include_array = (arrays & (1UL << i)) > 0;
8989 struct bpf_prog_info_array_desc *desc;
8992 desc = bpf_prog_info_array_desc + i;
8994 /* kernel is too old to support this field */
8995 if (info_len < desc->array_offset + sizeof(__u32) ||
8996 info_len < desc->count_offset + sizeof(__u32) ||
8997 (desc->size_offset > 0 && info_len < desc->size_offset))
8998 include_array = false;
9000 if (!include_array) {
9001 arrays &= ~(1UL << i); /* clear the bit */
9005 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
9006 size = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
9008 data_len += count * size;
9011 /* step 3: allocate continuous memory */
9012 data_len = roundup(data_len, sizeof(__u64));
9013 info_linear = malloc(sizeof(struct bpf_prog_info_linear) + data_len);
9015 return ERR_PTR(-ENOMEM);
9017 /* step 4: fill data to info_linear->info */
9018 info_linear->arrays = arrays;
9019 memset(&info_linear->info, 0, sizeof(info));
9020 ptr = info_linear->data;
9022 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
9023 struct bpf_prog_info_array_desc *desc;
9026 if ((arrays & (1UL << i)) == 0)
9029 desc = bpf_prog_info_array_desc + i;
9030 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
9031 size = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
9032 bpf_prog_info_set_offset_u32(&info_linear->info,
9033 desc->count_offset, count);
9034 bpf_prog_info_set_offset_u32(&info_linear->info,
9035 desc->size_offset, size);
9036 bpf_prog_info_set_offset_u64(&info_linear->info,
9039 ptr += count * size;
9042 /* step 5: call syscall again to get required arrays */
9043 err = bpf_obj_get_info_by_fd(fd, &info_linear->info, &info_len);
9045 pr_debug("can't get prog info: %s", strerror(errno));
9047 return ERR_PTR(-EFAULT);
9050 /* step 6: verify the data */
9051 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
9052 struct bpf_prog_info_array_desc *desc;
9055 if ((arrays & (1UL << i)) == 0)
9058 desc = bpf_prog_info_array_desc + i;
9059 v1 = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
9060 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
9061 desc->count_offset);
9063 pr_warn("%s: mismatch in element count\n", __func__);
9065 v1 = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
9066 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
9069 pr_warn("%s: mismatch in rec size\n", __func__);
9072 /* step 7: update info_len and data_len */
9073 info_linear->info_len = sizeof(struct bpf_prog_info);
9074 info_linear->data_len = data_len;
9079 void bpf_program__bpil_addr_to_offs(struct bpf_prog_info_linear *info_linear)
9083 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
9084 struct bpf_prog_info_array_desc *desc;
9087 if ((info_linear->arrays & (1UL << i)) == 0)
9090 desc = bpf_prog_info_array_desc + i;
9091 addr = bpf_prog_info_read_offset_u64(&info_linear->info,
9092 desc->array_offset);
9093 offs = addr - ptr_to_u64(info_linear->data);
9094 bpf_prog_info_set_offset_u64(&info_linear->info,
9095 desc->array_offset, offs);
9099 void bpf_program__bpil_offs_to_addr(struct bpf_prog_info_linear *info_linear)
9103 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
9104 struct bpf_prog_info_array_desc *desc;
9107 if ((info_linear->arrays & (1UL << i)) == 0)
9110 desc = bpf_prog_info_array_desc + i;
9111 offs = bpf_prog_info_read_offset_u64(&info_linear->info,
9112 desc->array_offset);
9113 addr = offs + ptr_to_u64(info_linear->data);
9114 bpf_prog_info_set_offset_u64(&info_linear->info,
9115 desc->array_offset, addr);
9119 int bpf_program__set_attach_target(struct bpf_program *prog,
9121 const char *attach_func_name)
9125 if (!prog || attach_prog_fd < 0 || !attach_func_name)
9129 btf_id = libbpf_find_prog_btf_id(attach_func_name,
9132 btf_id = __find_vmlinux_btf_id(prog->obj->btf_vmlinux,
9134 prog->expected_attach_type);
9139 prog->attach_btf_id = btf_id;
9140 prog->attach_prog_fd = attach_prog_fd;
9144 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
9146 int err = 0, n, len, start, end = -1;
9152 /* Each sub string separated by ',' has format \d+-\d+ or \d+ */
9154 if (*s == ',' || *s == '\n') {
9158 n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
9159 if (n <= 0 || n > 2) {
9160 pr_warn("Failed to get CPU range %s: %d\n", s, n);
9163 } else if (n == 1) {
9166 if (start < 0 || start > end) {
9167 pr_warn("Invalid CPU range [%d,%d] in %s\n",
9172 tmp = realloc(*mask, end + 1);
9178 memset(tmp + *mask_sz, 0, start - *mask_sz);
9179 memset(tmp + start, 1, end - start + 1);
9184 pr_warn("Empty CPU range\n");
9194 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
9196 int fd, err = 0, len;
9199 fd = open(fcpu, O_RDONLY);
9202 pr_warn("Failed to open cpu mask file %s: %d\n", fcpu, err);
9205 len = read(fd, buf, sizeof(buf));
9208 err = len ? -errno : -EINVAL;
9209 pr_warn("Failed to read cpu mask from %s: %d\n", fcpu, err);
9212 if (len >= sizeof(buf)) {
9213 pr_warn("CPU mask is too big in file %s\n", fcpu);
9218 return parse_cpu_mask_str(buf, mask, mask_sz);
9221 int libbpf_num_possible_cpus(void)
9223 static const char *fcpu = "/sys/devices/system/cpu/possible";
9225 int err, n, i, tmp_cpus;
9228 tmp_cpus = READ_ONCE(cpus);
9232 err = parse_cpu_mask_file(fcpu, &mask, &n);
9237 for (i = 0; i < n; i++) {
9243 WRITE_ONCE(cpus, tmp_cpus);
9247 int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
9248 const struct bpf_object_open_opts *opts)
9250 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, skel_opts,
9251 .object_name = s->name,
9253 struct bpf_object *obj;
9256 /* Attempt to preserve opts->object_name, unless overriden by user
9257 * explicitly. Overwriting object name for skeletons is discouraged,
9258 * as it breaks global data maps, because they contain object name
9259 * prefix as their own map name prefix. When skeleton is generated,
9260 * bpftool is making an assumption that this name will stay the same.
9263 memcpy(&skel_opts, opts, sizeof(*opts));
9264 if (!opts->object_name)
9265 skel_opts.object_name = s->name;
9268 obj = bpf_object__open_mem(s->data, s->data_sz, &skel_opts);
9270 pr_warn("failed to initialize skeleton BPF object '%s': %ld\n",
9271 s->name, PTR_ERR(obj));
9272 return PTR_ERR(obj);
9277 for (i = 0; i < s->map_cnt; i++) {
9278 struct bpf_map **map = s->maps[i].map;
9279 const char *name = s->maps[i].name;
9280 void **mmaped = s->maps[i].mmaped;
9282 *map = bpf_object__find_map_by_name(obj, name);
9284 pr_warn("failed to find skeleton map '%s'\n", name);
9288 /* externs shouldn't be pre-setup from user code */
9289 if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
9290 *mmaped = (*map)->mmaped;
9293 for (i = 0; i < s->prog_cnt; i++) {
9294 struct bpf_program **prog = s->progs[i].prog;
9295 const char *name = s->progs[i].name;
9297 *prog = bpf_object__find_program_by_name(obj, name);
9299 pr_warn("failed to find skeleton program '%s'\n", name);
9307 int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
9311 err = bpf_object__load(*s->obj);
9313 pr_warn("failed to load BPF skeleton '%s': %d\n", s->name, err);
9317 for (i = 0; i < s->map_cnt; i++) {
9318 struct bpf_map *map = *s->maps[i].map;
9319 size_t mmap_sz = bpf_map_mmap_sz(map);
9320 int prot, map_fd = bpf_map__fd(map);
9321 void **mmaped = s->maps[i].mmaped;
9326 if (!(map->def.map_flags & BPF_F_MMAPABLE)) {
9331 if (map->def.map_flags & BPF_F_RDONLY_PROG)
9334 prot = PROT_READ | PROT_WRITE;
9336 /* Remap anonymous mmap()-ed "map initialization image" as
9337 * a BPF map-backed mmap()-ed memory, but preserving the same
9338 * memory address. This will cause kernel to change process'
9339 * page table to point to a different piece of kernel memory,
9340 * but from userspace point of view memory address (and its
9341 * contents, being identical at this point) will stay the
9342 * same. This mapping will be released by bpf_object__close()
9343 * as per normal clean up procedure, so we don't need to worry
9344 * about it from skeleton's clean up perspective.
9346 *mmaped = mmap(map->mmaped, mmap_sz, prot,
9347 MAP_SHARED | MAP_FIXED, map_fd, 0);
9348 if (*mmaped == MAP_FAILED) {
9351 pr_warn("failed to re-mmap() map '%s': %d\n",
9352 bpf_map__name(map), err);
9360 int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
9364 for (i = 0; i < s->prog_cnt; i++) {
9365 struct bpf_program *prog = *s->progs[i].prog;
9366 struct bpf_link **link = s->progs[i].link;
9367 const struct bpf_sec_def *sec_def;
9368 const char *sec_name = bpf_program__title(prog, false);
9373 sec_def = find_sec_def(sec_name);
9374 if (!sec_def || !sec_def->attach_fn)
9377 *link = sec_def->attach_fn(sec_def, prog);
9378 if (IS_ERR(*link)) {
9379 pr_warn("failed to auto-attach program '%s': %ld\n",
9380 bpf_program__name(prog), PTR_ERR(*link));
9381 return PTR_ERR(*link);
9388 void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
9392 for (i = 0; i < s->prog_cnt; i++) {
9393 struct bpf_link **link = s->progs[i].link;
9395 bpf_link__destroy(*link);
9400 void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
9403 bpf_object__detach_skeleton(s);
9405 bpf_object__close(*s->obj);